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