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