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