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