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