]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
7b3baf52eaf2de4a0b15f379c8f46a13a4e55646
[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                         p.skip_spaces();
2183                         string s;
2184                         bool optarg = false;
2185                         if (p.next_token().cat() != catEscape &&
2186                             p.next_token().character() == '[') {
2187                                 p.get_token(); // eat '['
2188                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2189                                                        outer, context);
2190                                 optarg = true;
2191                         }
2192                         context.set_item();
2193                         context.check_layout(os);
2194                         if (context.has_item) {
2195                                 // An item in an unknown list-like environment
2196                                 // FIXME: Do this in check_layout()!
2197                                 context.has_item = false;
2198                                 if (optarg)
2199                                         handle_ert(os, "\\item", context);
2200                                 else
2201                                         handle_ert(os, "\\item ", context);
2202                         }
2203                         if (optarg) {
2204                                 if (context.layout->labeltype != LABEL_MANUAL) {
2205                                         // LyX does not support \item[\mybullet]
2206                                         // in itemize environments
2207                                         handle_ert(os, "[", context);
2208                                         os << s;
2209                                         handle_ert(os, "]", context);
2210                                 } else if (!s.empty()) {
2211                                         // The space is needed to separate the
2212                                         // item from the rest of the sentence.
2213                                         os << s << ' ';
2214                                         eat_whitespace(p, os, context, false);
2215                                 }
2216                         }
2217                 }
2218
2219                 else if (t.cs() == "bibitem") {
2220                         context.set_item();
2221                         context.check_layout(os);
2222                         string label = convert_command_inset_arg(p.getArg('[', ']'));
2223                         string key = convert_command_inset_arg(p.verbatim_item());
2224                         if (contains(label, '\\') || contains(key, '\\')) {
2225                                 // LyX can't handle LaTeX commands in labels or keys
2226                                 handle_ert(os, t.asInput() + '[' + label +
2227                                                "]{" + p.verbatim_item() + '}',
2228                                            context);
2229                         } else {
2230                                 begin_command_inset(os, "bibitem", "bibitem");
2231                                 os << "label \"" << label << "\"\n"
2232                                       "key \"" << key << "\"\n";
2233                                 end_inset(os);
2234                         }
2235                 }
2236
2237                 else if (is_macro(p))
2238                         parse_macro(p, os, context);
2239
2240                 else if (t.cs() == "noindent") {
2241                         p.skip_spaces();
2242                         context.add_par_extra_stuff("\\noindent\n");
2243                 }
2244
2245                 else if (t.cs() == "appendix") {
2246                         context.add_par_extra_stuff("\\start_of_appendix\n");
2247                         // We need to start a new paragraph. Otherwise the
2248                         // appendix in 'bla\appendix\chapter{' would start
2249                         // too late.
2250                         context.new_paragraph(os);
2251                         // We need to make sure that the paragraph is
2252                         // generated even if it is empty. Otherwise the
2253                         // appendix in '\par\appendix\par\chapter{' would
2254                         // start too late.
2255                         context.check_layout(os);
2256                         // FIXME: This is a hack to prevent paragraph
2257                         // deletion if it is empty. Handle this better!
2258                         handle_comment(os,
2259                                 "%dummy comment inserted by tex2lyx to "
2260                                 "ensure that this paragraph is not empty",
2261                                 context);
2262                         // Both measures above may generate an additional
2263                         // empty paragraph, but that does not hurt, because
2264                         // whitespace does not matter here.
2265                         eat_whitespace(p, os, context, true);
2266                 }
2267
2268                 // Must catch empty dates before findLayout is called below
2269                 else if (t.cs() == "date") {
2270                         string const date = p.verbatim_item();
2271                         if (date.empty())
2272                                 preamble.suppressDate(true);
2273                         else {
2274                                 preamble.suppressDate(false);
2275                                 if (context.new_layout_allowed &&
2276                                     (newlayout = findLayout(context.textclass,
2277                                                             t.cs(), true))) {
2278                                         // write the layout
2279                                         output_command_layout(os, p, outer,
2280                                                         context, newlayout);
2281                                         p.skip_spaces();
2282                                         if (!title_layout_found)
2283                                                 title_layout_found = newlayout->intitle;
2284                                 } else
2285                                         handle_ert(os, "\\date{" + date + '}',
2286                                                         context);
2287                         }
2288                 }
2289
2290                 // Starred section headings
2291                 // Must attempt to parse "Section*" before "Section".
2292                 else if ((p.next_token().asInput() == "*") &&
2293                          context.new_layout_allowed &&
2294                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2295                         // write the layout
2296                         p.get_token();
2297                         output_command_layout(os, p, outer, context, newlayout);
2298                         p.skip_spaces();
2299                         if (!title_layout_found)
2300                                 title_layout_found = newlayout->intitle;
2301                 }
2302
2303                 // Section headings and the like
2304                 else if (context.new_layout_allowed &&
2305                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2306                         // write the layout
2307                         output_command_layout(os, p, outer, context, newlayout);
2308                         p.skip_spaces();
2309                         if (!title_layout_found)
2310                                 title_layout_found = newlayout->intitle;
2311                 }
2312
2313                 else if (t.cs() == "caption") {
2314                         p.skip_spaces();
2315                         context.check_layout(os);
2316                         p.skip_spaces();
2317                         begin_inset(os, "Caption\n");
2318                         Context newcontext(true, context.textclass);
2319                         newcontext.font = context.font;
2320                         newcontext.check_layout(os);
2321                         if (p.next_token().cat() != catEscape &&
2322                             p.next_token().character() == '[') {
2323                                 p.get_token(); // eat '['
2324                                 begin_inset(os, "Argument\n");
2325                                 os << "status collapsed\n";
2326                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2327                                 end_inset(os);
2328                                 eat_whitespace(p, os, context, false);
2329                         }
2330                         parse_text(p, os, FLAG_ITEM, outer, context);
2331                         context.check_end_layout(os);
2332                         // We don't need really a new paragraph, but
2333                         // we must make sure that the next item gets a \begin_layout.
2334                         context.new_paragraph(os);
2335                         end_inset(os);
2336                         p.skip_spaces();
2337                         newcontext.check_end_layout(os);
2338                 }
2339
2340                 else if (t.cs() == "subfloat") {
2341                         // the syntax is \subfloat[caption]{content}
2342                         // if it is a table of figure depends on the surrounding float
2343                         bool has_caption = false;
2344                         p.skip_spaces();
2345                         // do nothing if there is no outer float
2346                         if (!float_type.empty()) {
2347                                 context.check_layout(os);
2348                                 p.skip_spaces();
2349                                 begin_inset(os, "Float " + float_type + "\n");
2350                                 os << "wide false"
2351                                    << "\nsideways false"
2352                                    << "\nstatus collapsed\n\n";
2353                                 // test for caption
2354                                 string caption;
2355                                 if (p.next_token().cat() != catEscape &&
2356                                                 p.next_token().character() == '[') {
2357                                                         p.get_token(); // eat '['
2358                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2359                                                         has_caption = true;
2360                                 }
2361                                 // the content
2362                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2363                                 // the caption comes always as the last
2364                                 if (has_caption) {
2365                                         // we must make sure that the caption gets a \begin_layout
2366                                         os << "\n\\begin_layout Plain Layout";
2367                                         p.skip_spaces();
2368                                         begin_inset(os, "Caption\n");
2369                                         Context newcontext(true, context.textclass);
2370                                         newcontext.font = context.font;
2371                                         newcontext.check_layout(os);
2372                                         os << caption << "\n";
2373                                         newcontext.check_end_layout(os);
2374                                         // We don't need really a new paragraph, but
2375                                         // we must make sure that the next item gets a \begin_layout.
2376                                         //newcontext.new_paragraph(os);
2377                                         end_inset(os);
2378                                         p.skip_spaces();
2379                                 }
2380                                 // We don't need really a new paragraph, but
2381                                 // we must make sure that the next item gets a \begin_layout.
2382                                 if (has_caption)
2383                                         context.new_paragraph(os);
2384                                 end_inset(os);
2385                                 p.skip_spaces();
2386                                 context.check_end_layout(os);
2387                                 // close the layout we opened
2388                                 if (has_caption)
2389                                         os << "\n\\end_layout\n";
2390                         } else {
2391                                 // if the float type is not supported or there is no surrounding float
2392                                 // output it as ERT
2393                                 if (p.hasOpt()) {
2394                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2395                                         handle_ert(os, t.asInput() + '[' + opt_arg +
2396                                                "]{" + p.verbatim_item() + '}', context);
2397                                 } else
2398                                         handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2399                         }
2400                 }
2401
2402                 else if (t.cs() == "includegraphics") {
2403                         bool const clip = p.next_token().asInput() == "*";
2404                         if (clip)
2405                                 p.get_token();
2406                         string const arg = p.getArg('[', ']');
2407                         map<string, string> opts;
2408                         vector<string> keys;
2409                         split_map(arg, opts, keys);
2410                         if (clip)
2411                                 opts["clip"] = string();
2412                         string name = normalize_filename(p.verbatim_item());
2413
2414                         string const path = getMasterFilePath();
2415                         // We want to preserve relative / absolute filenames,
2416                         // therefore path is only used for testing
2417                         if (!makeAbsPath(name, path).exists()) {
2418                                 // The file extension is probably missing.
2419                                 // Now try to find it out.
2420                                 string const dvips_name =
2421                                         find_file(name, path,
2422                                                   known_dvips_graphics_formats);
2423                                 string const pdftex_name =
2424                                         find_file(name, path,
2425                                                   known_pdftex_graphics_formats);
2426                                 if (!dvips_name.empty()) {
2427                                         if (!pdftex_name.empty()) {
2428                                                 cerr << "This file contains the "
2429                                                         "latex snippet\n"
2430                                                         "\"\\includegraphics{"
2431                                                      << name << "}\".\n"
2432                                                         "However, files\n\""
2433                                                      << dvips_name << "\" and\n\""
2434                                                      << pdftex_name << "\"\n"
2435                                                         "both exist, so I had to make a "
2436                                                         "choice and took the first one.\n"
2437                                                         "Please move the unwanted one "
2438                                                         "someplace else and try again\n"
2439                                                         "if my choice was wrong."
2440                                                      << endl;
2441                                         }
2442                                         name = dvips_name;
2443                                 } else if (!pdftex_name.empty()) {
2444                                         name = pdftex_name;
2445                                         pdflatex = true;
2446                                 }
2447                         }
2448
2449                         if (makeAbsPath(name, path).exists())
2450                                 fix_relative_filename(name);
2451                         else
2452                                 cerr << "Warning: Could not find graphics file '"
2453                                      << name << "'." << endl;
2454
2455                         context.check_layout(os);
2456                         begin_inset(os, "Graphics ");
2457                         os << "\n\tfilename " << name << '\n';
2458                         if (opts.find("width") != opts.end())
2459                                 os << "\twidth "
2460                                    << translate_len(opts["width"]) << '\n';
2461                         if (opts.find("height") != opts.end())
2462                                 os << "\theight "
2463                                    << translate_len(opts["height"]) << '\n';
2464                         if (opts.find("scale") != opts.end()) {
2465                                 istringstream iss(opts["scale"]);
2466                                 double val;
2467                                 iss >> val;
2468                                 val = val*100;
2469                                 os << "\tscale " << val << '\n';
2470                         }
2471                         if (opts.find("angle") != opts.end()) {
2472                                 os << "\trotateAngle "
2473                                    << opts["angle"] << '\n';
2474                                 vector<string>::const_iterator a =
2475                                         find(keys.begin(), keys.end(), "angle");
2476                                 vector<string>::const_iterator s =
2477                                         find(keys.begin(), keys.end(), "width");
2478                                 if (s == keys.end())
2479                                         s = find(keys.begin(), keys.end(), "height");
2480                                 if (s == keys.end())
2481                                         s = find(keys.begin(), keys.end(), "scale");
2482                                 if (s != keys.end() && distance(s, a) > 0)
2483                                         os << "\tscaleBeforeRotation\n";
2484                         }
2485                         if (opts.find("origin") != opts.end()) {
2486                                 ostringstream ss;
2487                                 string const opt = opts["origin"];
2488                                 if (opt.find('l') != string::npos) ss << "left";
2489                                 if (opt.find('r') != string::npos) ss << "right";
2490                                 if (opt.find('c') != string::npos) ss << "center";
2491                                 if (opt.find('t') != string::npos) ss << "Top";
2492                                 if (opt.find('b') != string::npos) ss << "Bottom";
2493                                 if (opt.find('B') != string::npos) ss << "Baseline";
2494                                 if (!ss.str().empty())
2495                                         os << "\trotateOrigin " << ss.str() << '\n';
2496                                 else
2497                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2498                         }
2499                         if (opts.find("keepaspectratio") != opts.end())
2500                                 os << "\tkeepAspectRatio\n";
2501                         if (opts.find("clip") != opts.end())
2502                                 os << "\tclip\n";
2503                         if (opts.find("draft") != opts.end())
2504                                 os << "\tdraft\n";
2505                         if (opts.find("bb") != opts.end())
2506                                 os << "\tBoundingBox "
2507                                    << opts["bb"] << '\n';
2508                         int numberOfbbOptions = 0;
2509                         if (opts.find("bbllx") != opts.end())
2510                                 numberOfbbOptions++;
2511                         if (opts.find("bblly") != opts.end())
2512                                 numberOfbbOptions++;
2513                         if (opts.find("bburx") != opts.end())
2514                                 numberOfbbOptions++;
2515                         if (opts.find("bbury") != opts.end())
2516                                 numberOfbbOptions++;
2517                         if (numberOfbbOptions == 4)
2518                                 os << "\tBoundingBox "
2519                                    << opts["bbllx"] << " " << opts["bblly"] << " "
2520                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
2521                         else if (numberOfbbOptions > 0)
2522                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2523                         numberOfbbOptions = 0;
2524                         if (opts.find("natwidth") != opts.end())
2525                                 numberOfbbOptions++;
2526                         if (opts.find("natheight") != opts.end())
2527                                 numberOfbbOptions++;
2528                         if (numberOfbbOptions == 2)
2529                                 os << "\tBoundingBox 0bp 0bp "
2530                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
2531                         else if (numberOfbbOptions > 0)
2532                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2533                         ostringstream special;
2534                         if (opts.find("hiresbb") != opts.end())
2535                                 special << "hiresbb,";
2536                         if (opts.find("trim") != opts.end())
2537                                 special << "trim,";
2538                         if (opts.find("viewport") != opts.end())
2539                                 special << "viewport=" << opts["viewport"] << ',';
2540                         if (opts.find("totalheight") != opts.end())
2541                                 special << "totalheight=" << opts["totalheight"] << ',';
2542                         if (opts.find("type") != opts.end())
2543                                 special << "type=" << opts["type"] << ',';
2544                         if (opts.find("ext") != opts.end())
2545                                 special << "ext=" << opts["ext"] << ',';
2546                         if (opts.find("read") != opts.end())
2547                                 special << "read=" << opts["read"] << ',';
2548                         if (opts.find("command") != opts.end())
2549                                 special << "command=" << opts["command"] << ',';
2550                         string s_special = special.str();
2551                         if (!s_special.empty()) {
2552                                 // We had special arguments. Remove the trailing ','.
2553                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2554                         }
2555                         // TODO: Handle the unknown settings better.
2556                         // Warn about invalid options.
2557                         // Check whether some option was given twice.
2558                         end_inset(os);
2559                 }
2560
2561                 else if (t.cs() == "footnote" ||
2562                          (t.cs() == "thanks" && context.layout->intitle)) {
2563                         p.skip_spaces();
2564                         context.check_layout(os);
2565                         begin_inset(os, "Foot\n");
2566                         os << "status collapsed\n\n";
2567                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2568                         end_inset(os);
2569                 }
2570
2571                 else if (t.cs() == "marginpar") {
2572                         p.skip_spaces();
2573                         context.check_layout(os);
2574                         begin_inset(os, "Marginal\n");
2575                         os << "status collapsed\n\n";
2576                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2577                         end_inset(os);
2578                 }
2579
2580                 else if (t.cs() == "ensuremath") {
2581                         p.skip_spaces();
2582                         context.check_layout(os);
2583                         string const s = p.verbatim_item();
2584                         //FIXME: this never triggers in UTF8
2585                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2586                                 os << s;
2587                         else
2588                                 handle_ert(os, "\\ensuremath{" + s + "}",
2589                                            context);
2590                 }
2591
2592                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2593                         if (title_layout_found) {
2594                                 // swallow this
2595                                 skip_spaces_braces(p);
2596                         } else
2597                                 handle_ert(os, t.asInput(), context);
2598                 }
2599
2600                 else if (t.cs() == "tableofcontents") {
2601                         context.check_layout(os);
2602                         begin_command_inset(os, "toc", "tableofcontents");
2603                         end_inset(os);
2604                         skip_spaces_braces(p);
2605                 }
2606
2607                 else if (t.cs() == "listoffigures") {
2608                         context.check_layout(os);
2609                         begin_inset(os, "FloatList figure\n");
2610                         end_inset(os);
2611                         skip_spaces_braces(p);
2612                 }
2613
2614                 else if (t.cs() == "listoftables") {
2615                         context.check_layout(os);
2616                         begin_inset(os, "FloatList table\n");
2617                         end_inset(os);
2618                         skip_spaces_braces(p);
2619                 }
2620
2621                 else if (t.cs() == "listof") {
2622                         p.skip_spaces(true);
2623                         string const name = p.get_token().cs();
2624                         if (context.textclass.floats().typeExist(name)) {
2625                                 context.check_layout(os);
2626                                 begin_inset(os, "FloatList ");
2627                                 os << name << "\n";
2628                                 end_inset(os);
2629                                 p.get_token(); // swallow second arg
2630                         } else
2631                                 handle_ert(os, "\\listof{" + name + "}", context);
2632                 }
2633
2634                 else if (t.cs() == "textrm")
2635                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2636                                               context, "\\family",
2637                                               context.font.family, "roman");
2638
2639                 else if (t.cs() == "textsf")
2640                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2641                                               context, "\\family",
2642                                               context.font.family, "sans");
2643
2644                 else if (t.cs() == "texttt")
2645                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2646                                               context, "\\family",
2647                                               context.font.family, "typewriter");
2648
2649                 else if (t.cs() == "textmd")
2650                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2651                                               context, "\\series",
2652                                               context.font.series, "medium");
2653
2654                 else if (t.cs() == "textbf")
2655                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2656                                               context, "\\series",
2657                                               context.font.series, "bold");
2658
2659                 else if (t.cs() == "textup")
2660                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2661                                               context, "\\shape",
2662                                               context.font.shape, "up");
2663
2664                 else if (t.cs() == "textit")
2665                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2666                                               context, "\\shape",
2667                                               context.font.shape, "italic");
2668
2669                 else if (t.cs() == "textsl")
2670                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2671                                               context, "\\shape",
2672                                               context.font.shape, "slanted");
2673
2674                 else if (t.cs() == "textsc")
2675                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2676                                               context, "\\shape",
2677                                               context.font.shape, "smallcaps");
2678
2679                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2680                         context.check_layout(os);
2681                         TeXFont oldFont = context.font;
2682                         context.font.init();
2683                         context.font.size = oldFont.size;
2684                         os << "\n\\family " << context.font.family << "\n";
2685                         os << "\n\\series " << context.font.series << "\n";
2686                         os << "\n\\shape " << context.font.shape << "\n";
2687                         if (t.cs() == "textnormal") {
2688                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2689                                 output_font_change(os, context.font, oldFont);
2690                                 context.font = oldFont;
2691                         } else
2692                                 eat_whitespace(p, os, context, false);
2693                 }
2694
2695                 else if (t.cs() == "textcolor") {
2696                         // scheme is \textcolor{color name}{text}
2697                         string const color = p.verbatim_item();
2698                         // we only support the predefined colors of the color package
2699                         if (color == "black" || color == "blue" || color == "cyan"
2700                                 || color == "green" || color == "magenta" || color == "red"
2701                                 || color == "white" || color == "yellow") {
2702                                         context.check_layout(os);
2703                                         os << "\n\\color " << color << "\n";
2704                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2705                                         context.check_layout(os);
2706                                         os << "\n\\color inherit\n";
2707                                         preamble.registerAutomaticallyLoadedPackage("color");
2708                         } else
2709                                 // for custom defined colors
2710                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
2711                 }
2712
2713                 else if (t.cs() == "underbar" || t.cs() == "uline") {
2714                         // \underbar is not 100% correct (LyX outputs \uline
2715                         // of ulem.sty). The difference is that \ulem allows
2716                         // line breaks, and \underbar does not.
2717                         // Do NOT handle \underline.
2718                         // \underbar cuts through y, g, q, p etc.,
2719                         // \underline does not.
2720                         context.check_layout(os);
2721                         os << "\n\\bar under\n";
2722                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2723                         context.check_layout(os);
2724                         os << "\n\\bar default\n";
2725                         preamble.registerAutomaticallyLoadedPackage("ulem");
2726                 }
2727
2728                 else if (t.cs() == "sout") {
2729                         context.check_layout(os);
2730                         os << "\n\\strikeout on\n";
2731                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2732                         context.check_layout(os);
2733                         os << "\n\\strikeout default\n";
2734                         preamble.registerAutomaticallyLoadedPackage("ulem");
2735                 }
2736
2737                 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2738                          t.cs() == "emph" || t.cs() == "noun") {
2739                         context.check_layout(os);
2740                         os << "\n\\" << t.cs() << " on\n";
2741                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2742                         context.check_layout(os);
2743                         os << "\n\\" << t.cs() << " default\n";
2744                         if (t.cs() == "uuline" || t.cs() == "uwave")
2745                                 preamble.registerAutomaticallyLoadedPackage("ulem");
2746                 }
2747
2748                 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2749                         context.check_layout(os);
2750                         string name = p.getArg('{', '}');
2751                         string localtime = p.getArg('{', '}');
2752                         preamble.registerAuthor(name);
2753                         Author const & author = preamble.getAuthor(name);
2754                         // from_ctime() will fail if LyX decides to output the
2755                         // time in the text language. It might also use a wrong
2756                         // time zone (if the original LyX document was exported
2757                         // with a different time zone).
2758                         time_t ptime = from_ctime(localtime);
2759                         if (ptime == static_cast<time_t>(-1)) {
2760                                 cerr << "Warning: Could not parse time `" << localtime
2761                                      << "´ for change tracking, using current time instead.\n";
2762                                 ptime = current_time();
2763                         }
2764                         if (t.cs() == "lyxadded")
2765                                 os << "\n\\change_inserted ";
2766                         else
2767                                 os << "\n\\change_deleted ";
2768                         os << author.bufferId() << ' ' << ptime << '\n';
2769                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2770                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
2771                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2772                                           LaTeXPackages::isAvailable("xcolor");
2773                         // No need to test for luatex, since luatex comes in
2774                         // two flavours (dvi and pdf), like latex, and those
2775                         // are detected by pdflatex.
2776                         if (pdflatex || xetex) {
2777                                 if (xcolorulem) {
2778                                         preamble.registerAutomaticallyLoadedPackage("ulem");
2779                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
2780                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2781                                 }
2782                         } else {
2783                                 if (dvipost) {
2784                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
2785                                 } else if (xcolorulem) {
2786                                         preamble.registerAutomaticallyLoadedPackage("ulem");
2787                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
2788                                 }
2789                         }
2790                 }
2791
2792                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2793                              t.cs() == "vphantom") {
2794                         context.check_layout(os);
2795                         if (t.cs() == "phantom")
2796                                 begin_inset(os, "Phantom Phantom\n");
2797                         if (t.cs() == "hphantom")
2798                                 begin_inset(os, "Phantom HPhantom\n");
2799                         if (t.cs() == "vphantom")
2800                                 begin_inset(os, "Phantom VPhantom\n");
2801                         os << "status open\n";
2802                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2803                                             "Phantom");
2804                         end_inset(os);
2805                 }
2806
2807                 else if (t.cs() == "href") {
2808                         context.check_layout(os);
2809                         string target = p.getArg('{', '}');
2810                         string name = p.getArg('{', '}');
2811                         string type;
2812                         size_t i = target.find(':');
2813                         if (i != string::npos) {
2814                                 type = target.substr(0, i + 1);
2815                                 if (type == "mailto:" || type == "file:")
2816                                         target = target.substr(i + 1);
2817                                 // handle the case that name is equal to target, except of "http://"
2818                                 else if (target.substr(i + 3) == name && type == "http:")
2819                                         target = name;
2820                         }
2821                         begin_command_inset(os, "href", "href");
2822                         if (name != target)
2823                                 os << "name \"" << name << "\"\n";
2824                         os << "target \"" << target << "\"\n";
2825                         if (type == "mailto:" || type == "file:")
2826                                 os << "type \"" << type << "\"\n";
2827                         end_inset(os);
2828                         skip_spaces_braces(p);
2829                 }
2830                 
2831                 else if (t.cs() == "lyxline") {
2832                         // swallow size argument (it is not used anyway)
2833                         p.getArg('{', '}');
2834                         if (!context.atParagraphStart()) {
2835                                 // so our line is in the middle of a paragraph
2836                                 // we need to add a new line, lest this line
2837                                 // follow the other content on that line and
2838                                 // run off the side of the page
2839                                 // FIXME: This may create an empty paragraph,
2840                                 //        but without that it would not be
2841                                 //        possible to set noindent below.
2842                                 //        Fortunately LaTeX does not care
2843                                 //        about the empty paragraph.
2844                                 context.new_paragraph(os);
2845                         }
2846                         if (preamble.indentParagraphs()) {
2847                                 // we need to unindent, lest the line be too long
2848                                 context.add_par_extra_stuff("\\noindent\n");
2849                         }
2850                         context.check_layout(os);
2851                         begin_command_inset(os, "line", "rule");
2852                         os << "offset \"0.5ex\"\n"
2853                               "width \"100line%\"\n"
2854                               "height \"1pt\"\n";
2855                         end_inset(os);
2856                 }
2857
2858                 else if (t.cs() == "rule") {
2859                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2860                         string const width = p.getArg('{', '}');
2861                         string const thickness = p.getArg('{', '}');
2862                         context.check_layout(os);
2863                         begin_command_inset(os, "line", "rule");
2864                         if (!offset.empty())
2865                                 os << "offset \"" << translate_len(offset) << "\"\n";
2866                         os << "width \"" << translate_len(width) << "\"\n"
2867                                   "height \"" << translate_len(thickness) << "\"\n";
2868                         end_inset(os);
2869                 }
2870
2871                 else if (is_known(t.cs(), known_phrases) ||
2872                          (t.cs() == "protect" &&
2873                           p.next_token().cat() == catEscape &&
2874                           is_known(p.next_token().cs(), known_phrases))) {
2875                         // LyX sometimes puts a \protect in front, so we have to ignore it
2876                         // FIXME: This needs to be changed when bug 4752 is fixed.
2877                         char const * const * where = is_known(
2878                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2879                                 known_phrases);
2880                         context.check_layout(os);
2881                         os << known_coded_phrases[where - known_phrases];
2882                         skip_spaces_braces(p);
2883                 }
2884
2885                 else if (is_known(t.cs(), known_ref_commands)) {
2886                         string const opt = p.getOpt();
2887                         if (opt.empty()) {
2888                                 context.check_layout(os);
2889                                 char const * const * where = is_known(t.cs(),
2890                                         known_ref_commands);
2891                                 begin_command_inset(os, "ref",
2892                                         known_coded_ref_commands[where - known_ref_commands]);
2893                                 os << "reference \""
2894                                    << convert_command_inset_arg(p.verbatim_item())
2895                                    << "\"\n";
2896                                 end_inset(os);
2897                         } else {
2898                                 // LyX does not support optional arguments of ref commands
2899                                 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2900                                                p.verbatim_item() + "}", context);
2901                         }
2902                 }
2903
2904                 else if (use_natbib &&
2905                          is_known(t.cs(), known_natbib_commands) &&
2906                          ((t.cs() != "citefullauthor" &&
2907                            t.cs() != "citeyear" &&
2908                            t.cs() != "citeyearpar") ||
2909                           p.next_token().asInput() != "*")) {
2910                         context.check_layout(os);
2911                         string command = t.cs();
2912                         if (p.next_token().asInput() == "*") {
2913                                 command += '*';
2914                                 p.get_token();
2915                         }
2916                         if (command == "citefullauthor")
2917                                 // alternative name for "\\citeauthor*"
2918                                 command = "citeauthor*";
2919
2920                         // text before the citation
2921                         string before;
2922                         // text after the citation
2923                         string after;
2924                         get_cite_arguments(p, true, before, after);
2925
2926                         if (command == "cite") {
2927                                 // \cite without optional argument means
2928                                 // \citet, \cite with at least one optional
2929                                 // argument means \citep.
2930                                 if (before.empty() && after.empty())
2931                                         command = "citet";
2932                                 else
2933                                         command = "citep";
2934                         }
2935                         if (before.empty() && after == "[]")
2936                                 // avoid \citet[]{a}
2937                                 after.erase();
2938                         else if (before == "[]" && after == "[]") {
2939                                 // avoid \citet[][]{a}
2940                                 before.erase();
2941                                 after.erase();
2942                         }
2943                         // remove the brackets around after and before
2944                         if (!after.empty()) {
2945                                 after.erase(0, 1);
2946                                 after.erase(after.length() - 1, 1);
2947                                 after = convert_command_inset_arg(after);
2948                         }
2949                         if (!before.empty()) {
2950                                 before.erase(0, 1);
2951                                 before.erase(before.length() - 1, 1);
2952                                 before = convert_command_inset_arg(before);
2953                         }
2954                         begin_command_inset(os, "citation", command);
2955                         os << "after " << '"' << after << '"' << "\n";
2956                         os << "before " << '"' << before << '"' << "\n";
2957                         os << "key \""
2958                            << convert_command_inset_arg(p.verbatim_item())
2959                            << "\"\n";
2960                         end_inset(os);
2961                 }
2962
2963                 else if (use_jurabib &&
2964                          is_known(t.cs(), known_jurabib_commands) &&
2965                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2966                         context.check_layout(os);
2967                         string command = t.cs();
2968                         if (p.next_token().asInput() == "*") {
2969                                 command += '*';
2970                                 p.get_token();
2971                         }
2972                         char argumentOrder = '\0';
2973                         vector<string> const options =
2974                                 preamble.getPackageOptions("jurabib");
2975                         if (find(options.begin(), options.end(),
2976                                       "natbiborder") != options.end())
2977                                 argumentOrder = 'n';
2978                         else if (find(options.begin(), options.end(),
2979                                            "jurabiborder") != options.end())
2980                                 argumentOrder = 'j';
2981
2982                         // text before the citation
2983                         string before;
2984                         // text after the citation
2985                         string after;
2986                         get_cite_arguments(p, argumentOrder != 'j', before, after);
2987
2988                         string const citation = p.verbatim_item();
2989                         if (!before.empty() && argumentOrder == '\0') {
2990                                 cerr << "Warning: Assuming argument order "
2991                                         "of jurabib version 0.6 for\n'"
2992                                      << command << before << after << '{'
2993                                      << citation << "}'.\n"
2994                                         "Add 'jurabiborder' to the jurabib "
2995                                         "package options if you used an\n"
2996                                         "earlier jurabib version." << endl;
2997                         }
2998                         if (!after.empty()) {
2999                                 after.erase(0, 1);
3000                                 after.erase(after.length() - 1, 1);
3001                         }
3002                         if (!before.empty()) {
3003                                 before.erase(0, 1);
3004                                 before.erase(before.length() - 1, 1);
3005                         }
3006                         begin_command_inset(os, "citation", command);
3007                         os << "after " << '"' << after << '"' << "\n";
3008                         os << "before " << '"' << before << '"' << "\n";
3009                         os << "key " << '"' << citation << '"' << "\n";
3010                         end_inset(os);
3011                 }
3012
3013                 else if (t.cs() == "cite"
3014                         || t.cs() == "nocite") {
3015                         context.check_layout(os);
3016                         string after = convert_command_inset_arg(p.getArg('[', ']'));
3017                         string key = convert_command_inset_arg(p.verbatim_item());
3018                         // store the case that it is "\nocite{*}" to use it later for
3019                         // the BibTeX inset
3020                         if (key != "*") {
3021                                 begin_command_inset(os, "citation", t.cs());
3022                                 os << "after " << '"' << after << '"' << "\n";
3023                                 os << "key " << '"' << key << '"' << "\n";
3024                                 end_inset(os);
3025                         } else if (t.cs() == "nocite")
3026                                 btprint = key;
3027                 }
3028
3029                 else if (t.cs() == "index") {
3030                         context.check_layout(os);
3031                         begin_inset(os, "Index idx\n");
3032                         os << "status collapsed\n";
3033                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3034                         end_inset(os);
3035                 }
3036
3037                 else if (t.cs() == "nomenclature") {
3038                         context.check_layout(os);
3039                         begin_command_inset(os, "nomenclature", "nomenclature");
3040                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3041                         if (!prefix.empty())
3042                                 os << "prefix " << '"' << prefix << '"' << "\n";
3043                         os << "symbol " << '"'
3044                            << convert_command_inset_arg(p.verbatim_item());
3045                         os << "\"\ndescription \""
3046                            << convert_command_inset_arg(p.verbatim_item())
3047                            << "\"\n";
3048                         end_inset(os);
3049                 }
3050                 
3051                 else if (t.cs() == "label") {
3052                         context.check_layout(os);
3053                         begin_command_inset(os, "label", "label");
3054                         os << "name \""
3055                            << convert_command_inset_arg(p.verbatim_item())
3056                            << "\"\n";
3057                         end_inset(os);
3058                 }
3059
3060                 else if (t.cs() == "printindex") {
3061                         context.check_layout(os);
3062                         begin_command_inset(os, "index_print", "printindex");
3063                         os << "type \"idx\"\n";
3064                         end_inset(os);
3065                         skip_spaces_braces(p);
3066                 }
3067
3068                 else if (t.cs() == "printnomenclature") {
3069                         string width = "";
3070                         string width_type = "";
3071                         context.check_layout(os);
3072                         begin_command_inset(os, "nomencl_print", "printnomenclature");
3073                         // case of a custom width
3074                         if (p.hasOpt()) {
3075                                 width = p.getArg('[', ']');
3076                                 width = translate_len(width);
3077                                 width_type = "custom";
3078                         }
3079                         // case of no custom width
3080                         // the case of no custom width but the width set
3081                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
3082                         // because the user could have set anything, not only the width
3083                         // of the longest label (which would be width_type = "auto")
3084                         string label = convert_command_inset_arg(p.getArg('{', '}'));
3085                         if (label.empty() && width_type.empty())
3086                                 width_type = "none";
3087                         os << "set_width \"" << width_type << "\"\n";
3088                         if (width_type == "custom")
3089                                 os << "width \"" << width << '\"';
3090                         end_inset(os);
3091                         skip_spaces_braces(p);
3092                 }
3093
3094                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3095                         context.check_layout(os);
3096                         begin_inset(os, "script ");
3097                         os << t.cs().substr(4) << '\n';
3098                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3099                         end_inset(os);
3100                         if (t.cs() == "textsubscript")
3101                                 preamble.registerAutomaticallyLoadedPackage("subscript");
3102                 }
3103
3104                 else if (is_known(t.cs(), known_quotes)) {
3105                         char const * const * where = is_known(t.cs(), known_quotes);
3106                         context.check_layout(os);
3107                         begin_inset(os, "Quotes ");
3108                         os << known_coded_quotes[where - known_quotes];
3109                         end_inset(os);
3110                         // LyX adds {} after the quote, so we have to eat
3111                         // spaces here if there are any before a possible
3112                         // {} pair.
3113                         eat_whitespace(p, os, context, false);
3114                         skip_braces(p);
3115                 }
3116
3117                 else if (is_known(t.cs(), known_sizes) &&
3118                          context.new_layout_allowed) {
3119                         char const * const * where = is_known(t.cs(), known_sizes);
3120                         context.check_layout(os);
3121                         TeXFont const oldFont = context.font;
3122                         context.font.size = known_coded_sizes[where - known_sizes];
3123                         output_font_change(os, oldFont, context.font);
3124                         eat_whitespace(p, os, context, false);
3125                 }
3126
3127                 else if (is_known(t.cs(), known_font_families) &&
3128                          context.new_layout_allowed) {
3129                         char const * const * where =
3130                                 is_known(t.cs(), known_font_families);
3131                         context.check_layout(os);
3132                         TeXFont const oldFont = context.font;
3133                         context.font.family =
3134                                 known_coded_font_families[where - known_font_families];
3135                         output_font_change(os, oldFont, context.font);
3136                         eat_whitespace(p, os, context, false);
3137                 }
3138
3139                 else if (is_known(t.cs(), known_font_series) &&
3140                          context.new_layout_allowed) {
3141                         char const * const * where =
3142                                 is_known(t.cs(), known_font_series);
3143                         context.check_layout(os);
3144                         TeXFont const oldFont = context.font;
3145                         context.font.series =
3146                                 known_coded_font_series[where - known_font_series];
3147                         output_font_change(os, oldFont, context.font);
3148                         eat_whitespace(p, os, context, false);
3149                 }
3150
3151                 else if (is_known(t.cs(), known_font_shapes) &&
3152                          context.new_layout_allowed) {
3153                         char const * const * where =
3154                                 is_known(t.cs(), known_font_shapes);
3155                         context.check_layout(os);
3156                         TeXFont const oldFont = context.font;
3157                         context.font.shape =
3158                                 known_coded_font_shapes[where - known_font_shapes];
3159                         output_font_change(os, oldFont, context.font);
3160                         eat_whitespace(p, os, context, false);
3161                 }
3162                 else if (is_known(t.cs(), known_old_font_families) &&
3163                          context.new_layout_allowed) {
3164                         char const * const * where =
3165                                 is_known(t.cs(), known_old_font_families);
3166                         context.check_layout(os);
3167                         TeXFont const oldFont = context.font;
3168                         context.font.init();
3169                         context.font.size = oldFont.size;
3170                         context.font.family =
3171                                 known_coded_font_families[where - known_old_font_families];
3172                         output_font_change(os, oldFont, context.font);
3173                         eat_whitespace(p, os, context, false);
3174                 }
3175
3176                 else if (is_known(t.cs(), known_old_font_series) &&
3177                          context.new_layout_allowed) {
3178                         char const * const * where =
3179                                 is_known(t.cs(), known_old_font_series);
3180                         context.check_layout(os);
3181                         TeXFont const oldFont = context.font;
3182                         context.font.init();
3183                         context.font.size = oldFont.size;
3184                         context.font.series =
3185                                 known_coded_font_series[where - known_old_font_series];
3186                         output_font_change(os, oldFont, context.font);
3187                         eat_whitespace(p, os, context, false);
3188                 }
3189
3190                 else if (is_known(t.cs(), known_old_font_shapes) &&
3191                          context.new_layout_allowed) {
3192                         char const * const * where =
3193                                 is_known(t.cs(), known_old_font_shapes);
3194                         context.check_layout(os);
3195                         TeXFont const oldFont = context.font;
3196                         context.font.init();
3197                         context.font.size = oldFont.size;
3198                         context.font.shape =
3199                                 known_coded_font_shapes[where - known_old_font_shapes];
3200                         output_font_change(os, oldFont, context.font);
3201                         eat_whitespace(p, os, context, false);
3202                 }
3203
3204                 else if (t.cs() == "selectlanguage") {
3205                         context.check_layout(os);
3206                         // save the language for the case that a
3207                         // \foreignlanguage is used 
3208
3209                         context.font.language = babel2lyx(p.verbatim_item());
3210                         os << "\n\\lang " << context.font.language << "\n";
3211                 }
3212
3213                 else if (t.cs() == "foreignlanguage") {
3214                         string const lang = babel2lyx(p.verbatim_item());
3215                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3216                                               context, "\\lang",
3217                                               context.font.language, lang);
3218                 }
3219
3220                 else if (t.cs() == "inputencoding") {
3221                         // nothing to write here
3222                         string const enc = subst(p.verbatim_item(), "\n", " ");
3223                         p.setEncoding(enc);
3224                 }
3225
3226                 else if (t.cs() == "ldots") {
3227                         context.check_layout(os);
3228                         os << "\\SpecialChar \\ldots{}\n";
3229                         skip_spaces_braces(p);
3230                 }
3231
3232                 else if (t.cs() == "lyxarrow") {
3233                         context.check_layout(os);
3234                         os << "\\SpecialChar \\menuseparator\n";
3235                         skip_spaces_braces(p);
3236                 }
3237
3238                 else if (t.cs() == "textcompwordmark") {
3239                         context.check_layout(os);
3240                         os << "\\SpecialChar \\textcompwordmark{}\n";
3241                         skip_spaces_braces(p);
3242                 }
3243
3244                 else if (t.cs() == "slash") {
3245                         context.check_layout(os);
3246                         os << "\\SpecialChar \\slash{}\n";
3247                         skip_spaces_braces(p);
3248                 }
3249
3250                 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3251                         context.check_layout(os);
3252                         os << "\\SpecialChar \\nobreakdash-\n";
3253                         p.get_token();
3254                 }
3255
3256                 else if (t.cs() == "textquotedbl") {
3257                         context.check_layout(os);
3258                         os << "\"";
3259                         skip_braces(p);
3260                 }
3261
3262                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3263                         context.check_layout(os);
3264                         os << "\\SpecialChar \\@.\n";
3265                         p.get_token();
3266                 }
3267
3268                 else if (t.cs() == "-") {
3269                         context.check_layout(os);
3270                         os << "\\SpecialChar \\-\n";
3271                 }
3272
3273                 else if (t.cs() == "textasciitilde") {
3274                         context.check_layout(os);
3275                         os << '~';
3276                         skip_spaces_braces(p);
3277                 }
3278
3279                 else if (t.cs() == "textasciicircum") {
3280                         context.check_layout(os);
3281                         os << '^';
3282                         skip_spaces_braces(p);
3283                 }
3284
3285                 else if (t.cs() == "textbackslash") {
3286                         context.check_layout(os);
3287                         os << "\n\\backslash\n";
3288                         skip_spaces_braces(p);
3289                 }
3290
3291                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3292                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3293                             || t.cs() == "%") {
3294                         context.check_layout(os);
3295                         os << t.cs();
3296                 }
3297
3298                 else if (t.cs() == "char") {
3299                         context.check_layout(os);
3300                         if (p.next_token().character() == '`') {
3301                                 p.get_token();
3302                                 if (p.next_token().cs() == "\"") {
3303                                         p.get_token();
3304                                         os << '"';
3305                                         skip_braces(p);
3306                                 } else {
3307                                         handle_ert(os, "\\char`", context);
3308                                 }
3309                         } else {
3310                                 handle_ert(os, "\\char", context);
3311                         }
3312                 }
3313
3314                 else if (t.cs() == "verb") {
3315                         context.check_layout(os);
3316                         char const delimiter = p.next_token().character();
3317                         string const arg = p.getArg(delimiter, delimiter);
3318                         ostringstream oss;
3319                         oss << "\\verb" << delimiter << arg << delimiter;
3320                         handle_ert(os, oss.str(), context);
3321                 }
3322
3323                 // Problem: \= creates a tabstop inside the tabbing environment
3324                 // and else an accent. In the latter case we really would want
3325                 // \={o} instead of \= o.
3326                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3327                         handle_ert(os, t.asInput(), context);
3328
3329                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3330                 else if (t.cs().size() == 1 
3331                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3332                         context.check_layout(os);
3333                         // try to see whether the string is in unicodesymbols
3334                         docstring rem;
3335                         string command = t.asInput() + "{" 
3336                                 + trimSpaceAndEol(p.verbatim_item())
3337                                 + "}";
3338                         docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3339                         if (!s.empty()) {
3340                                 if (!rem.empty())
3341                                         cerr << "When parsing " << command 
3342                                              << ", result is " << to_utf8(s)
3343                                              << "+" << to_utf8(rem) << endl;
3344                                 os << to_utf8(s);
3345                         } else
3346                                 // we did not find a non-ert version
3347                                 handle_ert(os, command, context);
3348                 }
3349
3350                 else if (t.cs() == "\\") {
3351                         context.check_layout(os);
3352                         if (p.hasOpt())
3353                                 handle_ert(os, "\\\\" + p.getOpt(), context);
3354                         else if (p.next_token().asInput() == "*") {
3355                                 p.get_token();
3356                                 // getOpt() eats the following space if there
3357                                 // is no optional argument, but that is OK
3358                                 // here since it has no effect in the output.
3359                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
3360                         }
3361                         else {
3362                                 begin_inset(os, "Newline newline");
3363                                 end_inset(os);
3364                         }
3365                 }
3366
3367                 else if (t.cs() == "newline" ||
3368                          (t.cs() == "linebreak" && !p.hasOpt())) {
3369                         context.check_layout(os);
3370                         begin_inset(os, "Newline ");
3371                         os << t.cs();
3372                         end_inset(os);
3373                         skip_spaces_braces(p);
3374                 }
3375
3376                 else if (t.cs() == "input" || t.cs() == "include"
3377                          || t.cs() == "verbatiminput") {
3378                         string name = t.cs();
3379                         if (t.cs() == "verbatiminput"
3380                             && p.next_token().asInput() == "*")
3381                                 name += p.get_token().asInput();
3382                         context.check_layout(os);
3383                         string filename(normalize_filename(p.getArg('{', '}')));
3384                         string const path = getMasterFilePath();
3385                         // We want to preserve relative / absolute filenames,
3386                         // therefore path is only used for testing
3387                         if ((t.cs() == "include" || t.cs() == "input") &&
3388                             !makeAbsPath(filename, path).exists()) {
3389                                 // The file extension is probably missing.
3390                                 // Now try to find it out.
3391                                 string const tex_name =
3392                                         find_file(filename, path,
3393                                                   known_tex_extensions);
3394                                 if (!tex_name.empty())
3395                                         filename = tex_name;
3396                         }
3397                         bool external = false;
3398                         string outname;
3399                         if (makeAbsPath(filename, path).exists()) {
3400                                 string const abstexname =
3401                                         makeAbsPath(filename, path).absFileName();
3402                                 string const abslyxname =
3403                                         changeExtension(abstexname, ".lyx");
3404                                 string const absfigname =
3405                                         changeExtension(abstexname, ".fig");
3406                                 fix_relative_filename(filename);
3407                                 string const lyxname =
3408                                         changeExtension(filename, ".lyx");
3409                                 bool xfig = false;
3410                                 external = FileName(absfigname).exists();
3411                                 if (t.cs() == "input") {
3412                                         string const ext = getExtension(abstexname);
3413
3414                                         // Combined PS/LaTeX:
3415                                         // x.eps, x.pstex_t (old xfig)
3416                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3417                                         FileName const absepsname(
3418                                                 changeExtension(abstexname, ".eps"));
3419                                         FileName const abspstexname(
3420                                                 changeExtension(abstexname, ".pstex"));
3421                                         bool const xfigeps =
3422                                                 (absepsname.exists() ||
3423                                                  abspstexname.exists()) &&
3424                                                 ext == "pstex_t";
3425
3426                                         // Combined PDF/LaTeX:
3427                                         // x.pdf, x.pdftex_t (old xfig)
3428                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3429                                         FileName const abspdfname(
3430                                                 changeExtension(abstexname, ".pdf"));
3431                                         bool const xfigpdf =
3432                                                 abspdfname.exists() &&
3433                                                 (ext == "pdftex_t" || ext == "pdf_t");
3434                                         if (xfigpdf)
3435                                                 pdflatex = true;
3436
3437                                         // Combined PS/PDF/LaTeX:
3438                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3439                                         string const absbase2(
3440                                                 removeExtension(abstexname) + "_pspdftex");
3441                                         FileName const abseps2name(
3442                                                 addExtension(absbase2, ".eps"));
3443                                         FileName const abspdf2name(
3444                                                 addExtension(absbase2, ".pdf"));
3445                                         bool const xfigboth =
3446                                                 abspdf2name.exists() &&
3447                                                 abseps2name.exists() && ext == "pspdftex";
3448
3449                                         xfig = xfigpdf || xfigeps || xfigboth;
3450                                         external = external && xfig;
3451                                 }
3452                                 if (external) {
3453                                         outname = changeExtension(filename, ".fig");
3454                                 } else if (xfig) {
3455                                         // Don't try to convert, the result
3456                                         // would be full of ERT.
3457                                         outname = filename;
3458                                 } else if (t.cs() != "verbatiminput" &&
3459                                     tex2lyx(abstexname, FileName(abslyxname),
3460                                             p.getEncoding())) {
3461                                         outname = lyxname;
3462                                 } else {
3463                                         outname = filename;
3464                                 }
3465                         } else {
3466                                 cerr << "Warning: Could not find included file '"
3467                                      << filename << "'." << endl;
3468                                 outname = filename;
3469                         }
3470                         if (external) {
3471                                 begin_inset(os, "External\n");
3472                                 os << "\ttemplate XFig\n"
3473                                    << "\tfilename " << outname << '\n';
3474                         } else {
3475                                 begin_command_inset(os, "include", name);
3476                                 os << "preview false\n"
3477                                       "filename \"" << outname << "\"\n";
3478                         }
3479                         end_inset(os);
3480                 }
3481
3482                 else if (t.cs() == "bibliographystyle") {
3483                         // store new bibliographystyle
3484                         bibliographystyle = p.verbatim_item();
3485                         // If any other command than \bibliography and
3486                         // \nocite{*} follows, we need to output the style
3487                         // (because it might be used by that command).
3488                         // Otherwise, it will automatically be output by LyX.
3489                         p.pushPosition();
3490                         bool output = true;
3491                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3492                                 if (t2.cat() == catBegin)
3493                                         break;
3494                                 if (t2.cat() != catEscape)
3495                                         continue;
3496                                 if (t2.cs() == "nocite") {
3497                                         if (p.getArg('{', '}') == "*")
3498                                                 continue;
3499                                 } else if (t2.cs() == "bibliography")
3500                                         output = false;
3501                                 break;
3502                         }
3503                         p.popPosition();
3504                         if (output) {
3505                                 handle_ert(os,
3506                                         "\\bibliographystyle{" + bibliographystyle + '}',
3507                                         context);
3508                         }
3509                 }
3510
3511                 else if (t.cs() == "bibliography") {
3512                         context.check_layout(os);
3513                         begin_command_inset(os, "bibtex", "bibtex");
3514                         if (!btprint.empty()) {
3515                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3516                                 // clear the string because the next BibTeX inset can be without the
3517                                 // \nocite{*} option
3518                                 btprint.clear();
3519                         }
3520                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3521                         // Do we have a bibliographystyle set?
3522                         if (!bibliographystyle.empty())
3523                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
3524                         end_inset(os);
3525                 }
3526
3527                 else if (t.cs() == "parbox") {
3528                         // Test whether this is an outer box of a shaded box
3529                         p.pushPosition();
3530                         // swallow arguments
3531                         while (p.hasOpt()) {
3532                                 p.getArg('[', ']');
3533                                 p.skip_spaces(true);
3534                         }
3535                         p.getArg('{', '}');
3536                         p.skip_spaces(true);
3537                         // eat the '{'
3538                         if (p.next_token().cat() == catBegin)
3539                                 p.get_token();
3540                         p.skip_spaces(true);
3541                         Token to = p.get_token();
3542                         bool shaded = false;
3543                         if (to.asInput() == "\\begin") {
3544                                 p.skip_spaces(true);
3545                                 if (p.getArg('{', '}') == "shaded")
3546                                         shaded = true;
3547                         }
3548                         p.popPosition();
3549                         if (shaded) {
3550                                 parse_outer_box(p, os, FLAG_ITEM, outer,
3551                                                 context, "parbox", "shaded");
3552                         } else
3553                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3554                                           "", "", t.cs());
3555                 }
3556
3557                 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3558                          t.cs() == "shadowbox" || t.cs() == "doublebox")
3559                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3560
3561                 else if (t.cs() == "framebox") {
3562                         string special = p.getFullOpt();
3563                         special += p.getOpt();
3564                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3565                 }
3566
3567                 //\makebox() is part of the picture environment and different from \makebox{}
3568                 //\makebox{} will be parsed by parse_box
3569                 else if (t.cs() == "makebox") {
3570                         string arg = t.asInput();
3571                         if (p.next_token().character() == '(') {
3572                                 //the syntax is: \makebox(x,y)[position]{content}
3573                                 arg += p.getFullParentheseArg();
3574                                 arg += p.getFullOpt();
3575                                 eat_whitespace(p, os, context, false);
3576                                 handle_ert(os, arg + '{', context);
3577                                 eat_whitespace(p, os, context, false);
3578                                 parse_text(p, os, FLAG_ITEM, outer, context);
3579                                 handle_ert(os, "}", context);
3580                         } else
3581                                 //the syntax is: \makebox[width][position]{content}
3582                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3583                                           "", "", t.cs());
3584                 }
3585
3586                 else if (t.cs() == "smallskip" ||
3587                          t.cs() == "medskip" ||
3588                          t.cs() == "bigskip" ||
3589                          t.cs() == "vfill") {
3590                         context.check_layout(os);
3591                         begin_inset(os, "VSpace ");
3592                         os << t.cs();
3593                         end_inset(os);
3594                         skip_spaces_braces(p);
3595                 }
3596
3597                 else if (is_known(t.cs(), known_spaces)) {
3598                         char const * const * where = is_known(t.cs(), known_spaces);
3599                         context.check_layout(os);
3600                         begin_inset(os, "space ");
3601                         os << '\\' << known_coded_spaces[where - known_spaces]
3602                            << '\n';
3603                         end_inset(os);
3604                         // LaTeX swallows whitespace after all spaces except
3605                         // "\\,". We have to do that here, too, because LyX
3606                         // adds "{}" which would make the spaces significant.
3607                         if (t.cs() !=  ",")
3608                                 eat_whitespace(p, os, context, false);
3609                         // LyX adds "{}" after all spaces except "\\ " and
3610                         // "\\,", so we have to remove "{}".
3611                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
3612                         // remove the braces after "\\,", too.
3613                         if (t.cs() != " ")
3614                                 skip_braces(p);
3615                 }
3616
3617                 else if (t.cs() == "newpage" ||
3618                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
3619                          t.cs() == "clearpage" ||
3620                          t.cs() == "cleardoublepage") {
3621                         context.check_layout(os);
3622                         begin_inset(os, "Newpage ");
3623                         os << t.cs();
3624                         end_inset(os);
3625                         skip_spaces_braces(p);
3626                 }
3627
3628                 else if (t.cs() == "DeclareRobustCommand" ||
3629                          t.cs() == "DeclareRobustCommandx" ||
3630                          t.cs() == "newcommand" ||
3631                          t.cs() == "newcommandx" ||
3632                          t.cs() == "providecommand" ||
3633                          t.cs() == "providecommandx" ||
3634                          t.cs() == "renewcommand" ||
3635                          t.cs() == "renewcommandx") {
3636                         // DeclareRobustCommand, DeclareRobustCommandx,
3637                         // providecommand and providecommandx could be handled
3638                         // by parse_command(), but we need to call
3639                         // add_known_command() here.
3640                         string name = t.asInput();
3641                         if (p.next_token().asInput() == "*") {
3642                                 // Starred form. Eat '*'
3643                                 p.get_token();
3644                                 name += '*';
3645                         }
3646                         string const command = p.verbatim_item();
3647                         string const opt1 = p.getFullOpt();
3648                         string const opt2 = p.getFullOpt();
3649                         add_known_command(command, opt1, !opt2.empty());
3650                         string const ert = name + '{' + command + '}' +
3651                                            opt1 + opt2 +
3652                                            '{' + p.verbatim_item() + '}';
3653
3654                         if (t.cs() == "DeclareRobustCommand" ||
3655                             t.cs() == "DeclareRobustCommandx" ||
3656                             t.cs() == "providecommand" ||
3657                             t.cs() == "providecommandx" ||
3658                             name[name.length()-1] == '*')
3659                                 handle_ert(os, ert, context);
3660                         else {
3661                                 context.check_layout(os);
3662                                 begin_inset(os, "FormulaMacro");
3663                                 os << "\n" << ert;
3664                                 end_inset(os);
3665                         }
3666                 }
3667
3668                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3669                         // let could be handled by parse_command(),
3670                         // but we need to call add_known_command() here.
3671                         string ert = t.asInput();
3672                         string name;
3673                         p.skip_spaces();
3674                         if (p.next_token().cat() == catBegin) {
3675                                 name = p.verbatim_item();
3676                                 ert += '{' + name + '}';
3677                         } else {
3678                                 name = p.verbatim_item();
3679                                 ert += name;
3680                         }
3681                         string command;
3682                         p.skip_spaces();
3683                         if (p.next_token().cat() == catBegin) {
3684                                 command = p.verbatim_item();
3685                                 ert += '{' + command + '}';
3686                         } else {
3687                                 command = p.verbatim_item();
3688                                 ert += command;
3689                         }
3690                         // If command is known, make name known too, to parse
3691                         // its arguments correctly. For this reason we also
3692                         // have commands in syntax.default that are hardcoded.
3693                         CommandMap::iterator it = known_commands.find(command);
3694                         if (it != known_commands.end())
3695                                 known_commands[t.asInput()] = it->second;
3696                         handle_ert(os, ert, context);
3697                 }
3698
3699                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3700                         bool starred = false;
3701                         if (p.next_token().asInput() == "*") {
3702                                 p.get_token();
3703                                 starred = true;
3704                         }
3705                         string name = t.asInput();
3706                         string const length = p.verbatim_item();
3707                         string unit;
3708                         string valstring;
3709                         bool valid = splitLatexLength(length, valstring, unit);
3710                         bool known_hspace = false;
3711                         bool known_vspace = false;
3712                         bool known_unit = false;
3713                         double value;
3714                         if (valid) {
3715                                 istringstream iss(valstring);
3716                                 iss >> value;
3717                                 if (value == 1.0) {
3718                                         if (t.cs()[0] == 'h') {
3719                                                 if (unit == "\\fill") {
3720                                                         if (!starred) {
3721                                                                 unit = "";
3722                                                                 name = "\\hfill";
3723                                                         }
3724                                                         known_hspace = true;
3725                                                 }
3726                                         } else {
3727                                                 if (unit == "\\smallskipamount") {
3728                                                         unit = "smallskip";
3729                                                         known_vspace = true;
3730                                                 } else if (unit == "\\medskipamount") {
3731                                                         unit = "medskip";
3732                                                         known_vspace = true;
3733                                                 } else if (unit == "\\bigskipamount") {
3734                                                         unit = "bigskip";
3735                                                         known_vspace = true;
3736                                                 } else if (unit == "\\fill") {
3737                                                         unit = "vfill";
3738                                                         known_vspace = true;
3739                                                 }
3740                                         }
3741                                 }
3742                                 if (!known_hspace && !known_vspace) {
3743                                         switch (unitFromString(unit)) {
3744                                         case Length::SP:
3745                                         case Length::PT:
3746                                         case Length::BP:
3747                                         case Length::DD:
3748                                         case Length::MM:
3749                                         case Length::PC:
3750                                         case Length::CC:
3751                                         case Length::CM:
3752                                         case Length::IN:
3753                                         case Length::EX:
3754                                         case Length::EM:
3755                                         case Length::MU:
3756                                                 known_unit = true;
3757                                                 break;
3758                                         default:
3759                                                 break;
3760                                         }
3761                                 }
3762                         }
3763
3764                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3765                                 // Literal horizontal length or known variable
3766                                 context.check_layout(os);
3767                                 begin_inset(os, "space ");
3768                                 os << name;
3769                                 if (starred)
3770                                         os << '*';
3771                                 os << '{';
3772                                 if (known_hspace)
3773                                         os << unit;
3774                                 os << "}";
3775                                 if (known_unit && !known_hspace)
3776                                         os << "\n\\length "
3777                                            << translate_len(length);
3778                                 end_inset(os);
3779                         } else if (known_unit || known_vspace) {
3780                                 // Literal vertical length or known variable
3781                                 context.check_layout(os);
3782                                 begin_inset(os, "VSpace ");
3783                                 if (known_unit)
3784                                         os << value;
3785                                 os << unit;
3786                                 if (starred)
3787                                         os << '*';
3788                                 end_inset(os);
3789                         } else {
3790                                 // LyX can't handle other length variables in Inset VSpace/space
3791                                 if (starred)
3792                                         name += '*';
3793                                 if (valid) {
3794                                         if (value == 1.0)
3795                                                 handle_ert(os, name + '{' + unit + '}', context);
3796                                         else if (value == -1.0)
3797                                                 handle_ert(os, name + "{-" + unit + '}', context);
3798                                         else
3799                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
3800                                 } else
3801                                         handle_ert(os, name + '{' + length + '}', context);
3802                         }
3803                 }
3804
3805                 // The single '=' is meant here.
3806                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3807                         p.skip_spaces();
3808                         context.check_layout(os);
3809                         begin_inset(os, "Flex ");
3810                         os << to_utf8(newinsetlayout->name()) << '\n'
3811                            << "status collapsed\n";
3812                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3813                         end_inset(os);
3814                 }
3815
3816                 else {
3817                         // try to see whether the string is in unicodesymbols
3818                         // Only use text mode commands, since we are in text mode here,
3819                         // and math commands may be invalid (bug 6797)
3820                         docstring rem;
3821                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3822                                                                  rem, Encodings::TEXT_CMD);
3823                         if (!s.empty()) {
3824                                 if (!rem.empty())
3825                                         cerr << "When parsing " << t.cs() 
3826                                              << ", result is " << to_utf8(s)
3827                                              << "+" << to_utf8(rem) << endl;
3828                                 context.check_layout(os);
3829                                 os << to_utf8(s);
3830                                 skip_spaces_braces(p);
3831                         }
3832                         //cerr << "#: " << t << " mode: " << mode << endl;
3833                         // heuristic: read up to next non-nested space
3834                         /*
3835                         string s = t.asInput();
3836                         string z = p.verbatim_item();
3837                         while (p.good() && z != " " && z.size()) {
3838                                 //cerr << "read: " << z << endl;
3839                                 s += z;
3840                                 z = p.verbatim_item();
3841                         }
3842                         cerr << "found ERT: " << s << endl;
3843                         handle_ert(os, s + ' ', context);
3844                         */
3845                         else {
3846                                 string name = t.asInput();
3847                                 if (p.next_token().asInput() == "*") {
3848                                         // Starred commands like \vspace*{}
3849                                         p.get_token();  // Eat '*'
3850                                         name += '*';
3851                                 }
3852                                 if (!parse_command(name, p, os, outer, context))
3853                                         handle_ert(os, name, context);
3854                         }
3855                 }
3856
3857                 if (flags & FLAG_LEAVE) {
3858                         flags &= ~FLAG_LEAVE;
3859                         break;
3860                 }
3861         }
3862 }
3863
3864 // }])
3865
3866
3867 } // namespace lyx