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