]> git.lyx.org Git - features.git/blob - src/tex2lyx/text.cpp
tex2lyx: support for btUnit (multibib)
[features.git] / src / tex2lyx / text.cpp
1 /**
2  * \file tex2lyx/text.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Jean-Marc Lasgouttes
8  * \author Uwe Stöhr
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 // {[(
14
15 #include <config.h>
16
17 #include "tex2lyx.h"
18
19 #include "Context.h"
20 #include "Encoding.h"
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
23 #include "Layout.h"
24 #include "Length.h"
25 #include "Preamble.h"
26
27 #include "insets/ExternalTemplate.h"
28
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
35
36 #include <algorithm>
37 #include <iostream>
38 #include <map>
39 #include <sstream>
40 #include <vector>
41
42 using namespace std;
43 using namespace lyx::support;
44
45 namespace lyx {
46
47
48 namespace {
49
50 void output_arguments(ostream &, Parser &, bool, bool, string, Context &,
51                       Layout::LaTeXArgMap const &);
52
53 }
54
55
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57                 Context const & context, InsetLayout const * layout,
58                 string const rdelim)
59 {
60         bool const forcePlainLayout =
61                 layout ? layout->forcePlainLayout() : false;
62         Context newcontext(true, context.textclass);
63         if (forcePlainLayout)
64                 newcontext.layout = &context.textclass.plainLayout();
65         else
66                 newcontext.font = context.font;
67         if (layout)
68                 output_arguments(os, p, outer, false, string(), newcontext,
69                                  layout->latexargs());
70         // 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         if (is_math_env(name)) {
1587                 parent_context.check_layout(os);
1588                 begin_inset(os, "Formula ");
1589                 os << "\\begin{" << name << "}";
1590                 parse_math(p, os, FLAG_END, MATH_MODE);
1591                 os << "\\end{" << name << "}";
1592                 end_inset(os);
1593                 if (is_display_math_env(name)) {
1594                         // Prevent the conversion of a line break to a space
1595                         // (bug 7668). This does not change the output, but
1596                         // looks ugly in LyX.
1597                         eat_whitespace(p, os, parent_context, false);
1598                 }
1599         }
1600
1601         else if (is_known(name, preamble.polyglossia_languages)) {
1602                 // We must begin a new paragraph if not already done
1603                 if (! parent_context.atParagraphStart()) {
1604                         parent_context.check_end_layout(os);
1605                         parent_context.new_paragraph(os);
1606                 }
1607                 // save the language in the context so that it is
1608                 // handled by parse_text
1609                 parent_context.font.language = preamble.polyglossia2lyx(name);
1610                 parse_text(p, os, FLAG_END, outer, parent_context);
1611                 // Just in case the environment is empty
1612                 parent_context.extra_stuff.erase();
1613                 // We must begin a new paragraph to reset the language
1614                 parent_context.new_paragraph(os);
1615                 p.skip_spaces();
1616         }
1617
1618         else if (unstarred_name == "tabular" || name == "longtable"
1619                  || name == "tabularx" || name == "xltabular") {
1620                 eat_whitespace(p, os, parent_context, false);
1621                 string width = "0pt";
1622                 string halign;
1623                 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1624                         string const opt = p.getArg('[', ']');
1625                         if (opt == "c")
1626                                 halign = "center";
1627                         else if (opt == "l")
1628                                 halign = "left";
1629                         else if (opt == "r")
1630                                 halign = "right";
1631                 }
1632                 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1633                         width = lyx::translate_len(p.getArg('{', '}'));
1634                         eat_whitespace(p, os, parent_context, false);
1635                 }
1636                 parent_context.check_layout(os);
1637                 begin_inset(os, "Tabular ");
1638                 handle_tabular(p, os, name, width, halign, parent_context);
1639                 end_inset(os);
1640                 p.skip_spaces();
1641         }
1642
1643         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1644                 eat_whitespace(p, os, parent_context, false);
1645                 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1646                 eat_whitespace(p, os, parent_context, false);
1647                 parent_context.check_layout(os);
1648                 begin_inset(os, "Float " + unstarred_name + "\n");
1649                 // store the float type for subfloats
1650                 // subfloats only work with figures and tables
1651                 if (unstarred_name == "figure")
1652                         float_type = unstarred_name;
1653                 else if (unstarred_name == "table")
1654                         float_type = unstarred_name;
1655                 else
1656                         float_type = "";
1657                 if (!opt.empty())
1658                         os << "placement " << opt << '\n';
1659                 if (contains(opt, "H"))
1660                         preamble.registerAutomaticallyLoadedPackage("float");
1661                 else {
1662                         Floating const & fl = parent_context.textclass.floats()
1663                                               .getType(unstarred_name);
1664                         if (!fl.floattype().empty() && fl.usesFloatPkg())
1665                                 preamble.registerAutomaticallyLoadedPackage("float");
1666                 }
1667
1668                 os << "wide " << convert<string>(is_starred)
1669                    << "\nsideways false"
1670                    << "\nstatus open\n\n";
1671                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1672                 end_inset(os);
1673                 // We don't need really a new paragraph, but
1674                 // we must make sure that the next item gets a \begin_layout.
1675                 parent_context.new_paragraph(os);
1676                 p.skip_spaces();
1677                 // the float is parsed thus delete the type
1678                 float_type = "";
1679         }
1680
1681         else if (unstarred_name == "sidewaysfigure"
1682                 || unstarred_name == "sidewaystable"
1683                 || unstarred_name == "sidewaysalgorithm") {
1684                 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1685                 eat_whitespace(p, os, parent_context, false);
1686                 parent_context.check_layout(os);
1687                 if (unstarred_name == "sidewaysfigure")
1688                         begin_inset(os, "Float figure\n");
1689                 else if (unstarred_name == "sidewaystable")
1690                         begin_inset(os, "Float table\n");
1691                 else if (unstarred_name == "sidewaysalgorithm")
1692                         begin_inset(os, "Float algorithm\n");
1693                 if (!opt.empty())
1694                         os << "placement " << opt << '\n';
1695                 if (contains(opt, "H"))
1696                         preamble.registerAutomaticallyLoadedPackage("float");
1697                 os << "wide " << convert<string>(is_starred)
1698                    << "\nsideways true"
1699                    << "\nstatus open\n\n";
1700                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1701                 end_inset(os);
1702                 // We don't need really a new paragraph, but
1703                 // we must make sure that the next item gets a \begin_layout.
1704                 parent_context.new_paragraph(os);
1705                 p.skip_spaces();
1706                 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1707         }
1708
1709         else if (name == "wrapfigure" || name == "wraptable") {
1710                 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1711                 eat_whitespace(p, os, parent_context, false);
1712                 parent_context.check_layout(os);
1713                 // default values
1714                 string lines = "0";
1715                 string overhang = "0col%";
1716                 // parse
1717                 if (p.hasOpt())
1718                         lines = p.getArg('[', ']');
1719                 string const placement = p.getArg('{', '}');
1720                 if (p.hasOpt())
1721                         overhang = p.getArg('[', ']');
1722                 string const width = p.getArg('{', '}');
1723                 // write
1724                 if (name == "wrapfigure")
1725                         begin_inset(os, "Wrap figure\n");
1726                 else
1727                         begin_inset(os, "Wrap table\n");
1728                 os << "lines " << lines
1729                    << "\nplacement " << placement
1730                    << "\noverhang " << lyx::translate_len(overhang)
1731                    << "\nwidth " << lyx::translate_len(width)
1732                    << "\nstatus open\n\n";
1733                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1734                 end_inset(os);
1735                 // We don't need really a new paragraph, but
1736                 // we must make sure that the next item gets a \begin_layout.
1737                 parent_context.new_paragraph(os);
1738                 p.skip_spaces();
1739                 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1740         }
1741
1742         else if (name == "minipage") {
1743                 eat_whitespace(p, os, parent_context, false);
1744                 // Test whether this is an outer box of a shaded box
1745                 p.pushPosition();
1746                 // swallow arguments
1747                 while (p.hasOpt()) {
1748                         p.getArg('[', ']');
1749                         p.skip_spaces(true);
1750                 }
1751                 p.getArg('{', '}');
1752                 p.skip_spaces(true);
1753                 Token t = p.get_token();
1754                 bool shaded = false;
1755                 if (t.asInput() == "\\begin") {
1756                         p.skip_spaces(true);
1757                         if (p.getArg('{', '}') == "shaded")
1758                                 shaded = true;
1759                 }
1760                 p.popPosition();
1761                 if (shaded)
1762                         parse_outer_box(p, os, FLAG_END, outer,
1763                                         parent_context, name, "shaded");
1764                 else
1765                         parse_box(p, os, 0, FLAG_END, outer, parent_context,
1766                                   "", "", name, "", "");
1767                 p.skip_spaces();
1768         }
1769
1770         else if (name == "comment") {
1771                 eat_whitespace(p, os, parent_context, false);
1772                 parent_context.check_layout(os);
1773                 begin_inset(os, "Note Comment\n");
1774                 os << "status open\n";
1775                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1776                 end_inset(os);
1777                 p.skip_spaces();
1778                 skip_braces(p); // eat {} that might by set by LyX behind comments
1779                 preamble.registerAutomaticallyLoadedPackage("verbatim");
1780         }
1781
1782         else if (unstarred_name == "verbatim") {
1783                 // FIXME: this should go in the generic code that
1784                 // handles environments defined in layout file that
1785                 // have "PassThru 1". However, the code over there is
1786                 // already too complicated for my taste.
1787                 string const ascii_name =
1788                         (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1789                 parent_context.new_paragraph(os);
1790                 Context context(true, parent_context.textclass,
1791                                 &parent_context.textclass[from_ascii(ascii_name)]);
1792                 string s = p.verbatimEnvironment(name);
1793                 output_ert(os, s, context);
1794                 p.skip_spaces();
1795         }
1796
1797         else if (name == "IPA") {
1798                 eat_whitespace(p, os, parent_context, false);
1799                 parent_context.check_layout(os);
1800                 begin_inset(os, "IPA\n");
1801                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1802                 end_inset(os);
1803                 p.skip_spaces();
1804                 preamble.registerAutomaticallyLoadedPackage("tipa");
1805                 preamble.registerAutomaticallyLoadedPackage("tipx");
1806         }
1807         
1808         else if (name == parent_context.textclass.titlename()
1809                  && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1810                         parse_text(p, os, FLAG_END, outer, parent_context);
1811                         // Just in case the environment is empty
1812                         parent_context.extra_stuff.erase();
1813                         // We must begin a new paragraph
1814                         parent_context.new_paragraph(os);
1815                         p.skip_spaces();
1816         }
1817
1818         else if (name == "CJK") {
1819                 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1820                 // It is impossible to decide if a CJK environment was in its own paragraph or within
1821                 // a line. We therefore always assume a paragraph since the latter is a rare case.
1822                 eat_whitespace(p, os, parent_context, false);
1823                 parent_context.check_end_layout(os);
1824                 // store the encoding to be able to reset it
1825                 string const encoding_old = p.getEncoding();
1826                 string const encoding = p.getArg('{', '}');
1827                 // FIXME: For some reason JIS does not work. Although the text
1828                 // in tests/CJK.tex is identical with the SJIS version if you
1829                 // convert both snippets using the recode command line utility,
1830                 // the resulting .lyx file contains some extra characters if
1831                 // you set buggy_encoding to false for JIS.
1832                 bool const buggy_encoding = encoding == "JIS";
1833                 if (!buggy_encoding)
1834                         p.setEncoding(encoding, Encoding::CJK);
1835                 else {
1836                         // FIXME: This will read garbage, since the data is not encoded in utf8.
1837                         p.setEncoding("UTF-8");
1838                 }
1839                 // LyX only supports the same mapping for all CJK
1840                 // environments, so we might need to output everything as ERT
1841                 string const mapping = trim(p.getArg('{', '}'));
1842                 char const * const * const where =
1843                         is_known(encoding, supported_CJK_encodings);
1844                 if (!buggy_encoding && !preamble.fontCJKSet())
1845                         preamble.fontCJK(mapping);
1846                 bool knownMapping = mapping == preamble.fontCJK();
1847                 if (buggy_encoding || !knownMapping || !where) {
1848                         parent_context.check_layout(os);
1849                         output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1850                                        parent_context);
1851                         // we must parse the content as verbatim because e.g. JIS can contain
1852                         // normally invalid characters
1853                         // FIXME: This works only for the most simple cases.
1854                         //        Since TeX control characters are not parsed,
1855                         //        things like comments are completely wrong.
1856                         string const s = p.plainEnvironment("CJK");
1857                         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1858                                 string snip;
1859                                 snip += *it;
1860                                 if (snip == "\\" || is_known(snip, known_escaped_chars))
1861                                         output_ert_inset(os, snip, parent_context);
1862                                 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1863                                         os << "\n ";
1864                                 else
1865                                         os << *it;
1866                         }
1867                         output_ert_inset(os, "\\end{" + name + "}",
1868                                        parent_context);
1869                 } else {
1870                         string const lang =
1871                                 supported_CJK_languages[where - supported_CJK_encodings];
1872                         // store the language because we must reset it at the end
1873                         string const lang_old = parent_context.font.language;
1874                         parent_context.font.language = lang;
1875                         parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1876                         parent_context.font.language = lang_old;
1877                         parent_context.new_paragraph(os);
1878                 }
1879                 p.setEncoding(encoding_old);
1880                 p.skip_spaces();
1881         }
1882
1883         else if (name == "lyxgreyedout") {
1884                 eat_whitespace(p, os, parent_context, false);
1885                 parent_context.check_layout(os);
1886                 begin_inset(os, "Note Greyedout\n");
1887                 os << "status open\n";
1888                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1889                 end_inset(os);
1890                 p.skip_spaces();
1891                 if (!preamble.notefontcolor().empty())
1892                         preamble.registerAutomaticallyLoadedPackage("color");
1893         }
1894
1895         else if (name == "btSect") {
1896                 eat_whitespace(p, os, parent_context, false);
1897                 parent_context.check_layout(os);
1898                 begin_command_inset(os, "bibtex", "bibtex");
1899                 string bibstyle = "plain";
1900                 if (p.hasOpt()) {
1901                         bibstyle = p.getArg('[', ']');
1902                         p.skip_spaces(true);
1903                 }
1904                 string const bibfile = p.getArg('{', '}');
1905                 eat_whitespace(p, os, parent_context, false);
1906                 Token t = p.get_token();
1907                 if (t.asInput() == "\\btPrintCited") {
1908                         p.skip_spaces(true);
1909                         os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1910                 }
1911                 if (t.asInput() == "\\btPrintNotCited") {
1912                         p.skip_spaces(true);
1913                         os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1914                 }
1915                 if (t.asInput() == "\\btPrintAll") {
1916                         p.skip_spaces(true);
1917                         os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1918                 }
1919                 os << "bibfiles " << '"' << bibfile << "\"\n"
1920                    << "options " << '"' << bibstyle << "\"\n";
1921                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1922                 end_inset(os);
1923                 p.skip_spaces();
1924         }
1925
1926         else if (name == "btUnit") {
1927                 string const nt = p.next_next_token().cs();
1928                 active_environments.push_back("btUnit");
1929                 if (nt == "part")
1930                         preamble.multibib("part");
1931                 else if (nt == "chapter")
1932                         preamble.multibib("chapter");
1933                 else if (nt == "section")
1934                         preamble.multibib("section");
1935                 else if (nt == "subsection")
1936                         preamble.multibib("subsection");
1937                 else {
1938                         parse_unknown_environment(p, name, os, FLAG_END, outer,
1939                                                   parent_context);
1940                         active_environments.pop_back();
1941                 }
1942         }
1943
1944         else if (name == "framed" || name == "shaded") {
1945                 eat_whitespace(p, os, parent_context, false);
1946                 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1947                 p.skip_spaces();
1948                 preamble.registerAutomaticallyLoadedPackage("framed");
1949         }
1950
1951         else if (name == "listing") {
1952                 minted_float = "float";
1953                 eat_whitespace(p, os, parent_context, false);
1954                 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1955                 if (!opt.empty())
1956                         minted_float += "=" + opt;
1957                 // If something precedes \begin{minted}, we output it at the end
1958                 // as a caption, in order to keep it inside the listings inset.
1959                 eat_whitespace(p, os, parent_context, true);
1960                 p.pushPosition();
1961                 Token const & t = p.get_token();
1962                 p.skip_spaces(true);
1963                 string const envname = p.next_token().cat() == catBegin
1964                                                 ? p.getArg('{', '}') : string();
1965                 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1966                 p.popPosition();
1967                 minted_float_has_caption = false;
1968                 string content = parse_text_snippet(p, FLAG_END, outer,
1969                                                     parent_context);
1970                 size_t i = content.find("\\begin_inset listings");
1971                 bool minted_env = i != string::npos;
1972                 string caption;
1973                 if (prologue) {
1974                         caption = content.substr(0, i);
1975                         content.erase(0, i);
1976                 }
1977                 parent_context.check_layout(os);
1978                 if (minted_env && minted_float_has_caption) {
1979                         eat_whitespace(p, os, parent_context, true);
1980                         os << content << "\n";
1981                         if (!caption.empty())
1982                                 os << caption << "\n";
1983                         os << "\n\\end_layout\n"; // close inner layout
1984                         end_inset(os);            // close caption inset
1985                         os << "\n\\end_layout\n"; // close outer layout
1986                 } else if (!caption.empty()) {
1987                         if (!minted_env) {
1988                                 begin_inset(os, "listings\n");
1989                                 os << "lstparams " << '"' << minted_float << '"' << '\n';
1990                                 os << "inline false\n";
1991                                 os << "status collapsed\n";
1992                         }
1993                         os << "\n\\begin_layout Plain Layout\n";
1994                         begin_inset(os, "Caption Standard\n");
1995                         Context newcontext(true, parent_context.textclass,
1996                                            0, 0, parent_context.font);
1997                         newcontext.check_layout(os);
1998                         os << caption << "\n";
1999                         newcontext.check_end_layout(os);
2000                         end_inset(os);
2001                         os << "\n\\end_layout\n";
2002                 } else if (content.empty()) {
2003                         begin_inset(os, "listings\n");
2004                         os << "lstparams " << '"' << minted_float << '"' << '\n';
2005                         os << "inline false\n";
2006                         os << "status collapsed\n";
2007                 } else {
2008                         os << content << "\n";
2009                 }
2010                 end_inset(os); // close listings inset
2011                 parent_context.check_end_layout(os);
2012                 parent_context.new_paragraph(os);
2013                 p.skip_spaces();
2014                 minted_float.clear();
2015                 minted_float_has_caption = false;
2016         }
2017
2018         else if (name == "lstlisting" || name == "minted") {
2019                 bool use_minted = name == "minted";
2020                 // with listings, we do not eat newlines here since
2021                 // \begin{lstlistings}
2022                 // [foo]
2023                 // and
2024                 // // \begin{lstlistings}%
2025                 //
2026                 // [foo]
2027                 // reads [foo] as content, whereas
2028                 // // \begin{lstlistings}%
2029                 // [foo]
2030                 // or
2031                 // \begin{lstlistings}[foo,
2032                 // bar]
2033                 // reads [foo...] as argument.
2034                 eat_whitespace(p, os, parent_context, false, use_minted);
2035                 if (use_minted && minted_float.empty()) {
2036                         // look ahead for a bottom caption
2037                         p.pushPosition();
2038                         bool found_end_minted = false;
2039                         while (!found_end_minted && p.good()) {
2040                                 Token const & t = p.get_token();
2041                                 p.skip_spaces();
2042                                 string const envname =
2043                                         p.next_token().cat() == catBegin
2044                                                 ? p.getArg('{', '}') : string();
2045                                 found_end_minted = t.asInput() == "\\end"
2046                                                         && envname == "minted";
2047                         }
2048                         eat_whitespace(p, os, parent_context, true);
2049                         Token const & t = p.get_token();
2050                         p.skip_spaces(true);
2051                         if (t.asInput() == "\\lyxmintcaption") {
2052                                 string const pos = p.getArg('[', ']');
2053                                 if (pos == "b") {
2054                                         string const caption =
2055                                                 parse_text_snippet(p, FLAG_ITEM,
2056                                                         false, parent_context);
2057                                         minted_nonfloat_caption = "[b]" + caption;
2058                                         eat_whitespace(p, os, parent_context, true);
2059                                 }
2060                         }
2061                         p.popPosition();
2062                 }
2063                 parse_listings(p, os, parent_context, false, use_minted);
2064                 p.skip_spaces();
2065         }
2066
2067         else if (!parent_context.new_layout_allowed)
2068                 parse_unknown_environment(p, name, os, FLAG_END, outer,
2069                                           parent_context);
2070
2071         // Alignment and spacing settings
2072         // FIXME (bug xxxx): These settings can span multiple paragraphs and
2073         //                                       therefore are totally broken!
2074         // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2075         // they are commands not environments. They are furthermore switches that
2076         // can be ended by another switches, but also by commands like \footnote or
2077         // \parbox. So the only safe way is to leave them untouched.
2078         // However, we support the pseudo-environments
2079         // \begin{centering} ... \end{centering}
2080         // \begin{raggedright} ... \end{raggedright}
2081         // \begin{raggedleft} ... \end{raggedleft}
2082         // since they are used by LyX in floats (for spacing reasons)
2083         else if (name == "center" || name == "centering" ||
2084                  name == "flushleft" || name == "raggedright" ||
2085                  name == "flushright" || name == "raggedleft" ||
2086                  name == "singlespace" || name == "onehalfspace" ||
2087                  name == "doublespace" || name == "spacing") {
2088                 eat_whitespace(p, os, parent_context, false);
2089                 // We must begin a new paragraph if not already done
2090                 if (! parent_context.atParagraphStart()) {
2091                         parent_context.check_end_layout(os);
2092                         parent_context.new_paragraph(os);
2093                 }
2094                 if (name == "flushleft" || name == "raggedright")
2095                         parent_context.add_extra_stuff("\\align left\n");
2096                 else if (name == "flushright" || name == "raggedleft")
2097                         parent_context.add_extra_stuff("\\align right\n");
2098                 else if (name == "center" || name == "centering")
2099                         parent_context.add_extra_stuff("\\align center\n");
2100                 else if (name == "singlespace")
2101                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2102                 else if (name == "onehalfspace") {
2103                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2104                         preamble.registerAutomaticallyLoadedPackage("setspace");
2105                 } else if (name == "doublespace") {
2106                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2107                         preamble.registerAutomaticallyLoadedPackage("setspace");
2108                 } else if (name == "spacing") {
2109                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2110                         preamble.registerAutomaticallyLoadedPackage("setspace");
2111                 }
2112                 parse_text(p, os, FLAG_END, outer, parent_context);
2113                 // Just in case the environment is empty
2114                 parent_context.extra_stuff.erase();
2115                 // We must begin a new paragraph to reset the alignment
2116                 parent_context.new_paragraph(os);
2117                 p.skip_spaces();
2118         }
2119
2120         // The single '=' is meant here.
2121         else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2122                 eat_whitespace(p, os, parent_context, false);
2123                 Context context(true, parent_context.textclass, newlayout,
2124                                 parent_context.layout, parent_context.font);
2125                 if (parent_context.deeper_paragraph) {
2126                         // We are beginning a nested environment after a
2127                         // deeper paragraph inside the outer list environment.
2128                         // Therefore we don't need to output a "begin deeper".
2129                         context.need_end_deeper = true;
2130                 }
2131                 parent_context.check_end_layout(os);
2132                 if (last_env == name) {
2133                         // we need to output a separator since LyX would export
2134                         // the two environments as one otherwise (bug 5716)
2135                         TeX2LyXDocClass const & textclass(parent_context.textclass);
2136                         Context newcontext(true, textclass,
2137                                         &(textclass.defaultLayout()));
2138                         newcontext.check_layout(os);
2139                         begin_inset(os, "Separator plain\n");
2140                         end_inset(os);
2141                         newcontext.check_end_layout(os);
2142                 }
2143                 switch (context.layout->latextype) {
2144                 case  LATEX_LIST_ENVIRONMENT:
2145                         context.add_par_extra_stuff("\\labelwidthstring "
2146                                                     + p.verbatim_item() + '\n');
2147                         p.skip_spaces();
2148                         break;
2149                 case  LATEX_BIB_ENVIRONMENT:
2150                         p.verbatim_item(); // swallow next arg
2151                         p.skip_spaces();
2152                         break;
2153                 default:
2154                         break;
2155                 }
2156                 context.check_deeper(os);
2157                 if (newlayout->keepempty) {
2158                         // We need to start a new paragraph
2159                         // even if it is empty.
2160                         context.new_paragraph(os);
2161                         context.check_layout(os);
2162                 }
2163                 // handle known optional and required arguments
2164                 if (context.layout->latextype == LATEX_ENVIRONMENT)
2165                         output_arguments(os, p, outer, false, string(), context,
2166                                          context.layout->latexargs());
2167                 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2168                         ostringstream oss;
2169                         output_arguments(oss, p, outer, false, string(), context,
2170                                          context.layout->latexargs());
2171                         context.list_extra_stuff = oss.str();
2172                 }
2173                 parse_text(p, os, FLAG_END, outer, context);
2174                 if (context.layout->latextype == LATEX_ENVIRONMENT)
2175                         output_arguments(os, p, outer, false, "post", context,
2176                                          context.layout->postcommandargs());
2177                 context.check_end_layout(os);
2178                 if (parent_context.deeper_paragraph) {
2179                         // We must suppress the "end deeper" because we
2180                         // suppressed the "begin deeper" above.
2181                         context.need_end_deeper = false;
2182                 }
2183                 context.check_end_deeper(os);
2184                 parent_context.new_paragraph(os);
2185                 p.skip_spaces();
2186                 if (!preamble.titleLayoutFound())
2187                         preamble.titleLayoutFound(newlayout->intitle);
2188                 set<string> const & req = newlayout->requires();
2189                 set<string>::const_iterator it = req.begin();
2190                 set<string>::const_iterator en = req.end();
2191                 for (; it != en; ++it)
2192                         preamble.registerAutomaticallyLoadedPackage(*it);
2193         }
2194
2195         // The single '=' is meant here.
2196         else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2197                 eat_whitespace(p, os, parent_context, false);
2198                 parent_context.check_layout(os);
2199                 begin_inset(os, "Flex ");
2200                 docstring flex_name = newinsetlayout->name();
2201                 // FIXME: what do we do if the prefix is not Flex: ?
2202                 if (prefixIs(flex_name, from_ascii("Flex:")))
2203                         flex_name.erase(0, 5);
2204                 os << to_utf8(flex_name) << '\n'
2205                    << "status collapsed\n";
2206                 if (newinsetlayout->isPassThru()) {
2207                         string const arg = p.verbatimEnvironment(name);
2208                         Context context(true, parent_context.textclass,
2209                                         &parent_context.textclass.plainLayout(),
2210                                         parent_context.layout);
2211                         output_ert(os, arg, parent_context);
2212                 } else
2213                         parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2214                 end_inset(os);
2215         }
2216
2217         else if (name == "appendix") {
2218                 // This is no good latex style, but it works and is used in some documents...
2219                 eat_whitespace(p, os, parent_context, false);
2220                 parent_context.check_end_layout(os);
2221                 Context context(true, parent_context.textclass, parent_context.layout,
2222                                 parent_context.layout, parent_context.font);
2223                 context.check_layout(os);
2224                 os << "\\start_of_appendix\n";
2225                 parse_text(p, os, FLAG_END, outer, context);
2226                 context.check_end_layout(os);
2227                 p.skip_spaces();
2228         }
2229
2230         else if (known_environments.find(name) != known_environments.end()) {
2231                 vector<ArgumentType> arguments = known_environments[name];
2232                 // The last "argument" denotes wether we may translate the
2233                 // environment contents to LyX
2234                 // The default required if no argument is given makes us
2235                 // compatible with the reLyXre environment.
2236                 ArgumentType contents = arguments.empty() ?
2237                         required :
2238                         arguments.back();
2239                 if (!arguments.empty())
2240                         arguments.pop_back();
2241                 // See comment in parse_unknown_environment()
2242                 bool const specialfont =
2243                         (parent_context.font != parent_context.normalfont);
2244                 bool const new_layout_allowed =
2245                         parent_context.new_layout_allowed;
2246                 if (specialfont)
2247                         parent_context.new_layout_allowed = false;
2248                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2249                                 outer, parent_context);
2250                 if (contents == verbatim)
2251                         output_ert_inset(os, p.ertEnvironment(name),
2252                                    parent_context);
2253                 else
2254                         parse_text_snippet(p, os, FLAG_END, outer,
2255                                            parent_context);
2256                 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2257                 if (specialfont)
2258                         parent_context.new_layout_allowed = new_layout_allowed;
2259         }
2260
2261         else
2262                 parse_unknown_environment(p, name, os, FLAG_END, outer,
2263                                           parent_context);
2264
2265         last_env = name;
2266         active_environments.pop_back();
2267 }
2268
2269
2270 /// parses a comment and outputs it to \p os.
2271 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2272                    bool skipNewlines = false)
2273 {
2274         LASSERT(t.cat() == catComment, return);
2275         if (!t.cs().empty()) {
2276                 context.check_layout(os);
2277                 output_comment(p, os, t.cs(), context);
2278                 if (p.next_token().cat() == catNewline) {
2279                         // A newline after a comment line starts a new
2280                         // paragraph
2281                         if (context.new_layout_allowed) {
2282                                 if(!context.atParagraphStart())
2283                                         // Only start a new paragraph if not already
2284                                         // done (we might get called recursively)
2285                                         context.new_paragraph(os);
2286                         } else
2287                                 output_ert_inset(os, "\n", context);
2288                         eat_whitespace(p, os, context, true);
2289                 }
2290         } else if (!skipNewlines) {
2291                 // "%\n" combination
2292                 p.skip_spaces();
2293         }
2294 }
2295
2296
2297 /*!
2298  * Reads spaces and comments until the first non-space, non-comment token.
2299  * New paragraphs (double newlines or \\par) are handled like simple spaces
2300  * if \p eatParagraph is true.
2301  * If \p eatNewline is false, newlines won't be treated as whitespace.
2302  * Spaces are skipped, but comments are written to \p os.
2303  */
2304 void eat_whitespace(Parser & p, ostream & os, Context & context,
2305                     bool eatParagraph, bool eatNewline)
2306 {
2307         while (p.good()) {
2308                 Token const & t = p.get_token();
2309                 if (t.cat() == catComment)
2310                         parse_comment(p, os, t, context, !eatNewline);
2311                 else if ((!eatParagraph && p.isParagraph()) ||
2312                          (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2313                         p.putback();
2314                         return;
2315                 }
2316         }
2317 }
2318
2319
2320 /*!
2321  * Set a font attribute, parse text and reset the font attribute.
2322  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2323  * \param currentvalue Current value of the attribute. Is set to the new
2324  * value during parsing.
2325  * \param newvalue New value of the attribute
2326  */
2327 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2328                            Context & context, string const & attribute,
2329                            string & currentvalue, string const & newvalue)
2330 {
2331         context.check_layout(os);
2332         string const oldvalue = currentvalue;
2333         currentvalue = newvalue;
2334         os << '\n' << attribute << ' ' << newvalue << "\n";
2335         parse_text_snippet(p, os, flags, outer, context);
2336         context.check_layout(os);
2337         os << '\n' << attribute << ' ' << oldvalue << "\n";
2338         currentvalue = oldvalue;
2339 }
2340
2341
2342 /// get the arguments of a natbib or jurabib citation command
2343 void get_cite_arguments(Parser & p, bool natbibOrder,
2344         string & before, string & after, bool const qualified = false)
2345 {
2346         // We need to distinguish "" and "[]", so we can't use p.getOpt().
2347
2348         // text before the citation
2349         before.clear();
2350         // text after the citation
2351         after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2352
2353         if (!after.empty()) {
2354                 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2355                 if (natbibOrder && !before.empty())
2356                         swap(before, after);
2357         }
2358 }
2359
2360
2361 void copy_file(FileName const & src, string dstname)
2362 {
2363         if (!copyFiles())
2364                 return;
2365         string const absParent = getParentFilePath(false);
2366         FileName dst;
2367         if (FileName::isAbsolute(dstname))
2368                 dst = FileName(dstname);
2369         else
2370                 dst = makeAbsPath(dstname, absParent);
2371         FileName const srcpath = src.onlyPath();
2372         FileName const dstpath = dst.onlyPath();
2373         if (equivalent(srcpath, dstpath))
2374                 return;
2375         if (!dstpath.isDirectory()) {
2376                 if (!dstpath.createPath()) {
2377                         cerr << "Warning: Could not create directory for file `"
2378                              << dst.absFileName() << "´." << endl;
2379                         return;
2380                 }
2381         }
2382         if (dst.isReadableFile()) {
2383                 if (overwriteFiles())
2384                         cerr << "Warning: Overwriting existing file `"
2385                              << dst.absFileName() << "´." << endl;
2386                 else {
2387                         cerr << "Warning: Not overwriting existing file `"
2388                              << dst.absFileName() << "´." << endl;
2389                         return;
2390                 }
2391         }
2392         if (!src.copyTo(dst))
2393                 cerr << "Warning: Could not copy file `" << src.absFileName()
2394                      << "´ to `" << dst.absFileName() << "´." << endl;
2395 }
2396
2397
2398 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2399 bool parse_chunk(Parser & p, ostream & os, Context & context)
2400 {
2401         // check whether a chunk is possible here.
2402         if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2403                 return false;
2404         }
2405
2406         p.pushPosition();
2407
2408         // read the parameters
2409         Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2410         if (!params.first) {
2411                 p.popPosition();
2412                 return false;
2413         }
2414
2415         Parser::Arg const code = p.verbatimStuff("\n@");
2416         if (!code.first) {
2417                 p.popPosition();
2418                 return false;
2419         }
2420         string const post_chunk = p.verbatimStuff("\n").second + '\n';
2421         if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2422                 p.popPosition();
2423                 return false;
2424         }
2425         // The last newline read is important for paragraph handling
2426         p.putback();
2427         p.deparse();
2428
2429         //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2430         // We must have a valid layout before outputting the Chunk inset.
2431         context.check_layout(os);
2432         Context chunkcontext(true, context.textclass);
2433         chunkcontext.layout = &context.textclass.plainLayout();
2434         begin_inset(os, "Flex Chunk");
2435         os << "\nstatus open\n";
2436         if (!params.second.empty()) {
2437                 chunkcontext.check_layout(os);
2438                 Context paramscontext(true, context.textclass);
2439                 paramscontext.layout = &context.textclass.plainLayout();
2440                 begin_inset(os, "Argument 1");
2441                 os << "\nstatus open\n";
2442                 output_ert(os, params.second, paramscontext);
2443                 end_inset(os);
2444         }
2445         output_ert(os, code.second, chunkcontext);
2446         end_inset(os);
2447
2448         p.dropPosition();
2449         return true;
2450 }
2451
2452
2453 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2454 bool is_macro(Parser & p)
2455 {
2456         Token first = p.curr_token();
2457         if (first.cat() != catEscape || !p.good())
2458                 return false;
2459         if (first.cs() == "def")
2460                 return true;
2461         if (first.cs() != "global" && first.cs() != "long")
2462                 return false;
2463         Token second = p.get_token();
2464         int pos = 1;
2465         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2466                second.cat() == catNewline || second.cat() == catComment)) {
2467                 second = p.get_token();
2468                 pos++;
2469         }
2470         bool secondvalid = second.cat() == catEscape;
2471         Token third;
2472         bool thirdvalid = false;
2473         if (p.good() && first.cs() == "global" && secondvalid &&
2474             second.cs() == "long") {
2475                 third = p.get_token();
2476                 pos++;
2477                 while (p.good() && !p.isParagraph() &&
2478                        (third.cat() == catSpace ||
2479                         third.cat() == catNewline ||
2480                         third.cat() == catComment)) {
2481                         third = p.get_token();
2482                         pos++;
2483                 }
2484                 thirdvalid = third.cat() == catEscape;
2485         }
2486         for (int i = 0; i < pos; ++i)
2487                 p.putback();
2488         if (!secondvalid)
2489                 return false;
2490         if (!thirdvalid)
2491                 return (first.cs() == "global" || first.cs() == "long") &&
2492                        second.cs() == "def";
2493         return first.cs() == "global" && second.cs() == "long" &&
2494                third.cs() == "def";
2495 }
2496
2497
2498 /// Parse a macro definition (assumes that is_macro() returned true)
2499 void parse_macro(Parser & p, ostream & os, Context & context)
2500 {
2501         context.check_layout(os);
2502         Token first = p.curr_token();
2503         Token second;
2504         Token third;
2505         string command = first.asInput();
2506         if (first.cs() != "def") {
2507                 p.get_token();
2508                 eat_whitespace(p, os, context, false);
2509                 second = p.curr_token();
2510                 command += second.asInput();
2511                 if (second.cs() != "def") {
2512                         p.get_token();
2513                         eat_whitespace(p, os, context, false);
2514                         third = p.curr_token();
2515                         command += third.asInput();
2516                 }
2517         }
2518         eat_whitespace(p, os, context, false);
2519         string const name = p.get_token().cs();
2520         eat_whitespace(p, os, context, false);
2521
2522         // parameter text
2523         bool simple = true;
2524         string paramtext;
2525         int arity = 0;
2526         while (p.next_token().cat() != catBegin) {
2527                 if (p.next_token().cat() == catParameter) {
2528                         // # found
2529                         p.get_token();
2530                         paramtext += "#";
2531
2532                         // followed by number?
2533                         if (p.next_token().cat() == catOther) {
2534                                 string s = p.get_token().asInput();
2535                                 paramtext += s;
2536                                 // number = current arity + 1?
2537                                 if (s.size() == 1 && s[0] == arity + '0' + 1)
2538                                         ++arity;
2539                                 else
2540                                         simple = false;
2541                         } else
2542                                 paramtext += p.get_token().cs();
2543                 } else {
2544                         paramtext += p.get_token().cs();
2545                         simple = false;
2546                 }
2547         }
2548
2549         // only output simple (i.e. compatible) macro as FormulaMacros
2550         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2551         if (simple) {
2552                 context.check_layout(os);
2553                 begin_inset(os, "FormulaMacro");
2554                 os << "\n\\def" << ert;
2555                 end_inset(os);
2556         } else
2557                 output_ert_inset(os, command + ert, context);
2558 }
2559
2560
2561 void registerExternalTemplatePackages(string const & name)
2562 {
2563         external::TemplateManager const & etm = external::TemplateManager::get();
2564         external::Template const * const et = etm.getTemplateByName(name);
2565         if (!et)
2566                 return;
2567         external::Template::Formats::const_iterator cit = et->formats.end();
2568         if (pdflatex)
2569                 cit = et->formats.find("PDFLaTeX");
2570         if (cit == et->formats.end())
2571                 // If the template has not specified a PDFLaTeX output,
2572                 // we try the LaTeX format.
2573                 cit = et->formats.find("LaTeX");
2574         if (cit == et->formats.end())
2575                 return;
2576         vector<string>::const_iterator qit = cit->second.requirements.begin();
2577         vector<string>::const_iterator qend = cit->second.requirements.end();
2578         for (; qit != qend; ++qit)
2579                 preamble.registerAutomaticallyLoadedPackage(*qit);
2580 }
2581
2582 } // anonymous namespace
2583
2584
2585 /*!
2586  * Find a file with basename \p name in path \p path and an extension
2587  * in \p extensions.
2588  */
2589 string find_file(string const & name, string const & path,
2590                  char const * const * extensions)
2591 {
2592         for (char const * const * what = extensions; *what; ++what) {
2593                 string const trial = addExtension(name, *what);
2594                 if (makeAbsPath(trial, path).exists())
2595                         return trial;
2596         }
2597         return string();
2598 }
2599
2600
2601 /// Convert filenames with TeX macros and/or quotes to something LyX
2602 /// can understand
2603 string const normalize_filename(string const & name)
2604 {
2605         Parser p(name);
2606         ostringstream os;
2607         while (p.good()) {
2608                 Token const & t = p.get_token();
2609                 if (t.cat() != catEscape)
2610                         os << t.asInput();
2611                 else if (t.cs() == "lyxdot") {
2612                         // This is used by LyX for simple dots in relative
2613                         // names
2614                         os << '.';
2615                         p.skip_spaces();
2616                 } else if (t.cs() == "space") {
2617                         os << ' ';
2618                         p.skip_spaces();
2619                 } else if (t.cs() == "string") {
2620                         // Convert \string" to " and \string~ to ~
2621                         Token const & n = p.next_token();
2622                         if (n.asInput() != "\"" && n.asInput() != "~")
2623                                 os << t.asInput();
2624                 } else
2625                         os << t.asInput();
2626         }
2627         // Strip quotes. This is a bit complicated (see latex_path()).
2628         string full = os.str();
2629         if (!full.empty() && full[0] == '"') {
2630                 string base = removeExtension(full);
2631                 string ext = getExtension(full);
2632                 if (!base.empty() && base[base.length()-1] == '"')
2633                         // "a b"
2634                         // "a b".tex
2635                         return addExtension(trim(base, "\""), ext);
2636                 if (full[full.length()-1] == '"')
2637                         // "a b.c"
2638                         // "a b.c".tex
2639                         return trim(full, "\"");
2640         }
2641         return full;
2642 }
2643
2644
2645 /// Convert \p name from TeX convention (relative to master file) to LyX
2646 /// convention (relative to .lyx file) if it is relative
2647 void fix_child_filename(string & name)
2648 {
2649         string const absMasterTeX = getMasterFilePath(true);
2650         bool const isabs = FileName::isAbsolute(name);
2651         // convert from "relative to .tex master" to absolute original path
2652         if (!isabs)
2653                 name = makeAbsPath(name, absMasterTeX).absFileName();
2654         bool copyfile = copyFiles();
2655         string const absParentLyX = getParentFilePath(false);
2656         string abs = name;
2657         if (copyfile) {
2658                 // convert from absolute original path to "relative to master file"
2659                 string const rel = to_utf8(makeRelPath(from_utf8(name),
2660                                                        from_utf8(absMasterTeX)));
2661                 // re-interpret "relative to .tex file" as "relative to .lyx file"
2662                 // (is different if the master .lyx file resides in a
2663                 // different path than the master .tex file)
2664                 string const absMasterLyX = getMasterFilePath(false);
2665                 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2666                 // Do not copy if the new path is impossible to create. Example:
2667                 // absMasterTeX = "/foo/bar/"
2668                 // absMasterLyX = "/bar/"
2669                 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2670                 if (contains(name, "/../"))
2671                         copyfile = false;
2672         }
2673         if (copyfile) {
2674                 if (isabs)
2675                         name = abs;
2676                 else {
2677                         // convert from absolute original path to
2678                         // "relative to .lyx file"
2679                         name = to_utf8(makeRelPath(from_utf8(abs),
2680                                                    from_utf8(absParentLyX)));
2681                 }
2682         }
2683         else if (!isabs) {
2684                 // convert from absolute original path to "relative to .lyx file"
2685                 name = to_utf8(makeRelPath(from_utf8(name),
2686                                            from_utf8(absParentLyX)));
2687         }
2688 }
2689
2690
2691 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2692                 Context & context, string const rdelim)
2693 {
2694         Layout const * newlayout = 0;
2695         InsetLayout const * newinsetlayout = 0;
2696         char const * const * where = 0;
2697         // Store the latest bibliographystyle, addcontentslineContent and
2698         // nocite{*} option (needed for bibtex inset)
2699         string btprint;
2700         string contentslineContent;
2701         // Some classes provide a \bibliographystyle, so do not output
2702         // any if none is explicitly set.
2703         string bibliographystyle;
2704         bool const use_natbib = isProvided("natbib");
2705         bool const use_jurabib = isProvided("jurabib");
2706         bool const use_biblatex = isProvided("biblatex")
2707                         && preamble.citeEngine() != "biblatex-natbib";
2708         bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2709                         || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2710         need_commentbib = use_biblatex || use_biblatex_natbib;
2711         string last_env;
2712
2713         // it is impossible to determine the correct encoding for non-CJK Japanese.
2714         // Therefore write a note at the beginning of the document
2715         if (is_nonCJKJapanese) {
2716                 context.check_layout(os);
2717                 begin_inset(os, "Note Note\n");
2718                 os << "status open\n\\begin_layout Plain Layout\n"
2719                    << "\\series bold\n"
2720                    << "Important information:\n"
2721                    << "\\end_layout\n\n"
2722                    << "\\begin_layout Plain Layout\n"
2723                    << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2724                    << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2725                    << " The iconv encoding " << p.getEncoding() << " was used.\n"
2726                    << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2727                    << " and specify the encoding using the -e command-line switch.\n"
2728                    << " In addition, you might want to double check that the desired output encoding\n"
2729                    << " is correctly selected in Document > Settings > Language.\n"
2730                    << "\\end_layout\n";
2731                 end_inset(os);
2732                 is_nonCJKJapanese = false;
2733         }
2734
2735         bool have_cycled = false;
2736         while (p.good()) {
2737                 // Leave here only after at least one cycle
2738                 if (have_cycled && flags & FLAG_LEAVE) {
2739                         flags &= ~FLAG_LEAVE;
2740                         break;
2741                 }
2742
2743                 Token const & t = p.get_token();
2744 #ifdef FILEDEBUG
2745                 debugToken(cerr, t, flags);
2746 #endif
2747
2748                 if (flags & FLAG_ITEM) {
2749                         if (t.cat() == catSpace)
2750                                 continue;
2751
2752                         flags &= ~FLAG_ITEM;
2753                         if (t.cat() == catBegin) {
2754                                 // skip the brace and collect everything to the next matching
2755                                 // closing brace
2756                                 flags |= FLAG_BRACE_LAST;
2757                                 continue;
2758                         }
2759
2760                         // handle only this single token, leave the loop if done
2761                         flags |= FLAG_LEAVE;
2762                 }
2763
2764                 if (t.cat() != catEscape && t.character() == ']' &&
2765                     (flags & FLAG_BRACK_LAST))
2766                         return;
2767                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2768                         return;
2769                 string tok = t.asInput();
2770                 // we only support delimiters with max 2 chars for now.
2771                 if (rdelim.size() > 1)
2772                         tok += p.next_token().asInput();
2773                 if (t.cat() != catEscape && !rdelim.empty()
2774                     && tok == rdelim && (flags & FLAG_RDELIM)) {
2775                         if (rdelim.size() > 1)
2776                                 p.get_token(); // eat rdelim
2777                         return;
2778                 }
2779
2780                 // If there is anything between \end{env} and \begin{env} we
2781                 // don't need to output a separator.
2782                 if (t.cat() != catSpace && t.cat() != catNewline &&
2783                     t.asInput() != "\\begin")
2784                         last_env = "";
2785
2786                 //
2787                 // cat codes
2788                 //
2789                 have_cycled = true;
2790                 bool const starred = p.next_token().asInput() == "*";
2791                 string const starredname(starred ? (t.cs() + '*') : t.cs());
2792                 if (t.cat() == catMath) {
2793                         // we are inside some text mode thingy, so opening new math is allowed
2794                         context.check_layout(os);
2795                         begin_inset(os, "Formula ");
2796                         Token const & n = p.get_token();
2797                         bool const display(n.cat() == catMath && outer);
2798                         if (display) {
2799                                 // TeX's $$...$$ syntax for displayed math
2800                                 os << "\\[";
2801                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2802                                 os << "\\]";
2803                                 p.get_token(); // skip the second '$' token
2804                         } else {
2805                                 // simple $...$  stuff
2806                                 p.putback();
2807                                 os << '$';
2808                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2809                                 os << '$';
2810                         }
2811                         end_inset(os);
2812                         if (display) {
2813                                 // Prevent the conversion of a line break to a
2814                                 // space (bug 7668). This does not change the
2815                                 // output, but looks ugly in LyX.
2816                                 eat_whitespace(p, os, context, false);
2817                         }
2818                         continue;
2819                 }
2820
2821                 if (t.cat() == catSuper || t.cat() == catSub) {
2822                         cerr << "catcode " << t << " illegal in text mode\n";
2823                         continue;
2824                 }
2825
2826                 // Basic support for quotes. We try to disambiguate
2827                 // quotes from the context (e.g., a left english quote is
2828                 // the same as a right german quote...).
2829                 // Try to make a smart guess about the side
2830                 Token const prev = p.prev_token();
2831                 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2832                                 && prev.character() != '\n' && prev.character() != '~');
2833                 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2834                         context.check_layout(os);
2835                         begin_inset(os, "Quotes ");
2836                         os << guessQuoteStyle("eld", opening);
2837                         end_inset(os);
2838                         p.get_token();
2839                         skip_braces(p);
2840                         continue;
2841                 }
2842                 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2843                         context.check_layout(os);
2844                         begin_inset(os, "Quotes ");
2845                         os << guessQuoteStyle("erd", opening);
2846                         end_inset(os);
2847                         p.get_token();
2848                         skip_braces(p);
2849                         continue;
2850                 }
2851
2852                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2853                         context.check_layout(os);
2854                         begin_inset(os, "Quotes ");
2855                         os << guessQuoteStyle("ald", opening);
2856                         end_inset(os);
2857                         p.get_token();
2858                         skip_braces(p);
2859                         continue;
2860                 }
2861
2862                 if (t.asInput() == "<"
2863                          && p.next_token().asInput() == "<") {
2864                         bool has_chunk = false;
2865                         if (noweb_mode) {
2866                                 p.pushPosition();
2867                                 p.get_token();
2868                                 has_chunk = parse_chunk(p, os, context);
2869                                 if (!has_chunk)
2870                                         p.popPosition();
2871                         }
2872
2873                         if (!has_chunk) {
2874                                 context.check_layout(os);
2875                                 begin_inset(os, "Quotes ");
2876                                 os << guessQuoteStyle("ard", opening);
2877                                 end_inset(os);
2878                                 p.get_token();
2879                                 skip_braces(p);
2880                         }
2881                         continue;
2882                 }
2883
2884                 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2885                         check_space(p, os, context);
2886                         continue;
2887                 }
2888
2889                 // babel shorthands (also used by polyglossia)
2890                 // Since these can have different meanings for different languages
2891                 // we import them as ERT (but they must be put in ERT to get output
2892                 // verbatim).
2893                 if (t.asInput() == "\"") {
2894                         string s = "\"";
2895                         // These are known pairs. We put them together in
2896                         // one ERT inset. In other cases (such as "a), only
2897                         // the quotation mark is ERTed.
2898                         if (p.next_token().asInput() == "\""
2899                             || p.next_token().asInput() == "|"
2900                             || p.next_token().asInput() == "-"
2901                             || p.next_token().asInput() == "~"
2902                             || p.next_token().asInput() == "="
2903                             || p.next_token().asInput() == "/"
2904                             || p.next_token().asInput() == "~"
2905                             || p.next_token().asInput() == "'"
2906                             || p.next_token().asInput() == "`"
2907                             || p.next_token().asInput() == "<"
2908                             || p.next_token().asInput() == ">") {
2909                                 s += p.next_token().asInput();
2910                                 p.get_token();
2911                         }
2912                         output_ert_inset(os, s, context);
2913                         continue;
2914                 }
2915
2916                 if (t.character() == '[' && noweb_mode &&
2917                          p.next_token().character() == '[') {
2918                         // These can contain underscores
2919                         p.putback();
2920                         string const s = p.getFullOpt() + ']';
2921                         if (p.next_token().character() == ']')
2922                                 p.get_token();
2923                         else
2924                                 cerr << "Warning: Inserting missing ']' in '"
2925                                      << s << "'." << endl;
2926                         output_ert_inset(os, s, context);
2927                         continue;
2928                 }
2929
2930                 if (t.cat() == catLetter) {
2931                         context.check_layout(os);
2932                         os << t.cs();
2933                         continue;
2934                 }
2935
2936                 if (t.cat() == catOther ||
2937                                t.cat() == catAlign ||
2938                                t.cat() == catParameter) {
2939                         context.check_layout(os);
2940                         if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2941                             context.merging_hyphens_allowed &&
2942                             context.font.family != "ttfamily" &&
2943                             !context.layout->pass_thru) {
2944                                 if (p.next_next_token().asInput() == "-") {
2945                                         // --- is emdash
2946                                         os << to_utf8(docstring(1, 0x2014));
2947                                         p.get_token();
2948                                 } else
2949                                         // -- is endash
2950                                         os << to_utf8(docstring(1, 0x2013));
2951                                 p.get_token();
2952                         } else
2953                                 // This translates "&" to "\\&" which may be wrong...
2954                                 os << t.cs();
2955                         continue;
2956                 }
2957
2958                 if (p.isParagraph()) {
2959                         // In minted floating listings we will collect
2960                         // everything into the caption, where multiple
2961                         // paragraphs are forbidden.
2962                         if (minted_float.empty()) {
2963                                 if (context.new_layout_allowed)
2964                                         context.new_paragraph(os);
2965                                 else
2966                                         output_ert_inset(os, "\\par ", context);
2967                         } else
2968                                 os << ' ';
2969                         eat_whitespace(p, os, context, true);
2970                         continue;
2971                 }
2972
2973                 if (t.cat() == catActive) {
2974                         context.check_layout(os);
2975                         if (t.character() == '~') {
2976                                 if (context.layout->free_spacing)
2977                                         os << ' ';
2978                                 else {
2979                                         begin_inset(os, "space ~\n");
2980                                         end_inset(os);
2981                                 }
2982                         } else
2983                                 os << t.cs();
2984                         continue;
2985                 }
2986
2987                 if (t.cat() == catBegin) {
2988                         Token const next = p.next_token();
2989                         Token const end = p.next_next_token();
2990                         if (next.cat() == catEnd) {
2991                                 // {}
2992                                 Token const prev = p.prev_token();
2993                                 p.get_token();
2994                                 if (p.next_token().character() == '`')
2995                                         ; // ignore it in {}``
2996                                 else
2997                                         output_ert_inset(os, "{}", context);
2998                         } else if (next.cat() == catEscape &&
2999                                    is_known(next.cs(), known_quotes) &&
3000                                    end.cat() == catEnd) {
3001                                 // Something like {\textquoteright} (e.g.
3002                                 // from writer2latex). We may skip the
3003                                 // braces here for better readability.
3004                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3005                                                    outer, context);
3006                         } else if (p.next_token().asInput() == "\\ascii") {
3007                                 // handle the \ascii characters
3008                                 // (the case without braces is handled later)
3009                                 // the code is "{\ascii\xxx}"
3010                                 p.get_token(); // eat \ascii
3011                                 string name2 = p.get_token().asInput();
3012                                 p.get_token(); // eat the final '}'
3013                                 string const name = "{\\ascii" + name2 + "}";
3014                                 bool termination;
3015                                 docstring rem;
3016                                 set<string> req;
3017                                 // get the character from unicodesymbols
3018                                 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3019                                         Encodings::TEXT_CMD, termination, rem, &req);
3020                                 if (!s.empty()) {
3021                                         context.check_layout(os);
3022                                         os << to_utf8(s);
3023                                         if (!rem.empty())
3024                                                 output_ert_inset(os,
3025                                                         to_utf8(rem), context);
3026                                         for (set<string>::const_iterator it = req.begin();
3027                                              it != req.end(); ++it)
3028                                                 preamble.registerAutomaticallyLoadedPackage(*it);
3029                                 } else
3030                                         // we did not find a non-ert version
3031                                         output_ert_inset(os, name, context);
3032                         } else {
3033                         context.check_layout(os);
3034                         // special handling of font attribute changes
3035                         Token const prev = p.prev_token();
3036                         TeXFont const oldFont = context.font;
3037                         if (next.character() == '[' ||
3038                             next.character() == ']' ||
3039                             next.character() == '*') {
3040                                 p.get_token();
3041                                 if (p.next_token().cat() == catEnd) {
3042                                         os << next.cs();
3043                                         p.get_token();
3044                                 } else {
3045                                         p.putback();
3046                                         output_ert_inset(os, "{", context);
3047                                         parse_text_snippet(p, os,
3048                                                         FLAG_BRACE_LAST,
3049                                                         outer, context);
3050                                         output_ert_inset(os, "}", context);
3051                                 }
3052                         } else if (! context.new_layout_allowed) {
3053                                 output_ert_inset(os, "{", context);
3054                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3055                                                    outer, context);
3056                                 output_ert_inset(os, "}", context);
3057                         } else if (is_known(next.cs(), known_sizes)) {
3058                                 // next will change the size, so we must
3059                                 // reset it here
3060                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3061                                                    outer, context);
3062                                 if (!context.atParagraphStart())
3063                                         os << "\n\\size "
3064                                            << context.font.size << "\n";
3065                         } else if (is_known(next.cs(), known_font_families)) {
3066                                 // next will change the font family, so we
3067                                 // must reset it here
3068                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3069                                                    outer, context);
3070                                 if (!context.atParagraphStart())
3071                                         os << "\n\\family "
3072                                            << context.font.family << "\n";
3073                         } else if (is_known(next.cs(), known_font_series)) {
3074                                 // next will change the font series, so we
3075                                 // must reset it here
3076                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3077                                                    outer, context);
3078                                 if (!context.atParagraphStart())
3079                                         os << "\n\\series "
3080                                            << context.font.series << "\n";
3081                         } else if (is_known(next.cs(), known_font_shapes)) {
3082                                 // next will change the font shape, so we
3083                                 // must reset it here
3084                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3085                                                    outer, context);
3086                                 if (!context.atParagraphStart())
3087                                         os << "\n\\shape "
3088                                            << context.font.shape << "\n";
3089                         } else if (is_known(next.cs(), known_old_font_families) ||
3090                                    is_known(next.cs(), known_old_font_series) ||
3091                                    is_known(next.cs(), known_old_font_shapes)) {
3092                                 // next will change the font family, series
3093                                 // and shape, so we must reset it here
3094                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3095                                                    outer, context);
3096                                 if (!context.atParagraphStart())
3097                                         os <<  "\n\\family "
3098                                            << context.font.family
3099                                            << "\n\\series "
3100                                            << context.font.series
3101                                            << "\n\\shape "
3102                                            << context.font.shape << "\n";
3103                         } else {
3104                                 output_ert_inset(os, "{", context);
3105                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3106                                                    outer, context);
3107                                 output_ert_inset(os, "}", context);
3108                                 }
3109                         }
3110                         continue;
3111                 }
3112
3113                 if (t.cat() == catEnd) {
3114                         if (flags & FLAG_BRACE_LAST) {
3115                                 return;
3116                         }
3117                         cerr << "stray '}' in text\n";
3118                         output_ert_inset(os, "}", context);
3119                         continue;
3120                 }
3121
3122                 if (t.cat() == catComment) {
3123                         parse_comment(p, os, t, context);
3124                         continue;
3125                 }
3126
3127                 //
3128                 // control sequences
3129                 //
3130
3131                 if (t.cs() == "(" || t.cs() == "[") {
3132                         bool const simple = t.cs() == "(";
3133                         context.check_layout(os);
3134                         begin_inset(os, "Formula");
3135                         os << " \\" << t.cs();
3136                         parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3137                         os << '\\' << (simple ? ')' : ']');
3138                         end_inset(os);
3139                         if (!simple) {
3140                                 // Prevent the conversion of a line break to a
3141                                 // space (bug 7668). This does not change the
3142                                 // output, but looks ugly in LyX.
3143                                 eat_whitespace(p, os, context, false);
3144                         }
3145                         continue;
3146                 }
3147
3148                 if (t.cs() == "begin") {
3149                         parse_environment(p, os, outer, last_env,
3150                                           context);
3151                         continue;
3152                 }
3153
3154                 if (t.cs() == "end") {
3155                         if (flags & FLAG_END) {
3156                                 // eat environment name
3157                                 string const name = p.getArg('{', '}');
3158                                 if (name != active_environment())
3159                                         cerr << "\\end{" + name + "} does not match \\begin{"
3160                                                 + active_environment() + "}\n";
3161                                 return;
3162                         }
3163                         p.error("found 'end' unexpectedly");
3164                         continue;
3165                 }
3166
3167                 // "item" by default, but could be something else
3168                 if (t.cs() == context.layout->itemcommand()) {
3169                         string s;
3170                         if (context.layout->labeltype == LABEL_MANUAL) {
3171                                 // FIXME: This swallows comments, but we cannot use
3172                                 //        eat_whitespace() since we must not output
3173                                 //        anything before the item.
3174                                 p.skip_spaces(true);
3175                                 s = p.verbatimOption();
3176                         } else
3177                                 p.skip_spaces(false);
3178                         context.set_item();
3179                         context.check_layout(os);
3180                         if (context.has_item) {
3181                                 // An item in an unknown list-like environment
3182                                 // FIXME: Do this in check_layout()!
3183                                 context.has_item = false;
3184                                 string item = "\\" + context.layout->itemcommand();
3185                                 if (!p.hasOpt())
3186                                         item += " ";
3187                                 output_ert_inset(os, item, context);
3188                         }
3189                         if (context.layout->labeltype != LABEL_MANUAL)
3190                                 output_arguments(os, p, outer, false, "item", context,
3191                                                  context.layout->itemargs());
3192                         if (!context.list_extra_stuff.empty()) {
3193                                 os << context.list_extra_stuff;
3194                                 context.list_extra_stuff.clear();
3195                         }
3196                         else if (!s.empty()) {
3197                                         // LyX adds braces around the argument,
3198                                         // so we need to remove them here.
3199                                         if (s.size() > 2 && s[0] == '{' &&
3200                                             s[s.size()-1] == '}')
3201                                                 s = s.substr(1, s.size()-2);
3202                                         // If the argument contains a space we
3203                                         // must put it into ERT: Otherwise LyX
3204                                         // would misinterpret the space as
3205                                         // item delimiter (bug 7663)
3206                                         if (contains(s, ' ')) {
3207                                                 output_ert_inset(os, s, context);
3208                                         } else {
3209                                                 Parser p2(s + ']');
3210                                                 os << parse_text_snippet(p2,
3211                                                         FLAG_BRACK_LAST, outer, context);
3212                                         }
3213                                         // The space is needed to separate the
3214                                         // item from the rest of the sentence.
3215                                         os << ' ';
3216                                         eat_whitespace(p, os, context, false);
3217                                 }
3218                         continue;
3219                 }
3220
3221                 if (t.cs() == "bibitem") {
3222                         context.set_item();
3223                         context.check_layout(os);
3224                         eat_whitespace(p, os, context, false);
3225                         string label = p.verbatimOption();
3226                         pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3227                         bool const literal = !lbl.first;
3228                         label = literal ? subst(label, "\n", " ") : lbl.second;
3229                         string lit = literal ? "\"true\"" : "\"false\"";
3230                         string key = convert_literate_command_inset_arg(p.verbatim_item());
3231                         begin_command_inset(os, "bibitem", "bibitem");
3232                         os << "label \"" << label << "\"\n"
3233                            << "key \"" << key << "\"\n"
3234                            << "literal " << lit << "\n";
3235                         end_inset(os);
3236                         continue;
3237                 }
3238
3239                 if (is_macro(p)) {
3240                         // catch the case of \def\inputGnumericTable
3241                         bool macro = true;
3242                         if (t.cs() == "def") {
3243                                 Token second = p.next_token();
3244                                 if (second.cs() == "inputGnumericTable") {
3245                                         p.pushPosition();
3246                                         p.get_token();
3247                                         skip_braces(p);
3248                                         Token third = p.get_token();
3249                                         p.popPosition();
3250                                         if (third.cs() == "input") {
3251                                                 p.get_token();
3252                                                 skip_braces(p);
3253                                                 p.get_token();
3254                                                 string name = normalize_filename(p.verbatim_item());
3255                                                 string const path = getMasterFilePath(true);
3256                                                 // We want to preserve relative / absolute filenames,
3257                                                 // therefore path is only used for testing
3258                                                 // The file extension is in every case ".tex".
3259                                                 // So we need to remove this extension and check for
3260                                                 // the original one.
3261                                                 name = removeExtension(name);
3262                                                 if (!makeAbsPath(name, path).exists()) {
3263                                                         char const * const Gnumeric_formats[] = {"gnumeric",
3264                                                                 "ods", "xls", 0};
3265                                                         string const Gnumeric_name =
3266                                                                 find_file(name, path, Gnumeric_formats);
3267                                                         if (!Gnumeric_name.empty())
3268                                                                 name = Gnumeric_name;
3269                                                 }
3270                                                 FileName const absname = makeAbsPath(name, path);
3271                                                 if (absname.exists()) {
3272                                                         fix_child_filename(name);
3273                                                         copy_file(absname, name);
3274                                                 } else
3275                                                         cerr << "Warning: Could not find file '"
3276                                                              << name << "'." << endl;
3277                                                 context.check_layout(os);
3278                                                 begin_inset(os, "External\n\ttemplate ");
3279                                                 os << "GnumericSpreadsheet\n\tfilename "
3280                                                    << name << "\n";
3281                                                 end_inset(os);
3282                                                 context.check_layout(os);
3283                                                 macro = false;
3284                                                 // register the packages that are automatically loaded
3285                                                 // by the Gnumeric template
3286                                                 registerExternalTemplatePackages("GnumericSpreadsheet");
3287                                         }
3288                                 }
3289                         }
3290                         if (macro)
3291                                 parse_macro(p, os, context);
3292                         continue;
3293                 }
3294
3295                 if (t.cs() == "noindent") {
3296                         p.skip_spaces();
3297                         context.add_par_extra_stuff("\\noindent\n");
3298                         continue;
3299                 }
3300
3301                 if (t.cs() == "appendix") {
3302                         context.add_par_extra_stuff("\\start_of_appendix\n");
3303                         // We need to start a new paragraph. Otherwise the
3304                         // appendix in 'bla\appendix\chapter{' would start
3305                         // too late.
3306                         context.new_paragraph(os);
3307                         // We need to make sure that the paragraph is
3308                         // generated even if it is empty. Otherwise the
3309                         // appendix in '\par\appendix\par\chapter{' would
3310                         // start too late.
3311                         context.check_layout(os);
3312                         // FIXME: This is a hack to prevent paragraph
3313                         // deletion if it is empty. Handle this better!
3314                         output_comment(p, os,
3315                                 "dummy comment inserted by tex2lyx to "
3316                                 "ensure that this paragraph is not empty",
3317                                 context);
3318                         // Both measures above may generate an additional
3319                         // empty paragraph, but that does not hurt, because
3320                         // whitespace does not matter here.
3321                         eat_whitespace(p, os, context, true);
3322                         continue;
3323                 }
3324
3325                 // Must catch empty dates before findLayout is called below
3326                 if (t.cs() == "date") {
3327                         eat_whitespace(p, os, context, false);
3328                         p.pushPosition();
3329                         string const date = p.verbatim_item();
3330                         p.popPosition();
3331                         if (date.empty()) {
3332                                 preamble.suppressDate(true);
3333                                 p.verbatim_item();
3334                         } else {
3335                                 preamble.suppressDate(false);
3336                                 if (context.new_layout_allowed &&
3337                                     (newlayout = findLayout(context.textclass,
3338                                                             t.cs(), true))) {
3339                                         // write the layout
3340                                         output_command_layout(os, p, outer,
3341                                                         context, newlayout);
3342                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3343                                         if (!preamble.titleLayoutFound())
3344                                                 preamble.titleLayoutFound(newlayout->intitle);
3345                                         set<string> const & req = newlayout->requires();
3346                                         set<string>::const_iterator it = req.begin();
3347                                         set<string>::const_iterator en = req.end();
3348                                         for (; it != en; ++it)
3349                                                 preamble.registerAutomaticallyLoadedPackage(*it);
3350                                 } else
3351                                         output_ert_inset(os,
3352                                                 "\\date{" + p.verbatim_item() + '}',
3353                                                 context);
3354                         }
3355                         continue;
3356                 }
3357
3358                 // Before we look for the layout name with star and alone below, we check the layouts including
3359                 // the LateXParam, which might be one or several options or a star.
3360                 // The single '=' is meant here.
3361                 if (context.new_layout_allowed &&
3362                    (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3363                         // store the latexparam here. This is eaten in output_command_layout
3364                         context.latexparam = newlayout->latexparam();
3365                         // write the layout
3366                         output_command_layout(os, p, outer, context, newlayout);
3367                         context.latexparam.clear();
3368                         p.skip_spaces();
3369                         if (!preamble.titleLayoutFound())
3370                                 preamble.titleLayoutFound(newlayout->intitle);
3371                         set<string> const & req = newlayout->requires();
3372                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3373                                 preamble.registerAutomaticallyLoadedPackage(*it);
3374                         continue;
3375                 }
3376
3377
3378                 // Starred section headings
3379                 // Must attempt to parse "Section*" before "Section".
3380                 if ((p.next_token().asInput() == "*") &&
3381                          context.new_layout_allowed &&
3382                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3383                         // write the layout
3384                         p.get_token();
3385                         output_command_layout(os, p, outer, context, newlayout);
3386                         p.skip_spaces();
3387                         if (!preamble.titleLayoutFound())
3388                                 preamble.titleLayoutFound(newlayout->intitle);
3389                         set<string> const & req = newlayout->requires();
3390                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3391                                 preamble.registerAutomaticallyLoadedPackage(*it);
3392                         continue;
3393                 }
3394
3395                 // Section headings and the like
3396                 if (context.new_layout_allowed &&
3397                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
3398                         // write the layout
3399                         output_command_layout(os, p, outer, context, newlayout);
3400                         p.skip_spaces();
3401                         if (!preamble.titleLayoutFound())
3402                                 preamble.titleLayoutFound(newlayout->intitle);
3403                         set<string> const & req = newlayout->requires();
3404                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3405                                 preamble.registerAutomaticallyLoadedPackage(*it);
3406                         continue;
3407                 }
3408
3409                 if (t.cs() == "subfloat") {
3410                         // the syntax is \subfloat[list entry][sub caption]{content}
3411                         // if it is a table of figure depends on the surrounding float
3412                         p.skip_spaces();
3413                         // do nothing if there is no outer float
3414                         if (!float_type.empty()) {
3415                                 context.check_layout(os);
3416                                 p.skip_spaces();
3417                                 begin_inset(os, "Float " + float_type + "\n");
3418                                 os << "wide false"
3419                                    << "\nsideways false"
3420                                    << "\nstatus collapsed\n\n";
3421                                 // test for caption
3422                                 string caption;
3423                                 bool has_caption = false;
3424                                 if (p.next_token().cat() != catEscape &&
3425                                                 p.next_token().character() == '[') {
3426                                                         p.get_token(); // eat '['
3427                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3428                                                         has_caption = true;
3429                                 }
3430                                 // In case we have two optional args, the second is the caption.
3431                                 if (p.next_token().cat() != catEscape &&
3432                                                 p.next_token().character() == '[') {
3433                                                         p.get_token(); // eat '['
3434                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3435                                 }
3436                                 // the content
3437                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3438                                 // the caption comes always as the last
3439                                 if (has_caption) {
3440                                         // we must make sure that the caption gets a \begin_layout
3441                                         os << "\n\\begin_layout Plain Layout";
3442                                         p.skip_spaces();
3443                                         begin_inset(os, "Caption Standard\n");
3444                                         Context newcontext(true, context.textclass,
3445                                                            0, 0, context.font);
3446                                         newcontext.check_layout(os);
3447                                         os << caption << "\n";
3448                                         newcontext.check_end_layout(os);
3449                                         end_inset(os);
3450                                         p.skip_spaces();
3451                                         // close the layout we opened
3452                                         os << "\n\\end_layout";
3453                                 }
3454                                 end_inset(os);
3455                                 p.skip_spaces();
3456                         } else {
3457                                 // if the float type is not supported or there is no surrounding float
3458                                 // output it as ERT
3459                                 string opt_arg1;
3460                                 string opt_arg2;
3461                                 if (p.hasOpt()) {
3462                                         opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3463                                         if (p.hasOpt())
3464                                                 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3465                                 }
3466                                 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3467                                                  + "{" + p.verbatim_item() + '}', context);
3468                         }
3469                         continue;
3470                 }
3471
3472                 if (t.cs() == "xymatrix") {
3473                         // we must open a new math because LyX's xy support is in math
3474                         context.check_layout(os);
3475                         begin_inset(os, "Formula ");
3476                         os << '$';
3477                         os << "\\" << t.cs() << '{';
3478                         parse_math(p, os, FLAG_ITEM, MATH_MODE);
3479                         os << '}' << '$';
3480                         end_inset(os);
3481                         preamble.registerAutomaticallyLoadedPackage("xy");
3482                         continue;
3483                 }
3484
3485                 if (t.cs() == "includegraphics") {
3486                         bool const clip = p.next_token().asInput() == "*";
3487                         if (clip)
3488                                 p.get_token();
3489                         string const arg = p.getArg('[', ']');
3490                         map<string, string> opts;
3491                         vector<string> keys;
3492                         split_map(arg, opts, keys);
3493                         if (clip)
3494                                 opts["clip"] = string();
3495                         string name = normalize_filename(p.verbatim_item());
3496
3497                         string const path = getMasterFilePath(true);
3498                         // We want to preserve relative / absolute filenames,
3499                         // therefore path is only used for testing
3500                         if (!makeAbsPath(name, path).exists()) {
3501                                 // The file extension is probably missing.
3502                                 // Now try to find it out.
3503                                 string const dvips_name =
3504                                         find_file(name, path,
3505                                                   known_dvips_graphics_formats);
3506                                 string const pdftex_name =
3507                                         find_file(name, path,
3508                                                   known_pdftex_graphics_formats);
3509                                 if (!dvips_name.empty()) {
3510                                         if (!pdftex_name.empty()) {
3511                                                 cerr << "This file contains the "
3512                                                         "latex snippet\n"
3513                                                         "\"\\includegraphics{"
3514                                                      << name << "}\".\n"
3515                                                         "However, files\n\""
3516                                                      << dvips_name << "\" and\n\""
3517                                                      << pdftex_name << "\"\n"
3518                                                         "both exist, so I had to make a "
3519                                                         "choice and took the first one.\n"
3520                                                         "Please move the unwanted one "
3521                                                         "someplace else and try again\n"
3522                                                         "if my choice was wrong."
3523                                                      << endl;
3524                                         }
3525                                         name = dvips_name;
3526                                 } else if (!pdftex_name.empty()) {
3527                                         name = pdftex_name;
3528                                         pdflatex = true;
3529                                 }
3530                         }
3531
3532                         FileName const absname = makeAbsPath(name, path);
3533                         if (absname.exists()) {
3534                                 fix_child_filename(name);
3535                                 copy_file(absname, name);
3536                         } else
3537                                 cerr << "Warning: Could not find graphics file '"
3538                                      << name << "'." << endl;
3539
3540                         context.check_layout(os);
3541                         begin_inset(os, "Graphics ");
3542                         os << "\n\tfilename " << name << '\n';
3543                         if (opts.find("width") != opts.end())
3544                                 os << "\twidth "
3545                                    << translate_len(opts["width"]) << '\n';
3546                         if (opts.find("height") != opts.end())
3547                                 os << "\theight "
3548                                    << translate_len(opts["height"]) << '\n';
3549                         if (opts.find("scale") != opts.end()) {
3550                                 istringstream iss(opts["scale"]);
3551                                 double val;
3552                                 iss >> val;
3553                                 val = val*100;
3554                                 os << "\tscale " << val << '\n';
3555                         }
3556                         if (opts.find("angle") != opts.end()) {
3557                                 os << "\trotateAngle "
3558                                    << opts["angle"] << '\n';
3559                                 vector<string>::const_iterator a =
3560                                         find(keys.begin(), keys.end(), "angle");
3561                                 vector<string>::const_iterator s =
3562                                         find(keys.begin(), keys.end(), "width");
3563                                 if (s == keys.end())
3564                                         s = find(keys.begin(), keys.end(), "height");
3565                                 if (s == keys.end())
3566                                         s = find(keys.begin(), keys.end(), "scale");
3567                                 if (s != keys.end() && distance(s, a) > 0)
3568                                         os << "\tscaleBeforeRotation\n";
3569                         }
3570                         if (opts.find("origin") != opts.end()) {
3571                                 ostringstream ss;
3572                                 string const opt = opts["origin"];
3573                                 if (opt.find('l') != string::npos) ss << "left";
3574                                 if (opt.find('r') != string::npos) ss << "right";
3575                                 if (opt.find('c') != string::npos) ss << "center";
3576                                 if (opt.find('t') != string::npos) ss << "Top";
3577                                 if (opt.find('b') != string::npos) ss << "Bottom";
3578                                 if (opt.find('B') != string::npos) ss << "Baseline";
3579                                 if (!ss.str().empty())
3580                                         os << "\trotateOrigin " << ss.str() << '\n';
3581                                 else
3582                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3583                         }
3584                         if (opts.find("keepaspectratio") != opts.end())
3585                                 os << "\tkeepAspectRatio\n";
3586                         if (opts.find("clip") != opts.end())
3587                                 os << "\tclip\n";
3588                         if (opts.find("draft") != opts.end())
3589                                 os << "\tdraft\n";
3590                         if (opts.find("bb") != opts.end())
3591                                 os << "\tBoundingBox "
3592                                    << opts["bb"] << '\n';
3593                         int numberOfbbOptions = 0;
3594                         if (opts.find("bbllx") != opts.end())
3595                                 numberOfbbOptions++;
3596                         if (opts.find("bblly") != opts.end())
3597                                 numberOfbbOptions++;
3598                         if (opts.find("bburx") != opts.end())
3599                                 numberOfbbOptions++;
3600                         if (opts.find("bbury") != opts.end())
3601                                 numberOfbbOptions++;
3602                         if (numberOfbbOptions == 4)
3603                                 os << "\tBoundingBox "
3604                                    << opts["bbllx"] << " " << opts["bblly"] << " "
3605                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
3606                         else if (numberOfbbOptions > 0)
3607                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3608                         numberOfbbOptions = 0;
3609                         if (opts.find("natwidth") != opts.end())
3610                                 numberOfbbOptions++;
3611                         if (opts.find("natheight") != opts.end())
3612                                 numberOfbbOptions++;
3613                         if (numberOfbbOptions == 2)
3614                                 os << "\tBoundingBox 0bp 0bp "
3615                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
3616                         else if (numberOfbbOptions > 0)
3617                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3618                         ostringstream special;
3619                         if (opts.find("hiresbb") != opts.end())
3620                                 special << "hiresbb,";
3621                         if (opts.find("trim") != opts.end())
3622                                 special << "trim,";
3623                         if (opts.find("viewport") != opts.end())
3624                                 special << "viewport=" << opts["viewport"] << ',';
3625                         if (opts.find("totalheight") != opts.end())
3626                                 special << "totalheight=" << opts["totalheight"] << ',';
3627                         if (opts.find("type") != opts.end())
3628                                 special << "type=" << opts["type"] << ',';
3629                         if (opts.find("ext") != opts.end())
3630                                 special << "ext=" << opts["ext"] << ',';
3631                         if (opts.find("read") != opts.end())
3632                                 special << "read=" << opts["read"] << ',';
3633                         if (opts.find("command") != opts.end())
3634                                 special << "command=" << opts["command"] << ',';
3635                         string s_special = special.str();
3636                         if (!s_special.empty()) {
3637                                 // We had special arguments. Remove the trailing ','.
3638                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3639                         }
3640                         // TODO: Handle the unknown settings better.
3641                         // Warn about invalid options.
3642                         // Check whether some option was given twice.
3643                         end_inset(os);
3644                         preamble.registerAutomaticallyLoadedPackage("graphicx");
3645                         continue;
3646                 }
3647
3648                 if (t.cs() == "footnote" ||
3649                          (t.cs() == "thanks" && context.layout->intitle)) {
3650                         p.skip_spaces();
3651                         context.check_layout(os);
3652                         begin_inset(os, "Foot\n");
3653                         os << "status collapsed\n\n";
3654                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3655                         end_inset(os);
3656                         continue;
3657                 }
3658
3659                 if (t.cs() == "marginpar") {
3660                         p.skip_spaces();
3661                         context.check_layout(os);
3662                         begin_inset(os, "Marginal\n");
3663                         os << "status collapsed\n\n";
3664                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3665                         end_inset(os);
3666                         continue;
3667                 }
3668
3669                 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3670                         bool const use_minted = t.cs() == "mintinline";
3671                         p.skip_spaces();
3672                         parse_listings(p, os, context, true, use_minted);
3673                         continue;
3674                 }
3675
3676                 if (t.cs() == "ensuremath") {
3677                         p.skip_spaces();
3678                         context.check_layout(os);
3679                         string const s = p.verbatim_item();
3680                         //FIXME: this never triggers in UTF8
3681                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3682                                 os << s;
3683                         else
3684                                 output_ert_inset(os, "\\ensuremath{" + s + "}",
3685                                            context);
3686                         continue;
3687                 }
3688
3689                 else if (t.cs() == "makeindex"
3690                          || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3691                              && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3692                         if (preamble.titleLayoutFound()) {
3693                                 // swallow this
3694                                 skip_spaces_braces(p);
3695                         } else
3696                                 output_ert_inset(os, t.asInput(), context);
3697                         continue;
3698                 }
3699
3700                 if (t.cs() == "tableofcontents"
3701                                 || t.cs() == "lstlistoflistings"
3702                                 || t.cs() == "listoflistings") {
3703                         string name = t.cs();
3704                         if (preamble.minted() && name == "listoflistings")
3705                                 name.insert(0, "lst");
3706                         context.check_layout(os);
3707                         begin_command_inset(os, "toc", name);
3708                         end_inset(os);
3709                         skip_spaces_braces(p);
3710                         if (name == "lstlistoflistings") {
3711                                 if (preamble.minted())
3712                                         preamble.registerAutomaticallyLoadedPackage("minted");
3713                                 else
3714                                         preamble.registerAutomaticallyLoadedPackage("listings");
3715                         }
3716                         continue;
3717                 }
3718
3719                 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3720                         context.check_layout(os);
3721                         if (t.cs() == "listoffigures")
3722                                 begin_inset(os, "FloatList figure\n");
3723                         else
3724                                 begin_inset(os, "FloatList table\n");
3725                         end_inset(os);
3726                         skip_spaces_braces(p);
3727                         continue;
3728                 }
3729
3730                 if (t.cs() == "listof") {
3731                         p.skip_spaces(true);
3732                         string const name = p.get_token().cs();
3733                         if (context.textclass.floats().typeExist(name)) {
3734                                 context.check_layout(os);
3735                                 begin_inset(os, "FloatList ");
3736                                 os << name << "\n";
3737                                 end_inset(os);
3738                                 p.get_token(); // swallow second arg
3739                         } else
3740                                 output_ert_inset(os, "\\listof{" + name + "}", context);
3741                         continue;
3742                 }
3743
3744                 if ((where = is_known(t.cs(), known_text_font_families))) {
3745                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3746                                 context, "\\family", context.font.family,
3747                                 known_coded_font_families[where - known_text_font_families]);
3748                         continue;
3749                 }
3750
3751                 // beamer has a \textbf<overlay>{} inset
3752                 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3753                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3754                                 context, "\\series", context.font.series,
3755                                 known_coded_font_series[where - known_text_font_series]);
3756                         continue;
3757                 }
3758
3759                 // beamer has a \textit<overlay>{} inset
3760                 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3761                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3762                                 context, "\\shape", context.font.shape,
3763                                 known_coded_font_shapes[where - known_text_font_shapes]);
3764                         continue;
3765                 }
3766
3767                 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3768                         context.check_layout(os);
3769                         TeXFont oldFont = context.font;
3770                         context.font.init();
3771                         context.font.size = oldFont.size;
3772                         os << "\n\\family " << context.font.family << "\n";
3773                         os << "\n\\series " << context.font.series << "\n";
3774                         os << "\n\\shape " << context.font.shape << "\n";
3775                         if (t.cs() == "textnormal") {
3776                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3777                                 output_font_change(os, context.font, oldFont);
3778                                 context.font = oldFont;
3779                         } else
3780                                 eat_whitespace(p, os, context, false);
3781                         continue;
3782                 }
3783
3784                 if (t.cs() == "textcolor") {
3785                         // scheme is \textcolor{color name}{text}
3786                         string const color = p.verbatim_item();
3787                         // we support the predefined colors of the color  and the xcolor package
3788                         if (color == "black" || color == "blue" || color == "cyan"
3789                                 || color == "green" || color == "magenta" || color == "red"
3790                                 || color == "white" || color == "yellow") {
3791                                         context.check_layout(os);
3792                                         os << "\n\\color " << color << "\n";
3793                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3794                                         context.check_layout(os);
3795                                         os << "\n\\color inherit\n";
3796                                         preamble.registerAutomaticallyLoadedPackage("color");
3797                         } else if (color == "brown" || color == "darkgray" || color == "gray"
3798                                 || color == "lightgray" || color == "lime" || color == "olive"
3799                                 || color == "orange" || color == "pink" || color == "purple"
3800                                 || color == "teal" || color == "violet") {
3801                                         context.check_layout(os);
3802                                         os << "\n\\color " << color << "\n";
3803                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3804                                         context.check_layout(os);
3805                                         os << "\n\\color inherit\n";
3806                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3807                         } else
3808                                 // for custom defined colors
3809                                 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3810                         continue;
3811                 }
3812
3813                 if (t.cs() == "underbar" || t.cs() == "uline") {
3814                         // \underbar is not 100% correct (LyX outputs \uline
3815                         // of ulem.sty). The difference is that \ulem allows
3816                         // line breaks, and \underbar does not.
3817                         // Do NOT handle \underline.
3818                         // \underbar cuts through y, g, q, p etc.,
3819                         // \underline does not.
3820                         context.check_layout(os);
3821                         os << "\n\\bar under\n";
3822                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3823                         context.check_layout(os);
3824                         os << "\n\\bar default\n";
3825                         preamble.registerAutomaticallyLoadedPackage("ulem");
3826                         continue;
3827                 }
3828
3829                 if (t.cs() == "sout") {
3830                         context.check_layout(os);
3831                         os << "\n\\strikeout on\n";
3832                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3833                         context.check_layout(os);
3834                         os << "\n\\strikeout default\n";
3835                         preamble.registerAutomaticallyLoadedPackage("ulem");
3836                         continue;
3837                 }
3838
3839                 // beamer has an \emph<overlay>{} inset
3840                 if ((t.cs() == "uuline" || t.cs() == "uwave"
3841                         || t.cs() == "emph" || t.cs() == "noun"
3842                         || t.cs() == "xout") && !p.hasOpt("<")) {
3843                         context.check_layout(os);
3844                         os << "\n\\" << t.cs() << " on\n";
3845                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3846                         context.check_layout(os);
3847                         os << "\n\\" << t.cs() << " default\n";
3848                         if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3849                                 preamble.registerAutomaticallyLoadedPackage("ulem");
3850                         continue;
3851                 }
3852
3853                 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3854                         context.check_layout(os);
3855                         string name = p.getArg('{', '}');
3856                         string localtime = p.getArg('{', '}');
3857                         preamble.registerAuthor(name);
3858                         Author const & author = preamble.getAuthor(name);
3859                         // from_asctime_utc() will fail if LyX decides to output the
3860                         // time in the text language.
3861                         time_t ptime = from_asctime_utc(localtime);
3862                         if (ptime == static_cast<time_t>(-1)) {
3863                                 cerr << "Warning: Could not parse time `" << localtime
3864                                      << "´ for change tracking, using current time instead.\n";
3865                                 ptime = current_time();
3866                         }
3867                         if (t.cs() == "lyxadded")
3868                                 os << "\n\\change_inserted ";
3869                         else
3870                                 os << "\n\\change_deleted ";
3871                         os << author.bufferId() << ' ' << ptime << '\n';
3872                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3873                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
3874                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3875                                           LaTeXPackages::isAvailable("xcolor");
3876                         // No need to test for luatex, since luatex comes in
3877                         // two flavours (dvi and pdf), like latex, and those
3878                         // are detected by pdflatex.
3879                         if (pdflatex || xetex) {
3880                                 if (xcolorulem) {
3881                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3882                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3883                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3884                                 }
3885                         } else {
3886                                 if (dvipost) {
3887                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
3888                                 } else if (xcolorulem) {
3889                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3890                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3891                                 }
3892                         }
3893                         continue;
3894                 }
3895
3896                 if (t.cs() == "textipa") {
3897                         context.check_layout(os);
3898                         begin_inset(os, "IPA\n");
3899                         bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3900                         context.merging_hyphens_allowed = false;
3901                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3902                         context.merging_hyphens_allowed = merging_hyphens_allowed;
3903                         end_inset(os);
3904                         preamble.registerAutomaticallyLoadedPackage("tipa");
3905                         preamble.registerAutomaticallyLoadedPackage("tipx");
3906                         continue;
3907                 }
3908
3909                 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3910                     || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3911                         context.check_layout(os);
3912                         if (t.cs() == "t")
3913                                 // swallow star
3914                                 p.get_token();
3915                         string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3916                         begin_inset(os, "IPADeco " + type + "\n");
3917                         os << "status open\n";
3918                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3919                         end_inset(os);
3920                         p.skip_spaces();
3921                         continue;
3922                 }
3923
3924                 if (t.cs() == "textvertline") {
3925                         // FIXME: This is not correct, \textvertline is higher than |
3926                         os << "|";
3927                         skip_braces(p);
3928                         continue;
3929                 }
3930
3931                 if (t.cs() == "tone" ) {
3932                         context.check_layout(os);
3933                         // register the tone package
3934                         preamble.registerAutomaticallyLoadedPackage("tone");
3935                         string content = trimSpaceAndEol(p.verbatim_item());
3936                         string command = t.asInput() + "{" + content + "}";
3937                         // some tones can be detected by unicodesymbols, some need special code
3938                         if (is_known(content, known_tones)) {
3939                                 os << "\\IPAChar " << command << "\n";
3940                                 continue;
3941                         }
3942                         // try to see whether the string is in unicodesymbols
3943                         bool termination;
3944                         docstring rem;
3945                         set<string> req;
3946                         docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3947                                 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3948                                 termination, rem, &req);
3949                         if (!s.empty()) {
3950                                 os << to_utf8(s);
3951                                 if (!rem.empty())
3952                                         output_ert_inset(os, to_utf8(rem), context);
3953                                 for (set<string>::const_iterator it = req.begin();
3954                                      it != req.end(); ++it)
3955                                         preamble.registerAutomaticallyLoadedPackage(*it);
3956                         } else
3957                                 // we did not find a non-ert version
3958                                 output_ert_inset(os, command, context);
3959                         continue;
3960                 }
3961
3962                 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3963                              t.cs() == "vphantom") {
3964                         context.check_layout(os);
3965                         if (t.cs() == "phantom")
3966                                 begin_inset(os, "Phantom Phantom\n");
3967                         if (t.cs() == "hphantom")
3968                                 begin_inset(os, "Phantom HPhantom\n");
3969                         if (t.cs() == "vphantom")
3970                                 begin_inset(os, "Phantom VPhantom\n");
3971                         os << "status open\n";
3972                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3973                                             "Phantom");
3974                         end_inset(os);
3975                         continue;
3976                 }
3977
3978                 if (t.cs() == "href") {
3979                         context.check_layout(os);
3980                         string target = convert_literate_command_inset_arg(p.verbatim_item());
3981                         string name = p.verbatim_item();
3982                         pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3983                         bool const literal = !nm.first;
3984                         name = literal ? subst(name, "\n", " ") : nm.second;
3985                         string lit = literal ? "\"true\"" : "\"false\"";
3986                         string type;
3987                         size_t i = target.find(':');
3988                         if (i != string::npos) {
3989                                 type = target.substr(0, i + 1);
3990                                 if (type == "mailto:" || type == "file:")
3991                                         target = target.substr(i + 1);
3992                                 // handle the case that name is equal to target, except of "http(s)://"
3993                                 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3994                                         target = name;
3995                         }
3996                         begin_command_inset(os, "href", "href");
3997                         if (name != target)
3998                                 os << "name \"" << name << "\"\n";
3999                         os << "target \"" << target << "\"\n";
4000                         if (type == "mailto:" || type == "file:")
4001                                 os << "type \"" << type << "\"\n";
4002                         os << "literal " << lit << "\n";
4003                         end_inset(os);
4004                         skip_spaces_braces(p);
4005                         continue;
4006                 }
4007
4008                 if (t.cs() == "lyxline") {
4009                         // swallow size argument (it is not used anyway)
4010                         p.getArg('{', '}');
4011                         if (!context.atParagraphStart()) {
4012                                 // so our line is in the middle of a paragraph
4013                                 // we need to add a new line, lest this line
4014                                 // follow the other content on that line and
4015                                 // run off the side of the page
4016                                 // FIXME: This may create an empty paragraph,
4017                                 //        but without that it would not be
4018                                 //        possible to set noindent below.
4019                                 //        Fortunately LaTeX does not care
4020                                 //        about the empty paragraph.
4021                                 context.new_paragraph(os);
4022                         }
4023                         if (preamble.indentParagraphs()) {
4024                                 // we need to unindent, lest the line be too long
4025                                 context.add_par_extra_stuff("\\noindent\n");
4026                         }
4027                         context.check_layout(os);
4028                         begin_command_inset(os, "line", "rule");
4029                         os << "offset \"0.5ex\"\n"
4030                               "width \"100line%\"\n"
4031                               "height \"1pt\"\n";
4032                         end_inset(os);
4033                         continue;
4034                 }
4035
4036                 if (t.cs() == "rule") {
4037                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4038                         string const width = p.getArg('{', '}');
4039                         string const thickness = p.getArg('{', '}');
4040                         context.check_layout(os);
4041                         begin_command_inset(os, "line", "rule");
4042                         if (!offset.empty())
4043                                 os << "offset \"" << translate_len(offset) << "\"\n";
4044                         os << "width \"" << translate_len(width) << "\"\n"
4045                                   "height \"" << translate_len(thickness) << "\"\n";
4046                         end_inset(os);
4047                         continue;
4048                 }
4049
4050                 // handle refstyle first to catch \eqref which can also occur
4051                 // without refstyle. Only recognize these commands if
4052                 // refstyle.sty was found in the preamble (otherwise \eqref
4053                 // and user defined ref commands could be misdetected).
4054                 if ((where = is_known(t.cs(), known_refstyle_commands))
4055                      && preamble.refstyle()) {
4056                         context.check_layout(os);
4057                         begin_command_inset(os, "ref", "formatted");
4058                         os << "reference \"";
4059                         os << known_refstyle_prefixes[where - known_refstyle_commands]
4060                            << ":";
4061                         os << convert_literate_command_inset_arg(p.verbatim_item())
4062                            << "\"\n";
4063                         os << "plural \"false\"\n";
4064                         os << "caps \"false\"\n";
4065                         os << "noprefix \"false\"\n";
4066                         end_inset(os);
4067                         preamble.registerAutomaticallyLoadedPackage("refstyle");
4068                         continue;
4069                 }
4070
4071                 // if refstyle is used, we must not convert \prettyref to a
4072                 // formatted reference, since that would result in a refstyle command.
4073                 if ((where = is_known(t.cs(), known_ref_commands)) &&
4074                          (t.cs() != "prettyref" || !preamble.refstyle())) {
4075                         string const opt = p.getOpt();
4076                         if (opt.empty()) {
4077                                 context.check_layout(os);
4078                                 begin_command_inset(os, "ref",
4079                                         known_coded_ref_commands[where - known_ref_commands]);
4080                                 os << "reference \""
4081                                    << convert_literate_command_inset_arg(p.verbatim_item())
4082                                    << "\"\n";
4083                                 os << "plural \"false\"\n";
4084                                 os << "caps \"false\"\n";
4085                                 os << "noprefix \"false\"\n";
4086                                 end_inset(os);
4087                                 if (t.cs() == "vref" || t.cs() == "vpageref")
4088                                         preamble.registerAutomaticallyLoadedPackage("varioref");
4089                                 else if (t.cs() == "prettyref")
4090                                         preamble.registerAutomaticallyLoadedPackage("prettyref");
4091                         } else {
4092                                 // LyX does not yet support optional arguments of ref commands
4093                                 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
4094                                        p.verbatim_item() + '}', context);
4095                         }
4096                         continue;
4097                 }
4098
4099                 if (use_natbib &&
4100                          is_known(t.cs(), known_natbib_commands) &&
4101                          ((t.cs() != "citefullauthor" &&
4102                            t.cs() != "citeyear" &&
4103                            t.cs() != "citeyearpar") ||
4104                           p.next_token().asInput() != "*")) {
4105                         context.check_layout(os);
4106                         string command = t.cs();
4107                         if (p.next_token().asInput() == "*") {
4108                                 command += '*';
4109                                 p.get_token();
4110                         }
4111                         if (command == "citefullauthor")
4112                                 // alternative name for "\\citeauthor*"
4113                                 command = "citeauthor*";
4114
4115                         // text before the citation
4116                         string before;
4117                         // text after the citation
4118                         string after;
4119                         get_cite_arguments(p, true, before, after);
4120
4121                         if (command == "cite") {
4122                                 // \cite without optional argument means
4123                                 // \citet, \cite with at least one optional
4124                                 // argument means \citep.
4125                                 if (before.empty() && after.empty())
4126                                         command = "citet";
4127                                 else
4128                                         command = "citep";
4129                         }
4130                         if (before.empty() && after == "[]")
4131                                 // avoid \citet[]{a}
4132                                 after.erase();
4133                         else if (before == "[]" && after == "[]") {
4134                                 // avoid \citet[][]{a}
4135                                 before.erase();
4136                                 after.erase();
4137                         }
4138                         bool literal = false;
4139                         pair<bool, string> aft;
4140                         pair<bool, string> bef;
4141                         // remove the brackets around after and before
4142                         if (!after.empty()) {
4143                                 after.erase(0, 1);
4144                                 after.erase(after.length() - 1, 1);
4145                                 aft = convert_latexed_command_inset_arg(after);
4146                                 literal = !aft.first;
4147                                 after = literal ? subst(after, "\n", " ") : aft.second;
4148                         }
4149                         if (!before.empty()) {
4150                                 before.erase(0, 1);
4151                                 before.erase(before.length() - 1, 1);
4152                                 bef = convert_latexed_command_inset_arg(before);
4153                                 literal |= !bef.first;
4154                                 before = literal ? subst(before, "\n", " ") : bef.second;
4155                                 if (literal && !after.empty())
4156                                         after = subst(after, "\n", " ");
4157                         }
4158                         string lit = literal ? "\"true\"" : "\"false\"";
4159                         begin_command_inset(os, "citation", command);
4160                         os << "after " << '"' << after << '"' << "\n";
4161                         os << "before " << '"' << before << '"' << "\n";
4162                         os << "key \""
4163                            << convert_literate_command_inset_arg(p.verbatim_item())
4164                            << "\"\n"
4165                            << "literal " << lit << "\n";
4166                         end_inset(os);
4167                         // Need to set the cite engine if natbib is loaded by
4168                         // the document class directly
4169                         if (preamble.citeEngine() == "basic")
4170                                 preamble.citeEngine("natbib");
4171                         continue;
4172                 }
4173
4174                 if ((use_biblatex
4175                          && is_known(t.cs(), known_biblatex_commands)
4176                          && ((t.cs() == "cite"
4177                              || t.cs() == "citeauthor"
4178                              || t.cs() == "Citeauthor"
4179                              || t.cs() == "parencite"
4180                              || t.cs() == "citetitle")
4181                          || p.next_token().asInput() != "*"))
4182                         || (use_biblatex_natbib
4183                             && (is_known(t.cs(), known_biblatex_commands)
4184                               || is_known(t.cs(), known_natbib_commands))
4185                             && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4186                                || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4187                                || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4188                                || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4189                                || t.cs() == "parencite" || t.cs() == "citetitle")
4190                                || p.next_token().asInput() != "*"))){
4191                         context.check_layout(os);
4192                         string command = t.cs();
4193                         if (p.next_token().asInput() == "*") {
4194                                 command += '*';
4195                                 p.get_token();
4196                         }
4197
4198                         bool const qualified = suffixIs(command, "s");
4199                         if (qualified)
4200                                 command = rtrim(command, "s");
4201
4202                         // text before the citation
4203                         string before;
4204                         // text after the citation
4205                         string after;
4206                         get_cite_arguments(p, true, before, after, qualified);
4207
4208                         // These use natbib cmd names in LyX
4209                         // for inter-citeengine compativility
4210                         if (command == "citeyear")
4211                                 command = "citebyear";
4212                         else if (command == "cite*")
4213                                 command = "citeyear";
4214                         else if (command == "textcite")
4215                                 command = "citet";
4216                         else if (command == "Textcite")
4217                                 command = "Citet";
4218                         else if (command == "parencite")
4219                                 command = "citep";
4220                         else if (command == "Parencite")
4221                                 command = "Citep";
4222                         else if (command == "parencite*")
4223                                 command = "citeyearpar";
4224                         else if (command == "smartcite")
4225                                 command = "footcite";
4226                         else if (command == "Smartcite")
4227                                 command = "Footcite";
4228
4229                         string const emptyarg = qualified ? "()" : "[]";
4230                         if (before.empty() && after == emptyarg)
4231                                 // avoid \cite[]{a}
4232                                 after.erase();
4233                         else if (before == emptyarg && after == emptyarg) {
4234                                 // avoid \cite[][]{a}
4235                                 before.erase();
4236                                 after.erase();
4237                         }
4238                         bool literal = false;
4239                         pair<bool, string> aft;
4240                         pair<bool, string> bef;
4241                         // remove the brackets around after and before
4242                         if (!after.empty()) {
4243                                 after.erase(0, 1);
4244                                 after.erase(after.length() - 1, 1);
4245                                 aft = convert_latexed_command_inset_arg(after);
4246                                 literal = !aft.first;
4247                                 after = literal ? subst(after, "\n", " ") : aft.second;
4248                         }
4249                         if (!before.empty()) {
4250                                 before.erase(0, 1);
4251                                 before.erase(before.length() - 1, 1);
4252                                 bef = convert_latexed_command_inset_arg(before);
4253                                 literal |= !bef.first;
4254                                 before = literal ? subst(before, "\n", " ") : bef.second;
4255                         }
4256                         string keys, pretextlist, posttextlist;
4257                         if (qualified) {
4258                                 map<string, string> pres, posts, preslit, postslit;
4259                                 vector<string> lkeys;
4260                                 // text before the citation
4261                                 string lbefore, lbeforelit;
4262                                 // text after the citation
4263                                 string lafter, lafterlit;
4264                                 string lkey;    
4265                                 pair<bool, string> laft, lbef;
4266                                 while (true) {
4267                                         get_cite_arguments(p, true, lbefore, lafter);
4268                                         // remove the brackets around after and before
4269                                         if (!lafter.empty()) {
4270                                                 lafter.erase(0, 1);
4271                                                 lafter.erase(lafter.length() - 1, 1);
4272                                                 laft = convert_latexed_command_inset_arg(lafter);
4273                                                 literal |= !laft.first;
4274                                                 lafter = laft.second;
4275                                                 lafterlit = subst(lbefore, "\n", " ");
4276                                         }
4277                                         if (!lbefore.empty()) {
4278                                                 lbefore.erase(0, 1);
4279                                                 lbefore.erase(lbefore.length() - 1, 1);
4280                                                 lbef = convert_latexed_command_inset_arg(lbefore);
4281                                                 literal |= !lbef.first;
4282                                                 lbefore = lbef.second;
4283                                                 lbeforelit = subst(lbefore, "\n", " ");
4284                                         }
4285                                         if (lbefore.empty() && lafter == "[]") {
4286                                                 // avoid \cite[]{a}
4287                                                 lafter.erase();
4288                                                 lafterlit.erase();
4289                                         }
4290                                         else if (lbefore == "[]" && lafter == "[]") {
4291                                                 // avoid \cite[][]{a}
4292                                                 lbefore.erase();
4293                                                 lafter.erase();
4294                                                 lbeforelit.erase();
4295                                                 lafterlit.erase();
4296                                         }
4297                                         lkey = p.getArg('{', '}');
4298                                         if (lkey.empty())
4299                                                 break;
4300                                         if (!lbefore.empty()) {
4301                                                 pres.insert(make_pair(lkey, lbefore));
4302                                                 preslit.insert(make_pair(lkey, lbeforelit));
4303                                         }
4304                                         if (!lafter.empty()) {
4305                                                 posts.insert(make_pair(lkey, lafter));
4306                                                 postslit.insert(make_pair(lkey, lafterlit));
4307                                         }
4308                                         lkeys.push_back(lkey);
4309                                 }
4310                                 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4311                                 if (literal) {
4312                                         pres = preslit;
4313                                         posts = postslit;
4314                                 }
4315                                 for (auto const & ptl : pres) {
4316                                         if (!pretextlist.empty())
4317                                                 pretextlist += '\t';
4318                                         pretextlist += ptl.first + " " + ptl.second;
4319                                 }
4320                                 for (auto const & potl : posts) {
4321                                         if (!posttextlist.empty())
4322                                                 posttextlist += '\t';
4323                                         posttextlist += potl.first + " " + potl.second;
4324                                 }
4325                         } else
4326                                 keys = convert_literate_command_inset_arg(p.verbatim_item());
4327                         if (literal) {
4328                                 if (!after.empty())
4329                                         after = subst(after, "\n", " ");
4330                                 if (!before.empty())
4331                                         before = subst(after, "\n", " ");
4332                         }
4333                         string lit = literal ? "\"true\"" : "\"false\"";
4334                         begin_command_inset(os, "citation", command);
4335                         os << "after " << '"' << after << '"' << "\n";
4336                         os << "before " << '"' << before << '"' << "\n";
4337                         os << "key \""
4338                            << keys
4339                            << "\"\n";
4340                         if (!pretextlist.empty())
4341                                 os << "pretextlist " << '"'  << pretextlist << '"' << "\n";
4342                         if (!posttextlist.empty())
4343                                 os << "posttextlist " << '"'  << posttextlist << '"' << "\n";
4344                         os << "literal " << lit << "\n";
4345                         end_inset(os);
4346                         // Need to set the cite engine if biblatex is loaded by
4347                         // the document class directly
4348                         if (preamble.citeEngine() == "basic")
4349                                 use_biblatex_natbib ?
4350                                           preamble.citeEngine("biblatex-natbib")
4351                                         : preamble.citeEngine("biblatex");
4352                         continue;
4353                 }
4354
4355                 if (use_jurabib &&
4356                          is_known(t.cs(), known_jurabib_commands) &&
4357                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4358                         context.check_layout(os);
4359                         string command = t.cs();
4360                         if (p.next_token().asInput() == "*") {
4361                                 command += '*';
4362                                 p.get_token();
4363                         }
4364                         char argumentOrder = '\0';
4365                         vector<string> const options =
4366                                 preamble.getPackageOptions("jurabib");
4367                         if (find(options.begin(), options.end(),
4368                                       "natbiborder") != options.end())
4369                                 argumentOrder = 'n';
4370                         else if (find(options.begin(), options.end(),
4371                                            "jurabiborder") != options.end())
4372                                 argumentOrder = 'j';
4373
4374                         // text before the citation
4375                         string before;
4376                         // text after the citation
4377                         string after;
4378                         get_cite_arguments(p, argumentOrder != 'j', before, after);
4379
4380                         string const citation = p.verbatim_item();
4381                         if (!before.empty() && argumentOrder == '\0') {
4382                                 cerr << "Warning: Assuming argument order "
4383                                         "of jurabib version 0.6 for\n'"
4384                                      << command << before << after << '{'
4385                                      << citation << "}'.\n"
4386                                         "Add 'jurabiborder' to the jurabib "
4387                                         "package options if you used an\n"
4388                                         "earlier jurabib version." << endl;
4389                         }
4390                         bool literal = false;
4391                         pair<bool, string> aft;
4392                         pair<bool, string> bef;
4393                         // remove the brackets around after and before
4394                         if (!after.empty()) {
4395                                 after.erase(0, 1);
4396                                 after.erase(after.length() - 1, 1);
4397                                 aft = convert_latexed_command_inset_arg(after);
4398                                 literal = !aft.first;
4399                                 after = literal ? subst(after, "\n", " ") : aft.second;
4400                         }
4401                         if (!before.empty()) {
4402                                 before.erase(0, 1);
4403                                 before.erase(before.length() - 1, 1);
4404                                 bef = convert_latexed_command_inset_arg(before);
4405                                 literal |= !bef.first;
4406                                 before = literal ? subst(before, "\n", " ") : bef.second;
4407                                 if (literal && !after.empty())
4408                                         after = subst(after, "\n", " ");
4409                         }
4410                         string lit = literal ? "\"true\"" : "\"false\"";
4411                         begin_command_inset(os, "citation", command);
4412                         os << "after " << '"' << after << "\"\n"
4413                            << "before " << '"' << before << "\"\n"
4414                            << "key " << '"' << citation << "\"\n"
4415                            << "literal " << lit << "\n";
4416                         end_inset(os);
4417                         // Need to set the cite engine if jurabib is loaded by
4418                         // the document class directly
4419                         if (preamble.citeEngine() == "basic")
4420                                 preamble.citeEngine("jurabib");
4421                         continue;
4422                 }
4423
4424                 if (t.cs() == "cite"
4425                         || t.cs() == "nocite") {
4426                         context.check_layout(os);
4427                         string after = p.getArg('[', ']');
4428                         pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4429                         bool const literal = !aft.first;
4430                         after = literal ? subst(after, "\n", " ") : aft.second;
4431                         string lit = literal ? "\"true\"" : "\"false\"";
4432                         string key = convert_literate_command_inset_arg(p.verbatim_item());
4433                         // store the case that it is "\nocite{*}" to use it later for
4434                         // the BibTeX inset
4435                         if (key != "*") {
4436                                 begin_command_inset(os, "citation", t.cs());
4437                                 os << "after " << '"' << after << "\"\n"
4438                                    << "key " << '"' << key << "\"\n"
4439                                    << "literal " << lit << "\n";
4440                                 end_inset(os);
4441                         } else if (t.cs() == "nocite")
4442                                 btprint = key;
4443                         continue;
4444                 }
4445
4446                 if (t.cs() == "index" ||
4447                     (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4448                         context.check_layout(os);
4449                         string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4450                                 p.getArg('[', ']') : "";
4451                         string const kind = arg.empty() ? "idx" : arg;
4452                         begin_inset(os, "Index ");
4453                         os << kind << "\nstatus collapsed\n";
4454                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4455                         end_inset(os);
4456                         if (kind != "idx")
4457                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
4458                         continue;
4459                 }
4460
4461                 if (t.cs() == "nomenclature") {
4462                         context.check_layout(os);
4463                         begin_command_inset(os, "nomenclature", "nomenclature");
4464                         string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4465                         if (!prefix.empty())
4466                                 os << "prefix " << '"' << prefix << '"' << "\n";
4467                         string symbol = p.verbatim_item();
4468                         pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4469                         bool literal = !sym.first;
4470                         string description = p.verbatim_item();
4471                         pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4472                         literal |= !desc.first;
4473                         if (literal) {
4474                                 symbol = subst(symbol, "\n", " ");
4475                                 description = subst(description, "\n", " ");
4476                         } else {
4477                                 symbol = sym.second;
4478                                 description = desc.second;
4479                         }
4480                         string lit = literal ? "\"true\"" : "\"false\"";
4481                         os << "symbol " << '"' << symbol;
4482                         os << "\"\ndescription \""
4483                            << description << "\"\n"
4484                            << "literal " << lit << "\n";
4485                         end_inset(os);
4486                         preamble.registerAutomaticallyLoadedPackage("nomencl");
4487                         continue;
4488                 }
4489
4490                 if (t.cs() == "label") {
4491                         context.check_layout(os);
4492                         begin_command_inset(os, "label", "label");
4493                         os << "name \""
4494                            << convert_literate_command_inset_arg(p.verbatim_item())
4495                            << "\"\n";
4496                         end_inset(os);
4497                         continue;
4498                 }
4499
4500                 if (t.cs() == "lyxmintcaption") {
4501                         string const pos = p.getArg('[', ']');
4502                         if (pos == "t") {
4503                                 string const caption =
4504                                         parse_text_snippet(p, FLAG_ITEM, false,
4505                                                            context);
4506                                 minted_nonfloat_caption = "[t]" + caption;
4507                         } else {
4508                                 // We already got the caption at the bottom,
4509                                 // so simply skip it.
4510                                 parse_text_snippet(p, FLAG_ITEM, false, context);
4511                         }
4512                         eat_whitespace(p, os, context, true);
4513                         continue;
4514                 }
4515
4516                 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4517                         context.check_layout(os);
4518                         string commandname = t.cs();
4519                         bool star = false;
4520                         if (p.next_token().asInput() == "*") {
4521                                 commandname += "*";
4522                                 star = true;
4523                                 p.get_token();
4524                         }
4525                         begin_command_inset(os, "index_print", commandname);
4526                         string const indexname = p.getArg('[', ']');
4527                         if (!star) {
4528                                 if (indexname.empty())
4529                                         os << "type \"idx\"\n";
4530                                 else
4531                                         os << "type \"" << indexname << "\"\n";
4532                                 os << "literal \"true\"\n";
4533                         }
4534                         end_inset(os);
4535                         skip_spaces_braces(p);
4536                         preamble.registerAutomaticallyLoadedPackage("makeidx");
4537                         if (preamble.use_indices() == "true")
4538                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
4539                         continue;
4540                 }
4541
4542                 if (t.cs() == "printnomenclature") {
4543                         string width = "";
4544                         string width_type = "";
4545                         context.check_layout(os);
4546                         begin_command_inset(os, "nomencl_print", "printnomenclature");
4547                         // case of a custom width
4548                         if (p.hasOpt()) {
4549                                 width = p.getArg('[', ']');
4550                                 width = translate_len(width);
4551                                 width_type = "custom";
4552                         }
4553                         // case of no custom width
4554                         // the case of no custom width but the width set
4555                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
4556                         // because the user could have set anything, not only the width
4557                         // of the longest label (which would be width_type = "auto")
4558                         string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4559                         if (label.empty() && width_type.empty())
4560                                 width_type = "none";
4561                         os << "set_width \"" << width_type << "\"\n";
4562                         if (width_type == "custom")
4563                                 os << "width \"" << width << '\"';
4564                         end_inset(os);
4565                         skip_spaces_braces(p);
4566                         preamble.registerAutomaticallyLoadedPackage("nomencl");
4567                         continue;
4568                 }
4569
4570                 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4571                         context.check_layout(os);
4572                         begin_inset(os, "script ");
4573                         os << t.cs().substr(4) << '\n';
4574                         newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4575                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4576                         end_inset(os);
4577                         if (t.cs() == "textsubscript")
4578                                 preamble.registerAutomaticallyLoadedPackage("subscript");
4579                         continue;
4580                 }
4581
4582                 if ((where = is_known(t.cs(), known_quotes))) {
4583                         context.check_layout(os);
4584                         begin_inset(os, "Quotes ");
4585                         string quotetype = known_coded_quotes[where - known_quotes];
4586                         // try to make a smart guess about the side
4587                         Token const prev = p.prev_token();
4588                         bool const opening = (prev.cat() != catSpace && prev.character() != 0
4589                                         && prev.character() != '\n' && prev.character() != '~');
4590                         quotetype = guessQuoteStyle(quotetype, opening);
4591                         os << quotetype;
4592                         end_inset(os);
4593                         // LyX adds {} after the quote, so we have to eat
4594                         // spaces here if there are any before a possible
4595                         // {} pair.
4596                         eat_whitespace(p, os, context, false);
4597                         skip_braces(p);
4598                         continue;
4599                 }
4600
4601                 if ((where = is_known(t.cs(), known_sizes)) &&
4602                         context.new_layout_allowed) {
4603                         context.check_layout(os);
4604                         TeXFont const oldFont = context.font;
4605                         context.font.size = known_coded_sizes[where - known_sizes];
4606                         output_font_change(os, oldFont, context.font);
4607                         eat_whitespace(p, os, context, false);
4608                         continue;
4609                 }
4610
4611                 if ((where = is_known(t.cs(), known_font_families)) &&
4612                          context.new_layout_allowed) {
4613                         context.check_layout(os);
4614                         TeXFont const oldFont = context.font;
4615                         context.font.family =
4616                                 known_coded_font_families[where - known_font_families];
4617                         output_font_change(os, oldFont, context.font);
4618                         eat_whitespace(p, os, context, false);
4619                         continue;
4620                 }
4621
4622                 if ((where = is_known(t.cs(), known_font_series)) &&
4623                          context.new_layout_allowed) {
4624                         context.check_layout(os);
4625                         TeXFont const oldFont = context.font;
4626                         context.font.series =
4627                                 known_coded_font_series[where - known_font_series];
4628                         output_font_change(os, oldFont, context.font);
4629                         eat_whitespace(p, os, context, false);
4630                         continue;
4631                 }
4632
4633                 if ((where = is_known(t.cs(), known_font_shapes)) &&
4634                          context.new_layout_allowed) {
4635                         context.check_layout(os);
4636                         TeXFont const oldFont = context.font;
4637                         context.font.shape =
4638                                 known_coded_font_shapes[where - known_font_shapes];
4639                         output_font_change(os, oldFont, context.font);
4640                         eat_whitespace(p, os, context, false);
4641                         continue;
4642                 }
4643                 if ((where = is_known(t.cs(), known_old_font_families)) &&
4644                          context.new_layout_allowed) {
4645                         context.check_layout(os);
4646                         TeXFont const oldFont = context.font;
4647                         context.font.init();
4648                         context.font.size = oldFont.size;
4649                         context.font.family =
4650                                 known_coded_font_families[where - known_old_font_families];
4651                         output_font_change(os, oldFont, context.font);
4652                         eat_whitespace(p, os, context, false);
4653                         continue;
4654                 }
4655
4656                 if ((where = is_known(t.cs(), known_old_font_series)) &&
4657                          context.new_layout_allowed) {
4658                         context.check_layout(os);
4659                         TeXFont const oldFont = context.font;
4660                         context.font.init();
4661                         context.font.size = oldFont.size;
4662                         context.font.series =
4663                                 known_coded_font_series[where - known_old_font_series];
4664                         output_font_change(os, oldFont, context.font);
4665                         eat_whitespace(p, os, context, false);
4666                         continue;
4667                 }
4668
4669                 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4670                          context.new_layout_allowed) {
4671                         context.check_layout(os);
4672                         TeXFont const oldFont = context.font;
4673                         context.font.init();
4674                         context.font.size = oldFont.size;
4675                         context.font.shape =
4676                                 known_coded_font_shapes[where - known_old_font_shapes];
4677                         output_font_change(os, oldFont, context.font);
4678                         eat_whitespace(p, os, context, false);
4679                         continue;
4680                 }
4681
4682                 if (t.cs() == "selectlanguage") {
4683                         context.check_layout(os);
4684                         // save the language for the case that a
4685                         // \foreignlanguage is used
4686                         context.font.language = babel2lyx(p.verbatim_item());
4687                         os << "\n\\lang " << context.font.language << "\n";
4688                         continue;
4689                 }
4690
4691                 if (t.cs() == "foreignlanguage") {
4692                         string const lang = babel2lyx(p.verbatim_item());
4693                         parse_text_attributes(p, os, FLAG_ITEM, outer,
4694                                               context, "\\lang",
4695                                               context.font.language, lang);
4696                         continue;
4697                 }
4698
4699                 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4700                          && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4701                         // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4702                         string lang;
4703                         // We have to output the whole command if it has an option
4704                         // because LyX doesn't support this yet, see bug #8214,
4705                         // only if there is a single option specifying a variant, we can handle it.
4706                         if (p.hasOpt()) {
4707                                 string langopts = p.getOpt();
4708                                 // check if the option contains a variant, if yes, extract it
4709                                 string::size_type pos_var = langopts.find("variant");
4710                                 string::size_type i = langopts.find(',');
4711                                 string::size_type k = langopts.find('=', pos_var);
4712                                 if (pos_var != string::npos && i == string::npos) {
4713                                         string variant;
4714                                         variant = langopts.substr(k + 1, langopts.length() - k - 2);
4715                                         lang = preamble.polyglossia2lyx(variant);
4716                                         parse_text_attributes(p, os, FLAG_ITEM, outer,
4717                                                                   context, "\\lang",
4718                                                                   context.font.language, lang);
4719                                 } else
4720                                         output_ert_inset(os, t.asInput() + langopts, context);
4721                         } else {
4722                                 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4723                                 parse_text_attributes(p, os, FLAG_ITEM, outer,
4724                                                           context, "\\lang",
4725                                                           context.font.language, lang);
4726                         }
4727                         continue;
4728                 }
4729
4730                 if (t.cs() == "inputencoding") {
4731                         // nothing to write here
4732                         string const enc = subst(p.verbatim_item(), "\n", " ");
4733                         p.setEncoding(enc, Encoding::inputenc);
4734                         continue;
4735                 }
4736
4737                 if (is_known(t.cs(), known_special_chars) ||
4738                     (t.cs() == "protect" &&
4739                      p.next_token().cat() == catEscape &&
4740                      is_known(p.next_token().cs(), known_special_protect_chars))) {
4741                         // LyX sometimes puts a \protect in front, so we have to ignore it
4742                         where = is_known(
4743                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4744                                 known_special_chars);
4745                         context.check_layout(os);
4746                         os << known_coded_special_chars[where - known_special_chars];
4747                         skip_spaces_braces(p);
4748                         continue;
4749                 }
4750
4751                 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4752                          (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4753                           p.next_next_token().asInput() == "-") ||
4754                          (t.cs() == "@" && p.next_token().asInput() == ".")) {
4755                         // LyX sometimes puts a \protect in front, so we have to ignore it
4756                         if (t.cs() == "protect")
4757                                 p.get_token();
4758                         context.check_layout(os);
4759                         if (t.cs() == "nobreakdash")
4760                                 os << "\\SpecialChar nobreakdash\n";
4761                         else
4762                                 os << "\\SpecialChar endofsentence\n";
4763                         p.get_token();
4764                         continue;
4765                 }
4766
4767                 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4768                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4769                             || t.cs() == "%" || t.cs() == "-") {
4770                         context.check_layout(os);
4771                         if (t.cs() == "-")
4772                                 os << "\\SpecialChar softhyphen\n";
4773                         else
4774                                 os << t.cs();
4775                         continue;
4776                 }
4777
4778                 if (t.cs() == "char") {
4779                         context.check_layout(os);
4780                         if (p.next_token().character() == '`') {
4781                                 p.get_token();
4782                                 if (p.next_token().cs() == "\"") {
4783                                         p.get_token();
4784                                         os << '"';
4785                                         skip_braces(p);
4786                                 } else {
4787                                         output_ert_inset(os, "\\char`", context);
4788                                 }
4789                         } else {
4790                                 output_ert_inset(os, "\\char", context);
4791                         }
4792                         continue;
4793                 }
4794
4795                 if (t.cs() == "verb") {
4796                         context.check_layout(os);
4797                         // set catcodes to verbatim early, just in case.
4798                         p.setCatcodes(VERBATIM_CATCODES);
4799                         string delim = p.get_token().asInput();
4800                         Parser::Arg arg = p.verbatimStuff(delim);
4801                         if (arg.first)
4802                                 output_ert_inset(os, "\\verb" + delim
4803                                                  + arg.second + delim, context);
4804                         else
4805                                 cerr << "invalid \\verb command. Skipping" << endl;
4806                         continue;
4807                 }
4808
4809                 // Problem: \= creates a tabstop inside the tabbing environment
4810                 // and else an accent. In the latter case we really would want
4811                 // \={o} instead of \= o.
4812                 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4813                         output_ert_inset(os, t.asInput(), context);
4814                         continue;
4815                 }
4816
4817                 if (t.cs() == "\\") {
4818                         context.check_layout(os);
4819                         if (p.hasOpt())
4820                                 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4821                         else if (p.next_token().asInput() == "*") {
4822                                 p.get_token();
4823                                 // getOpt() eats the following space if there
4824                                 // is no optional argument, but that is OK
4825                                 // here since it has no effect in the output.
4826                                 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4827                         }
4828                         else {
4829                                 begin_inset(os, "Newline newline");
4830                                 end_inset(os);
4831                         }
4832                         continue;
4833                 }
4834
4835                 if (t.cs() == "newline" ||
4836                     (t.cs() == "linebreak" && !p.hasOpt())) {
4837                         context.check_layout(os);
4838                         begin_inset(os, "Newline ");
4839                         os << t.cs();
4840                         end_inset(os);
4841                         skip_spaces_braces(p);
4842                         continue;
4843                 }
4844
4845                 if (t.cs() == "input" || t.cs() == "include"
4846                     || t.cs() == "verbatiminput"
4847                     || t.cs() == "lstinputlisting"
4848                     || t.cs() == "inputminted") {
4849                         string name = t.cs();
4850                         if (name == "verbatiminput"
4851                             && p.next_token().asInput() == "*")
4852                                 name += p.get_token().asInput();
4853                         context.check_layout(os);
4854                         string lstparams;
4855                         bool literal = false;
4856                         if (name == "lstinputlisting" && p.hasOpt()) {
4857                                 lstparams = p.getArg('[', ']');
4858                                 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4859                                 literal = !oa.first;
4860                                 if (literal)
4861                                         lstparams = subst(lstparams, "\n", " ");
4862                                 else
4863                                         lstparams = oa.second;
4864                         } else if (name == "inputminted") {
4865                                 name = "lstinputlisting";
4866                                 string const lang = p.getArg('{', '}');
4867                                 if (lang != "tex") {
4868                                         string cmd = "\\inputminted{" + lang + "}{";
4869                                         cmd += p.getArg('{', '}') + "}";
4870                                         output_ert_inset(os, cmd, context);
4871                                         continue;
4872                                 }
4873                                 if (prefixIs(minted_nonfloat_caption, "[t]")) {
4874                                         minted_nonfloat_caption.erase(0,3);
4875                                         // extract label and caption from the already produced LyX code
4876                                         vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
4877                                         string const caption = nfc.front();
4878                                         string label;
4879                                         vector<string>::iterator it =
4880                                                 find(nfc.begin(), nfc.end(), "LatexCommand label");
4881                                         if (it != nfc.end()) {
4882                                                 ++it;
4883                                                 if (it != nfc.end())
4884                                                         label = *it;
4885                                                 label = support::split(label, '"');
4886                                                 label.pop_back();
4887                                         }
4888                                         minted_nonfloat_caption.clear();
4889                                         lstparams = "caption=" + caption;
4890                                         if (!label.empty())
4891                                                 lstparams += ",label=" + label;
4892                                         pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4893                                         literal = !oa.first;
4894                                         if (literal)
4895                                                 lstparams = subst(lstparams, "\n", " ");
4896                                         else
4897                                                 lstparams = oa.second;
4898                                 }
4899                         }
4900                         string lit = literal ? "\"true\"" : "\"false\"";
4901                         string filename(normalize_filename(p.getArg('{', '}')));
4902                         string const path = getMasterFilePath(true);
4903                         // We want to preserve relative / absolute filenames,
4904                         // therefore path is only used for testing
4905                         if ((t.cs() == "include" || t.cs() == "input") &&
4906                             !makeAbsPath(filename, path).exists()) {
4907                                 // The file extension is probably missing.
4908                                 // Now try to find it out.
4909                                 string const tex_name =
4910                                         find_file(filename, path,
4911                                                   known_tex_extensions);
4912                                 if (!tex_name.empty())
4913                                         filename = tex_name;
4914                         }
4915                         bool external = false;
4916                         string outname;
4917                         if (makeAbsPath(filename, path).exists()) {
4918                                 string const abstexname =
4919                                         makeAbsPath(filename, path).absFileName();
4920                                 string const absfigname =
4921                                         changeExtension(abstexname, ".fig");
4922                                 fix_child_filename(filename);
4923                                 string const lyxname = changeExtension(filename,
4924                                         roundtripMode() ? ".lyx.lyx" : ".lyx");
4925                                 string const abslyxname = makeAbsPath(
4926                                         lyxname, getParentFilePath(false)).absFileName();
4927                                 bool xfig = false;
4928                                 if (!skipChildren())
4929                                         external = FileName(absfigname).exists();
4930                                 if (t.cs() == "input" && !skipChildren()) {
4931                                         string const ext = getExtension(abstexname);
4932
4933                                         // Combined PS/LaTeX:
4934                                         // x.eps, x.pstex_t (old xfig)
4935                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4936                                         FileName const absepsname(
4937                                                 changeExtension(abstexname, ".eps"));
4938                                         FileName const abspstexname(
4939                                                 changeExtension(abstexname, ".pstex"));
4940                                         bool const xfigeps =
4941                                                 (absepsname.exists() ||
4942                                                  abspstexname.exists()) &&
4943                                                 ext == "pstex_t";
4944
4945                                         // Combined PDF/LaTeX:
4946                                         // x.pdf, x.pdftex_t (old xfig)
4947                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4948                                         FileName const abspdfname(
4949                                                 changeExtension(abstexname, ".pdf"));
4950                                         bool const xfigpdf =
4951                                                 abspdfname.exists() &&
4952                                                 (ext == "pdftex_t" || ext == "pdf_t");
4953                                         if (xfigpdf)
4954                                                 pdflatex = true;
4955
4956                                         // Combined PS/PDF/LaTeX:
4957                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4958                                         string const absbase2(
4959                                                 removeExtension(abstexname) + "_pspdftex");
4960                                         FileName const abseps2name(
4961                                                 addExtension(absbase2, ".eps"));
4962                                         FileName const abspdf2name(
4963                                                 addExtension(absbase2, ".pdf"));
4964                                         bool const xfigboth =
4965                                                 abspdf2name.exists() &&
4966                                                 abseps2name.exists() && ext == "pspdftex";
4967
4968                                         xfig = xfigpdf || xfigeps || xfigboth;
4969                                         external = external && xfig;
4970                                 }
4971                                 if (external) {
4972                                         outname = changeExtension(filename, ".fig");
4973                                         FileName abssrc(changeExtension(abstexname, ".fig"));
4974                                         copy_file(abssrc, outname);
4975                                 } else if (xfig) {
4976                                         // Don't try to convert, the result
4977                                         // would be full of ERT.
4978                                         outname = filename;
4979                                         FileName abssrc(abstexname);
4980                                         copy_file(abssrc, outname);
4981                                 } else if (t.cs() != "verbatiminput" &&
4982                                            !skipChildren() &&
4983                                     tex2lyx(abstexname, FileName(abslyxname),
4984                                             p.getEncoding())) {
4985                                         outname = lyxname;
4986                                         // no need to call copy_file
4987                                         // tex2lyx creates the file
4988                                 } else {
4989                                         outname = filename;
4990                                         FileName abssrc(abstexname);
4991                                         copy_file(abssrc, outname);
4992                                 }
4993                         } else {
4994                                 cerr << "Warning: Could not find included file '"
4995                                      << filename << "'." << endl;
4996                                 outname = filename;
4997                         }
4998                         if (external) {
4999                                 begin_inset(os, "External\n");
5000                                 os << "\ttemplate XFig\n"
5001                                    << "\tfilename " << outname << '\n';
5002                                 registerExternalTemplatePackages("XFig");
5003                         } else {
5004                                 begin_command_inset(os, "include", name);
5005                                 outname = subst(outname, "\"", "\\\"");
5006                                 os << "preview false\n"
5007                                       "filename \"" << outname << "\"\n";
5008                                 if (!lstparams.empty())
5009                                         os << "lstparams \"" << lstparams << "\"\n";
5010                                 os << "literal " << lit << "\n";
5011                                 if (t.cs() == "verbatiminput")
5012                                         preamble.registerAutomaticallyLoadedPackage("verbatim");
5013                         }
5014                         end_inset(os);
5015                         continue;
5016                 }
5017
5018                 if (t.cs() == "bibliographystyle") {
5019                         // store new bibliographystyle
5020                         bibliographystyle = p.verbatim_item();
5021                         // If any other command than \bibliography, \addcontentsline
5022                         // and \nocite{*} follows, we need to output the style
5023                         // (because it might be used by that command).
5024                         // Otherwise, it will automatically be output by LyX.
5025                         p.pushPosition();
5026                         bool output = true;
5027                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5028                                 if (t2.cat() == catBegin)
5029                                         break;
5030                                 if (t2.cat() != catEscape)
5031                                         continue;
5032                                 if (t2.cs() == "nocite") {
5033                                         if (p.getArg('{', '}') == "*")
5034                                                 continue;
5035                                 } else if (t2.cs() == "bibliography")
5036                                         output = false;
5037                                 else if (t2.cs() == "phantomsection") {
5038                                         output = false;
5039                                         continue;
5040                                 }
5041                                 else if (t2.cs() == "addcontentsline") {
5042                                         // get the 3 arguments of \addcontentsline
5043                                         p.getArg('{', '}');
5044                                         p.getArg('{', '}');
5045                                         contentslineContent = p.getArg('{', '}');
5046                                         // if the last argument is not \refname we must output
5047                                         if (contentslineContent == "\\refname")
5048                                                 output = false;
5049                                 }
5050                                 break;
5051                         }
5052                         p.popPosition();
5053                         if (output) {
5054                                 output_ert_inset(os,
5055                                         "\\bibliographystyle{" + bibliographystyle + '}',
5056                                         context);
5057                         }
5058                         continue;
5059                 }
5060
5061                 if (t.cs() == "phantomsection") {
5062                         // we only support this if it occurs between
5063                         // \bibliographystyle and \bibliography
5064                         if (bibliographystyle.empty())
5065                                 output_ert_inset(os, "\\phantomsection", context);
5066                         continue;
5067                 }
5068
5069                 if (t.cs() == "addcontentsline") {
5070                         context.check_layout(os);
5071                         // get the 3 arguments of \addcontentsline
5072                         string const one = p.getArg('{', '}');
5073                         string const two = p.getArg('{', '}');
5074                         string const three = p.getArg('{', '}');
5075                         // only if it is a \refname, we support if for the bibtex inset
5076                         if (contentslineContent != "\\refname") {
5077                                 output_ert_inset(os,
5078                                         "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5079                                         context);
5080                         }
5081                         continue;
5082                 }
5083
5084                 else if (t.cs() == "bibliography") {
5085                         context.check_layout(os);
5086                         string BibOpts;
5087                         begin_command_inset(os, "bibtex", "bibtex");
5088                         if (!btprint.empty()) {
5089                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5090                                 // clear the string because the next BibTeX inset can be without the
5091                                 // \nocite{*} option
5092                                 btprint.clear();
5093                         }
5094                         os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5095                         // Do we have addcontentsline?
5096                         if (contentslineContent == "\\refname") {
5097                                 BibOpts = "bibtotoc";
5098                                 // clear string because next BibTeX inset can be without addcontentsline
5099                                 contentslineContent.clear();
5100                         }
5101                         // Do we have a bibliographystyle set?
5102                         if (!bibliographystyle.empty()) {
5103                                 if (BibOpts.empty())
5104                                         BibOpts = normalize_filename(bibliographystyle);
5105                                 else
5106                                         BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5107                                 // clear it because each bibtex entry has its style
5108                                 // and we need an empty string to handle \phantomsection
5109                                 bibliographystyle.clear();
5110                         }
5111                         os << "options " << '"' << BibOpts << '"' << "\n";
5112                         if (p.getEncoding() != preamble.docencoding) {
5113                                 Encoding const * const enc = encodings.fromIconvName(
5114                                         p.getEncoding(), Encoding::inputenc, true);
5115                                 if (!enc) {
5116                                         cerr << "Unknown bib encoding " << p.getEncoding()
5117                                              << ". Ignoring." << std::endl;
5118                                 } else
5119                                         os << "encoding " << '"' << enc->name() << '"' << "\n";
5120                         }
5121                         end_inset(os);
5122                         continue;
5123                 }
5124
5125                 if (t.cs() == "printbibliography") {
5126                         context.check_layout(os);
5127                         string BibOpts;
5128                         string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5129                         vector<string> opts = getVectorFromString(bbloptions);
5130                         vector<string>::iterator it =
5131                                 find(opts.begin(), opts.end(), "heading=bibintoc");
5132                         if (it != opts.end()) {
5133                                 opts.erase(it);
5134                                 BibOpts = "bibtotoc";
5135                         }
5136                         bbloptions = getStringFromVector(opts);
5137                         begin_command_inset(os, "bibtex", "bibtex");
5138                         if (!btprint.empty()) {
5139                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5140                                 // clear the string because the next BibTeX inset can be without the
5141                                 // \nocite{*} option
5142                                 btprint.clear();
5143                         }
5144                         string bibfiles;
5145                         for (auto const & bf : preamble.biblatex_bibliographies) {
5146                                 if (!bibfiles.empty())
5147                                         bibfiles += ",";
5148                                 bibfiles += normalize_filename(bf);
5149                         }
5150                         if (!bibfiles.empty())
5151                                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5152                         // Do we have addcontentsline?
5153                         if (contentslineContent == "\\refname") {
5154                                 BibOpts = "bibtotoc";
5155                                 // clear string because next BibTeX inset can be without addcontentsline
5156                                 contentslineContent.clear();
5157                         }
5158                         os << "options " << '"' << BibOpts << '"' << "\n";
5159                         if (!bbloptions.empty())
5160                                 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5161                         if (!preamble.bibencoding.empty()) {
5162                                 Encoding const * const enc = encodings.fromLaTeXName(
5163                                         preamble.bibencoding, Encoding::inputenc, true);
5164                                 if (!enc) {
5165                                         cerr << "Unknown bib encoding " << preamble.bibencoding
5166                                              << ". Ignoring." << std::endl;
5167                                 } else
5168                                         os << "encoding " << '"' << enc->name() << '"' << "\n";
5169                         }
5170                         end_inset(os);
5171                         need_commentbib = false;
5172                         continue;
5173                 }
5174
5175                 if (t.cs() == "bibbysection") {
5176                         context.check_layout(os);
5177                         string BibOpts;
5178                         string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5179                         vector<string> opts = getVectorFromString(bbloptions);
5180                         vector<string>::iterator it =
5181                                 find(opts.begin(), opts.end(), "heading=bibintoc");
5182                         if (it != opts.end()) {
5183                                 opts.erase(it);
5184                                 BibOpts = "bibtotoc";
5185                         }
5186                         bbloptions = getStringFromVector(opts);
5187                         begin_command_inset(os, "bibtex", "bibtex");
5188                         os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5189                         string bibfiles;
5190                         for (auto const & bf : preamble.biblatex_bibliographies) {
5191                                 if (!bibfiles.empty())
5192                                         bibfiles += ",";
5193                                 bibfiles += normalize_filename(bf);
5194                         }
5195                         if (!bibfiles.empty())
5196                                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5197                         os << "options " << '"' << BibOpts << '"' << "\n";
5198                         if (!bbloptions.empty())
5199                                 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5200                         end_inset(os);
5201                         need_commentbib = false;
5202                         continue;
5203                 }
5204
5205                 if (t.cs() == "parbox") {
5206                         // Test whether this is an outer box of a shaded box
5207                         p.pushPosition();
5208                         // swallow arguments
5209                         while (p.hasOpt()) {
5210                                 p.getArg('[', ']');
5211                                 p.skip_spaces(true);
5212                         }
5213                         p.getArg('{', '}');
5214                         p.skip_spaces(true);
5215                         // eat the '{'
5216                         if (p.next_token().cat() == catBegin)
5217                                 p.get_token();
5218                         p.skip_spaces(true);
5219                         Token to = p.get_token();
5220                         bool shaded = false;
5221                         if (to.asInput() == "\\begin") {
5222                                 p.skip_spaces(true);
5223                                 if (p.getArg('{', '}') == "shaded")
5224                                         shaded = true;
5225                         }
5226                         p.popPosition();
5227                         if (shaded) {
5228                                 parse_outer_box(p, os, FLAG_ITEM, outer,
5229                                                 context, "parbox", "shaded");
5230                         } else
5231                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5232                                           "", "", t.cs(), "", "");
5233                         continue;
5234                 }
5235
5236                 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5237                     t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5238                     t.cs() == "shadowbox" || t.cs() == "doublebox") {
5239                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5240                         continue;
5241                 }
5242
5243                 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5244                         string backgroundcolor;
5245                         preamble.registerAutomaticallyLoadedPackage("xcolor");
5246                         if (t.cs() == "fcolorbox") {
5247                                 string const framecolor = p.getArg('{', '}');
5248                                 backgroundcolor = p.getArg('{', '}');
5249                                 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5250                         } else {
5251                                 backgroundcolor = p.getArg('{', '}');
5252                                 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5253                         }
5254                         continue;
5255                 }
5256
5257                 // FIXME: due to the compiler limit of "if" nestings
5258                 // the code for the alignment was put here
5259                 // put them in their own if if this is fixed
5260                 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5261                     || t.cs() == "shadowsize"
5262                     || t.cs() == "raggedleft" || t.cs() == "centering"
5263                     || t.cs() == "raggedright") {
5264                         if (t.cs() == "fboxrule")
5265                                 fboxrule = "";
5266                         if (t.cs() == "fboxsep")
5267                                 fboxsep = "";
5268                         if (t.cs() == "shadowsize")
5269                                 shadow_size = "";
5270                         if (t.cs() != "raggedleft" && t.cs() != "centering"
5271                          && t.cs() != "raggedright") {
5272                                 p.skip_spaces(true);
5273                                 while (p.good() && p.next_token().cat() != catSpace
5274                                        && p.next_token().cat() != catNewline
5275                                        && p.next_token().cat() != catEscape) {
5276                                         if (t.cs() == "fboxrule")
5277                                                 fboxrule = fboxrule + p.get_token().asInput();
5278                                         if (t.cs() == "fboxsep")
5279                                                 fboxsep = fboxsep + p.get_token().asInput();
5280                                         if (t.cs() == "shadowsize")
5281                                                 shadow_size = shadow_size + p.get_token().asInput();
5282                                 }
5283                         } else {
5284                                 output_ert_inset(os, t.asInput(), context);
5285                         }
5286                         continue;
5287                 }
5288
5289                 //\framebox() is part of the picture environment and different from \framebox{}
5290                 //\framebox{} will be parsed by parse_outer_box
5291                 if (t.cs() == "framebox") {
5292                         if (p.next_token().character() == '(') {
5293                                 //the syntax is: \framebox(x,y)[position]{content}
5294                                 string arg = t.asInput();
5295                                 arg += p.getFullParentheseArg();
5296                                 arg += p.getFullOpt();
5297                                 eat_whitespace(p, os, context, false);
5298                                 output_ert_inset(os, arg + '{', context);
5299                                 parse_text(p, os, FLAG_ITEM, outer, context);
5300                                 output_ert_inset(os, "}", context);
5301                         } else {
5302                                 //the syntax is: \framebox[width][position]{content}
5303                                 string special = p.getFullOpt();
5304                                 special += p.getOpt();
5305                                 parse_outer_box(p, os, FLAG_ITEM, outer,
5306                                                     context, t.cs(), special);
5307                         }
5308                         continue;
5309                 }
5310
5311                 //\makebox() is part of the picture environment and different from \makebox{}
5312                 //\makebox{} will be parsed by parse_box
5313                 if (t.cs() == "makebox") {
5314                         if (p.next_token().character() == '(') {
5315                                 //the syntax is: \makebox(x,y)[position]{content}
5316                                 string arg = t.asInput();
5317                                 arg += p.getFullParentheseArg();
5318                                 arg += p.getFullOpt();
5319                                 eat_whitespace(p, os, context, false);
5320                                 output_ert_inset(os, arg + '{', context);
5321                                 parse_text(p, os, FLAG_ITEM, outer, context);
5322                                 output_ert_inset(os, "}", context);
5323                         } else
5324                                 //the syntax is: \makebox[width][position]{content}
5325                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5326                                           "", "", t.cs(), "", "");
5327                         continue;
5328                 }
5329
5330                 if (t.cs() == "smallskip" ||
5331                     t.cs() == "medskip" ||
5332                     t.cs() == "bigskip" ||
5333                     t.cs() == "vfill") {
5334                         context.check_layout(os);
5335                         begin_inset(os, "VSpace ");
5336                         os << t.cs();
5337                         end_inset(os);
5338                         skip_spaces_braces(p);
5339                         continue;
5340                 }
5341
5342                 if ((where = is_known(t.cs(), known_spaces))) {
5343                         context.check_layout(os);
5344                         begin_inset(os, "space ");
5345                         os << '\\' << known_coded_spaces[where - known_spaces]
5346                            << '\n';
5347                         end_inset(os);
5348                         // LaTeX swallows whitespace after all spaces except
5349                         // "\\,". We have to do that here, too, because LyX
5350                         // adds "{}" which would make the spaces significant.
5351                         if (t.cs() !=  ",")
5352                                 eat_whitespace(p, os, context, false);
5353                         // LyX adds "{}" after all spaces except "\\ " and
5354                         // "\\,", so we have to remove "{}".
5355                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
5356                         // remove the braces after "\\,", too.
5357                         if (t.cs() != " ")
5358                                 skip_braces(p);
5359                         continue;
5360                 }
5361
5362                 if (t.cs() == "newpage" ||
5363                     (t.cs() == "pagebreak" && !p.hasOpt()) ||
5364                     t.cs() == "clearpage" ||
5365                     t.cs() == "cleardoublepage") {
5366                         context.check_layout(os);
5367                         begin_inset(os, "Newpage ");
5368                         os << t.cs();
5369                         end_inset(os);
5370                         skip_spaces_braces(p);
5371                         continue;
5372                 }
5373
5374                 if (t.cs() == "DeclareRobustCommand" ||
5375                          t.cs() == "DeclareRobustCommandx" ||
5376                          t.cs() == "newcommand" ||
5377                          t.cs() == "newcommandx" ||
5378                          t.cs() == "providecommand" ||
5379                          t.cs() == "providecommandx" ||
5380                          t.cs() == "renewcommand" ||
5381                          t.cs() == "renewcommandx") {
5382                         // DeclareRobustCommand, DeclareRobustCommandx,
5383                         // providecommand and providecommandx could be handled
5384                         // by parse_command(), but we need to call
5385                         // add_known_command() here.
5386                         string name = t.asInput();
5387                         if (p.next_token().asInput() == "*") {
5388                                 // Starred form. Eat '*'
5389                                 p.get_token();
5390                                 name += '*';
5391                         }
5392                         string const command = p.verbatim_item();
5393                         string const opt1 = p.getFullOpt();
5394                         string const opt2 = p.getFullOpt();
5395                         add_known_command(command, opt1, !opt2.empty());
5396                         string const ert = name + '{' + command + '}' +
5397                                            opt1 + opt2 +
5398                                            '{' + p.verbatim_item() + '}';
5399
5400                         if (t.cs() == "DeclareRobustCommand" ||
5401                             t.cs() == "DeclareRobustCommandx" ||
5402                             t.cs() == "providecommand" ||
5403                             t.cs() == "providecommandx" ||
5404                             name[name.length()-1] == '*')
5405                                 output_ert_inset(os, ert, context);
5406                         else {
5407                                 context.check_layout(os);
5408                                 begin_inset(os, "FormulaMacro");
5409                                 os << "\n" << ert;
5410                                 end_inset(os);
5411                         }
5412                         continue;
5413                 }
5414
5415                 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5416                         // let could be handled by parse_command(),
5417                         // but we need to call add_known_command() here.
5418                         string ert = t.asInput();
5419                         string name;
5420                         p.skip_spaces();
5421                         if (p.next_token().cat() == catBegin) {
5422                                 name = p.verbatim_item();
5423                                 ert += '{' + name + '}';
5424                         } else {
5425                                 name = p.verbatim_item();
5426                                 ert += name;
5427                         }
5428                         string command;
5429                         p.skip_spaces();
5430                         if (p.next_token().cat() == catBegin) {
5431                                 command = p.verbatim_item();
5432                                 ert += '{' + command + '}';
5433                         } else {
5434                                 command = p.verbatim_item();
5435                                 ert += command;
5436                         }
5437                         // If command is known, make name known too, to parse
5438                         // its arguments correctly. For this reason we also
5439                         // have commands in syntax.default that are hardcoded.
5440                         CommandMap::iterator it = known_commands.find(command);
5441                         if (it != known_commands.end())
5442                                 known_commands[t.asInput()] = it->second;
5443                         output_ert_inset(os, ert, context);
5444                         continue;
5445                 }
5446
5447                 if (t.cs() == "hspace" || t.cs() == "vspace") {
5448                         if (starred)
5449                                 p.get_token();
5450                         string name = t.asInput();
5451                         string const length = p.verbatim_item();
5452                         string unit;
5453                         string valstring;
5454                         bool valid = splitLatexLength(length, valstring, unit);
5455                         bool known_hspace = false;
5456                         bool known_vspace = false;
5457                         bool known_unit = false;
5458                         double value = 0.0;
5459                         if (valid) {
5460                                 istringstream iss(valstring);
5461                                 iss >> value;
5462                                 if (value == 1.0) {
5463                                         if (t.cs()[0] == 'h') {
5464                                                 if (unit == "\\fill") {
5465                                                         if (!starred) {
5466                                                                 unit = "";
5467                                                                 name = "\\hfill";
5468                                                         }
5469                                                         known_hspace = true;
5470                                                 }
5471                                         } else {
5472                                                 if (unit == "\\smallskipamount") {
5473                                                         unit = "smallskip";
5474                                                         known_vspace = true;
5475                                                 } else if (unit == "\\medskipamount") {
5476                                                         unit = "medskip";
5477                                                         known_vspace = true;
5478                                                 } else if (unit == "\\bigskipamount") {
5479                                                         unit = "bigskip";
5480                                                         known_vspace = true;
5481                                                 } else if (unit == "\\fill") {
5482                                                         unit = "vfill";
5483                                                         known_vspace = true;
5484                                                 }
5485                                         }
5486                                 }
5487                                 if (!known_hspace && !known_vspace) {
5488                                         switch (unitFromString(unit)) {
5489                                         case Length::SP:
5490                                         case Length::PT:
5491                                         case Length::BP:
5492                                         case Length::DD:
5493                                         case Length::MM:
5494                                         case Length::PC:
5495                                         case Length::CC:
5496                                         case Length::CM:
5497                                         case Length::IN:
5498                                         case Length::EX:
5499                                         case Length::EM:
5500                                         case Length::MU:
5501                                                 known_unit = true;
5502                                                 break;
5503                                         default: {
5504                                                 //unitFromString(unit) fails for relative units like Length::PCW
5505                                                 // therefore handle them separately
5506                                                 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5507                                                         || unit == "\\textwidth" || unit == "\\linewidth"
5508                                                         || unit == "\\textheight" || unit == "\\paperheight"
5509                                                         || unit == "\\baselineskip")
5510                                                         known_unit = true;
5511                                                 break;
5512                                                          }
5513                                         }
5514                                 }
5515                         }
5516
5517                         // check for glue lengths
5518                         bool is_gluelength = false;
5519                         string gluelength = length;
5520                         string::size_type i = length.find(" minus");
5521                         if (i == string::npos) {
5522                                 i = length.find(" plus");
5523                                 if (i != string::npos)
5524                                         is_gluelength = true;
5525                         } else
5526                                 is_gluelength = true;
5527                         // if yes transform "9xx minus 8yy plus 7zz"
5528                         // to "9xx-8yy+7zz"
5529                         if (is_gluelength) {
5530                                 i = gluelength.find(" minus");
5531                                 if (i != string::npos)
5532                                         gluelength.replace(i, 7, "-");
5533                                 i = gluelength.find(" plus");
5534                                 if (i != string::npos)
5535                                         gluelength.replace(i, 6, "+");
5536                         }
5537
5538                         if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5539                                 // Literal horizontal length or known variable
5540                                 context.check_layout(os);
5541                                 begin_inset(os, "space ");
5542                                 os << name;
5543                                 if (starred)
5544                                         os << '*';
5545                                 os << '{';
5546                                 if (known_hspace)
5547                                         os << unit;
5548                                 os << "}";
5549                                 if (known_unit && !known_hspace)
5550                                         os << "\n\\length " << translate_len(length);
5551                                 if (is_gluelength)
5552                                         os << "\n\\length " << gluelength;
5553                                 end_inset(os);
5554                         } else if (known_unit || known_vspace || is_gluelength) {
5555                                 // Literal vertical length or known variable
5556                                 context.check_layout(os);
5557                                 begin_inset(os, "VSpace ");
5558                                 if (known_vspace)
5559                                         os << unit;
5560                                 if (known_unit && !known_vspace)
5561                                         os << translate_len(length);
5562                                 if (is_gluelength)
5563                                         os << gluelength;
5564                                 if (starred)
5565                                         os << '*';
5566                                 end_inset(os);
5567                         } else {
5568                                 // LyX can't handle other length variables in Inset VSpace/space
5569                                 if (starred)
5570                                         name += '*';
5571                                 if (valid) {
5572                                         if (value == 1.0)
5573                                                 output_ert_inset(os, name + '{' + unit + '}', context);
5574                                         else if (value == -1.0)
5575                                                 output_ert_inset(os, name + "{-" + unit + '}', context);
5576                                         else
5577                                                 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5578                                 } else
5579                                         output_ert_inset(os, name + '{' + length + '}', context);
5580                         }
5581                         continue;
5582                 }
5583
5584                 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5585                 // might be one or several options or a star.
5586                 // The single '=' is meant here.
5587                 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5588                         if (starred)
5589                                 p.get_token();
5590                         p.skip_spaces();
5591                         context.check_layout(os);
5592                         // store the latexparam here. This is eaten in parse_text_in_inset
5593                         context.latexparam = newinsetlayout->latexparam();
5594                         docstring name = newinsetlayout->name();
5595                         bool const caption = name.find(from_ascii("Caption:")) == 0;
5596                         if (caption) {
5597                                 // Already done for floating minted listings.
5598                                 if (minted_float.empty()) {
5599                                         begin_inset(os, "Caption ");
5600                                         os << to_utf8(name.substr(8)) << '\n';
5601                                 }
5602                         } else {
5603                                 // FIXME: what do we do if the prefix is not Flex: ?
5604                                 if (prefixIs(name, from_ascii("Flex:")))
5605                                         name.erase(0, 5);
5606                                 begin_inset(os, "Flex ");
5607                                 os << to_utf8(name) << '\n'
5608                                    << "status collapsed\n";
5609                         }
5610                         if (!minted_float.empty()) {
5611                                 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5612                         } else if (newinsetlayout->isPassThru()) {
5613                                 // set catcodes to verbatim early, just in case.
5614                                 p.setCatcodes(VERBATIM_CATCODES);
5615                                 string delim = p.get_token().asInput();
5616                                 if (delim != "{")
5617                                         cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5618                                 //FIXME: handle error condition
5619                                 string const arg = p.verbatimStuff("}").second;
5620                                 Context newcontext(true, context.textclass);
5621                                 if (newinsetlayout->forcePlainLayout())
5622                                         newcontext.layout = &context.textclass.plainLayout();
5623                                 output_ert(os, arg, newcontext);
5624                         } else
5625                                 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5626                         context.latexparam.clear();
5627                         if (caption)
5628                                 p.skip_spaces();
5629                         // Minted caption insets are not closed here because
5630                         // we collect everything into the caption.
5631                         if (minted_float.empty())
5632                                 end_inset(os);
5633                         continue;
5634                 }
5635
5636                 // The single '=' is meant here.
5637                 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5638                         if (starred)
5639                                 p.get_token();
5640                         p.skip_spaces();
5641                         context.check_layout(os);
5642                         docstring name = newinsetlayout->name();
5643                         bool const caption = name.find(from_ascii("Caption:")) == 0;
5644                         if (caption) {
5645                                 // Already done for floating minted listings.
5646                                 if (minted_float.empty()) {
5647                                         begin_inset(os, "Caption ");
5648                                         os << to_utf8(name.substr(8)) << '\n';
5649                                 }
5650                         } else {
5651                                 // FIXME: what do we do if the prefix is not Flex: ?
5652                                 if (prefixIs(name, from_ascii("Flex:")))
5653                                         name.erase(0, 5);
5654                                 begin_inset(os, "Flex ");
5655                                 os << to_utf8(name) << '\n'
5656                                    << "status collapsed\n";
5657                         }
5658                         if (!minted_float.empty()) {
5659                                 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5660                         } else if (newinsetlayout->isPassThru()) {
5661                                 // set catcodes to verbatim early, just in case.
5662                                 p.setCatcodes(VERBATIM_CATCODES);
5663                                 string delim = p.get_token().asInput();
5664                                 if (delim != "{")
5665                                         cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5666                                 //FIXME: handle error condition
5667                                 string const arg = p.verbatimStuff("}").second;
5668                                 Context newcontext(true, context.textclass);
5669                                 if (newinsetlayout->forcePlainLayout())
5670                                         newcontext.layout = &context.textclass.plainLayout();
5671                                 output_ert(os, arg, newcontext);
5672                         } else
5673                                 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5674                         if (caption)
5675                                 p.skip_spaces();
5676                         // Minted caption insets are not closed here because
5677                         // we collect everything into the caption.
5678                         if (minted_float.empty())
5679                                 end_inset(os);
5680                         continue;
5681                 }
5682
5683                 if (t.cs() == "includepdf") {
5684                         p.skip_spaces();
5685                         string const arg = p.getArg('[', ']');
5686                         map<string, string> opts;
5687                         vector<string> keys;
5688                         split_map(arg, opts, keys);
5689                         string name = normalize_filename(p.verbatim_item());
5690                         string const path = getMasterFilePath(true);
5691                         // We want to preserve relative / absolute filenames,
5692                         // therefore path is only used for testing
5693                         if (!makeAbsPath(name, path).exists()) {
5694                                 // The file extension is probably missing.
5695                                 // Now try to find it out.
5696                                 char const * const pdfpages_format[] = {"pdf", 0};
5697                                 string const pdftex_name =
5698                                         find_file(name, path, pdfpages_format);
5699                                 if (!pdftex_name.empty()) {
5700                                         name = pdftex_name;
5701                                         pdflatex = true;
5702                                 }
5703                         }
5704                         FileName const absname = makeAbsPath(name, path);
5705                         if (absname.exists())
5706                         {
5707                                 fix_child_filename(name);
5708                                 copy_file(absname, name);
5709                         } else
5710                                 cerr << "Warning: Could not find file '"
5711                                      << name << "'." << endl;
5712                         // write output
5713                         context.check_layout(os);
5714                         begin_inset(os, "External\n\ttemplate ");
5715                         os << "PDFPages\n\tfilename "
5716                            << name << "\n";
5717                         // parse the options
5718                         if (opts.find("pages") != opts.end())
5719                                 os << "\textra LaTeX \"pages="
5720                                    << opts["pages"] << "\"\n";
5721                         if (opts.find("angle") != opts.end())
5722                                 os << "\trotateAngle "
5723                                    << opts["angle"] << '\n';
5724                         if (opts.find("origin") != opts.end()) {
5725                                 ostringstream ss;
5726                                 string const opt = opts["origin"];
5727                                 if (opt == "tl") ss << "topleft";
5728                                 if (opt == "bl") ss << "bottomleft";
5729                                 if (opt == "Bl") ss << "baselineleft";
5730                                 if (opt == "c") ss << "center";
5731                                 if (opt == "tc") ss << "topcenter";
5732                                 if (opt == "bc") ss << "bottomcenter";
5733                                 if (opt == "Bc") ss << "baselinecenter";
5734                                 if (opt == "tr") ss << "topright";
5735                                 if (opt == "br") ss << "bottomright";
5736                                 if (opt == "Br") ss << "baselineright";
5737                                 if (!ss.str().empty())
5738                                         os << "\trotateOrigin " << ss.str() << '\n';
5739                                 else
5740                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5741                         }
5742                         if (opts.find("width") != opts.end())
5743                                 os << "\twidth "
5744                                    << translate_len(opts["width"]) << '\n';
5745                         if (opts.find("height") != opts.end())
5746                                 os << "\theight "
5747                                    << translate_len(opts["height"]) << '\n';
5748                         if (opts.find("keepaspectratio") != opts.end())
5749                                 os << "\tkeepAspectRatio\n";
5750                         end_inset(os);
5751                         context.check_layout(os);
5752                         registerExternalTemplatePackages("PDFPages");
5753                         continue;
5754                 }
5755
5756                 if (t.cs() == "loadgame") {
5757                         p.skip_spaces();
5758                         string name = normalize_filename(p.verbatim_item());
5759                         string const path = getMasterFilePath(true);
5760                         // We want to preserve relative / absolute filenames,
5761                         // therefore path is only used for testing
5762                         if (!makeAbsPath(name, path).exists()) {
5763                                 // The file extension is probably missing.
5764                                 // Now try to find it out.
5765                                 char const * const lyxskak_format[] = {"fen", 0};
5766                                 string const lyxskak_name =
5767                                         find_file(name, path, lyxskak_format);
5768                                 if (!lyxskak_name.empty())
5769                                         name = lyxskak_name;
5770                         }
5771                         FileName const absname = makeAbsPath(name, path);
5772                         if (absname.exists())
5773                         {
5774                                 fix_child_filename(name);
5775                                 copy_file(absname, name);
5776                         } else
5777                                 cerr << "Warning: Could not find file '"
5778                                      << name << "'." << endl;
5779                         context.check_layout(os);
5780                         begin_inset(os, "External\n\ttemplate ");
5781                         os << "ChessDiagram\n\tfilename "
5782                            << name << "\n";
5783                         end_inset(os);
5784                         context.check_layout(os);
5785                         // after a \loadgame follows a \showboard
5786                         if (p.get_token().asInput() == "showboard")
5787                                 p.get_token();
5788                         registerExternalTemplatePackages("ChessDiagram");
5789                         continue;
5790                 }
5791
5792                 // try to see whether the string is in unicodesymbols
5793                 // Only use text mode commands, since we are in text mode here,
5794                 // and math commands may be invalid (bug 6797)
5795                 string name = t.asInput();
5796                 // handle the dingbats, cyrillic and greek
5797                 if (name == "\\textcyr")
5798                         name = "\\textcyrillic";
5799                 if (name == "\\ding" || name == "\\textcyrillic" ||
5800                     (name == "\\textgreek" && !preamble.usePolyglossia()))
5801                         name = name + '{' + p.getArg('{', '}') + '}';
5802                 // handle the ifsym characters
5803                 else if (name == "\\textifsymbol") {
5804                         string const optif = p.getFullOpt();
5805                         string const argif = p.getArg('{', '}');
5806                         name = name + optif + '{' + argif + '}';
5807                 }
5808                 // handle the \ascii characters
5809                 // the case of \ascii within braces, as LyX outputs it, is already
5810                 // handled for t.cat() == catBegin
5811                 else if (name == "\\ascii") {
5812                         // the code is "\asci\xxx"
5813                         name = "{" + name + p.get_token().asInput() + "}";
5814                         skip_braces(p);
5815                 }
5816                 // handle some TIPA special characters
5817                 else if (preamble.isPackageUsed("tipa")) {
5818                         if (name == "\\s") {
5819                                 // fromLaTeXCommand() does not yet
5820                                 // recognize tipa short cuts
5821                                 name = "\\textsyllabic";
5822                         } else if (name == "\\=" &&
5823                                    p.next_token().asInput() == "*") {
5824                                 // fromLaTeXCommand() does not yet
5825                                 // recognize tipa short cuts
5826                                 p.get_token();
5827                                 name = "\\textsubbar";
5828                         } else if (name == "\\textdoublevertline") {
5829                                 // FIXME: This is not correct,
5830                                 // \textvertline is higher than \textbardbl
5831                                 name = "\\textbardbl";
5832                                 skip_braces(p);
5833                         } else if (name == "\\!" ) {
5834                                 if (p.next_token().asInput() == "b") {
5835                                         p.get_token();  // eat 'b'
5836                                         name = "\\texthtb";
5837                                         skip_braces(p);
5838                                 } else if (p.next_token().asInput() == "d") {
5839                                         p.get_token();
5840                                         name = "\\texthtd";
5841                                         skip_braces(p);
5842                                 } else if (p.next_token().asInput() == "g") {
5843                                         p.get_token();
5844                                         name = "\\texthtg";
5845                                         skip_braces(p);
5846                                 } else if (p.next_token().asInput() == "G") {
5847                                         p.get_token();
5848                                         name = "\\texthtscg";
5849                                         skip_braces(p);
5850                                 } else if (p.next_token().asInput() == "j") {
5851                                         p.get_token();
5852                                         name = "\\texthtbardotlessj";
5853                                         skip_braces(p);
5854                                 } else if (p.next_token().asInput() == "o") {
5855                                         p.get_token();
5856                                         name = "\\textbullseye";
5857                                         skip_braces(p);
5858                                 }
5859                         } else if (name == "\\*" ) {
5860                                 if (p.next_token().asInput() == "k") {
5861                                         p.get_token();
5862                                         name = "\\textturnk";
5863                                         skip_braces(p);
5864                                 } else if (p.next_token().asInput() == "r") {
5865                                         p.get_token();  // eat 'b'
5866                                         name = "\\textturnr";
5867                                         skip_braces(p);
5868                                 } else if (p.next_token().asInput() == "t") {
5869                                         p.get_token();
5870                                         name = "\\textturnt";
5871                                         skip_braces(p);
5872                                 } else if (p.next_token().asInput() == "w") {
5873                                         p.get_token();
5874                                         name = "\\textturnw";
5875                                         skip_braces(p);
5876                                 }
5877                         }
5878                 }
5879                 if ((name.size() == 2 &&
5880                      contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5881                      p.next_token().asInput() != "*") ||
5882                     is_known(name.substr(1), known_tipa_marks)) {
5883                         // name is a command that corresponds to a
5884                         // combining character in unicodesymbols.
5885                         // Append the argument, fromLaTeXCommand()
5886                         // will either convert it to a single
5887                         // character or a combining sequence.
5888                         name += '{' + p.verbatim_item() + '}';
5889                 }
5890                 // now get the character from unicodesymbols
5891                 bool termination;
5892                 docstring rem;
5893                 set<string> req;
5894                 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5895                                 Encodings::TEXT_CMD, termination, rem, &req));
5896                 if (!s.empty()) {
5897                         context.check_layout(os);
5898                         os << to_utf8(s);
5899                         if (!rem.empty())
5900                                 output_ert_inset(os, to_utf8(rem), context);
5901                         if (termination)
5902                                 skip_spaces_braces(p);
5903                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5904                                 preamble.registerAutomaticallyLoadedPackage(*it);
5905                 }
5906                 //cerr << "#: " << t << " mode: " << mode << endl;
5907                 // heuristic: read up to next non-nested space
5908                 /*
5909                 string s = t.asInput();
5910                 string z = p.verbatim_item();
5911                 while (p.good() && z != " " && !z.empty()) {
5912                         //cerr << "read: " << z << endl;
5913                         s += z;
5914                         z = p.verbatim_item();
5915                 }
5916                 cerr << "found ERT: " << s << endl;
5917                 output_ert_inset(os, s + ' ', context);
5918                 */
5919                 else {
5920                         if (t.asInput() == name &&
5921                             p.next_token().asInput() == "*") {
5922                                 // Starred commands like \vspace*{}
5923                                 p.get_token();  // Eat '*'
5924                                 name += '*';
5925                         }
5926                         if (!parse_command(name, p, os, outer, context))
5927                                 output_ert_inset(os, name, context);
5928                 }
5929         }
5930 }
5931
5932
5933 string guessLanguage(Parser & p, string const & lang)
5934 {
5935         typedef std::map<std::string, size_t> LangMap;
5936         // map from language names to number of characters
5937         LangMap used;
5938         used[lang] = 0;
5939         for (char const * const * i = supported_CJK_languages; *i; i++)
5940                 used[string(*i)] = 0;
5941
5942         while (p.good()) {
5943                 Token const t = p.get_token();
5944                 // comments are not counted for any language
5945                 if (t.cat() == catComment)
5946                         continue;
5947                 // commands are not counted as well, but we need to detect
5948                 // \begin{CJK} and switch encoding if needed
5949                 if (t.cat() == catEscape) {
5950                         if (t.cs() == "inputencoding") {
5951                                 string const enc = subst(p.verbatim_item(), "\n", " ");
5952                                 p.setEncoding(enc, Encoding::inputenc);
5953                                 continue;
5954                         }
5955                         if (t.cs() != "begin")
5956                                 continue;
5957                 } else {
5958                         // Non-CJK content is counted for lang.
5959                         // We do not care about the real language here:
5960                         // If we have more non-CJK contents than CJK contents,
5961                         // we simply use the language that was specified as
5962                         // babel main language.
5963                         used[lang] += t.asInput().length();
5964                         continue;
5965                 }
5966                 // Now we are starting an environment
5967                 p.pushPosition();
5968                 string const name = p.getArg('{', '}');
5969                 if (name != "CJK") {
5970                         p.popPosition();
5971                         continue;
5972                 }
5973                 // It is a CJK environment
5974                 p.popPosition();
5975                 /* name = */ p.getArg('{', '}');
5976                 string const encoding = p.getArg('{', '}');
5977                 /* mapping = */ p.getArg('{', '}');
5978                 string const encoding_old = p.getEncoding();
5979                 char const * const * const where =
5980                         is_known(encoding, supported_CJK_encodings);
5981                 if (where)
5982                         p.setEncoding(encoding, Encoding::CJK);
5983                 else
5984                         p.setEncoding("UTF-8");
5985                 string const text = p.ertEnvironment("CJK");
5986                 p.setEncoding(encoding_old);
5987                 p.skip_spaces();
5988                 if (!where) {
5989                         // ignore contents in unknown CJK encoding
5990                         continue;
5991                 }
5992                 // the language of the text
5993                 string const cjk =
5994                         supported_CJK_languages[where - supported_CJK_encodings];
5995                 used[cjk] += text.length();
5996         }
5997         LangMap::const_iterator use = used.begin();
5998         for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5999                 if (it->second > use->second)
6000                         use = it;
6001         }
6002         return use->first;
6003 }
6004
6005
6006 void check_comment_bib(ostream & os, Context & context)
6007 {
6008         if (!need_commentbib)
6009                 return;
6010         // We have a bibliography database, but no bibliography with biblatex
6011         // which is completely valid. Insert a bibtex inset in a note.
6012         context.check_layout(os);
6013         begin_inset(os, "Note Note\n");
6014         os << "status open\n";
6015         os << "\\begin_layout Plain Layout\n";
6016         begin_command_inset(os, "bibtex", "bibtex");
6017         string bibfiles;
6018         for (auto const & bf : preamble.biblatex_bibliographies) {
6019                 if (!bibfiles.empty())
6020                         bibfiles += ",";
6021                 bibfiles += normalize_filename(bf);
6022         }
6023         if (!bibfiles.empty())
6024                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6025         end_inset(os);// Bibtex
6026         os << "\\end_layout\n";
6027         end_inset(os);// Note
6028 }
6029
6030 // }])
6031
6032
6033 } // namespace lyx