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