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