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