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