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