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