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