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