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