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