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