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