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