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