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