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