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