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