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