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