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