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