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