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