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