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