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