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