]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
tex2lyx: refsection and bibbysection support (biblatex)
[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                 docstring flex_name = newinsetlayout->name();
2010                 // FIXME: what do we do if the prefix is not Flex: ?
2011                 if (prefixIs(flex_name, from_ascii("Flex:")))
2012                         flex_name.erase(0, 5);
2013                 os << to_utf8(flex_name) << '\n'
2014                    << "status collapsed\n";
2015                 if (newinsetlayout->isPassThru()) {
2016                         string const arg = p.verbatimEnvironment(name);
2017                         Context context(true, parent_context.textclass,
2018                                         &parent_context.textclass.plainLayout(),
2019                                         parent_context.layout);
2020                         output_ert(os, arg, parent_context);
2021                 } else
2022                         parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2023                 end_inset(os);
2024         }
2025
2026         else if (name == "appendix") {
2027                 // This is no good latex style, but it works and is used in some documents...
2028                 eat_whitespace(p, os, parent_context, false);
2029                 parent_context.check_end_layout(os);
2030                 Context context(true, parent_context.textclass, parent_context.layout,
2031                                 parent_context.layout, parent_context.font);
2032                 context.check_layout(os);
2033                 os << "\\start_of_appendix\n";
2034                 parse_text(p, os, FLAG_END, outer, context);
2035                 context.check_end_layout(os);
2036                 p.skip_spaces();
2037         }
2038
2039         else if (known_environments.find(name) != known_environments.end()) {
2040                 vector<ArgumentType> arguments = known_environments[name];
2041                 // The last "argument" denotes wether we may translate the
2042                 // environment contents to LyX
2043                 // The default required if no argument is given makes us
2044                 // compatible with the reLyXre environment.
2045                 ArgumentType contents = arguments.empty() ?
2046                         required :
2047                         arguments.back();
2048                 if (!arguments.empty())
2049                         arguments.pop_back();
2050                 // See comment in parse_unknown_environment()
2051                 bool const specialfont =
2052                         (parent_context.font != parent_context.normalfont);
2053                 bool const new_layout_allowed =
2054                         parent_context.new_layout_allowed;
2055                 if (specialfont)
2056                         parent_context.new_layout_allowed = false;
2057                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2058                                 outer, parent_context);
2059                 if (contents == verbatim)
2060                         output_ert_inset(os, p.ertEnvironment(name),
2061                                    parent_context);
2062                 else
2063                         parse_text_snippet(p, os, FLAG_END, outer,
2064                                            parent_context);
2065                 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2066                 if (specialfont)
2067                         parent_context.new_layout_allowed = new_layout_allowed;
2068         }
2069
2070         else
2071                 parse_unknown_environment(p, name, os, FLAG_END, outer,
2072                                           parent_context);
2073
2074         last_env = name;
2075         active_environments.pop_back();
2076 }
2077
2078
2079 /// parses a comment and outputs it to \p os.
2080 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2081 {
2082         LASSERT(t.cat() == catComment, return);
2083         if (!t.cs().empty()) {
2084                 context.check_layout(os);
2085                 output_comment(p, os, t.cs(), context);
2086                 if (p.next_token().cat() == catNewline) {
2087                         // A newline after a comment line starts a new
2088                         // paragraph
2089                         if (context.new_layout_allowed) {
2090                                 if(!context.atParagraphStart())
2091                                         // Only start a new paragraph if not already
2092                                         // done (we might get called recursively)
2093                                         context.new_paragraph(os);
2094                         } else
2095                                 output_ert_inset(os, "\n", context);
2096                         eat_whitespace(p, os, context, true);
2097                 }
2098         } else {
2099                 // "%\n" combination
2100                 p.skip_spaces();
2101         }
2102 }
2103
2104
2105 /*!
2106  * Reads spaces and comments until the first non-space, non-comment token.
2107  * New paragraphs (double newlines or \\par) are handled like simple spaces
2108  * if \p eatParagraph is true.
2109  * Spaces are skipped, but comments are written to \p os.
2110  */
2111 void eat_whitespace(Parser & p, ostream & os, Context & context,
2112                     bool eatParagraph)
2113 {
2114         while (p.good()) {
2115                 Token const & t = p.get_token();
2116                 if (t.cat() == catComment)
2117                         parse_comment(p, os, t, context);
2118                 else if ((! eatParagraph && p.isParagraph()) ||
2119                          (t.cat() != catSpace && t.cat() != catNewline)) {
2120                         p.putback();
2121                         return;
2122                 }
2123         }
2124 }
2125
2126
2127 /*!
2128  * Set a font attribute, parse text and reset the font attribute.
2129  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2130  * \param currentvalue Current value of the attribute. Is set to the new
2131  * value during parsing.
2132  * \param newvalue New value of the attribute
2133  */
2134 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2135                            Context & context, string const & attribute,
2136                            string & currentvalue, string const & newvalue)
2137 {
2138         context.check_layout(os);
2139         string const oldvalue = currentvalue;
2140         currentvalue = newvalue;
2141         os << '\n' << attribute << ' ' << newvalue << "\n";
2142         parse_text_snippet(p, os, flags, outer, context);
2143         context.check_layout(os);
2144         os << '\n' << attribute << ' ' << oldvalue << "\n";
2145         currentvalue = oldvalue;
2146 }
2147
2148
2149 /// get the arguments of a natbib or jurabib citation command
2150 void get_cite_arguments(Parser & p, bool natbibOrder,
2151         string & before, string & after)
2152 {
2153         // We need to distinguish "" and "[]", so we can't use p.getOpt().
2154
2155         // text before the citation
2156         before.clear();
2157         // text after the citation
2158         after = p.getFullOpt();
2159
2160         if (!after.empty()) {
2161                 before = p.getFullOpt();
2162                 if (natbibOrder && !before.empty())
2163                         swap(before, after);
2164         }
2165 }
2166
2167
2168 /// Convert filenames with TeX macros and/or quotes to something LyX
2169 /// can understand
2170 string const normalize_filename(string const & name)
2171 {
2172         Parser p(name);
2173         ostringstream os;
2174         while (p.good()) {
2175                 Token const & t = p.get_token();
2176                 if (t.cat() != catEscape)
2177                         os << t.asInput();
2178                 else if (t.cs() == "lyxdot") {
2179                         // This is used by LyX for simple dots in relative
2180                         // names
2181                         os << '.';
2182                         p.skip_spaces();
2183                 } else if (t.cs() == "space") {
2184                         os << ' ';
2185                         p.skip_spaces();
2186                 } else if (t.cs() == "string") {
2187                         // Convert \string" to " and \string~ to ~
2188                         Token const & n = p.next_token();
2189                         if (n.asInput() != "\"" && n.asInput() != "~")
2190                                 os << t.asInput();
2191                 } else
2192                         os << t.asInput();
2193         }
2194         // Strip quotes. This is a bit complicated (see latex_path()).
2195         string full = os.str();
2196         if (!full.empty() && full[0] == '"') {
2197                 string base = removeExtension(full);
2198                 string ext = getExtension(full);
2199                 if (!base.empty() && base[base.length()-1] == '"')
2200                         // "a b"
2201                         // "a b".tex
2202                         return addExtension(trim(base, "\""), ext);
2203                 if (full[full.length()-1] == '"')
2204                         // "a b.c"
2205                         // "a b.c".tex
2206                         return trim(full, "\"");
2207         }
2208         return full;
2209 }
2210
2211
2212 /// Convert \p name from TeX convention (relative to master file) to LyX
2213 /// convention (relative to .lyx file) if it is relative
2214 void fix_child_filename(string & name)
2215 {
2216         string const absMasterTeX = getMasterFilePath(true);
2217         bool const isabs = FileName::isAbsolute(name);
2218         // convert from "relative to .tex master" to absolute original path
2219         if (!isabs)
2220                 name = makeAbsPath(name, absMasterTeX).absFileName();
2221         bool copyfile = copyFiles();
2222         string const absParentLyX = getParentFilePath(false);
2223         string abs = name;
2224         if (copyfile) {
2225                 // convert from absolute original path to "relative to master file"
2226                 string const rel = to_utf8(makeRelPath(from_utf8(name),
2227                                                        from_utf8(absMasterTeX)));
2228                 // re-interpret "relative to .tex file" as "relative to .lyx file"
2229                 // (is different if the master .lyx file resides in a
2230                 // different path than the master .tex file)
2231                 string const absMasterLyX = getMasterFilePath(false);
2232                 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2233                 // Do not copy if the new path is impossible to create. Example:
2234                 // absMasterTeX = "/foo/bar/"
2235                 // absMasterLyX = "/bar/"
2236                 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2237                 if (contains(name, "/../"))
2238                         copyfile = false;
2239         }
2240         if (copyfile) {
2241                 if (isabs)
2242                         name = abs;
2243                 else {
2244                         // convert from absolute original path to
2245                         // "relative to .lyx file"
2246                         name = to_utf8(makeRelPath(from_utf8(abs),
2247                                                    from_utf8(absParentLyX)));
2248                 }
2249         }
2250         else if (!isabs) {
2251                 // convert from absolute original path to "relative to .lyx file"
2252                 name = to_utf8(makeRelPath(from_utf8(name),
2253                                            from_utf8(absParentLyX)));
2254         }
2255 }
2256
2257
2258 void copy_file(FileName const & src, string dstname)
2259 {
2260         if (!copyFiles())
2261                 return;
2262         string const absParent = getParentFilePath(false);
2263         FileName dst;
2264         if (FileName::isAbsolute(dstname))
2265                 dst = FileName(dstname);
2266         else
2267                 dst = makeAbsPath(dstname, absParent);
2268         FileName const srcpath = src.onlyPath();
2269         FileName const dstpath = dst.onlyPath();
2270         if (equivalent(srcpath, dstpath))
2271                 return;
2272         if (!dstpath.isDirectory()) {
2273                 if (!dstpath.createPath()) {
2274                         cerr << "Warning: Could not create directory for file `"
2275                              << dst.absFileName() << "´." << endl;
2276                         return;
2277                 }
2278         }
2279         if (dst.isReadableFile()) {
2280                 if (overwriteFiles())
2281                         cerr << "Warning: Overwriting existing file `"
2282                              << dst.absFileName() << "´." << endl;
2283                 else {
2284                         cerr << "Warning: Not overwriting existing file `"
2285                              << dst.absFileName() << "´." << endl;
2286                         return;
2287                 }
2288         }
2289         if (!src.copyTo(dst))
2290                 cerr << "Warning: Could not copy file `" << src.absFileName()
2291                      << "´ to `" << dst.absFileName() << "´." << endl;
2292 }
2293
2294
2295 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2296 bool parse_chunk(Parser & p, ostream & os, Context & context)
2297 {
2298         // check whether a chunk is possible here.
2299         if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2300                 return false;
2301         }
2302
2303         p.pushPosition();
2304
2305         // read the parameters
2306         Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2307         if (!params.first) {
2308                 p.popPosition();
2309                 return false;
2310         }
2311
2312         Parser::Arg const code = p.verbatimStuff("\n@");
2313         if (!code.first) {
2314                 p.popPosition();
2315                 return false;
2316         }
2317         string const post_chunk = p.verbatimStuff("\n").second + '\n';
2318         if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2319                 p.popPosition();
2320                 return false;
2321         }
2322         // The last newline read is important for paragraph handling
2323         p.putback();
2324         p.deparse();
2325
2326         //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2327         // We must have a valid layout before outputting the Chunk inset.
2328         context.check_layout(os);
2329         Context chunkcontext(true, context.textclass);
2330         chunkcontext.layout = &context.textclass.plainLayout();
2331         begin_inset(os, "Flex Chunk");
2332         os << "\nstatus open\n";
2333         if (!params.second.empty()) {
2334                 chunkcontext.check_layout(os);
2335                 Context paramscontext(true, context.textclass);
2336                 paramscontext.layout = &context.textclass.plainLayout();
2337                 begin_inset(os, "Argument 1");
2338                 os << "\nstatus open\n";
2339                 output_ert(os, params.second, paramscontext);
2340                 end_inset(os);
2341         }
2342         output_ert(os, code.second, chunkcontext);
2343         end_inset(os);
2344
2345         p.dropPosition();
2346         return true;
2347 }
2348
2349
2350 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2351 bool is_macro(Parser & p)
2352 {
2353         Token first = p.curr_token();
2354         if (first.cat() != catEscape || !p.good())
2355                 return false;
2356         if (first.cs() == "def")
2357                 return true;
2358         if (first.cs() != "global" && first.cs() != "long")
2359                 return false;
2360         Token second = p.get_token();
2361         int pos = 1;
2362         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2363                second.cat() == catNewline || second.cat() == catComment)) {
2364                 second = p.get_token();
2365                 pos++;
2366         }
2367         bool secondvalid = second.cat() == catEscape;
2368         Token third;
2369         bool thirdvalid = false;
2370         if (p.good() && first.cs() == "global" && secondvalid &&
2371             second.cs() == "long") {
2372                 third = p.get_token();
2373                 pos++;
2374                 while (p.good() && !p.isParagraph() &&
2375                        (third.cat() == catSpace ||
2376                         third.cat() == catNewline ||
2377                         third.cat() == catComment)) {
2378                         third = p.get_token();
2379                         pos++;
2380                 }
2381                 thirdvalid = third.cat() == catEscape;
2382         }
2383         for (int i = 0; i < pos; ++i)
2384                 p.putback();
2385         if (!secondvalid)
2386                 return false;
2387         if (!thirdvalid)
2388                 return (first.cs() == "global" || first.cs() == "long") &&
2389                        second.cs() == "def";
2390         return first.cs() == "global" && second.cs() == "long" &&
2391                third.cs() == "def";
2392 }
2393
2394
2395 /// Parse a macro definition (assumes that is_macro() returned true)
2396 void parse_macro(Parser & p, ostream & os, Context & context)
2397 {
2398         context.check_layout(os);
2399         Token first = p.curr_token();
2400         Token second;
2401         Token third;
2402         string command = first.asInput();
2403         if (first.cs() != "def") {
2404                 p.get_token();
2405                 eat_whitespace(p, os, context, false);
2406                 second = p.curr_token();
2407                 command += second.asInput();
2408                 if (second.cs() != "def") {
2409                         p.get_token();
2410                         eat_whitespace(p, os, context, false);
2411                         third = p.curr_token();
2412                         command += third.asInput();
2413                 }
2414         }
2415         eat_whitespace(p, os, context, false);
2416         string const name = p.get_token().cs();
2417         eat_whitespace(p, os, context, false);
2418
2419         // parameter text
2420         bool simple = true;
2421         string paramtext;
2422         int arity = 0;
2423         while (p.next_token().cat() != catBegin) {
2424                 if (p.next_token().cat() == catParameter) {
2425                         // # found
2426                         p.get_token();
2427                         paramtext += "#";
2428
2429                         // followed by number?
2430                         if (p.next_token().cat() == catOther) {
2431                                 string s = p.get_token().asInput();
2432                                 paramtext += s;
2433                                 // number = current arity + 1?
2434                                 if (s.size() == 1 && s[0] == arity + '0' + 1)
2435                                         ++arity;
2436                                 else
2437                                         simple = false;
2438                         } else
2439                                 paramtext += p.get_token().cs();
2440                 } else {
2441                         paramtext += p.get_token().cs();
2442                         simple = false;
2443                 }
2444         }
2445
2446         // only output simple (i.e. compatible) macro as FormulaMacros
2447         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2448         if (simple) {
2449                 context.check_layout(os);
2450                 begin_inset(os, "FormulaMacro");
2451                 os << "\n\\def" << ert;
2452                 end_inset(os);
2453         } else
2454                 output_ert_inset(os, command + ert, context);
2455 }
2456
2457
2458 void registerExternalTemplatePackages(string const & name)
2459 {
2460         external::TemplateManager const & etm = external::TemplateManager::get();
2461         external::Template const * const et = etm.getTemplateByName(name);
2462         if (!et)
2463                 return;
2464         external::Template::Formats::const_iterator cit = et->formats.end();
2465         if (pdflatex)
2466                 cit = et->formats.find("PDFLaTeX");
2467         if (cit == et->formats.end())
2468                 // If the template has not specified a PDFLaTeX output,
2469                 // we try the LaTeX format.
2470                 cit = et->formats.find("LaTeX");
2471         if (cit == et->formats.end())
2472                 return;
2473         vector<string>::const_iterator qit = cit->second.requirements.begin();
2474         vector<string>::const_iterator qend = cit->second.requirements.end();
2475         for (; qit != qend; ++qit)
2476                 preamble.registerAutomaticallyLoadedPackage(*qit);
2477 }
2478
2479 } // anonymous namespace
2480
2481
2482 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2483                 Context & context)
2484 {
2485         Layout const * newlayout = 0;
2486         InsetLayout const * newinsetlayout = 0;
2487         char const * const * where = 0;
2488         // Store the latest bibliographystyle, addcontentslineContent and
2489         // nocite{*} option (needed for bibtex inset)
2490         string btprint;
2491         string contentslineContent;
2492         // Some classes provide a \bibliographystyle, so do not output
2493         // any if none is explicitly set.
2494         string bibliographystyle;
2495         bool const use_natbib = isProvided("natbib");
2496         bool const use_jurabib = isProvided("jurabib");
2497         bool const use_biblatex = isProvided("biblatex")
2498                         && preamble.citeEngine() != "biblatex-natbib";
2499         bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2500                         || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2501         need_commentbib = use_biblatex || use_biblatex_natbib;
2502         string last_env;
2503
2504         // it is impossible to determine the correct encoding for non-CJK Japanese.
2505         // Therefore write a note at the beginning of the document
2506         if (is_nonCJKJapanese) {
2507                 context.check_layout(os);
2508                 begin_inset(os, "Note Note\n");
2509                 os << "status open\n\\begin_layout Plain Layout\n"
2510                    << "\\series bold\n"
2511                    << "Important information:\n"
2512                    << "\\end_layout\n\n"
2513                    << "\\begin_layout Plain Layout\n"
2514                    << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2515                    << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2516                    << " The iconv encoding " << p.getEncoding() << " was used.\n"
2517                    << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2518                    << " and specify the encoding using the -e command-line switch.\n"
2519                    << " In addition, you might want to double check that the desired output encoding\n"
2520                    << " is correctly selected in Document > Settings > Language.\n"
2521                    << "\\end_layout\n";
2522                 end_inset(os);
2523                 is_nonCJKJapanese = false;
2524         }
2525
2526         while (p.good()) {
2527                 Token const & t = p.get_token();
2528 #ifdef FILEDEBUG
2529                 debugToken(cerr, t, flags);
2530 #endif
2531
2532                 if (flags & FLAG_ITEM) {
2533                         if (t.cat() == catSpace)
2534                                 continue;
2535
2536                         flags &= ~FLAG_ITEM;
2537                         if (t.cat() == catBegin) {
2538                                 // skip the brace and collect everything to the next matching
2539                                 // closing brace
2540                                 flags |= FLAG_BRACE_LAST;
2541                                 continue;
2542                         }
2543
2544                         // handle only this single token, leave the loop if done
2545                         flags |= FLAG_LEAVE;
2546                 }
2547
2548                 if (t.cat() != catEscape && t.character() == ']' &&
2549                     (flags & FLAG_BRACK_LAST))
2550                         return;
2551                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2552                         return;
2553
2554                 // If there is anything between \end{env} and \begin{env} we
2555                 // don't need to output a separator.
2556                 if (t.cat() != catSpace && t.cat() != catNewline &&
2557                     t.asInput() != "\\begin")
2558                         last_env = "";
2559
2560                 //
2561                 // cat codes
2562                 //
2563                 bool const starred = p.next_token().asInput() == "*";
2564                 string const starredname(starred ? (t.cs() + '*') : t.cs());
2565                 if (t.cat() == catMath) {
2566                         // we are inside some text mode thingy, so opening new math is allowed
2567                         context.check_layout(os);
2568                         begin_inset(os, "Formula ");
2569                         Token const & n = p.get_token();
2570                         bool const display(n.cat() == catMath && outer);
2571                         if (display) {
2572                                 // TeX's $$...$$ syntax for displayed math
2573                                 os << "\\[";
2574                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2575                                 os << "\\]";
2576                                 p.get_token(); // skip the second '$' token
2577                         } else {
2578                                 // simple $...$  stuff
2579                                 p.putback();
2580                                 os << '$';
2581                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2582                                 os << '$';
2583                         }
2584                         end_inset(os);
2585                         if (display) {
2586                                 // Prevent the conversion of a line break to a
2587                                 // space (bug 7668). This does not change the
2588                                 // output, but looks ugly in LyX.
2589                                 eat_whitespace(p, os, context, false);
2590                         }
2591                 }
2592
2593                 else if (t.cat() == catSuper || t.cat() == catSub)
2594                         cerr << "catcode " << t << " illegal in text mode\n";
2595
2596                 // Basic support for english quotes. This should be
2597                 // extended to other quotes, but is not so easy (a
2598                 // left english quote is the same as a right german
2599                 // quote...)
2600                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2601                         context.check_layout(os);
2602                         begin_inset(os, "Quotes ");
2603                         os << "eld";
2604                         end_inset(os);
2605                         p.get_token();
2606                         skip_braces(p);
2607                 }
2608                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2609                         context.check_layout(os);
2610                         begin_inset(os, "Quotes ");
2611                         os << "erd";
2612                         end_inset(os);
2613                         p.get_token();
2614                         skip_braces(p);
2615                 }
2616
2617                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2618                         context.check_layout(os);
2619                         begin_inset(os, "Quotes ");
2620                         os << "ald";
2621                         end_inset(os);
2622                         p.get_token();
2623                         skip_braces(p);
2624                 }
2625
2626                 else if (t.asInput() == "<"
2627                          && p.next_token().asInput() == "<") {
2628                         bool has_chunk = false;
2629                         if (noweb_mode) {
2630                                 p.pushPosition();
2631                                 p.get_token();
2632                                 has_chunk = parse_chunk(p, os, context);
2633                                 if (!has_chunk)
2634                                         p.popPosition();
2635                         }
2636
2637                         if (!has_chunk) {
2638                                 context.check_layout(os);
2639                                 begin_inset(os, "Quotes ");
2640                                 //FIXME: this is a right danish quote;
2641                                 // why not a left french quote?
2642                                 os << "ard";
2643                                 end_inset(os);
2644                                 p.get_token();
2645                                 skip_braces(p);
2646                         }
2647                 }
2648
2649                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2650                         check_space(p, os, context);
2651
2652                 // babel shorthands (also used by polyglossia)
2653                 // Since these can have different meanings for different languages
2654                 // we import them as ERT (but they must be put in ERT to get output
2655                 // verbatim).
2656                 else if (t.asInput() == "\"") {
2657                         string s = "\"";
2658                         // These are known pairs. We put them together in
2659                         // one ERT inset. In other cases (such as "a), only
2660                         // the quotation mark is ERTed.
2661                         if (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                             || p.next_token().asInput() == "/"
2667                             || p.next_token().asInput() == "~"
2668                             || p.next_token().asInput() == "'"
2669                             || p.next_token().asInput() == "`"
2670                             || p.next_token().asInput() == "<"
2671                             || p.next_token().asInput() == ">") {
2672                                 s += p.next_token().asInput();
2673                                 p.get_token();
2674                         }
2675                         output_ert_inset(os, s, context);
2676                 }
2677
2678                 else if (t.character() == '[' && noweb_mode &&
2679                          p.next_token().character() == '[') {
2680                         // These can contain underscores
2681                         p.putback();
2682                         string const s = p.getFullOpt() + ']';
2683                         if (p.next_token().character() == ']')
2684                                 p.get_token();
2685                         else
2686                                 cerr << "Warning: Inserting missing ']' in '"
2687                                      << s << "'." << endl;
2688                         output_ert_inset(os, s, context);
2689                 }
2690
2691                 else if (t.cat() == catLetter) {
2692                         context.check_layout(os);
2693                         os << t.cs();
2694                 }
2695
2696                 else if (t.cat() == catOther ||
2697                                t.cat() == catAlign ||
2698                                t.cat() == catParameter) {
2699                         context.check_layout(os);
2700                         if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2701                             context.merging_hyphens_allowed &&
2702                             context.font.family != "ttfamily" &&
2703                             !context.layout->pass_thru) {
2704                                 if (p.next_next_token().asInput() == "-") {
2705                                         // --- is emdash
2706                                         os << to_utf8(docstring(1, 0x2014));
2707                                         p.get_token();
2708                                 } else
2709                                         // -- is endash
2710                                         os << to_utf8(docstring(1, 0x2013));
2711                                 p.get_token();
2712                         } else
2713                                 // This translates "&" to "\\&" which may be wrong...
2714                                 os << t.cs();
2715                 }
2716
2717                 else if (p.isParagraph()) {
2718                         // In minted floating listings we will collect
2719                         // everything into the caption, where multiple
2720                         // paragraphs are forbidden.
2721                         if (minted_float.empty()) {
2722                                 if (context.new_layout_allowed)
2723                                         context.new_paragraph(os);
2724                                 else
2725                                         output_ert_inset(os, "\\par ", context);
2726                         } else
2727                                 os << ' ';
2728                         eat_whitespace(p, os, context, true);
2729                 }
2730
2731                 else if (t.cat() == catActive) {
2732                         context.check_layout(os);
2733                         if (t.character() == '~') {
2734                                 if (context.layout->free_spacing)
2735                                         os << ' ';
2736                                 else {
2737                                         begin_inset(os, "space ~\n");
2738                                         end_inset(os);
2739                                 }
2740                         } else
2741                                 os << t.cs();
2742                 }
2743
2744                 else if (t.cat() == catBegin) {
2745                         Token const next = p.next_token();
2746                         Token const end = p.next_next_token();
2747                         if (next.cat() == catEnd) {
2748                                 // {}
2749                                 Token const prev = p.prev_token();
2750                                 p.get_token();
2751                                 if (p.next_token().character() == '`')
2752                                         ; // ignore it in {}``
2753                                 else
2754                                         output_ert_inset(os, "{}", context);
2755                         } else if (next.cat() == catEscape &&
2756                                    is_known(next.cs(), known_quotes) &&
2757                                    end.cat() == catEnd) {
2758                                 // Something like {\textquoteright} (e.g.
2759                                 // from writer2latex). LyX writes
2760                                 // \textquoteright{}, so we may skip the
2761                                 // braces here for better readability.
2762                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2763                                                    outer, context);
2764                         } else if (p.next_token().asInput() == "\\ascii") {
2765                                 // handle the \ascii characters
2766                                 // (the case without braces is handled later)
2767                                 // the code is "{\ascii\xxx}"
2768                                 p.get_token(); // eat \ascii
2769                                 string name2 = p.get_token().asInput();
2770                                 p.get_token(); // eat the final '}'
2771                                 string const name = "{\\ascii" + name2 + "}";
2772                                 bool termination;
2773                                 docstring rem;
2774                                 set<string> req;
2775                                 // get the character from unicodesymbols
2776                                 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2777                                         Encodings::TEXT_CMD, termination, rem, &req);
2778                                 if (!s.empty()) {
2779                                         context.check_layout(os);
2780                                         os << to_utf8(s);
2781                                         if (!rem.empty())
2782                                                 output_ert_inset(os,
2783                                                         to_utf8(rem), context);
2784                                         for (set<string>::const_iterator it = req.begin();
2785                                              it != req.end(); ++it)
2786                                                 preamble.registerAutomaticallyLoadedPackage(*it);
2787                                 } else
2788                                         // we did not find a non-ert version
2789                                         output_ert_inset(os, name, context);
2790                         } else {
2791                         context.check_layout(os);
2792                         // special handling of font attribute changes
2793                         Token const prev = p.prev_token();
2794                         TeXFont const oldFont = context.font;
2795                         if (next.character() == '[' ||
2796                             next.character() == ']' ||
2797                             next.character() == '*') {
2798                                 p.get_token();
2799                                 if (p.next_token().cat() == catEnd) {
2800                                         os << next.cs();
2801                                         p.get_token();
2802                                 } else {
2803                                         p.putback();
2804                                         output_ert_inset(os, "{", context);
2805                                         parse_text_snippet(p, os,
2806                                                         FLAG_BRACE_LAST,
2807                                                         outer, context);
2808                                         output_ert_inset(os, "}", context);
2809                                 }
2810                         } else if (! context.new_layout_allowed) {
2811                                 output_ert_inset(os, "{", context);
2812                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2813                                                    outer, context);
2814                                 output_ert_inset(os, "}", context);
2815                         } else if (is_known(next.cs(), known_sizes)) {
2816                                 // next will change the size, so we must
2817                                 // reset it here
2818                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2819                                                    outer, context);
2820                                 if (!context.atParagraphStart())
2821                                         os << "\n\\size "
2822                                            << context.font.size << "\n";
2823                         } else if (is_known(next.cs(), known_font_families)) {
2824                                 // next will change the font family, so we
2825                                 // must reset it here
2826                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2827                                                    outer, context);
2828                                 if (!context.atParagraphStart())
2829                                         os << "\n\\family "
2830                                            << context.font.family << "\n";
2831                         } else if (is_known(next.cs(), known_font_series)) {
2832                                 // next will change the font series, so we
2833                                 // must reset it here
2834                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2835                                                    outer, context);
2836                                 if (!context.atParagraphStart())
2837                                         os << "\n\\series "
2838                                            << context.font.series << "\n";
2839                         } else if (is_known(next.cs(), known_font_shapes)) {
2840                                 // next will change the font shape, so we
2841                                 // must reset it here
2842                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2843                                                    outer, context);
2844                                 if (!context.atParagraphStart())
2845                                         os << "\n\\shape "
2846                                            << context.font.shape << "\n";
2847                         } else if (is_known(next.cs(), known_old_font_families) ||
2848                                    is_known(next.cs(), known_old_font_series) ||
2849                                    is_known(next.cs(), known_old_font_shapes)) {
2850                                 // next will change the font family, series
2851                                 // and shape, so we must reset it here
2852                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2853                                                    outer, context);
2854                                 if (!context.atParagraphStart())
2855                                         os <<  "\n\\family "
2856                                            << context.font.family
2857                                            << "\n\\series "
2858                                            << context.font.series
2859                                            << "\n\\shape "
2860                                            << context.font.shape << "\n";
2861                         } else {
2862                                 output_ert_inset(os, "{", context);
2863                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2864                                                    outer, context);
2865                                 output_ert_inset(os, "}", context);
2866                                 }
2867                         }
2868                 }
2869
2870                 else if (t.cat() == catEnd) {
2871                         if (flags & FLAG_BRACE_LAST) {
2872                                 return;
2873                         }
2874                         cerr << "stray '}' in text\n";
2875                         output_ert_inset(os, "}", context);
2876                 }
2877
2878                 else if (t.cat() == catComment)
2879                         parse_comment(p, os, t, context);
2880
2881                 //
2882                 // control sequences
2883                 //
2884
2885                 else if (t.cs() == "(" || t.cs() == "[") {
2886                         bool const simple = t.cs() == "(";
2887                         context.check_layout(os);
2888                         begin_inset(os, "Formula");
2889                         os << " \\" << t.cs();
2890                         parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2891                         os << '\\' << (simple ? ')' : ']');
2892                         end_inset(os);
2893                         if (!simple) {
2894                                 // Prevent the conversion of a line break to a
2895                                 // space (bug 7668). This does not change the
2896                                 // output, but looks ugly in LyX.
2897                                 eat_whitespace(p, os, context, false);
2898                         }
2899                 }
2900
2901                 else if (t.cs() == "begin")
2902                         parse_environment(p, os, outer, last_env,
2903                                           context);
2904
2905                 else if (t.cs() == "end") {
2906                         if (flags & FLAG_END) {
2907                                 // eat environment name
2908                                 string const name = p.getArg('{', '}');
2909                                 if (name != active_environment())
2910                                         cerr << "\\end{" + name + "} does not match \\begin{"
2911                                                 + active_environment() + "}\n";
2912                                 return;
2913                         }
2914                         p.error("found 'end' unexpectedly");
2915                 }
2916
2917                 else if (t.cs() == "item") {
2918                         string s;
2919                         bool const optarg = p.hasOpt();
2920                         if (optarg) {
2921                                 // FIXME: This swallows comments, but we cannot use
2922                                 //        eat_whitespace() since we must not output
2923                                 //        anything before the item.
2924                                 p.skip_spaces(true);
2925                                 s = p.verbatimOption();
2926                         } else
2927                                 p.skip_spaces(false);
2928                         context.set_item();
2929                         context.check_layout(os);
2930                         if (context.has_item) {
2931                                 // An item in an unknown list-like environment
2932                                 // FIXME: Do this in check_layout()!
2933                                 context.has_item = false;
2934                                 if (optarg)
2935                                         output_ert_inset(os, "\\item", context);
2936                                 else
2937                                         output_ert_inset(os, "\\item ", context);
2938                         }
2939                         if (optarg) {
2940                                 if (context.layout->labeltype != LABEL_MANUAL) {
2941                                         // handle option of itemize item
2942                                         begin_inset(os, "Argument item:1\n");
2943                                         os << "status open\n";
2944                                         os << "\n\\begin_layout Plain Layout\n";
2945                                         Parser p2(s + ']');
2946                                         os << parse_text_snippet(p2,
2947                                                 FLAG_BRACK_LAST, outer, context);
2948                                         // we must not use context.check_end_layout(os)
2949                                         // because that would close the outer itemize layout
2950                                         os << "\n\\end_layout\n";
2951                                         end_inset(os);
2952                                         eat_whitespace(p, os, context, false);
2953                                 } else if (!s.empty()) {
2954                                         // LyX adds braces around the argument,
2955                                         // so we need to remove them here.
2956                                         if (s.size() > 2 && s[0] == '{' &&
2957                                             s[s.size()-1] == '}')
2958                                                 s = s.substr(1, s.size()-2);
2959                                         // If the argument contains a space we
2960                                         // must put it into ERT: Otherwise LyX
2961                                         // would misinterpret the space as
2962                                         // item delimiter (bug 7663)
2963                                         if (contains(s, ' ')) {
2964                                                 output_ert_inset(os, s, context);
2965                                         } else {
2966                                                 Parser p2(s + ']');
2967                                                 os << parse_text_snippet(p2,
2968                                                         FLAG_BRACK_LAST, outer, context);
2969                                         }
2970                                         // The space is needed to separate the
2971                                         // item from the rest of the sentence.
2972                                         os << ' ';
2973                                         eat_whitespace(p, os, context, false);
2974                                 }
2975                         }
2976                 }
2977
2978                 else if (t.cs() == "bibitem") {
2979                         context.set_item();
2980                         context.check_layout(os);
2981                         eat_whitespace(p, os, context, false);
2982                         string label = convert_command_inset_arg(p.verbatimOption());
2983                         string key = convert_command_inset_arg(p.verbatim_item());
2984                         if (contains(label, '\\') || contains(key, '\\')) {
2985                                 // LyX can't handle LaTeX commands in labels or keys
2986                                 output_ert_inset(os, t.asInput() + '[' + label +
2987                                                "]{" + p.verbatim_item() + '}',
2988                                            context);
2989                         } else {
2990                                 begin_command_inset(os, "bibitem", "bibitem");
2991                                 os << "label \"" << label << "\"\n"
2992                                    << "key \"" << key << "\"\n"
2993                                    << "literal \"true\"\n";
2994                                 end_inset(os);
2995                         }
2996                 }
2997
2998                 else if (is_macro(p)) {
2999                         // catch the case of \def\inputGnumericTable
3000                         bool macro = true;
3001                         if (t.cs() == "def") {
3002                                 Token second = p.next_token();
3003                                 if (second.cs() == "inputGnumericTable") {
3004                                         p.pushPosition();
3005                                         p.get_token();
3006                                         skip_braces(p);
3007                                         Token third = p.get_token();
3008                                         p.popPosition();
3009                                         if (third.cs() == "input") {
3010                                                 p.get_token();
3011                                                 skip_braces(p);
3012                                                 p.get_token();
3013                                                 string name = normalize_filename(p.verbatim_item());
3014                                                 string const path = getMasterFilePath(true);
3015                                                 // We want to preserve relative / absolute filenames,
3016                                                 // therefore path is only used for testing
3017                                                 // The file extension is in every case ".tex".
3018                                                 // So we need to remove this extension and check for
3019                                                 // the original one.
3020                                                 name = removeExtension(name);
3021                                                 if (!makeAbsPath(name, path).exists()) {
3022                                                         char const * const Gnumeric_formats[] = {"gnumeric",
3023                                                                 "ods", "xls", 0};
3024                                                         string const Gnumeric_name =
3025                                                                 find_file(name, path, Gnumeric_formats);
3026                                                         if (!Gnumeric_name.empty())
3027                                                                 name = Gnumeric_name;
3028                                                 }
3029                                                 FileName const absname = makeAbsPath(name, path);
3030                                                 if (absname.exists()) {
3031                                                         fix_child_filename(name);
3032                                                         copy_file(absname, name);
3033                                                 } else
3034                                                         cerr << "Warning: Could not find file '"
3035                                                              << name << "'." << endl;
3036                                                 context.check_layout(os);
3037                                                 begin_inset(os, "External\n\ttemplate ");
3038                                                 os << "GnumericSpreadsheet\n\tfilename "
3039                                                    << name << "\n";
3040                                                 end_inset(os);
3041                                                 context.check_layout(os);
3042                                                 macro = false;
3043                                                 // register the packages that are automatically loaded
3044                                                 // by the Gnumeric template
3045                                                 registerExternalTemplatePackages("GnumericSpreadsheet");
3046                                         }
3047                                 }
3048                         }
3049                         if (macro)
3050                                 parse_macro(p, os, context);
3051                 }
3052
3053                 else if (t.cs() == "noindent") {
3054                         p.skip_spaces();
3055                         context.add_par_extra_stuff("\\noindent\n");
3056                 }
3057
3058                 else if (t.cs() == "appendix") {
3059                         context.add_par_extra_stuff("\\start_of_appendix\n");
3060                         // We need to start a new paragraph. Otherwise the
3061                         // appendix in 'bla\appendix\chapter{' would start
3062                         // too late.
3063                         context.new_paragraph(os);
3064                         // We need to make sure that the paragraph is
3065                         // generated even if it is empty. Otherwise the
3066                         // appendix in '\par\appendix\par\chapter{' would
3067                         // start too late.
3068                         context.check_layout(os);
3069                         // FIXME: This is a hack to prevent paragraph
3070                         // deletion if it is empty. Handle this better!
3071                         output_comment(p, os,
3072                                 "dummy comment inserted by tex2lyx to "
3073                                 "ensure that this paragraph is not empty",
3074                                 context);
3075                         // Both measures above may generate an additional
3076                         // empty paragraph, but that does not hurt, because
3077                         // whitespace does not matter here.
3078                         eat_whitespace(p, os, context, true);
3079                 }
3080
3081                 // Must catch empty dates before findLayout is called below
3082                 else if (t.cs() == "date") {
3083                         eat_whitespace(p, os, context, false);
3084                         p.pushPosition();
3085                         string const date = p.verbatim_item();
3086                         p.popPosition();
3087                         if (date.empty()) {
3088                                 preamble.suppressDate(true);
3089                                 p.verbatim_item();
3090                         } else {
3091                                 preamble.suppressDate(false);
3092                                 if (context.new_layout_allowed &&
3093                                     (newlayout = findLayout(context.textclass,
3094                                                             t.cs(), true))) {
3095                                         // write the layout
3096                                         output_command_layout(os, p, outer,
3097                                                         context, newlayout);
3098                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3099                                         if (!preamble.titleLayoutFound())
3100                                                 preamble.titleLayoutFound(newlayout->intitle);
3101                                         set<string> const & req = newlayout->requires();
3102                                         set<string>::const_iterator it = req.begin();
3103                                         set<string>::const_iterator en = req.end();
3104                                         for (; it != en; ++it)
3105                                                 preamble.registerAutomaticallyLoadedPackage(*it);
3106                                 } else
3107                                         output_ert_inset(os,
3108                                                 "\\date{" + p.verbatim_item() + '}',
3109                                                 context);
3110                         }
3111                 }
3112
3113                 // Starred section headings
3114                 // Must attempt to parse "Section*" before "Section".
3115                 else if ((p.next_token().asInput() == "*") &&
3116                          context.new_layout_allowed &&
3117                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3118                         // write the layout
3119                         p.get_token();
3120                         output_command_layout(os, p, outer, context, newlayout);
3121                         p.skip_spaces();
3122                         if (!preamble.titleLayoutFound())
3123                                 preamble.titleLayoutFound(newlayout->intitle);
3124                         set<string> const & req = newlayout->requires();
3125                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3126                                 preamble.registerAutomaticallyLoadedPackage(*it);
3127                 }
3128
3129                 // Section headings and the like
3130                 else if (context.new_layout_allowed &&
3131                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
3132                         // write the layout
3133                         output_command_layout(os, p, outer, context, newlayout);
3134                         p.skip_spaces();
3135                         if (!preamble.titleLayoutFound())
3136                                 preamble.titleLayoutFound(newlayout->intitle);
3137                         set<string> const & req = newlayout->requires();
3138                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3139                                 preamble.registerAutomaticallyLoadedPackage(*it);
3140                 }
3141
3142                 else if (t.cs() == "subfloat") {
3143                         // the syntax is \subfloat[list entry][sub caption]{content}
3144                         // if it is a table of figure depends on the surrounding float
3145                         // FIXME: second optional argument is not parsed
3146                         p.skip_spaces();
3147                         // do nothing if there is no outer float
3148                         if (!float_type.empty()) {
3149                                 context.check_layout(os);
3150                                 p.skip_spaces();
3151                                 begin_inset(os, "Float " + float_type + "\n");
3152                                 os << "wide false"
3153                                    << "\nsideways false"
3154                                    << "\nstatus collapsed\n\n";
3155                                 // test for caption
3156                                 string caption;
3157                                 bool has_caption = false;
3158                                 if (p.next_token().cat() != catEscape &&
3159                                                 p.next_token().character() == '[') {
3160                                                         p.get_token(); // eat '['
3161                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3162                                                         has_caption = true;
3163                                 }
3164                                 // the content
3165                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3166                                 // the caption comes always as the last
3167                                 if (has_caption) {
3168                                         // we must make sure that the caption gets a \begin_layout
3169                                         os << "\n\\begin_layout Plain Layout";
3170                                         p.skip_spaces();
3171                                         begin_inset(os, "Caption Standard\n");
3172                                         Context newcontext(true, context.textclass,
3173                                                            0, 0, context.font);
3174                                         newcontext.check_layout(os);
3175                                         os << caption << "\n";
3176                                         newcontext.check_end_layout(os);
3177                                         // We don't need really a new paragraph, but
3178                                         // we must make sure that the next item gets a \begin_layout.
3179                                         //newcontext.new_paragraph(os);
3180                                         end_inset(os);
3181                                         p.skip_spaces();
3182                                 }
3183                                 // We don't need really a new paragraph, but
3184                                 // we must make sure that the next item gets a \begin_layout.
3185                                 if (has_caption)
3186                                         context.new_paragraph(os);
3187                                 end_inset(os);
3188                                 p.skip_spaces();
3189                                 context.check_end_layout(os);
3190                                 // close the layout we opened
3191                                 if (has_caption)
3192                                         os << "\n\\end_layout\n";
3193                         } else {
3194                                 // if the float type is not supported or there is no surrounding float
3195                                 // output it as ERT
3196                                 if (p.hasOpt()) {
3197                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
3198                                         output_ert_inset(os, t.asInput() + '[' + opt_arg +
3199                                                "]{" + p.verbatim_item() + '}', context);
3200                                 } else
3201                                         output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
3202                         }
3203                 }
3204
3205                 else if (t.cs() == "includegraphics") {
3206                         bool const clip = p.next_token().asInput() == "*";
3207                         if (clip)
3208                                 p.get_token();
3209                         string const arg = p.getArg('[', ']');
3210                         map<string, string> opts;
3211                         vector<string> keys;
3212                         split_map(arg, opts, keys);
3213                         if (clip)
3214                                 opts["clip"] = string();
3215                         string name = normalize_filename(p.verbatim_item());
3216
3217                         string const path = getMasterFilePath(true);
3218                         // We want to preserve relative / absolute filenames,
3219                         // therefore path is only used for testing
3220                         if (!makeAbsPath(name, path).exists()) {
3221                                 // The file extension is probably missing.
3222                                 // Now try to find it out.
3223                                 string const dvips_name =
3224                                         find_file(name, path,
3225                                                   known_dvips_graphics_formats);
3226                                 string const pdftex_name =
3227                                         find_file(name, path,
3228                                                   known_pdftex_graphics_formats);
3229                                 if (!dvips_name.empty()) {
3230                                         if (!pdftex_name.empty()) {
3231                                                 cerr << "This file contains the "
3232                                                         "latex snippet\n"
3233                                                         "\"\\includegraphics{"
3234                                                      << name << "}\".\n"
3235                                                         "However, files\n\""
3236                                                      << dvips_name << "\" and\n\""
3237                                                      << pdftex_name << "\"\n"
3238                                                         "both exist, so I had to make a "
3239                                                         "choice and took the first one.\n"
3240                                                         "Please move the unwanted one "
3241                                                         "someplace else and try again\n"
3242                                                         "if my choice was wrong."
3243                                                      << endl;
3244                                         }
3245                                         name = dvips_name;
3246                                 } else if (!pdftex_name.empty()) {
3247                                         name = pdftex_name;
3248                                         pdflatex = true;
3249                                 }
3250                         }
3251
3252                         FileName const absname = makeAbsPath(name, path);
3253                         if (absname.exists()) {
3254                                 fix_child_filename(name);
3255                                 copy_file(absname, name);
3256                         } else
3257                                 cerr << "Warning: Could not find graphics file '"
3258                                      << name << "'." << endl;
3259
3260                         context.check_layout(os);
3261                         begin_inset(os, "Graphics ");
3262                         os << "\n\tfilename " << name << '\n';
3263                         if (opts.find("width") != opts.end())
3264                                 os << "\twidth "
3265                                    << translate_len(opts["width"]) << '\n';
3266                         if (opts.find("height") != opts.end())
3267                                 os << "\theight "
3268                                    << translate_len(opts["height"]) << '\n';
3269                         if (opts.find("scale") != opts.end()) {
3270                                 istringstream iss(opts["scale"]);
3271                                 double val;
3272                                 iss >> val;
3273                                 val = val*100;
3274                                 os << "\tscale " << val << '\n';
3275                         }
3276                         if (opts.find("angle") != opts.end()) {
3277                                 os << "\trotateAngle "
3278                                    << opts["angle"] << '\n';
3279                                 vector<string>::const_iterator a =
3280                                         find(keys.begin(), keys.end(), "angle");
3281                                 vector<string>::const_iterator s =
3282                                         find(keys.begin(), keys.end(), "width");
3283                                 if (s == keys.end())
3284                                         s = find(keys.begin(), keys.end(), "height");
3285                                 if (s == keys.end())
3286                                         s = find(keys.begin(), keys.end(), "scale");
3287                                 if (s != keys.end() && distance(s, a) > 0)
3288                                         os << "\tscaleBeforeRotation\n";
3289                         }
3290                         if (opts.find("origin") != opts.end()) {
3291                                 ostringstream ss;
3292                                 string const opt = opts["origin"];
3293                                 if (opt.find('l') != string::npos) ss << "left";
3294                                 if (opt.find('r') != string::npos) ss << "right";
3295                                 if (opt.find('c') != string::npos) ss << "center";
3296                                 if (opt.find('t') != string::npos) ss << "Top";
3297                                 if (opt.find('b') != string::npos) ss << "Bottom";
3298                                 if (opt.find('B') != string::npos) ss << "Baseline";
3299                                 if (!ss.str().empty())
3300                                         os << "\trotateOrigin " << ss.str() << '\n';
3301                                 else
3302                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3303                         }
3304                         if (opts.find("keepaspectratio") != opts.end())
3305                                 os << "\tkeepAspectRatio\n";
3306                         if (opts.find("clip") != opts.end())
3307                                 os << "\tclip\n";
3308                         if (opts.find("draft") != opts.end())
3309                                 os << "\tdraft\n";
3310                         if (opts.find("bb") != opts.end())
3311                                 os << "\tBoundingBox "
3312                                    << opts["bb"] << '\n';
3313                         int numberOfbbOptions = 0;
3314                         if (opts.find("bbllx") != opts.end())
3315                                 numberOfbbOptions++;
3316                         if (opts.find("bblly") != opts.end())
3317                                 numberOfbbOptions++;
3318                         if (opts.find("bburx") != opts.end())
3319                                 numberOfbbOptions++;
3320                         if (opts.find("bbury") != opts.end())
3321                                 numberOfbbOptions++;
3322                         if (numberOfbbOptions == 4)
3323                                 os << "\tBoundingBox "
3324                                    << opts["bbllx"] << " " << opts["bblly"] << " "
3325                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
3326                         else if (numberOfbbOptions > 0)
3327                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3328                         numberOfbbOptions = 0;
3329                         if (opts.find("natwidth") != opts.end())
3330                                 numberOfbbOptions++;
3331                         if (opts.find("natheight") != opts.end())
3332                                 numberOfbbOptions++;
3333                         if (numberOfbbOptions == 2)
3334                                 os << "\tBoundingBox 0bp 0bp "
3335                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
3336                         else if (numberOfbbOptions > 0)
3337                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3338                         ostringstream special;
3339                         if (opts.find("hiresbb") != opts.end())
3340                                 special << "hiresbb,";
3341                         if (opts.find("trim") != opts.end())
3342                                 special << "trim,";
3343                         if (opts.find("viewport") != opts.end())
3344                                 special << "viewport=" << opts["viewport"] << ',';
3345                         if (opts.find("totalheight") != opts.end())
3346                                 special << "totalheight=" << opts["totalheight"] << ',';
3347                         if (opts.find("type") != opts.end())
3348                                 special << "type=" << opts["type"] << ',';
3349                         if (opts.find("ext") != opts.end())
3350                                 special << "ext=" << opts["ext"] << ',';
3351                         if (opts.find("read") != opts.end())
3352                                 special << "read=" << opts["read"] << ',';
3353                         if (opts.find("command") != opts.end())
3354                                 special << "command=" << opts["command"] << ',';
3355                         string s_special = special.str();
3356                         if (!s_special.empty()) {
3357                                 // We had special arguments. Remove the trailing ','.
3358                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3359                         }
3360                         // TODO: Handle the unknown settings better.
3361                         // Warn about invalid options.
3362                         // Check whether some option was given twice.
3363                         end_inset(os);
3364                         preamble.registerAutomaticallyLoadedPackage("graphicx");
3365                 }
3366
3367                 else if (t.cs() == "footnote" ||
3368                          (t.cs() == "thanks" && context.layout->intitle)) {
3369                         p.skip_spaces();
3370                         context.check_layout(os);
3371                         begin_inset(os, "Foot\n");
3372                         os << "status collapsed\n\n";
3373                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3374                         end_inset(os);
3375                 }
3376
3377                 else if (t.cs() == "marginpar") {
3378                         p.skip_spaces();
3379                         context.check_layout(os);
3380                         begin_inset(os, "Marginal\n");
3381                         os << "status collapsed\n\n";
3382                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3383                         end_inset(os);
3384                 }
3385
3386                 else if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3387                         bool const use_minted = t.cs() == "mintinline";
3388                         p.skip_spaces();
3389                         parse_listings(p, os, context, true, use_minted);
3390                 }
3391
3392                 else if (t.cs() == "ensuremath") {
3393                         p.skip_spaces();
3394                         context.check_layout(os);
3395                         string const s = p.verbatim_item();
3396                         //FIXME: this never triggers in UTF8
3397                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3398                                 os << s;
3399                         else
3400                                 output_ert_inset(os, "\\ensuremath{" + s + "}",
3401                                            context);
3402                 }
3403
3404                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3405                         if (preamble.titleLayoutFound()) {
3406                                 // swallow this
3407                                 skip_spaces_braces(p);
3408                         } else
3409                                 output_ert_inset(os, t.asInput(), context);
3410                 }
3411
3412                 else if (t.cs() == "tableofcontents"
3413                                 || t.cs() == "lstlistoflistings"
3414                                 || t.cs() == "listoflistings") {
3415                         string name = t.cs();
3416                         if (preamble.minted() && name == "listoflistings")
3417                                 name.insert(0, "lst");
3418                         context.check_layout(os);
3419                         begin_command_inset(os, "toc", name);
3420                         end_inset(os);
3421                         skip_spaces_braces(p);
3422                         if (name == "lstlistoflistings") {
3423                                 if (preamble.minted())
3424                                         preamble.registerAutomaticallyLoadedPackage("minted");
3425                                 else
3426                                         preamble.registerAutomaticallyLoadedPackage("listings");
3427                         }
3428                 }
3429
3430                 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3431                         context.check_layout(os);
3432                         if (t.cs() == "listoffigures")
3433                                 begin_inset(os, "FloatList figure\n");
3434                         else
3435                                 begin_inset(os, "FloatList table\n");
3436                         end_inset(os);
3437                         skip_spaces_braces(p);
3438                 }
3439
3440                 else if (t.cs() == "listof") {
3441                         p.skip_spaces(true);
3442                         string const name = p.get_token().cs();
3443                         if (context.textclass.floats().typeExist(name)) {
3444                                 context.check_layout(os);
3445                                 begin_inset(os, "FloatList ");
3446                                 os << name << "\n";
3447                                 end_inset(os);
3448                                 p.get_token(); // swallow second arg
3449                         } else
3450                                 output_ert_inset(os, "\\listof{" + name + "}", context);
3451                 }
3452
3453                 else if ((where = is_known(t.cs(), known_text_font_families)))
3454                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3455                                 context, "\\family", context.font.family,
3456                                 known_coded_font_families[where - known_text_font_families]);
3457
3458                 else if ((where = is_known(t.cs(), known_text_font_series)))
3459                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3460                                 context, "\\series", context.font.series,
3461                                 known_coded_font_series[where - known_text_font_series]);
3462
3463                 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3464                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3465                                 context, "\\shape", context.font.shape,
3466                                 known_coded_font_shapes[where - known_text_font_shapes]);
3467
3468                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3469                         context.check_layout(os);
3470                         TeXFont oldFont = context.font;
3471                         context.font.init();
3472                         context.font.size = oldFont.size;
3473                         os << "\n\\family " << context.font.family << "\n";
3474                         os << "\n\\series " << context.font.series << "\n";
3475                         os << "\n\\shape " << context.font.shape << "\n";
3476                         if (t.cs() == "textnormal") {
3477                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3478                                 output_font_change(os, context.font, oldFont);
3479                                 context.font = oldFont;
3480                         } else
3481                                 eat_whitespace(p, os, context, false);
3482                 }
3483
3484                 else if (t.cs() == "textcolor") {
3485                         // scheme is \textcolor{color name}{text}
3486                         string const color = p.verbatim_item();
3487                         // we support the predefined colors of the color  and the xcolor package
3488                         if (color == "black" || color == "blue" || color == "cyan"
3489                                 || color == "green" || color == "magenta" || color == "red"
3490                                 || color == "white" || color == "yellow") {
3491                                         context.check_layout(os);
3492                                         os << "\n\\color " << color << "\n";
3493                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3494                                         context.check_layout(os);
3495                                         os << "\n\\color inherit\n";
3496                                         preamble.registerAutomaticallyLoadedPackage("color");
3497                         } else if (color == "brown" || color == "darkgray" || color == "gray"
3498                                 || color == "lightgray" || color == "lime" || color == "olive"
3499                                 || color == "orange" || color == "pink" || color == "purple"
3500                                 || color == "teal" || color == "violet") {
3501                                         context.check_layout(os);
3502                                         os << "\n\\color " << color << "\n";
3503                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3504                                         context.check_layout(os);
3505                                         os << "\n\\color inherit\n";
3506                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3507                         } else
3508                                 // for custom defined colors
3509                                 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3510                 }
3511
3512                 else if (t.cs() == "underbar" || t.cs() == "uline") {
3513                         // \underbar is not 100% correct (LyX outputs \uline
3514                         // of ulem.sty). The difference is that \ulem allows
3515                         // line breaks, and \underbar does not.
3516                         // Do NOT handle \underline.
3517                         // \underbar cuts through y, g, q, p etc.,
3518                         // \underline does not.
3519                         context.check_layout(os);
3520                         os << "\n\\bar under\n";
3521                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3522                         context.check_layout(os);
3523                         os << "\n\\bar default\n";
3524                         preamble.registerAutomaticallyLoadedPackage("ulem");
3525                 }
3526
3527                 else if (t.cs() == "sout") {
3528                         context.check_layout(os);
3529                         os << "\n\\strikeout on\n";
3530                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3531                         context.check_layout(os);
3532                         os << "\n\\strikeout default\n";
3533                         preamble.registerAutomaticallyLoadedPackage("ulem");
3534                 }
3535
3536                 else if (t.cs() == "uuline" || t.cs() == "uwave"
3537                         || t.cs() == "emph" || t.cs() == "noun"
3538                         || t.cs() == "xout") {
3539                         context.check_layout(os);
3540                         os << "\n\\" << t.cs() << " on\n";
3541                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3542                         context.check_layout(os);
3543                         os << "\n\\" << t.cs() << " default\n";
3544                         if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3545                                 preamble.registerAutomaticallyLoadedPackage("ulem");
3546                 }
3547
3548                 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3549                         context.check_layout(os);
3550                         string name = p.getArg('{', '}');
3551                         string localtime = p.getArg('{', '}');
3552                         preamble.registerAuthor(name);
3553                         Author const & author = preamble.getAuthor(name);
3554                         // from_asctime_utc() will fail if LyX decides to output the
3555                         // time in the text language.
3556                         time_t ptime = from_asctime_utc(localtime);
3557                         if (ptime == static_cast<time_t>(-1)) {
3558                                 cerr << "Warning: Could not parse time `" << localtime
3559                                      << "´ for change tracking, using current time instead.\n";
3560                                 ptime = current_time();
3561                         }
3562                         if (t.cs() == "lyxadded")
3563                                 os << "\n\\change_inserted ";
3564                         else
3565                                 os << "\n\\change_deleted ";
3566                         os << author.bufferId() << ' ' << ptime << '\n';
3567                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3568                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
3569                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3570                                           LaTeXPackages::isAvailable("xcolor");
3571                         // No need to test for luatex, since luatex comes in
3572                         // two flavours (dvi and pdf), like latex, and those
3573                         // are detected by pdflatex.
3574                         if (pdflatex || xetex) {
3575                                 if (xcolorulem) {
3576                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3577                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3578                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3579                                 }
3580                         } else {
3581                                 if (dvipost) {
3582                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
3583                                 } else if (xcolorulem) {
3584                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3585                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3586                                 }
3587                         }
3588                 }
3589
3590                 else if (t.cs() == "textipa") {
3591                         context.check_layout(os);
3592                         begin_inset(os, "IPA\n");
3593                         bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3594                         context.merging_hyphens_allowed = false;
3595                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3596                         context.merging_hyphens_allowed = merging_hyphens_allowed;
3597                         end_inset(os);
3598                         preamble.registerAutomaticallyLoadedPackage("tipa");
3599                         preamble.registerAutomaticallyLoadedPackage("tipx");
3600                 }
3601
3602                 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3603                         context.check_layout(os);
3604                         begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3605                         os << "status open\n";
3606                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3607                         end_inset(os);
3608                         p.skip_spaces();
3609                 }
3610
3611                 else if (t.cs() == "textvertline") {
3612                         // FIXME: This is not correct, \textvertline is higher than |
3613                         os << "|";
3614                         skip_braces(p);
3615                         continue;
3616                 }
3617
3618                 else if (t.cs() == "tone" ) {
3619                         context.check_layout(os);
3620                         // register the tone package
3621                         preamble.registerAutomaticallyLoadedPackage("tone");
3622                         string content = trimSpaceAndEol(p.verbatim_item());
3623                         string command = t.asInput() + "{" + content + "}";
3624                         // some tones can be detected by unicodesymbols, some need special code
3625                         if (is_known(content, known_tones)) {
3626                                 os << "\\IPAChar " << command << "\n";
3627                                 continue;
3628                         }
3629                         // try to see whether the string is in unicodesymbols
3630                         bool termination;
3631                         docstring rem;
3632                         set<string> req;
3633                         docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3634                                 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3635                                 termination, rem, &req);
3636                         if (!s.empty()) {
3637                                 os << to_utf8(s);
3638                                 if (!rem.empty())
3639                                         output_ert_inset(os, to_utf8(rem), context);
3640                                 for (set<string>::const_iterator it = req.begin();
3641                                      it != req.end(); ++it)
3642                                         preamble.registerAutomaticallyLoadedPackage(*it);
3643                         } else
3644                                 // we did not find a non-ert version
3645                                 output_ert_inset(os, command, context);
3646                 }
3647
3648                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3649                              t.cs() == "vphantom") {
3650                         context.check_layout(os);
3651                         if (t.cs() == "phantom")
3652                                 begin_inset(os, "Phantom Phantom\n");
3653                         if (t.cs() == "hphantom")
3654                                 begin_inset(os, "Phantom HPhantom\n");
3655                         if (t.cs() == "vphantom")
3656                                 begin_inset(os, "Phantom VPhantom\n");
3657                         os << "status open\n";
3658                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3659                                             "Phantom");
3660                         end_inset(os);
3661                 }
3662
3663                 else if (t.cs() == "href") {
3664                         context.check_layout(os);
3665                         string target = convert_command_inset_arg(p.verbatim_item());
3666                         string name = convert_command_inset_arg(p.verbatim_item());
3667                         string type;
3668                         size_t i = target.find(':');
3669                         if (i != string::npos) {
3670                                 type = target.substr(0, i + 1);
3671                                 if (type == "mailto:" || type == "file:")
3672                                         target = target.substr(i + 1);
3673                                 // handle the case that name is equal to target, except of "http(s)://"
3674                                 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3675                                         target = name;
3676                         }
3677                         begin_command_inset(os, "href", "href");
3678                         if (name != target)
3679                                 os << "name \"" << name << "\"\n";
3680                         os << "target \"" << target << "\"\n";
3681                         if (type == "mailto:" || type == "file:")
3682                                 os << "type \"" << type << "\"\n";
3683                         os << "literal \"true\"\n";
3684                         end_inset(os);
3685                         skip_spaces_braces(p);
3686                 }
3687
3688                 else if (t.cs() == "lyxline") {
3689                         // swallow size argument (it is not used anyway)
3690                         p.getArg('{', '}');
3691                         if (!context.atParagraphStart()) {
3692                                 // so our line is in the middle of a paragraph
3693                                 // we need to add a new line, lest this line
3694                                 // follow the other content on that line and
3695                                 // run off the side of the page
3696                                 // FIXME: This may create an empty paragraph,
3697                                 //        but without that it would not be
3698                                 //        possible to set noindent below.
3699                                 //        Fortunately LaTeX does not care
3700                                 //        about the empty paragraph.
3701                                 context.new_paragraph(os);
3702                         }
3703                         if (preamble.indentParagraphs()) {
3704                                 // we need to unindent, lest the line be too long
3705                                 context.add_par_extra_stuff("\\noindent\n");
3706                         }
3707                         context.check_layout(os);
3708                         begin_command_inset(os, "line", "rule");
3709                         os << "offset \"0.5ex\"\n"
3710                               "width \"100line%\"\n"
3711                               "height \"1pt\"\n";
3712                         end_inset(os);
3713                 }
3714
3715                 else if (t.cs() == "rule") {
3716                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3717                         string const width = p.getArg('{', '}');
3718                         string const thickness = p.getArg('{', '}');
3719                         context.check_layout(os);
3720                         begin_command_inset(os, "line", "rule");
3721                         if (!offset.empty())
3722                                 os << "offset \"" << translate_len(offset) << "\"\n";
3723                         os << "width \"" << translate_len(width) << "\"\n"
3724                                   "height \"" << translate_len(thickness) << "\"\n";
3725                         end_inset(os);
3726                 }
3727
3728                 // handle refstyle first to catch \eqref which can also occur
3729                 // without refstyle. Only recognize these commands if
3730                 // refstyle.sty was found in the preamble (otherwise \eqref
3731                 // and user defined ref commands could be misdetected).
3732                 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3733                          preamble.refstyle()) {
3734                         context.check_layout(os);
3735                         begin_command_inset(os, "ref", "formatted");
3736                         os << "reference \"";
3737                         os << known_refstyle_prefixes[where - known_refstyle_commands]
3738                            << ":";
3739                         os << convert_command_inset_arg(p.verbatim_item())
3740                            << "\"\n";
3741                         os << "plural \"false\"\n";
3742                         os << "caps \"false\"\n";
3743                         os << "noprefix \"false\"\n";
3744                         end_inset(os);
3745                         preamble.registerAutomaticallyLoadedPackage("refstyle");
3746                 }
3747
3748                 // if refstyle is used, we must not convert \prettyref to a
3749                 // formatted reference, since that would result in a refstyle command.
3750                 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3751                          (t.cs() != "prettyref" || !preamble.refstyle())) {
3752                         string const opt = p.getOpt();
3753                         if (opt.empty()) {
3754                                 context.check_layout(os);
3755                                 begin_command_inset(os, "ref",
3756                                         known_coded_ref_commands[where - known_ref_commands]);
3757                                 os << "reference \""
3758                                    << convert_command_inset_arg(p.verbatim_item())
3759                                    << "\"\n";
3760                                 os << "plural \"false\"\n";
3761                                 os << "caps \"false\"\n";
3762                                 os << "noprefix \"false\"\n";
3763                                 end_inset(os);
3764                                 if (t.cs() == "vref" || t.cs() == "vpageref")
3765                                         preamble.registerAutomaticallyLoadedPackage("varioref");
3766                                 else if (t.cs() == "prettyref")
3767                                         preamble.registerAutomaticallyLoadedPackage("prettyref");
3768                         } else {
3769                                 // LyX does not yet support optional arguments of ref commands
3770                                 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3771                                        p.verbatim_item() + '}', context);
3772                         }
3773                 }
3774
3775                 else if (use_natbib &&
3776                          is_known(t.cs(), known_natbib_commands) &&
3777                          ((t.cs() != "citefullauthor" &&
3778                            t.cs() != "citeyear" &&
3779                            t.cs() != "citeyearpar") ||
3780                           p.next_token().asInput() != "*")) {
3781                         context.check_layout(os);
3782                         string command = t.cs();
3783                         if (p.next_token().asInput() == "*") {
3784                                 command += '*';
3785                                 p.get_token();
3786                         }
3787                         if (command == "citefullauthor")
3788                                 // alternative name for "\\citeauthor*"
3789                                 command = "citeauthor*";
3790
3791                         // text before the citation
3792                         string before;
3793                         // text after the citation
3794                         string after;
3795                         get_cite_arguments(p, true, before, after);
3796
3797                         if (command == "cite") {
3798                                 // \cite without optional argument means
3799                                 // \citet, \cite with at least one optional
3800                                 // argument means \citep.
3801                                 if (before.empty() && after.empty())
3802                                         command = "citet";
3803                                 else
3804                                         command = "citep";
3805                         }
3806                         if (before.empty() && after == "[]")
3807                                 // avoid \citet[]{a}
3808                                 after.erase();
3809                         else if (before == "[]" && after == "[]") {
3810                                 // avoid \citet[][]{a}
3811                                 before.erase();
3812                                 after.erase();
3813                         }
3814                         // remove the brackets around after and before
3815                         if (!after.empty()) {
3816                                 after.erase(0, 1);
3817                                 after.erase(after.length() - 1, 1);
3818                                 after = convert_command_inset_arg(after);
3819                         }
3820                         if (!before.empty()) {
3821                                 before.erase(0, 1);
3822                                 before.erase(before.length() - 1, 1);
3823                                 before = convert_command_inset_arg(before);
3824                         }
3825                         begin_command_inset(os, "citation", command);
3826                         os << "after " << '"' << after << '"' << "\n";
3827                         os << "before " << '"' << before << '"' << "\n";
3828                         os << "key \""
3829                            << convert_command_inset_arg(p.verbatim_item())
3830                            << "\"\n"
3831                            << "literal \"true\"\n";
3832                         end_inset(os);
3833                         // Need to set the cite engine if natbib is loaded by
3834                         // the document class directly
3835                         if (preamble.citeEngine() == "basic")
3836                                 preamble.citeEngine("natbib");
3837                 }
3838
3839                 else if (use_biblatex
3840                          && is_known(t.cs(), known_biblatex_commands)
3841                          && ((t.cs() == "cite"
3842                              || t.cs() == "citeauthor"
3843                              || t.cs() == "Citeauthor"
3844                              || t.cs() == "parencite"
3845                              || t.cs() == "citetitle")
3846                          || p.next_token().asInput() != "*")) {
3847                         context.check_layout(os);
3848                         string command = t.cs();
3849                         if (p.next_token().asInput() == "*") {
3850                                 command += '*';
3851                                 p.get_token();
3852                         }
3853
3854                         // text before the citation
3855                         string before;
3856                         // text after the citation
3857                         string after;
3858                         get_cite_arguments(p, true, before, after);
3859
3860                         // These use natbib cmd names in LyX
3861                         // for inter-citeengine compativility
3862                         if (command == "citeyear")
3863                                 command = "citebyear";
3864                         else if (command == "cite*")
3865                                 command = "citeyear";
3866                         else if (command == "textcite")
3867                                 command = "citet";
3868                         else if (command == "Textcite")
3869                                 command = "Citet";
3870                         else if (command == "parencite")
3871                                 command = "citep";
3872                         else if (command == "Parencite")
3873                                 command = "Citep";
3874                         else if (command == "parencite*")
3875                                 command = "citeyearpar";
3876                         else if (command == "smartcite")
3877                                 command = "footcite";
3878                         else if (command == "Smartcite")
3879                                 command = "Footcite";
3880
3881                         if (before.empty() && after == "[]")
3882                                 // avoid \cite[]{a}
3883                                 after.erase();
3884                         else if (before == "[]" && after == "[]") {
3885                                 // avoid \cite[][]{a}
3886                                 before.erase();
3887                                 after.erase();
3888                         }
3889                         // remove the brackets around after and before
3890                         if (!after.empty()) {
3891                                 after.erase(0, 1);
3892                                 after.erase(after.length() - 1, 1);
3893                                 after = convert_command_inset_arg(after);
3894                         }
3895                         if (!before.empty()) {
3896                                 before.erase(0, 1);
3897                                 before.erase(before.length() - 1, 1);
3898                                 before = convert_command_inset_arg(before);
3899                         }
3900                         begin_command_inset(os, "citation", command);
3901                         os << "after " << '"' << after << '"' << "\n";
3902                         os << "before " << '"' << before << '"' << "\n";
3903                         os << "key \""
3904                            << convert_command_inset_arg(p.verbatim_item())
3905                            << "\"\n"
3906                            << "literal \"true\"\n";
3907                         end_inset(os);
3908                         // Need to set the cite engine if biblatex is loaded by
3909                         // the document class directly
3910                         if (preamble.citeEngine() == "basic")
3911                                 preamble.citeEngine("biblatex");
3912                 }
3913
3914                 else if (use_biblatex_natbib
3915                          && (is_known(t.cs(), known_biblatex_commands)
3916                              || is_known(t.cs(), known_natbib_commands))
3917                          && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
3918                               || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
3919                               || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
3920                               || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
3921                               || t.cs() == "parencite" || t.cs() == "citetitle")
3922                             || p.next_token().asInput() != "*")) {
3923                         context.check_layout(os);
3924                         string command = t.cs();
3925                         if (p.next_token().asInput() == "*") {
3926                                 command += '*';
3927                                 p.get_token();
3928                         }
3929
3930                         // text before the citation
3931                         string before;
3932                         // text after the citation
3933                         string after;
3934                         get_cite_arguments(p, true, before, after);
3935
3936                         // These use natbib cmd names in LyX
3937                         // for inter-citeengine compativility
3938                         if (command == "citeyear")
3939                                 command = "citebyear";
3940                         else if (command == "cite*")
3941                                 command = "citeyear";
3942                         else if (command == "textcite")
3943                                 command = "citet";
3944                         else if (command == "Textcite")
3945                                 command = "Citet";
3946                         else if (command == "parencite")
3947                                 command = "citep";
3948                         else if (command == "Parencite")
3949                                 command = "Citep";
3950                         else if (command == "parencite*")
3951                                 command = "citeyearpar";
3952                         else if (command == "smartcite")
3953                                 command = "footcite";
3954                         else if (command == "Smartcite")
3955                                 command = "Footcite";
3956
3957                         if (before.empty() && after == "[]")
3958                                 // avoid \cite[]{a}
3959                                 after.erase();
3960                         else if (before == "[]" && after == "[]") {
3961                                 // avoid \cite[][]{a}
3962                                 before.erase();
3963                                 after.erase();
3964                         }
3965                         // remove the brackets around after and before
3966                         if (!after.empty()) {
3967                                 after.erase(0, 1);
3968                                 after.erase(after.length() - 1, 1);
3969                                 after = convert_command_inset_arg(after);
3970                         }
3971                         if (!before.empty()) {
3972                                 before.erase(0, 1);
3973                                 before.erase(before.length() - 1, 1);
3974                                 before = convert_command_inset_arg(before);
3975                         }
3976                         begin_command_inset(os, "citation", command);
3977                         os << "after " << '"' << after << '"' << "\n";
3978                         os << "before " << '"' << before << '"' << "\n";
3979                         os << "key \""
3980                            << convert_command_inset_arg(p.verbatim_item())
3981                            << "\"\n"
3982                            << "literal \"true\"\n";
3983                         end_inset(os);
3984                         // Need to set the cite engine if biblatex is loaded by
3985                         // the document class directly
3986                         if (preamble.citeEngine() == "basic")
3987                                 preamble.citeEngine("biblatex-natbib");
3988                 }
3989
3990                 else if (use_jurabib &&
3991                          is_known(t.cs(), known_jurabib_commands) &&
3992                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3993                         context.check_layout(os);
3994                         string command = t.cs();
3995                         if (p.next_token().asInput() == "*") {
3996                                 command += '*';
3997                                 p.get_token();
3998                         }
3999                         char argumentOrder = '\0';
4000                         vector<string> const options =
4001                                 preamble.getPackageOptions("jurabib");
4002                         if (find(options.begin(), options.end(),
4003                                       "natbiborder") != options.end())
4004                                 argumentOrder = 'n';
4005                         else if (find(options.begin(), options.end(),
4006                                            "jurabiborder") != options.end())
4007                                 argumentOrder = 'j';
4008
4009                         // text before the citation
4010                         string before;
4011                         // text after the citation
4012                         string after;
4013                         get_cite_arguments(p, argumentOrder != 'j', before, after);
4014
4015                         string const citation = p.verbatim_item();
4016                         if (!before.empty() && argumentOrder == '\0') {
4017                                 cerr << "Warning: Assuming argument order "
4018                                         "of jurabib version 0.6 for\n'"
4019                                      << command << before << after << '{'
4020                                      << citation << "}'.\n"
4021                                         "Add 'jurabiborder' to the jurabib "
4022                                         "package options if you used an\n"
4023                                         "earlier jurabib version." << endl;
4024                         }
4025                         if (!after.empty()) {
4026                                 after.erase(0, 1);
4027                                 after.erase(after.length() - 1, 1);
4028                         }
4029                         if (!before.empty()) {
4030                                 before.erase(0, 1);
4031                                 before.erase(before.length() - 1, 1);
4032                         }
4033                         begin_command_inset(os, "citation", command);
4034                         os << "after " << '"' << after << "\"\n"
4035                            << "before " << '"' << before << "\"\n"
4036                            << "key " << '"' << citation << "\"\n"
4037                            << "literal \"true\"\n";
4038                         end_inset(os);
4039                         // Need to set the cite engine if jurabib is loaded by
4040                         // the document class directly
4041                         if (preamble.citeEngine() == "basic")
4042                                 preamble.citeEngine("jurabib");
4043                 }
4044
4045                 else if (t.cs() == "cite"
4046                         || t.cs() == "nocite") {
4047                         context.check_layout(os);
4048                         string after = convert_command_inset_arg(p.getArg('[', ']'));
4049                         string key = convert_command_inset_arg(p.verbatim_item());
4050                         // store the case that it is "\nocite{*}" to use it later for
4051                         // the BibTeX inset
4052                         if (key != "*") {
4053                                 begin_command_inset(os, "citation", t.cs());
4054                                 os << "after " << '"' << after << "\"\n"
4055                                    << "key " << '"' << key << "\"\n"
4056                                    << "literal \"true\"\n";
4057                                 end_inset(os);
4058                         } else if (t.cs() == "nocite")
4059                                 btprint = key;
4060                 }
4061
4062                 else if (t.cs() == "index" ||
4063                          (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4064                         context.check_layout(os);
4065                         string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4066                                 p.getArg('[', ']') : "";
4067                         string const kind = arg.empty() ? "idx" : arg;
4068                         begin_inset(os, "Index ");
4069                         os << kind << "\nstatus collapsed\n";
4070                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4071                         end_inset(os);
4072                         if (kind != "idx")
4073                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
4074                 }
4075
4076                 else if (t.cs() == "nomenclature") {
4077                         context.check_layout(os);
4078                         begin_command_inset(os, "nomenclature", "nomenclature");
4079                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
4080                         if (!prefix.empty())
4081                                 os << "prefix " << '"' << prefix << '"' << "\n";
4082                         os << "symbol " << '"'
4083                            << convert_command_inset_arg(p.verbatim_item());
4084                         os << "\"\ndescription \""
4085                            << convert_command_inset_arg(p.verbatim_item())
4086                            << "\"\n"
4087                            << "literal \"true\"\n";
4088                         end_inset(os);
4089                         preamble.registerAutomaticallyLoadedPackage("nomencl");
4090                 }
4091
4092                 else if (t.cs() == "label") {
4093                         context.check_layout(os);
4094                         begin_command_inset(os, "label", "label");
4095                         os << "name \""
4096                            << convert_command_inset_arg(p.verbatim_item())
4097                            << "\"\n";
4098                         end_inset(os);
4099                 }
4100
4101                 else if (t.cs() == "lyxmintcaption") {
4102                         string const pos = p.getArg('[', ']');
4103                         if (pos == "t") {
4104                                 string const caption =
4105                                         parse_text_snippet(p, FLAG_ITEM, false,
4106                                                            context);
4107                                 minted_nonfloat_caption = "[t]" + caption;
4108                         } else {
4109                                 // We already got the caption at the bottom,
4110                                 // so simply skip it.
4111                                 parse_text_snippet(p, FLAG_ITEM, false, context);
4112                         }
4113                 }
4114
4115                 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4116                         context.check_layout(os);
4117                         string commandname = t.cs();
4118                         bool star = false;
4119                         if (p.next_token().asInput() == "*") {
4120                                 commandname += "*";
4121                                 star = true;
4122                                 p.get_token();
4123                         }
4124                         begin_command_inset(os, "index_print", commandname);
4125                         string const indexname = p.getArg('[', ']');
4126                         if (!star) {
4127                                 if (indexname.empty())
4128                                         os << "type \"idx\"\n";
4129                                 else
4130                                         os << "type \"" << indexname << "\"\n";
4131                                 os << "literal \"true\"\n";
4132                         }
4133                         end_inset(os);
4134                         skip_spaces_braces(p);
4135                         preamble.registerAutomaticallyLoadedPackage("makeidx");
4136                         if (preamble.use_indices() == "true")
4137                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
4138                 }
4139
4140                 else if (t.cs() == "printnomenclature") {
4141                         string width = "";
4142                         string width_type = "";
4143                         context.check_layout(os);
4144                         begin_command_inset(os, "nomencl_print", "printnomenclature");
4145                         // case of a custom width
4146                         if (p.hasOpt()) {
4147                                 width = p.getArg('[', ']');
4148                                 width = translate_len(width);
4149                                 width_type = "custom";
4150                         }
4151                         // case of no custom width
4152                         // the case of no custom width but the width set
4153                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
4154                         // because the user could have set anything, not only the width
4155                         // of the longest label (which would be width_type = "auto")
4156                         string label = convert_command_inset_arg(p.getArg('{', '}'));
4157                         if (label.empty() && width_type.empty())
4158                                 width_type = "none";
4159                         os << "set_width \"" << width_type << "\"\n";
4160                         if (width_type == "custom")
4161                                 os << "width \"" << width << '\"';
4162                         end_inset(os);
4163                         skip_spaces_braces(p);
4164                         preamble.registerAutomaticallyLoadedPackage("nomencl");
4165                 }
4166
4167                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4168                         context.check_layout(os);
4169                         begin_inset(os, "script ");
4170                         os << t.cs().substr(4) << '\n';
4171                         newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4172                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4173                         end_inset(os);
4174                         if (t.cs() == "textsubscript")
4175                                 preamble.registerAutomaticallyLoadedPackage("subscript");
4176                 }
4177
4178                 else if ((where = is_known(t.cs(), known_quotes))) {
4179                         context.check_layout(os);
4180                         begin_inset(os, "Quotes ");
4181                         os << known_coded_quotes[where - known_quotes];
4182                         end_inset(os);
4183                         // LyX adds {} after the quote, so we have to eat
4184                         // spaces here if there are any before a possible
4185                         // {} pair.
4186                         eat_whitespace(p, os, context, false);
4187                         skip_braces(p);
4188                 }
4189
4190                 else if ((where = is_known(t.cs(), known_sizes)) &&
4191                          context.new_layout_allowed) {
4192                         context.check_layout(os);
4193                         TeXFont const oldFont = context.font;
4194                         context.font.size = known_coded_sizes[where - known_sizes];
4195                         output_font_change(os, oldFont, context.font);
4196                         eat_whitespace(p, os, context, false);
4197                 }
4198
4199                 else if ((where = is_known(t.cs(), known_font_families)) &&
4200                          context.new_layout_allowed) {
4201                         context.check_layout(os);
4202                         TeXFont const oldFont = context.font;
4203                         context.font.family =
4204                                 known_coded_font_families[where - known_font_families];
4205                         output_font_change(os, oldFont, context.font);
4206                         eat_whitespace(p, os, context, false);
4207                 }
4208
4209                 else if ((where = is_known(t.cs(), known_font_series)) &&
4210                          context.new_layout_allowed) {
4211                         context.check_layout(os);
4212                         TeXFont const oldFont = context.font;
4213                         context.font.series =
4214                                 known_coded_font_series[where - known_font_series];
4215                         output_font_change(os, oldFont, context.font);
4216                         eat_whitespace(p, os, context, false);
4217                 }
4218
4219                 else if ((where = is_known(t.cs(), known_font_shapes)) &&
4220                          context.new_layout_allowed) {
4221                         context.check_layout(os);
4222                         TeXFont const oldFont = context.font;
4223                         context.font.shape =
4224                                 known_coded_font_shapes[where - known_font_shapes];
4225                         output_font_change(os, oldFont, context.font);
4226                         eat_whitespace(p, os, context, false);
4227                 }
4228                 else if ((where = is_known(t.cs(), known_old_font_families)) &&
4229                          context.new_layout_allowed) {
4230                         context.check_layout(os);
4231                         TeXFont const oldFont = context.font;
4232                         context.font.init();
4233                         context.font.size = oldFont.size;
4234                         context.font.family =
4235                                 known_coded_font_families[where - known_old_font_families];
4236                         output_font_change(os, oldFont, context.font);
4237                         eat_whitespace(p, os, context, false);
4238                 }
4239
4240                 else if ((where = is_known(t.cs(), known_old_font_series)) &&
4241                          context.new_layout_allowed) {
4242                         context.check_layout(os);
4243                         TeXFont const oldFont = context.font;
4244                         context.font.init();
4245                         context.font.size = oldFont.size;
4246                         context.font.series =
4247                                 known_coded_font_series[where - known_old_font_series];
4248                         output_font_change(os, oldFont, context.font);
4249                         eat_whitespace(p, os, context, false);
4250                 }
4251
4252                 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4253                          context.new_layout_allowed) {
4254                         context.check_layout(os);
4255                         TeXFont const oldFont = context.font;
4256                         context.font.init();
4257                         context.font.size = oldFont.size;
4258                         context.font.shape =
4259                                 known_coded_font_shapes[where - known_old_font_shapes];
4260                         output_font_change(os, oldFont, context.font);
4261                         eat_whitespace(p, os, context, false);
4262                 }
4263
4264                 else if (t.cs() == "selectlanguage") {
4265                         context.check_layout(os);
4266                         // save the language for the case that a
4267                         // \foreignlanguage is used
4268                         context.font.language = babel2lyx(p.verbatim_item());
4269                         os << "\n\\lang " << context.font.language << "\n";
4270                 }
4271
4272                 else if (t.cs() == "foreignlanguage") {
4273                         string const lang = babel2lyx(p.verbatim_item());
4274                         parse_text_attributes(p, os, FLAG_ITEM, outer,
4275                                               context, "\\lang",
4276                                               context.font.language, lang);
4277                 }
4278
4279                 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4280                          && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4281                         // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4282                         string lang;
4283                         // We have to output the whole command if it has an option
4284                         // because LyX doesn't support this yet, see bug #8214,
4285                         // only if there is a single option specifying a variant, we can handle it.
4286                         if (p.hasOpt()) {
4287                                 string langopts = p.getOpt();
4288                                 // check if the option contains a variant, if yes, extract it
4289                                 string::size_type pos_var = langopts.find("variant");
4290                                 string::size_type i = langopts.find(',');
4291                                 string::size_type k = langopts.find('=', pos_var);
4292                                 if (pos_var != string::npos && i == string::npos) {
4293                                         string variant;
4294                                         variant = langopts.substr(k + 1, langopts.length() - k - 2);
4295                                         lang = preamble.polyglossia2lyx(variant);
4296                                         parse_text_attributes(p, os, FLAG_ITEM, outer,
4297                                                                   context, "\\lang",
4298                                                                   context.font.language, lang);
4299                                 } else
4300                                         output_ert_inset(os, t.asInput() + langopts, context);
4301                         } else {
4302                                 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4303                                 parse_text_attributes(p, os, FLAG_ITEM, outer,
4304                                                           context, "\\lang",
4305                                                           context.font.language, lang);
4306                         }
4307                 }
4308
4309                 else if (t.cs() == "inputencoding") {
4310                         // nothing to write here
4311                         string const enc = subst(p.verbatim_item(), "\n", " ");
4312                         p.setEncoding(enc, Encoding::inputenc);
4313                 }
4314
4315                 else if (is_known(t.cs(), known_special_chars) ||
4316                          (t.cs() == "protect" &&
4317                           p.next_token().cat() == catEscape &&
4318                           is_known(p.next_token().cs(), known_special_protect_chars))) {
4319                         // LyX sometimes puts a \protect in front, so we have to ignore it
4320                         where = is_known(
4321                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4322                                 known_special_chars);
4323                         context.check_layout(os);
4324                         os << known_coded_special_chars[where - known_special_chars];
4325                         skip_spaces_braces(p);
4326                 }
4327
4328                 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4329                          (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4330                           p.next_next_token().asInput() == "-") ||
4331                          (t.cs() == "@" && p.next_token().asInput() == ".")) {
4332                         // LyX sometimes puts a \protect in front, so we have to ignore it
4333                         if (t.cs() == "protect")
4334                                 p.get_token();
4335                         context.check_layout(os);
4336                         if (t.cs() == "nobreakdash")
4337                                 os << "\\SpecialChar nobreakdash\n";
4338                         else
4339                                 os << "\\SpecialChar endofsentence\n";
4340                         p.get_token();
4341                 }
4342
4343                 else if (t.cs() == "textquotedbl") {
4344                         context.check_layout(os);
4345                         os << "\"";
4346                         skip_braces(p);
4347                 }
4348
4349                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4350                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4351                             || t.cs() == "%" || t.cs() == "-") {
4352                         context.check_layout(os);
4353                         if (t.cs() == "-")
4354                                 os << "\\SpecialChar softhyphen\n";
4355                         else
4356                                 os << t.cs();
4357                 }
4358
4359                 else if (t.cs() == "char") {
4360                         context.check_layout(os);
4361                         if (p.next_token().character() == '`') {
4362                                 p.get_token();
4363                                 if (p.next_token().cs() == "\"") {
4364                                         p.get_token();
4365                                         os << '"';
4366                                         skip_braces(p);
4367                                 } else {
4368                                         output_ert_inset(os, "\\char`", context);
4369                                 }
4370                         } else {
4371                                 output_ert_inset(os, "\\char", context);
4372                         }
4373                 }
4374
4375                 else if (t.cs() == "verb") {
4376                         context.check_layout(os);
4377                         // set catcodes to verbatim early, just in case.
4378                         p.setCatcodes(VERBATIM_CATCODES);
4379                         string delim = p.get_token().asInput();
4380                         Parser::Arg arg = p.verbatimStuff(delim);
4381                         if (arg.first)
4382                                 output_ert_inset(os, "\\verb" + delim
4383                                                  + arg.second + delim, context);
4384                         else
4385                                 cerr << "invalid \\verb command. Skipping" << endl;
4386                 }
4387
4388                 // Problem: \= creates a tabstop inside the tabbing environment
4389                 // and else an accent. In the latter case we really would want
4390                 // \={o} instead of \= o.
4391                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
4392                         output_ert_inset(os, t.asInput(), context);
4393
4394                 else if (t.cs() == "\\") {
4395                         context.check_layout(os);
4396                         if (p.hasOpt())
4397                                 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4398                         else if (p.next_token().asInput() == "*") {
4399                                 p.get_token();
4400                                 // getOpt() eats the following space if there
4401                                 // is no optional argument, but that is OK
4402                                 // here since it has no effect in the output.
4403                                 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4404                         }
4405                         else {
4406                                 begin_inset(os, "Newline newline");
4407                                 end_inset(os);
4408                         }
4409                 }
4410
4411                 else if (t.cs() == "newline" ||
4412                          (t.cs() == "linebreak" && !p.hasOpt())) {
4413                         context.check_layout(os);
4414                         begin_inset(os, "Newline ");
4415                         os << t.cs();
4416                         end_inset(os);
4417                         skip_spaces_braces(p);
4418                 }
4419
4420                 else if (t.cs() == "input" || t.cs() == "include"
4421                          || t.cs() == "verbatiminput") {
4422                         string name = t.cs();
4423                         if (t.cs() == "verbatiminput"
4424                             && p.next_token().asInput() == "*")
4425                                 name += p.get_token().asInput();
4426                         context.check_layout(os);
4427                         string filename(normalize_filename(p.getArg('{', '}')));
4428                         string const path = getMasterFilePath(true);
4429                         // We want to preserve relative / absolute filenames,
4430                         // therefore path is only used for testing
4431                         if ((t.cs() == "include" || t.cs() == "input") &&
4432                             !makeAbsPath(filename, path).exists()) {
4433                                 // The file extension is probably missing.
4434                                 // Now try to find it out.
4435                                 string const tex_name =
4436                                         find_file(filename, path,
4437                                                   known_tex_extensions);
4438                                 if (!tex_name.empty())
4439                                         filename = tex_name;
4440                         }
4441                         bool external = false;
4442                         string outname;
4443                         if (makeAbsPath(filename, path).exists()) {
4444                                 string const abstexname =
4445                                         makeAbsPath(filename, path).absFileName();
4446                                 string const absfigname =
4447                                         changeExtension(abstexname, ".fig");
4448                                 fix_child_filename(filename);
4449                                 string const lyxname = changeExtension(filename,
4450                                         roundtripMode() ? ".lyx.lyx" : ".lyx");
4451                                 string const abslyxname = makeAbsPath(
4452                                         lyxname, getParentFilePath(false)).absFileName();
4453                                 bool xfig = false;
4454                                 if (!skipChildren())
4455                                         external = FileName(absfigname).exists();
4456                                 if (t.cs() == "input" && !skipChildren()) {
4457                                         string const ext = getExtension(abstexname);
4458
4459                                         // Combined PS/LaTeX:
4460                                         // x.eps, x.pstex_t (old xfig)
4461                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4462                                         FileName const absepsname(
4463                                                 changeExtension(abstexname, ".eps"));
4464                                         FileName const abspstexname(
4465                                                 changeExtension(abstexname, ".pstex"));
4466                                         bool const xfigeps =
4467                                                 (absepsname.exists() ||
4468                                                  abspstexname.exists()) &&
4469                                                 ext == "pstex_t";
4470
4471                                         // Combined PDF/LaTeX:
4472                                         // x.pdf, x.pdftex_t (old xfig)
4473                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4474                                         FileName const abspdfname(
4475                                                 changeExtension(abstexname, ".pdf"));
4476                                         bool const xfigpdf =
4477                                                 abspdfname.exists() &&
4478                                                 (ext == "pdftex_t" || ext == "pdf_t");
4479                                         if (xfigpdf)
4480                                                 pdflatex = true;
4481
4482                                         // Combined PS/PDF/LaTeX:
4483                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4484                                         string const absbase2(
4485                                                 removeExtension(abstexname) + "_pspdftex");
4486                                         FileName const abseps2name(
4487                                                 addExtension(absbase2, ".eps"));
4488                                         FileName const abspdf2name(
4489                                                 addExtension(absbase2, ".pdf"));
4490                                         bool const xfigboth =
4491                                                 abspdf2name.exists() &&
4492                                                 abseps2name.exists() && ext == "pspdftex";
4493
4494                                         xfig = xfigpdf || xfigeps || xfigboth;
4495                                         external = external && xfig;
4496                                 }
4497                                 if (external) {
4498                                         outname = changeExtension(filename, ".fig");
4499                                         FileName abssrc(changeExtension(abstexname, ".fig"));
4500                                         copy_file(abssrc, outname);
4501                                 } else if (xfig) {
4502                                         // Don't try to convert, the result
4503                                         // would be full of ERT.
4504                                         outname = filename;
4505                                         FileName abssrc(abstexname);
4506                                         copy_file(abssrc, outname);
4507                                 } else if (t.cs() != "verbatiminput" &&
4508                                            !skipChildren() &&
4509                                     tex2lyx(abstexname, FileName(abslyxname),
4510                                             p.getEncoding())) {
4511                                         outname = lyxname;
4512                                         // no need to call copy_file
4513                                         // tex2lyx creates the file
4514                                 } else {
4515                                         outname = filename;
4516                                         FileName abssrc(abstexname);
4517                                         copy_file(abssrc, outname);
4518                                 }
4519                         } else {
4520                                 cerr << "Warning: Could not find included file '"
4521                                      << filename << "'." << endl;
4522                                 outname = filename;
4523                         }
4524                         if (external) {
4525                                 begin_inset(os, "External\n");
4526                                 os << "\ttemplate XFig\n"
4527                                    << "\tfilename " << outname << '\n';
4528                                 registerExternalTemplatePackages("XFig");
4529                         } else {
4530                                 begin_command_inset(os, "include", name);
4531                                 outname = subst(outname, "\"", "\\\"");
4532                                 os << "preview false\n"
4533                                       "filename \"" << outname << "\"\n";
4534                                 if (t.cs() == "verbatiminput")
4535                                         preamble.registerAutomaticallyLoadedPackage("verbatim");
4536                         }
4537                         end_inset(os);
4538                 }
4539
4540                 else if (t.cs() == "bibliographystyle") {
4541                         // store new bibliographystyle
4542                         bibliographystyle = p.verbatim_item();
4543                         // If any other command than \bibliography, \addcontentsline
4544                         // and \nocite{*} follows, we need to output the style
4545                         // (because it might be used by that command).
4546                         // Otherwise, it will automatically be output by LyX.
4547                         p.pushPosition();
4548                         bool output = true;
4549                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4550                                 if (t2.cat() == catBegin)
4551                                         break;
4552                                 if (t2.cat() != catEscape)
4553                                         continue;
4554                                 if (t2.cs() == "nocite") {
4555                                         if (p.getArg('{', '}') == "*")
4556                                                 continue;
4557                                 } else if (t2.cs() == "bibliography")
4558                                         output = false;
4559                                 else if (t2.cs() == "phantomsection") {
4560                                         output = false;
4561                                         continue;
4562                                 }
4563                                 else if (t2.cs() == "addcontentsline") {
4564                                         // get the 3 arguments of \addcontentsline
4565                                         p.getArg('{', '}');
4566                                         p.getArg('{', '}');
4567                                         contentslineContent = p.getArg('{', '}');
4568                                         // if the last argument is not \refname we must output
4569                                         if (contentslineContent == "\\refname")
4570                                                 output = false;
4571                                 }
4572                                 break;
4573                         }
4574                         p.popPosition();
4575                         if (output) {
4576                                 output_ert_inset(os,
4577                                         "\\bibliographystyle{" + bibliographystyle + '}',
4578                                         context);
4579                         }
4580                 }
4581
4582                 else if (t.cs() == "phantomsection") {
4583                         // we only support this if it occurs between
4584                         // \bibliographystyle and \bibliography
4585                         if (bibliographystyle.empty())
4586                                 output_ert_inset(os, "\\phantomsection", context);
4587                 }
4588
4589                 else if (t.cs() == "addcontentsline") {
4590                         context.check_layout(os);
4591                         // get the 3 arguments of \addcontentsline
4592                         string const one = p.getArg('{', '}');
4593                         string const two = p.getArg('{', '}');
4594                         string const three = p.getArg('{', '}');
4595                         // only if it is a \refname, we support if for the bibtex inset
4596                         if (contentslineContent != "\\refname") {
4597                                 output_ert_inset(os,
4598                                         "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4599                                         context);
4600                         }
4601                 }
4602
4603                 else if (t.cs() == "bibliography") {
4604                         context.check_layout(os);
4605                         string BibOpts;
4606                         begin_command_inset(os, "bibtex", "bibtex");
4607                         if (!btprint.empty()) {
4608                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4609                                 // clear the string because the next BibTeX inset can be without the
4610                                 // \nocite{*} option
4611                                 btprint.clear();
4612                         }
4613                         os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4614                         // Do we have addcontentsline?
4615                         if (contentslineContent == "\\refname") {
4616                                 BibOpts = "bibtotoc";
4617                                 // clear string because next BibTeX inset can be without addcontentsline
4618                                 contentslineContent.clear();
4619                         }
4620                         // Do we have a bibliographystyle set?
4621                         if (!bibliographystyle.empty()) {
4622                                 if (BibOpts.empty())
4623                                         BibOpts = normalize_filename(bibliographystyle);
4624                                 else
4625                                         BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4626                                 // clear it because each bibtex entry has its style
4627                                 // and we need an empty string to handle \phantomsection
4628                                 bibliographystyle.clear();
4629                         }
4630                         os << "options " << '"' << BibOpts << '"' << "\n";
4631                         end_inset(os);
4632                 }
4633
4634                 else if (t.cs() == "printbibliography") {
4635                         context.check_layout(os);
4636                         string BibOpts;
4637                         string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4638                         vector<string> opts = getVectorFromString(bbloptions);
4639                         vector<string>::iterator it =
4640                                 find(opts.begin(), opts.end(), "heading=bibintoc");
4641                         if (it != opts.end()) {
4642                                 opts.erase(it);
4643                                 BibOpts = "bibtotoc";
4644                         }
4645                         bbloptions = getStringFromVector(opts);
4646                         begin_command_inset(os, "bibtex", "bibtex");
4647                         if (!btprint.empty()) {
4648                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4649                                 // clear the string because the next BibTeX inset can be without the
4650                                 // \nocite{*} option
4651                                 btprint.clear();
4652                         }
4653                         string bibfiles;
4654                         for (auto const & bf : preamble.biblatex_bibliographies) {
4655                                 if (!bibfiles.empty())
4656                                         bibfiles += ",";
4657                                 bibfiles += normalize_filename(bf);
4658                         }
4659                         if (!bibfiles.empty())
4660                                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4661                         // Do we have addcontentsline?
4662                         if (contentslineContent == "\\refname") {
4663                                 BibOpts = "bibtotoc";
4664                                 // clear string because next BibTeX inset can be without addcontentsline
4665                                 contentslineContent.clear();
4666                         }
4667                         os << "options " << '"' << BibOpts << '"' << "\n";
4668                         if (!bbloptions.empty())
4669                                 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4670                         end_inset(os);
4671                         need_commentbib = false;
4672                 }
4673
4674                 else if (t.cs() == "bibbysection") {
4675                         context.check_layout(os);
4676                         string BibOpts;
4677                         string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4678                         vector<string> opts = getVectorFromString(bbloptions);
4679                         vector<string>::iterator it =
4680                                 find(opts.begin(), opts.end(), "heading=bibintoc");
4681                         if (it != opts.end()) {
4682                                 opts.erase(it);
4683                                 BibOpts = "bibtotoc";
4684                         }
4685                         bbloptions = getStringFromVector(opts);
4686                         begin_command_inset(os, "bibtex", "bibtex");
4687                         os << "btprint " << '"' << "bibbysection" << '"' << "\n";
4688                         string bibfiles;
4689                         for (auto const & bf : preamble.biblatex_bibliographies) {
4690                                 if (!bibfiles.empty())
4691                                         bibfiles += ",";
4692                                 bibfiles += normalize_filename(bf);
4693                         }
4694                         if (!bibfiles.empty())
4695                                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4696                         os << "options " << '"' << BibOpts << '"' << "\n";
4697                         if (!bbloptions.empty())
4698                                 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4699                         end_inset(os);
4700                         need_commentbib = false;
4701                 }
4702
4703                 else if (t.cs() == "parbox") {
4704                         // Test whether this is an outer box of a shaded box
4705                         p.pushPosition();
4706                         // swallow arguments
4707                         while (p.hasOpt()) {
4708                                 p.getArg('[', ']');
4709                                 p.skip_spaces(true);
4710                         }
4711                         p.getArg('{', '}');
4712                         p.skip_spaces(true);
4713                         // eat the '{'
4714                         if (p.next_token().cat() == catBegin)
4715                                 p.get_token();
4716                         p.skip_spaces(true);
4717                         Token to = p.get_token();
4718                         bool shaded = false;
4719                         if (to.asInput() == "\\begin") {
4720                                 p.skip_spaces(true);
4721                                 if (p.getArg('{', '}') == "shaded")
4722                                         shaded = true;
4723                         }
4724                         p.popPosition();
4725                         if (shaded) {
4726                                 parse_outer_box(p, os, FLAG_ITEM, outer,
4727                                                 context, "parbox", "shaded");
4728                         } else
4729                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4730                                           "", "", t.cs(), "", "");
4731                 }
4732
4733                 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4734                              t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4735                          t.cs() == "shadowbox" || t.cs() == "doublebox")
4736                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4737
4738                 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4739                         string backgroundcolor;
4740                         preamble.registerAutomaticallyLoadedPackage("xcolor");
4741                         if (t.cs() == "fcolorbox") {
4742                                 string const framecolor = p.getArg('{', '}');
4743                                 backgroundcolor = p.getArg('{', '}');
4744                                 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4745                         } else {
4746                                 backgroundcolor = p.getArg('{', '}');
4747                                 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4748                         }
4749                 }
4750
4751                 // FIXME: due to the compiler limit of "if" nestings
4752                 // the code for the alignment was put here
4753                 // put them in their own if if this is fixed
4754                 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4755                              || t.cs() == "shadowsize"
4756                                  || t.cs() == "raggedleft" || t.cs() == "centering"
4757                          || t.cs() == "raggedright") {
4758                         if (t.cs() == "fboxrule")
4759                                 fboxrule = "";
4760                         if (t.cs() == "fboxsep")
4761                                 fboxsep = "";
4762                         if (t.cs() == "shadowsize")
4763                                 shadow_size = "";
4764                         if (t.cs() != "raggedleft" && t.cs() != "centering"
4765                          && t.cs() != "raggedright") {
4766                                 p.skip_spaces(true);
4767                                 while (p.good() && p.next_token().cat() != catSpace
4768                                        && p.next_token().cat() != catNewline
4769                                        && p.next_token().cat() != catEscape) {
4770                                         if (t.cs() == "fboxrule")
4771                                                 fboxrule = fboxrule + p.get_token().asInput();
4772                                         if (t.cs() == "fboxsep")
4773                                                 fboxsep = fboxsep + p.get_token().asInput();
4774                                         if (t.cs() == "shadowsize")
4775                                                 shadow_size = shadow_size + p.get_token().asInput();
4776                                 }
4777                         } else {
4778                                 output_ert_inset(os, t.asInput(), context);
4779                         }
4780                 }
4781
4782                 //\framebox() is part of the picture environment and different from \framebox{}
4783                 //\framebox{} will be parsed by parse_outer_box
4784                 else if (t.cs() == "framebox") {
4785                         if (p.next_token().character() == '(') {
4786                                 //the syntax is: \framebox(x,y)[position]{content}
4787                                 string arg = t.asInput();
4788                                 arg += p.getFullParentheseArg();
4789                                 arg += p.getFullOpt();
4790                                 eat_whitespace(p, os, context, false);
4791                                 output_ert_inset(os, arg + '{', context);
4792                                 parse_text(p, os, FLAG_ITEM, outer, context);
4793                                 output_ert_inset(os, "}", context);
4794                         } else {
4795                                 //the syntax is: \framebox[width][position]{content}
4796                                 string special = p.getFullOpt();
4797                                 special += p.getOpt();
4798                                 parse_outer_box(p, os, FLAG_ITEM, outer,
4799                                                     context, t.cs(), special);
4800                         }
4801                 }
4802
4803                 //\makebox() is part of the picture environment and different from \makebox{}
4804                 //\makebox{} will be parsed by parse_box
4805                 else if (t.cs() == "makebox") {
4806                         if (p.next_token().character() == '(') {
4807                                 //the syntax is: \makebox(x,y)[position]{content}
4808                                 string arg = t.asInput();
4809                                 arg += p.getFullParentheseArg();
4810                                 arg += p.getFullOpt();
4811                                 eat_whitespace(p, os, context, false);
4812                                 output_ert_inset(os, arg + '{', context);
4813                                 parse_text(p, os, FLAG_ITEM, outer, context);
4814                                 output_ert_inset(os, "}", context);
4815                         } else
4816                                 //the syntax is: \makebox[width][position]{content}
4817                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4818                                           "", "", t.cs(), "", "");
4819                 }
4820
4821                 else if (t.cs() == "smallskip" ||
4822                          t.cs() == "medskip" ||
4823                          t.cs() == "bigskip" ||
4824                          t.cs() == "vfill") {
4825                         context.check_layout(os);
4826                         begin_inset(os, "VSpace ");
4827                         os << t.cs();
4828                         end_inset(os);
4829                         skip_spaces_braces(p);
4830                 }
4831
4832                 else if ((where = is_known(t.cs(), known_spaces))) {
4833                         context.check_layout(os);
4834                         begin_inset(os, "space ");
4835                         os << '\\' << known_coded_spaces[where - known_spaces]
4836                            << '\n';
4837                         end_inset(os);
4838                         // LaTeX swallows whitespace after all spaces except
4839                         // "\\,". We have to do that here, too, because LyX
4840                         // adds "{}" which would make the spaces significant.
4841                         if (t.cs() !=  ",")
4842                                 eat_whitespace(p, os, context, false);
4843                         // LyX adds "{}" after all spaces except "\\ " and
4844                         // "\\,", so we have to remove "{}".
4845                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
4846                         // remove the braces after "\\,", too.
4847                         if (t.cs() != " ")
4848                                 skip_braces(p);
4849                 }
4850
4851                 else if (t.cs() == "newpage" ||
4852                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
4853                          t.cs() == "clearpage" ||
4854                          t.cs() == "cleardoublepage") {
4855                         context.check_layout(os);
4856                         begin_inset(os, "Newpage ");
4857                         os << t.cs();
4858                         end_inset(os);
4859                         skip_spaces_braces(p);
4860                 }
4861
4862                 else if (t.cs() == "DeclareRobustCommand" ||
4863                          t.cs() == "DeclareRobustCommandx" ||
4864                          t.cs() == "newcommand" ||
4865                          t.cs() == "newcommandx" ||
4866                          t.cs() == "providecommand" ||
4867                          t.cs() == "providecommandx" ||
4868                          t.cs() == "renewcommand" ||
4869                          t.cs() == "renewcommandx") {
4870                         // DeclareRobustCommand, DeclareRobustCommandx,
4871                         // providecommand and providecommandx could be handled
4872                         // by parse_command(), but we need to call
4873                         // add_known_command() here.
4874                         string name = t.asInput();
4875                         if (p.next_token().asInput() == "*") {
4876                                 // Starred form. Eat '*'
4877                                 p.get_token();
4878                                 name += '*';
4879                         }
4880                         string const command = p.verbatim_item();
4881                         string const opt1 = p.getFullOpt();
4882                         string const opt2 = p.getFullOpt();
4883                         add_known_command(command, opt1, !opt2.empty());
4884                         string const ert = name + '{' + command + '}' +
4885                                            opt1 + opt2 +
4886                                            '{' + p.verbatim_item() + '}';
4887
4888                         if (t.cs() == "DeclareRobustCommand" ||
4889                             t.cs() == "DeclareRobustCommandx" ||
4890                             t.cs() == "providecommand" ||
4891                             t.cs() == "providecommandx" ||
4892                             name[name.length()-1] == '*')
4893                                 output_ert_inset(os, ert, context);
4894                         else {
4895                                 context.check_layout(os);
4896                                 begin_inset(os, "FormulaMacro");
4897                                 os << "\n" << ert;
4898                                 end_inset(os);
4899                         }
4900                 }
4901
4902                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4903                         // let could be handled by parse_command(),
4904                         // but we need to call add_known_command() here.
4905                         string ert = t.asInput();
4906                         string name;
4907                         p.skip_spaces();
4908                         if (p.next_token().cat() == catBegin) {
4909                                 name = p.verbatim_item();
4910                                 ert += '{' + name + '}';
4911                         } else {
4912                                 name = p.verbatim_item();
4913                                 ert += name;
4914                         }
4915                         string command;
4916                         p.skip_spaces();
4917                         if (p.next_token().cat() == catBegin) {
4918                                 command = p.verbatim_item();
4919                                 ert += '{' + command + '}';
4920                         } else {
4921                                 command = p.verbatim_item();
4922                                 ert += command;
4923                         }
4924                         // If command is known, make name known too, to parse
4925                         // its arguments correctly. For this reason we also
4926                         // have commands in syntax.default that are hardcoded.
4927                         CommandMap::iterator it = known_commands.find(command);
4928                         if (it != known_commands.end())
4929                                 known_commands[t.asInput()] = it->second;
4930                         output_ert_inset(os, ert, context);
4931                 }
4932
4933                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4934                         if (starred)
4935                                 p.get_token();
4936                         string name = t.asInput();
4937                         string const length = p.verbatim_item();
4938                         string unit;
4939                         string valstring;
4940                         bool valid = splitLatexLength(length, valstring, unit);
4941                         bool known_hspace = false;
4942                         bool known_vspace = false;
4943                         bool known_unit = false;
4944                         double value = 0.0;
4945                         if (valid) {
4946                                 istringstream iss(valstring);
4947                                 iss >> value;
4948                                 if (value == 1.0) {
4949                                         if (t.cs()[0] == 'h') {
4950                                                 if (unit == "\\fill") {
4951                                                         if (!starred) {
4952                                                                 unit = "";
4953                                                                 name = "\\hfill";
4954                                                         }
4955                                                         known_hspace = true;
4956                                                 }
4957                                         } else {
4958                                                 if (unit == "\\smallskipamount") {
4959                                                         unit = "smallskip";
4960                                                         known_vspace = true;
4961                                                 } else if (unit == "\\medskipamount") {
4962                                                         unit = "medskip";
4963                                                         known_vspace = true;
4964                                                 } else if (unit == "\\bigskipamount") {
4965                                                         unit = "bigskip";
4966                                                         known_vspace = true;
4967                                                 } else if (unit == "\\fill") {
4968                                                         unit = "vfill";
4969                                                         known_vspace = true;
4970                                                 }
4971                                         }
4972                                 }
4973                                 if (!known_hspace && !known_vspace) {
4974                                         switch (unitFromString(unit)) {
4975                                         case Length::SP:
4976                                         case Length::PT:
4977                                         case Length::BP:
4978                                         case Length::DD:
4979                                         case Length::MM:
4980                                         case Length::PC:
4981                                         case Length::CC:
4982                                         case Length::CM:
4983                                         case Length::IN:
4984                                         case Length::EX:
4985                                         case Length::EM:
4986                                         case Length::MU:
4987                                                 known_unit = true;
4988                                                 break;
4989                                         default: {
4990                                                 //unitFromString(unit) fails for relative units like Length::PCW
4991                                                 // therefore handle them separately
4992                                                 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4993                                                         || unit == "\\textwidth" || unit == "\\linewidth"
4994                                                         || unit == "\\textheight" || unit == "\\paperheight"
4995                                                         || unit == "\\baselineskip")
4996                                                         known_unit = true;
4997                                                 break;
4998                                                          }
4999                                         }
5000                                 }
5001                         }
5002
5003                         // check for glue lengths
5004                         bool is_gluelength = false;
5005                         string gluelength = length;
5006                         string::size_type i = length.find(" minus");
5007                         if (i == string::npos) {
5008                                 i = length.find(" plus");
5009                                 if (i != string::npos)
5010                                         is_gluelength = true;
5011                         } else
5012                                 is_gluelength = true;
5013                         // if yes transform "9xx minus 8yy plus 7zz"
5014                         // to "9xx-8yy+7zz"
5015                         if (is_gluelength) {
5016                                 i = gluelength.find(" minus");
5017                                 if (i != string::npos)
5018                                         gluelength.replace(i, 7, "-");
5019                                 i = gluelength.find(" plus");
5020                                 if (i != string::npos)
5021                                         gluelength.replace(i, 6, "+");
5022                         }
5023
5024                         if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5025                                 // Literal horizontal length or known variable
5026                                 context.check_layout(os);
5027                                 begin_inset(os, "space ");
5028                                 os << name;
5029                                 if (starred)
5030                                         os << '*';
5031                                 os << '{';
5032                                 if (known_hspace)
5033                                         os << unit;
5034                                 os << "}";
5035                                 if (known_unit && !known_hspace)
5036                                         os << "\n\\length " << translate_len(length);
5037                                 if (is_gluelength)
5038                                         os << "\n\\length " << gluelength;
5039                                 end_inset(os);
5040                         } else if (known_unit || known_vspace || is_gluelength) {
5041                                 // Literal vertical length or known variable
5042                                 context.check_layout(os);
5043                                 begin_inset(os, "VSpace ");
5044                                 if (known_vspace)
5045                                         os << unit;
5046                                 if (known_unit && !known_vspace)
5047                                         os << translate_len(length);
5048                                 if (is_gluelength)
5049                                         os << gluelength;
5050                                 if (starred)
5051                                         os << '*';
5052                                 end_inset(os);
5053                         } else {
5054                                 // LyX can't handle other length variables in Inset VSpace/space
5055                                 if (starred)
5056                                         name += '*';
5057                                 if (valid) {
5058                                         if (value == 1.0)
5059                                                 output_ert_inset(os, name + '{' + unit + '}', context);
5060                                         else if (value == -1.0)
5061                                                 output_ert_inset(os, name + "{-" + unit + '}', context);
5062                                         else
5063                                                 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5064                                 } else
5065                                         output_ert_inset(os, name + '{' + length + '}', context);
5066                         }
5067                 }
5068
5069                 // The single '=' is meant here.
5070                 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5071                         if (starred)
5072                                 p.get_token();
5073                         p.skip_spaces();
5074                         context.check_layout(os);
5075                         docstring name = newinsetlayout->name();
5076                         bool const caption = name.find(from_ascii("Caption:")) == 0;
5077                         if (caption) {
5078                                 // Already done for floating minted listings.
5079                                 if (minted_float.empty()) {
5080                                         begin_inset(os, "Caption ");
5081                                         os << to_utf8(name.substr(8)) << '\n';
5082                                 }
5083                         } else {
5084                                 // FIXME: what do we do if the prefix is not Flex: ?
5085                                 if (prefixIs(name, from_ascii("Flex:")))
5086                                         name.erase(0, 5);
5087                                 begin_inset(os, "Flex ");
5088                                 os << to_utf8(name) << '\n'
5089                                    << "status collapsed\n";
5090                         }
5091                         if (!minted_float.empty()) {
5092                                 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5093                         } else if (newinsetlayout->isPassThru()) {
5094                                 // set catcodes to verbatim early, just in case.
5095                                 p.setCatcodes(VERBATIM_CATCODES);
5096                                 string delim = p.get_token().asInput();
5097                                 if (delim != "{")
5098                                         cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5099                                 //FIXME: handle error condition
5100                                 string const arg = p.verbatimStuff("}").second;
5101                                 Context newcontext(true, context.textclass);
5102                                 if (newinsetlayout->forcePlainLayout())
5103                                         newcontext.layout = &context.textclass.plainLayout();
5104                                 output_ert(os, arg, newcontext);
5105                         } else
5106                                 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5107                         if (caption)
5108                                 p.skip_spaces();
5109                         // Minted caption insets are not closed here because
5110                         // we collect everything into the caption.
5111                         if (minted_float.empty())
5112                                 end_inset(os);
5113                 }
5114
5115                 else if (t.cs() == "includepdf") {
5116                         p.skip_spaces();
5117                         string const arg = p.getArg('[', ']');
5118                         map<string, string> opts;
5119                         vector<string> keys;
5120                         split_map(arg, opts, keys);
5121                         string name = normalize_filename(p.verbatim_item());
5122                         string const path = getMasterFilePath(true);
5123                         // We want to preserve relative / absolute filenames,
5124                         // therefore path is only used for testing
5125                         if (!makeAbsPath(name, path).exists()) {
5126                                 // The file extension is probably missing.
5127                                 // Now try to find it out.
5128                                 char const * const pdfpages_format[] = {"pdf", 0};
5129                                 string const pdftex_name =
5130                                         find_file(name, path, pdfpages_format);
5131                                 if (!pdftex_name.empty()) {
5132                                         name = pdftex_name;
5133                                         pdflatex = true;
5134                                 }
5135                         }
5136                         FileName const absname = makeAbsPath(name, path);
5137                         if (absname.exists())
5138                         {
5139                                 fix_child_filename(name);
5140                                 copy_file(absname, name);
5141                         } else
5142                                 cerr << "Warning: Could not find file '"
5143                                      << name << "'." << endl;
5144                         // write output
5145                         context.check_layout(os);
5146                         begin_inset(os, "External\n\ttemplate ");
5147                         os << "PDFPages\n\tfilename "
5148                            << name << "\n";
5149                         // parse the options
5150                         if (opts.find("pages") != opts.end())
5151                                 os << "\textra LaTeX \"pages="
5152                                    << opts["pages"] << "\"\n";
5153                         if (opts.find("angle") != opts.end())
5154                                 os << "\trotateAngle "
5155                                    << opts["angle"] << '\n';
5156                         if (opts.find("origin") != opts.end()) {
5157                                 ostringstream ss;
5158                                 string const opt = opts["origin"];
5159                                 if (opt == "tl") ss << "topleft";
5160                                 if (opt == "bl") ss << "bottomleft";
5161                                 if (opt == "Bl") ss << "baselineleft";
5162                                 if (opt == "c") ss << "center";
5163                                 if (opt == "tc") ss << "topcenter";
5164                                 if (opt == "bc") ss << "bottomcenter";
5165                                 if (opt == "Bc") ss << "baselinecenter";
5166                                 if (opt == "tr") ss << "topright";
5167                                 if (opt == "br") ss << "bottomright";
5168                                 if (opt == "Br") ss << "baselineright";
5169                                 if (!ss.str().empty())
5170                                         os << "\trotateOrigin " << ss.str() << '\n';
5171                                 else
5172                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5173                         }
5174                         if (opts.find("width") != opts.end())
5175                                 os << "\twidth "
5176                                    << translate_len(opts["width"]) << '\n';
5177                         if (opts.find("height") != opts.end())
5178                                 os << "\theight "
5179                                    << translate_len(opts["height"]) << '\n';
5180                         if (opts.find("keepaspectratio") != opts.end())
5181                                 os << "\tkeepAspectRatio\n";
5182                         end_inset(os);
5183                         context.check_layout(os);
5184                         registerExternalTemplatePackages("PDFPages");
5185                 }
5186
5187                 else if (t.cs() == "loadgame") {
5188                         p.skip_spaces();
5189                         string name = normalize_filename(p.verbatim_item());
5190                         string const path = getMasterFilePath(true);
5191                         // We want to preserve relative / absolute filenames,
5192                         // therefore path is only used for testing
5193                         if (!makeAbsPath(name, path).exists()) {
5194                                 // The file extension is probably missing.
5195                                 // Now try to find it out.
5196                                 char const * const lyxskak_format[] = {"fen", 0};
5197                                 string const lyxskak_name =
5198                                         find_file(name, path, lyxskak_format);
5199                                 if (!lyxskak_name.empty())
5200                                         name = lyxskak_name;
5201                         }
5202                         FileName const absname = makeAbsPath(name, path);
5203                         if (absname.exists())
5204                         {
5205                                 fix_child_filename(name);
5206                                 copy_file(absname, name);
5207                         } else
5208                                 cerr << "Warning: Could not find file '"
5209                                      << name << "'." << endl;
5210                         context.check_layout(os);
5211                         begin_inset(os, "External\n\ttemplate ");
5212                         os << "ChessDiagram\n\tfilename "
5213                            << name << "\n";
5214                         end_inset(os);
5215                         context.check_layout(os);
5216                         // after a \loadgame follows a \showboard
5217                         if (p.get_token().asInput() == "showboard")
5218                                 p.get_token();
5219                         registerExternalTemplatePackages("ChessDiagram");
5220                 }
5221
5222                 else {
5223                         // try to see whether the string is in unicodesymbols
5224                         // Only use text mode commands, since we are in text mode here,
5225                         // and math commands may be invalid (bug 6797)
5226                         string name = t.asInput();
5227                         // handle the dingbats, cyrillic and greek
5228                         if (name == "\\ding" || name == "\\textcyr" ||
5229                             (name == "\\textgreek" && !preamble.usePolyglossia()))
5230                                 name = name + '{' + p.getArg('{', '}') + '}';
5231                         // handle the ifsym characters
5232                         else if (name == "\\textifsymbol") {
5233                                 string const optif = p.getFullOpt();
5234                                 string const argif = p.getArg('{', '}');
5235                                 name = name + optif + '{' + argif + '}';
5236                         }
5237                         // handle the \ascii characters
5238                         // the case of \ascii within braces, as LyX outputs it, is already
5239                         // handled for t.cat() == catBegin
5240                         else if (name == "\\ascii") {
5241                                 // the code is "\asci\xxx"
5242                                 name = "{" + name + p.get_token().asInput() + "}";
5243                                 skip_braces(p);
5244                         }
5245                         // handle some TIPA special characters
5246                         else if (preamble.isPackageUsed("tipa")) {
5247                                 if (name == "\\s") {
5248                                         // fromLaTeXCommand() does not yet
5249                                         // recognize tipa short cuts
5250                                         name = "\\textsyllabic";
5251                                 } else if (name == "\\=" &&
5252                                            p.next_token().asInput() == "*") {
5253                                         // fromLaTeXCommand() does not yet
5254                                         // recognize tipa short cuts
5255                                         p.get_token();
5256                                         name = "\\textsubbar";
5257                                 } else if (name == "\\textdoublevertline") {
5258                                         // FIXME: This is not correct,
5259                                         // \textvertline is higher than \textbardbl
5260                                         name = "\\textbardbl";
5261                                         skip_braces(p);
5262                                 } else if (name == "\\!" ) {
5263                                         if (p.next_token().asInput() == "b") {
5264                                                 p.get_token();  // eat 'b'
5265                                                 name = "\\texthtb";
5266                                                 skip_braces(p);
5267                                         } else if (p.next_token().asInput() == "d") {
5268                                                 p.get_token();
5269                                                 name = "\\texthtd";
5270                                                 skip_braces(p);
5271                                         } else if (p.next_token().asInput() == "g") {
5272                                                 p.get_token();
5273                                                 name = "\\texthtg";
5274                                                 skip_braces(p);
5275                                         } else if (p.next_token().asInput() == "G") {
5276                                                 p.get_token();
5277                                                 name = "\\texthtscg";
5278                                                 skip_braces(p);
5279                                         } else if (p.next_token().asInput() == "j") {
5280                                                 p.get_token();
5281                                                 name = "\\texthtbardotlessj";
5282                                                 skip_braces(p);
5283                                         } else if (p.next_token().asInput() == "o") {
5284                                                 p.get_token();
5285                                                 name = "\\textbullseye";
5286                                                 skip_braces(p);
5287                                         }
5288                                 } else if (name == "\\*" ) {
5289                                         if (p.next_token().asInput() == "k") {
5290                                                 p.get_token();
5291                                                 name = "\\textturnk";
5292                                                 skip_braces(p);
5293                                         } else if (p.next_token().asInput() == "r") {
5294                                                 p.get_token();  // eat 'b'
5295                                                 name = "\\textturnr";
5296                                                 skip_braces(p);
5297                                         } else if (p.next_token().asInput() == "t") {
5298                                                 p.get_token();
5299                                                 name = "\\textturnt";
5300                                                 skip_braces(p);
5301                                         } else if (p.next_token().asInput() == "w") {
5302                                                 p.get_token();
5303                                                 name = "\\textturnw";
5304                                                 skip_braces(p);
5305                                         }
5306                                 }
5307                         }
5308                         if ((name.size() == 2 &&
5309                              contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5310                              p.next_token().asInput() != "*") ||
5311                             is_known(name.substr(1), known_tipa_marks)) {
5312                                 // name is a command that corresponds to a
5313                                 // combining character in unicodesymbols.
5314                                 // Append the argument, fromLaTeXCommand()
5315                                 // will either convert it to a single
5316                                 // character or a combining sequence.
5317                                 name += '{' + p.verbatim_item() + '}';
5318                         }
5319                         // now get the character from unicodesymbols
5320                         bool termination;
5321                         docstring rem;
5322                         set<string> req;
5323                         docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5324                                         Encodings::TEXT_CMD, termination, rem, &req));
5325                         if (!s.empty()) {
5326                                 context.check_layout(os);
5327                                 os << to_utf8(s);
5328                                 if (!rem.empty())
5329                                         output_ert_inset(os, to_utf8(rem), context);
5330                                 if (termination)
5331                                         skip_spaces_braces(p);
5332                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5333                                         preamble.registerAutomaticallyLoadedPackage(*it);
5334                         }
5335                         //cerr << "#: " << t << " mode: " << mode << endl;
5336                         // heuristic: read up to next non-nested space
5337                         /*
5338                         string s = t.asInput();
5339                         string z = p.verbatim_item();
5340                         while (p.good() && z != " " && !z.empty()) {
5341                                 //cerr << "read: " << z << endl;
5342                                 s += z;
5343                                 z = p.verbatim_item();
5344                         }
5345                         cerr << "found ERT: " << s << endl;
5346                         output_ert_inset(os, s + ' ', context);
5347                         */
5348                         else {
5349                                 if (t.asInput() == name &&
5350                                     p.next_token().asInput() == "*") {
5351                                         // Starred commands like \vspace*{}
5352                                         p.get_token();  // Eat '*'
5353                                         name += '*';
5354                                 }
5355                                 if (!parse_command(name, p, os, outer, context))
5356                                         output_ert_inset(os, name, context);
5357                         }
5358                 }
5359
5360                 if (flags & FLAG_LEAVE) {
5361                         flags &= ~FLAG_LEAVE;
5362                         break;
5363                 }
5364         }
5365 }
5366
5367
5368 string guessLanguage(Parser & p, string const & lang)
5369 {
5370         typedef std::map<std::string, size_t> LangMap;
5371         // map from language names to number of characters
5372         LangMap used;
5373         used[lang] = 0;
5374         for (char const * const * i = supported_CJK_languages; *i; i++)
5375                 used[string(*i)] = 0;
5376
5377         while (p.good()) {
5378                 Token const t = p.get_token();
5379                 // comments are not counted for any language
5380                 if (t.cat() == catComment)
5381                         continue;
5382                 // commands are not counted as well, but we need to detect
5383                 // \begin{CJK} and switch encoding if needed
5384                 if (t.cat() == catEscape) {
5385                         if (t.cs() == "inputencoding") {
5386                                 string const enc = subst(p.verbatim_item(), "\n", " ");
5387                                 p.setEncoding(enc, Encoding::inputenc);
5388                                 continue;
5389                         }
5390                         if (t.cs() != "begin")
5391                                 continue;
5392                 } else {
5393                         // Non-CJK content is counted for lang.
5394                         // We do not care about the real language here:
5395                         // If we have more non-CJK contents than CJK contents,
5396                         // we simply use the language that was specified as
5397                         // babel main language.
5398                         used[lang] += t.asInput().length();
5399                         continue;
5400                 }
5401                 // Now we are starting an environment
5402                 p.pushPosition();
5403                 string const name = p.getArg('{', '}');
5404                 if (name != "CJK") {
5405                         p.popPosition();
5406                         continue;
5407                 }
5408                 // It is a CJK environment
5409                 p.popPosition();
5410                 /* name = */ p.getArg('{', '}');
5411                 string const encoding = p.getArg('{', '}');
5412                 /* mapping = */ p.getArg('{', '}');
5413                 string const encoding_old = p.getEncoding();
5414                 char const * const * const where =
5415                         is_known(encoding, supported_CJK_encodings);
5416                 if (where)
5417                         p.setEncoding(encoding, Encoding::CJK);
5418                 else
5419                         p.setEncoding("UTF-8");
5420                 string const text = p.ertEnvironment("CJK");
5421                 p.setEncoding(encoding_old);
5422                 p.skip_spaces();
5423                 if (!where) {
5424                         // ignore contents in unknown CJK encoding
5425                         continue;
5426                 }
5427                 // the language of the text
5428                 string const cjk =
5429                         supported_CJK_languages[where - supported_CJK_encodings];
5430                 used[cjk] += text.length();
5431         }
5432         LangMap::const_iterator use = used.begin();
5433         for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5434                 if (it->second > use->second)
5435                         use = it;
5436         }
5437         return use->first;
5438 }
5439
5440
5441 void check_comment_bib(ostream & os, Context & context)
5442 {
5443         if (!need_commentbib)
5444                 return;
5445         // We have a bibliography database, but no bibliography with biblatex
5446         // which is completely valid. Insert a bibtex inset in a note.
5447         context.check_layout(os);
5448         begin_inset(os, "Note Note\n");
5449         os << "status open\n";
5450         os << "\\begin_layout Plain Layout\n";
5451         begin_command_inset(os, "bibtex", "bibtex");
5452         string bibfiles;
5453         for (auto const & bf : preamble.biblatex_bibliographies) {
5454                 if (!bibfiles.empty())
5455                         bibfiles += ",";
5456                 bibfiles += normalize_filename(bf);
5457         }
5458         if (!bibfiles.empty())
5459                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5460         end_inset(os);// Bibtex
5461         os << "\\end_layout\n";
5462         end_inset(os);// Note
5463 }
5464
5465 // }])
5466
5467
5468 } // namespace lyx