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