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