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