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