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