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