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