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