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