]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.C
some tabular fixes for the problems reported by Helge
[lyx.git] / src / tex2lyx / text.C
1 /**
2  * \file tex2lyx/text.C
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  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 // {[(
13
14 #include <config.h>
15
16 #include "tex2lyx.h"
17 #include "context.h"
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/convert.h"
22 #include "support/filetools.h"
23
24 #include <boost/filesystem/operations.hpp>
25 #include <boost/tuple/tuple.hpp>
26
27 #include <iostream>
28 #include <map>
29 #include <sstream>
30 #include <vector>
31
32 using lyx::support::MakeAbsPath;
33 using lyx::support::rtrim;
34 using lyx::support::suffixIs;
35 using lyx::support::contains;
36 using lyx::support::subst;
37
38 using std::cerr;
39 using std::endl;
40
41 using std::map;
42 using std::ostream;
43 using std::ostringstream;
44 using std::istringstream;
45 using std::string;
46 using std::vector;
47
48 namespace fs = boost::filesystem;
49
50
51 /// thin wrapper around parse_text using a string
52 string parse_text(Parser & p, unsigned flags, const bool outer,
53                   Context & context)
54 {
55         ostringstream os;
56         parse_text(p, os, flags, outer, context);
57         return os.str();
58 }
59
60
61 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
62                 Context & context)
63 {
64         Context newcontext(true, context.textclass);
65         newcontext.font = context.font;
66         parse_text(p, os, flags, outer, newcontext);
67         newcontext.check_end_layout(os);
68 }
69
70
71 /// parses a paragraph snippet, useful for example for \emph{...}
72 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
73                 Context & context)
74 {
75         Context newcontext(false, context.textclass);
76         newcontext.font = context.font;
77         parse_text(p, os, flags, outer, newcontext);
78         // should not be needed
79         newcontext.check_end_layout(os);
80 }
81
82
83 namespace {
84
85 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
86 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
87
88 /*!
89  * natbib commands.
90  * We can't put these into known_latex_commands because the argument order
91  * is reversed in lyx if there are 2 arguments.
92  * The starred forms are also known.
93  */
94 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
95 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
96 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
97
98 /*!
99  * jurabib commands.
100  * We can't put these into known_latex_commands because the argument order
101  * is reversed in lyx if there are 2 arguments.
102  * No starred form other than "cite*" known.
103  */
104 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
105 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar", "fullcite",
106 // jurabib commands not (yet) supported by LyX:
107 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
108 // "footciteauthor", "footciteyear", "footciteyearpar",
109 "citefield", "citetitle", "cite*", 0 };
110
111 /// LaTeX names for quotes
112 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
113 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
114
115 /// the same as known_quotes with .lyx names
116 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
117 "grd", "gls", "fls", "frd", 0};
118
119 /// LaTeX names for font sizes
120 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
121 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
122
123 /// the same as known_sizes with .lyx names
124 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
125 "small", "normal", "large", "larger", "largest",  "huge", "giant", 0};
126
127 /// LaTeX 2.09 names for font families
128 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
129
130 /// LaTeX names for font families
131 char const * const known_font_families[] = { "rmfamily", "sffamily",
132 "ttfamily", 0};
133
134 /// the same as known_old_font_families and known_font_families with .lyx names
135 char const * const known_coded_font_families[] = { "roman", "sans",
136 "typewriter", 0};
137
138 /// LaTeX 2.09 names for font series
139 char const * const known_old_font_series[] = { "bf", 0};
140
141 /// LaTeX names for font series
142 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
143
144 /// the same as known_old_font_series and known_font_series with .lyx names
145 char const * const known_coded_font_series[] = { "bold", "medium", 0};
146
147 /// LaTeX 2.09 names for font shapes
148 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
149
150 /// LaTeX names for font shapes
151 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
152 "upshape", 0};
153
154 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
155 char const * const known_coded_font_shapes[] = { "italic", "slanted",
156 "smallcaps", "up", 0};
157
158 /*!
159  * Graphics file extensions known by the dvips driver of the graphics package.
160  * These extensions are used to complete the filename of an included
161  * graphics file if it does not contain an extension.
162  * The order must be the same that latex uses to find a file, because we
163  * will use the first extension that matches.
164  * This is only an approximation for the common cases. If we would want to
165  * do it right in all cases, we would need to know which graphics driver is
166  * used and know the extensions of every driver of the graphics package.
167  */
168 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
169 "ps.gz", "eps.Z", "ps.Z", 0};
170
171 /*!
172  * Graphics file extensions known by the pdftex driver of the graphics package.
173  * \see known_dvips_graphics_formats
174  */
175 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
176 "mps", "tif", 0};
177
178
179 /// splits "x=z, y=b" into a map
180 map<string, string> split_map(string const & s)
181 {
182         map<string, string> res;
183         vector<string> v;
184         split(s, v);
185         for (size_t i = 0; i < v.size(); ++i) {
186                 size_t const pos   = v[i].find('=');
187                 string const index = v[i].substr(0, pos);
188                 string const value = v[i].substr(pos + 1, string::npos);
189                 res[trim(index)] = trim(value);
190         }
191         return res;
192 }
193
194
195 /*!
196  * Split a LaTeX length into value and unit.
197  * The latter can be a real unit like "pt", or a latex length variable
198  * like "\textwidth". The unit may contain additional stuff like glue
199  * lengths, but we don't care, because such lengths are ERT anyway.
200  * \returns true if \p value and \p unit are valid.
201  */
202 bool splitLatexLength(string const & len, string & value, string & unit)
203 {
204         if (len.empty())
205                 return false;
206         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
207         //'4,5' is a valid LaTeX length number. Change it to '4.5'
208         string const length = subst(len, ',', '.');
209         if (i == string::npos)
210                 return false;
211         if (i == 0) {
212                 if (len[0] == '\\') {
213                         // We had something like \textwidth without a factor
214                         value = "1.0";
215                 } else {
216                         return false;
217                 }
218         } else {
219                 value = trim(string(length, 0, i));
220         }
221         if (value == "-")
222                 value = "-1.0";
223         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
224         if (contains(len, '\\'))
225                 unit = trim(string(len, i));
226         else
227                 unit = lyx::support::lowercase(trim(string(len, i)));
228         return true;
229 }
230
231
232 /// A simple function to translate a latex length to something lyx can
233 /// understand. Not perfect, but rather best-effort.
234 bool translate_len(string const & length, string & valstring, string & unit)
235 {
236         if (!splitLatexLength(length, valstring, unit))
237                 return false;
238         // LyX uses percent values
239         double value;
240         istringstream iss(valstring);
241         iss >> value;
242         value *= 100;
243         ostringstream oss;
244         oss << value;
245         string const percentval = oss.str();
246         // a normal length
247         if (unit.empty() || unit[0] != '\\')
248                 return true;
249         string::size_type const i = unit.find(' ');
250         string const endlen = (i == string::npos) ? string() : string(unit, i);
251         if (unit == "\\textwidth") {
252                 valstring = percentval;
253                 unit = "text%" + endlen;
254         } else if (unit == "\\columnwidth") {
255                 valstring = percentval;
256                 unit = "col%" + endlen;
257         } else if (unit == "\\paperwidth") {
258                 valstring = percentval;
259                 unit = "page%" + endlen;
260         } else if (unit == "\\linewidth") {
261                 valstring = percentval;
262                 unit = "line%" + endlen;
263         } else if (unit == "\\paperheight") {
264                 valstring = percentval;
265                 unit = "pheight%" + endlen;
266         } else if (unit == "\\textheight") {
267                 valstring = percentval;
268                 unit = "theight%" + endlen;
269         }
270         return true;
271 }
272
273
274 string translate_len(string const & length)
275 {
276         string unit;
277         string value;
278         if (translate_len(length, value, unit))
279                 return value + unit;
280         // If the input is invalid, return what we have.
281         return length;
282 }
283
284
285 /*!
286  * Translates a LaTeX length into \p value, \p unit and
287  * \p special parts suitable for a box inset.
288  * The difference from translate_len() is that a box inset knows about
289  * some special "units" that are stored in \p special.
290  */
291 void translate_box_len(string const & length, string & value, string & unit, string & special)
292 {
293         if (translate_len(length, value, unit)) {
294                 if (unit == "\\height" || unit == "\\depth" ||
295                     unit == "\\totalheight" || unit == "\\width") {
296                         special = unit.substr(1);
297                         // The unit is not used, but LyX requires a dummy setting
298                         unit = "in";
299                 } else
300                         special = "none";
301         } else {
302                 value.clear();
303                 unit = length;
304                 special = "none";
305         }
306 }
307
308
309 /*!
310  * Find a file with basename \p name in path \p path and an extension
311  * in \p extensions.
312  */
313 string find_file(string const & name, string const & path,
314                  char const * const * extensions)
315 {
316         for (char const * const * what = extensions; *what; ++what) {
317                 // We don't use ChangeExtension() because it does the wrong
318                 // thing if name contains a dot.
319                 string const trial = name + '.' + (*what);
320                 if (fs::exists(MakeAbsPath(trial, path)))
321                         return trial;
322         }
323         return string();
324 }
325
326
327 void begin_inset(ostream & os, string const & name)
328 {
329         os << "\n\\begin_inset " << name;
330 }
331
332
333 void end_inset(ostream & os)
334 {
335         os << "\n\\end_inset\n\n";
336 }
337
338
339 void skip_braces(Parser & p)
340 {
341         if (p.next_token().cat() != catBegin)
342                 return;
343         p.get_token();
344         if (p.next_token().cat() == catEnd) {
345                 p.get_token();
346                 return;
347         }
348         p.putback();
349 }
350
351
352 void handle_ert(ostream & os, string const & s, Context & context, bool check_layout = true)
353 {
354         if (check_layout) {
355                 // We must have a valid layout before outputting the ERT inset.
356                 context.check_layout(os);
357         }
358         Context newcontext(true, context.textclass);
359         begin_inset(os, "ERT");
360         os << "\nstatus collapsed\n";
361         newcontext.check_layout(os);
362         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
363                 if (*it == '\\')
364                         os << "\n\\backslash\n";
365                 else if (*it == '\n') {
366                         newcontext.new_paragraph(os);
367                         newcontext.check_layout(os);
368                 } else
369                         os << *it;
370         }
371         newcontext.check_end_layout(os);
372         end_inset(os);
373 }
374
375
376 void handle_comment(ostream & os, string const & s, Context & context)
377 {
378         // TODO: Handle this better
379         Context newcontext(true, context.textclass);
380         begin_inset(os, "ERT");
381         os << "\nstatus collapsed\n";
382         newcontext.check_layout(os);
383         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
384                 if (*it == '\\')
385                         os << "\n\\backslash\n";
386                 else
387                         os << *it;
388         }
389         // make sure that our comment is the last thing on the line
390         newcontext.new_paragraph(os);
391         newcontext.check_layout(os);
392         newcontext.check_end_layout(os);
393         end_inset(os);
394 }
395
396
397 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
398 public:
399         isLayout(string const name) : name_(name) {}
400         bool operator()(LyXLayout_ptr const & ptr) const {
401                 return ptr->latexname() == name_;
402         }
403 private:
404         string const name_;
405 };
406
407
408 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
409                          string const & name)
410 {
411         LyXTextClass::const_iterator beg  = textclass.begin();
412         LyXTextClass::const_iterator end = textclass.end();
413
414         LyXTextClass::const_iterator
415                 it = std::find_if(beg, end, isLayout(name));
416
417         return (it == end) ? LyXLayout_ptr() : *it;
418 }
419
420
421 void eat_whitespace(Parser &, ostream &, Context &, bool);
422
423
424 void output_command_layout(ostream & os, Parser & p, bool outer,
425                            Context & parent_context,
426                            LyXLayout_ptr newlayout)
427 {
428         parent_context.check_end_layout(os);
429         Context context(true, parent_context.textclass, newlayout,
430                         parent_context.layout, parent_context.font);
431         if (parent_context.deeper_paragraph) {
432                 // We are beginning a nested environment after a
433                 // deeper paragraph inside the outer list environment.
434                 // Therefore we don't need to output a "begin deeper".
435                 context.need_end_deeper = true;
436         }
437         context.check_deeper(os);
438         context.check_layout(os);
439         if (context.layout->optionalargs > 0) {
440                 eat_whitespace(p, os, context, false);
441                 if (p.next_token().character() == '[') {
442                         p.get_token(); // eat '['
443                         begin_inset(os, "OptArg\n");
444                         os << "status collapsed\n\n";
445                         parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
446                         end_inset(os);
447                         eat_whitespace(p, os, context, false);
448                 }
449         }
450         parse_text(p, os, FLAG_ITEM, outer, context);
451         context.check_end_layout(os);
452         if (parent_context.deeper_paragraph) {
453                 // We must suppress the "end deeper" because we
454                 // suppressed the "begin deeper" above.
455                 context.need_end_deeper = false;
456         }
457         context.check_end_deeper(os);
458         // We don't need really a new paragraph, but
459         // we must make sure that the next item gets a \begin_layout.
460         parent_context.new_paragraph(os);
461 }
462
463
464 /*!
465  * Output a space if necessary.
466  * This function gets called for every whitespace token.
467  *
468  * We have three cases here:
469  * 1. A space must be suppressed. Example: The lyxcode case below
470  * 2. A space may be suppressed. Example: Spaces before "\par"
471  * 3. A space must not be suppressed. Example: A space between two words
472  *
473  * We currently handle only 1. and 3 and from 2. only the case of
474  * spaces before newlines as a side effect.
475  *
476  * 2. could be used to suppress as many spaces as possible. This has two effects:
477  * - Reimporting LyX generated LaTeX files changes almost no whitespace
478  * - Superflous whitespace from non LyX generated LaTeX files is removed.
479  * The drawback is that the logic inside the function becomes
480  * complicated, and that is the reason why it is not implemented.
481  */
482 void check_space(Parser const & p, ostream & os, Context & context)
483 {
484         Token const next = p.next_token();
485         Token const curr = p.curr_token();
486         // A space before a single newline and vice versa must be ignored
487         // LyX emits a newline before \end{lyxcode}.
488         // This newline must be ignored,
489         // otherwise LyX will add an additional protected space.
490         if (next.cat() == catSpace ||
491             next.cat() == catNewline ||
492             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
493                 return;
494         }
495         context.check_layout(os);
496         os << ' ';
497 }
498
499
500 /*!
501  * Check whether \p command is a known command. If yes,
502  * handle the command with all arguments.
503  * \return true if the command was parsed, false otherwise.
504  */
505 bool parse_command(string const & command, Parser & p, ostream & os,
506                    bool outer, Context & context)
507 {
508         if (known_commands.find(command) != known_commands.end()) {
509                 vector<ArgumentType> const & template_arguments = known_commands[command];
510                 string ert = command;
511                 size_t no_arguments = template_arguments.size();
512                 for (size_t i = 0; i < no_arguments; ++i) {
513                         switch (template_arguments[i]) {
514                         case required:
515                                 // This argument contains regular LaTeX
516                                 handle_ert(os, ert + '{', context);
517                                 parse_text(p, os, FLAG_ITEM, outer, context);
518                                 ert = "}";
519                                 break;
520                         case verbatim:
521                                 // This argument may contain special characters
522                                 ert += '{' + p.verbatim_item() + '}';
523                                 break;
524                         case optional:
525                                 ert += p.getOpt();
526                                 break;
527                         }
528                 }
529                 handle_ert(os, ert, context);
530                 return true;
531         }
532         return false;
533 }
534
535
536 /// Parses a minipage or parbox
537 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
538                Context & parent_context, bool use_parbox)
539 {
540         string position;
541         string inner_pos;
542         string height_value = "0";
543         string height_unit = "pt";
544         string height_special = "none";
545         string latex_height;
546         if (p.next_token().asInput() == "[") {
547                 position = p.getArg('[', ']');
548                 if (position != "t" && position != "c" && position != "b") {
549                         position = "c";
550                         cerr << "invalid position for minipage/parbox" << endl;
551                 }
552                 if (p.next_token().asInput() == "[") {
553                         latex_height = p.getArg('[', ']');
554                         translate_box_len(latex_height, height_value, height_unit, height_special);
555
556                         if (p.next_token().asInput() == "[") {
557                                 inner_pos = p.getArg('[', ']');
558                                 if (inner_pos != "c" && inner_pos != "t" &&
559                                     inner_pos != "b" && inner_pos != "s") {
560                                         inner_pos = position;
561                                         cerr << "invalid inner_pos for minipage/parbox"
562                                              << endl;
563                                 }
564                         }
565                 }
566         }
567         string width_value;
568         string width_unit;
569         string const latex_width = p.verbatim_item();
570         translate_len(latex_width, width_value, width_unit);
571         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
572                 // LyX can't handle length variables
573                 ostringstream ss;
574                 if (use_parbox)
575                         ss << "\\parbox";
576                 else
577                         ss << "\\begin{minipage}";
578                 if (!position.empty())
579                         ss << '[' << position << ']';
580                 if (!latex_height.empty())
581                         ss << '[' << latex_height << ']';
582                 if (!inner_pos.empty())
583                         ss << '[' << inner_pos << ']';
584                 ss << "{" << latex_width << "}";
585                 if (use_parbox)
586                         ss << '{';
587                 handle_ert(os, ss.str(), parent_context);
588                 parent_context.new_paragraph(os);
589                 parse_text_in_inset(p, os, flags, outer, parent_context);
590                 if (use_parbox)
591                         handle_ert(os, "}", parent_context);
592                 else
593                         handle_ert(os, "\\end{minipage}", parent_context);
594         } else {
595                 // LyX does not like empty positions, so we have
596                 // to set them to the LaTeX default values here.
597                 if (position.empty())
598                         position = "c";
599                 if (inner_pos.empty())
600                         inner_pos = position;
601                 parent_context.check_layout(os);
602                 begin_inset(os, "Box Frameless\n");
603                 os << "position \"" << position << "\"\n";
604                 os << "hor_pos \"c\"\n";
605                 os << "has_inner_box 1\n";
606                 os << "inner_pos \"" << inner_pos << "\"\n";
607                 os << "use_parbox " << use_parbox << "\n";
608                 os << "width \"" << width_value << width_unit << "\"\n";
609                 os << "special \"none\"\n";
610                 os << "height \"" << height_value << height_unit << "\"\n";
611                 os << "height_special \"" << height_special << "\"\n";
612                 os << "status open\n\n";
613                 parse_text_in_inset(p, os, flags, outer, parent_context);
614                 end_inset(os);
615 #ifdef PRESERVE_LAYOUT
616                 // lyx puts a % after the end of the minipage
617                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
618                         // new paragraph
619                         //handle_comment(os, "%dummy", parent_context);
620                         p.get_token();
621                         p.skip_spaces();
622                         parent_context.new_paragraph(os);
623                 }
624                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
625                         //handle_comment(os, "%dummy", parent_context);
626                         p.get_token();
627                         p.skip_spaces();
628                         // We add a protected space if something real follows
629                         if (p.good() && p.next_token().cat() != catComment) {
630                                 os << "\\InsetSpace ~\n";
631                         }
632                 }
633 #endif
634         }
635 }
636
637
638 void parse_environment(Parser & p, ostream & os, bool outer,
639                        Context & parent_context)
640 {
641         LyXLayout_ptr newlayout;
642         string const name = p.getArg('{', '}');
643         const bool is_starred = suffixIs(name, '*');
644         string const unstarred_name = rtrim(name, "*");
645         eat_whitespace(p, os, parent_context, false);
646         active_environments.push_back(name);
647
648         if (is_math_env(name)) {
649                 parent_context.check_layout(os);
650                 begin_inset(os, "Formula ");
651                 os << "\\begin{" << name << "}";
652                 parse_math(p, os, FLAG_END, MATH_MODE);
653                 os << "\\end{" << name << "}";
654                 end_inset(os);
655         }
656
657         else if (name == "tabular" || name == "longtable") {
658                 parent_context.check_layout(os);
659                 begin_inset(os, "Tabular ");
660                 handle_tabular(p, os, name == "longtable", parent_context);
661                 end_inset(os);
662         }
663
664         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
665                 parent_context.check_layout(os);
666                 begin_inset(os, "Float " + unstarred_name + "\n");
667                 if (p.next_token().asInput() == "[") {
668                         os << "placement " << p.getArg('[', ']') << '\n';
669                 }
670                 os << "wide " << convert<string>(is_starred)
671                    << "\nsideways false"
672                    << "\nstatus open\n\n";
673                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
674                 end_inset(os);
675                 // We don't need really a new paragraph, but
676                 // we must make sure that the next item gets a \begin_layout.
677                 parent_context.new_paragraph(os);
678         }
679
680         else if (name == "minipage")
681                 parse_box(p, os, FLAG_END, outer, parent_context, false);
682
683         // Alignment settings
684         else if (name == "center" || name == "flushleft" || name == "flushright" ||
685                  name == "centering" || name == "raggedright" || name == "raggedleft") {
686                 // We must begin a new paragraph if not already done
687                 if (! parent_context.atParagraphStart()) {
688                         parent_context.check_end_layout(os);
689                         parent_context.new_paragraph(os);
690                 }
691                 if (name == "flushleft" || name == "raggedright")
692                         parent_context.add_extra_stuff("\\align left\n");
693                 else if (name == "flushright" || name == "raggedleft")
694                         parent_context.add_extra_stuff("\\align right\n");
695                 else
696                         parent_context.add_extra_stuff("\\align center\n");
697                 parse_text(p, os, FLAG_END, outer, parent_context);
698                 // Just in case the environment is empty ..
699                 parent_context.extra_stuff.erase();
700                 // We must begin a new paragraph to reset the alignment
701                 parent_context.new_paragraph(os);
702         }
703
704         // The single '=' is meant here.
705         else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
706                    newlayout->isEnvironment()) {
707                 Context context(true, parent_context.textclass, newlayout,
708                                 parent_context.layout, parent_context.font);
709                 if (parent_context.deeper_paragraph) {
710                         // We are beginning a nested environment after a
711                         // deeper paragraph inside the outer list environment.
712                         // Therefore we don't need to output a "begin deeper".
713                         context.need_end_deeper = true;
714                 }
715                 parent_context.check_end_layout(os);
716                 switch (context.layout->latextype) {
717                 case  LATEX_LIST_ENVIRONMENT:
718                         context.extra_stuff = "\\labelwidthstring "
719                                 + p.verbatim_item() + '\n';
720                         p.skip_spaces();
721                         break;
722                 case  LATEX_BIB_ENVIRONMENT:
723                         p.verbatim_item(); // swallow next arg
724                         p.skip_spaces();
725                         break;
726                 default:
727                         break;
728                 }
729                 context.check_deeper(os);
730                 parse_text(p, os, FLAG_END, outer, context);
731                 context.check_end_layout(os);
732                 if (parent_context.deeper_paragraph) {
733                         // We must suppress the "end deeper" because we
734                         // suppressed the "begin deeper" above.
735                         context.need_end_deeper = false;
736                 }
737                 context.check_end_deeper(os);
738                 parent_context.new_paragraph(os);
739         }
740
741         else if (name == "appendix") {
742                 // This is no good latex style, but it works and is used in some documents...
743                 parent_context.check_end_layout(os);
744                 Context context(true, parent_context.textclass, parent_context.layout,
745                                 parent_context.layout, parent_context.font);
746                 context.check_layout(os);
747                 os << "\\start_of_appendix\n";
748                 parse_text(p, os, FLAG_END, outer, context);
749                 context.check_end_layout(os);
750         }
751
752         else if (name == "comment") {
753                 parent_context.check_layout(os);
754                 begin_inset(os, "Note Comment\n");
755                 os << "status open\n";
756                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
757                 end_inset(os);
758         }
759
760         else if (name == "lyxgreyedout") {
761                 parent_context.check_layout(os);
762                 begin_inset(os, "Note Greyedout\n");
763                 os << "status open\n";
764                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
765                 end_inset(os);
766         }
767
768         else if (name == "tabbing") {
769                 // We need to remember that we have to handle '\=' specially
770                 handle_ert(os, "\\begin{" + name + "}", parent_context);
771                 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer, parent_context);
772                 handle_ert(os, "\\end{" + name + "}", parent_context);
773         }
774
775         else {
776                 handle_ert(os, "\\begin{" + name + "}", parent_context);
777                 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
778                 handle_ert(os, "\\end{" + name + "}", parent_context);
779         }
780
781         active_environments.pop_back();
782         if (name != "math")
783                 p.skip_spaces();
784 }
785
786 /// parses a comment and outputs it to \p os.
787 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
788 {
789         BOOST_ASSERT(t.cat() == catComment);
790         context.check_layout(os);
791         if (!t.cs().empty()) {
792                 handle_comment(os, '%' + t.cs(), context);
793                 if (p.next_token().cat() == catNewline) {
794                         // A newline after a comment line starts a new
795                         // paragraph
796                         if(!context.atParagraphStart()) {
797                                 // Only start a new paragraph if not already
798                                 // done (we might get called recursively)
799                                 context.new_paragraph(os);
800                         }
801                         eat_whitespace(p, os, context, true);
802                 }
803         } else {
804                 // "%\n" combination
805                 p.skip_spaces();
806         }
807 }
808
809
810 /*!
811  * Reads spaces and comments until the first non-space, non-comment token.
812  * New paragraphs (double newlines or \\par) are handled like simple spaces
813  * if \p eatParagraph is true.
814  * Spaces are skipped, but comments are written to \p os.
815  */
816 void eat_whitespace(Parser & p, ostream & os, Context & context,
817                     bool eatParagraph)
818 {
819         while (p.good()) {
820                 Token const & t = p.get_token();
821                 if (t.cat() == catComment)
822                         parse_comment(p, os, t, context);
823                 else if ((! eatParagraph && p.isParagraph()) ||
824                          (t.cat() != catSpace && t.cat() != catNewline)) {
825                         p.putback();
826                         return;
827                 }
828         }
829 }
830
831
832 /*!
833  * Set a font attribute, parse text and reset the font attribute.
834  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
835  * \param currentvalue Current value of the attribute. Is set to the new
836  * value during parsing.
837  * \param newvalue New value of the attribute
838  */
839 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
840                            Context & context, string const & attribute,
841                            string & currentvalue, string const & newvalue)
842 {
843         context.check_layout(os);
844         string oldvalue = currentvalue;
845         currentvalue = newvalue;
846         os << '\n' << attribute << ' ' << newvalue << "\n";
847         parse_text_snippet(p, os, flags, outer, context);
848         currentvalue = oldvalue;
849         os << '\n' << attribute << ' ' << oldvalue << "\n";
850 }
851
852
853 /// get the arguments of a natbib or jurabib citation command
854 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
855 {
856         // We need to distinguish "" and "[]", so we can't use p.getOpt().
857
858         // text before the citation
859         string before;
860         // text after the citation
861         string after = p.getFullOpt();
862
863         if (!after.empty()) {
864                 before = p.getFullOpt();
865                 if (natbibOrder && !before.empty())
866                         std::swap(before, after);
867         }
868         return std::make_pair(before, after);
869 }
870
871 } // anonymous namespace
872
873
874 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
875                 Context & context)
876 {
877         LyXLayout_ptr newlayout;
878         // Store the latest bibliographystyle (needed for bibtex inset)
879         string bibliographystyle;
880         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
881         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
882         while (p.good()) {
883                 Token const & t = p.get_token();
884
885 #ifdef FILEDEBUG
886                 cerr << "t: " << t << " flags: " << flags << "\n";
887 #endif
888
889                 if (flags & FLAG_ITEM) {
890                         if (t.cat() == catSpace)
891                                 continue;
892
893                         flags &= ~FLAG_ITEM;
894                         if (t.cat() == catBegin) {
895                                 // skip the brace and collect everything to the next matching
896                                 // closing brace
897                                 flags |= FLAG_BRACE_LAST;
898                                 continue;
899                         }
900
901                         // handle only this single token, leave the loop if done
902                         flags |= FLAG_LEAVE;
903                 }
904
905                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
906                         return;
907
908                 //
909                 // cat codes
910                 //
911                 if (t.cat() == catMath) {
912                         // we are inside some text mode thingy, so opening new math is allowed
913                         context.check_layout(os);
914                         begin_inset(os, "Formula ");
915                         Token const & n = p.get_token();
916                         if (n.cat() == catMath && outer) {
917                                 // TeX's $$...$$ syntax for displayed math
918                                 os << "\\[";
919                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
920                                 os << "\\]";
921                                 p.get_token(); // skip the second '$' token
922                         } else {
923                                 // simple $...$  stuff
924                                 p.putback();
925                                 os << '$';
926                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
927                                 os << '$';
928                         }
929                         end_inset(os);
930                 }
931
932                 else if (t.cat() == catSuper || t.cat() == catSub)
933                         cerr << "catcode " << t << " illegal in text mode\n";
934
935                 // Basic support for english quotes. This should be
936                 // extended to other quotes, but is not so easy (a
937                 // left english quote is the same as a right german
938                 // quote...)
939                 else if (t.asInput() == "`"
940                          && p.next_token().asInput() == "`") {
941                         context.check_layout(os);
942                         begin_inset(os, "Quotes ");
943                         os << "eld";
944                         end_inset(os);
945                         p.get_token();
946                         skip_braces(p);
947                 }
948                 else if (t.asInput() == "'"
949                          && p.next_token().asInput() == "'") {
950                         context.check_layout(os);
951                         begin_inset(os, "Quotes ");
952                         os << "erd";
953                         end_inset(os);
954                         p.get_token();
955                         skip_braces(p);
956                 }
957
958                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
959                         check_space(p, os, context);
960
961                 else if (t.cat() == catLetter ||
962                                t.cat() == catOther ||
963                                t.cat() == catAlign ||
964                                t.cat() == catParameter) {
965                         context.check_layout(os);
966                         os << t.character();
967                 }
968
969                 else if (p.isParagraph()) {
970                         context.new_paragraph(os);
971                         eat_whitespace(p, os, context, true);
972                 }
973
974                 else if (t.cat() == catActive) {
975                         context.check_layout(os);
976                         if (t.character() == '~') {
977                                 if (context.layout->free_spacing)
978                                         os << ' ';
979                                 else
980                                         os << "\\InsetSpace ~\n";
981                         } else
982                                 os << t.character();
983                 }
984
985                 else if (t.cat() == catBegin) {
986                         context.check_layout(os);
987                         // special handling of font attribute changes
988                         Token const prev = p.prev_token();
989                         Token const next = p.next_token();
990                         Font const oldFont = context.font;
991                         string const s = parse_text(p, FLAG_BRACE_LAST, outer,
992                                                     context);
993                         context.font = oldFont;
994                         if (s.empty() && (p.next_token().character() == '`' ||
995                                           (prev.character() == '-' &&
996                                            p.next_token().character() == '-')))
997                                 ; // ignore it in {}`` or -{}-
998                         else if (s == "[" || s == "]" || s == "*")
999                                 os << s;
1000                         else if (is_known(next.cs(), known_sizes)) {
1001                                 // s will change the size, so we must reset
1002                                 // it here
1003                                 os << s;
1004                                 if (!context.atParagraphStart())
1005                                         os << "\n\\size "
1006                                            << context.font.size << "\n";
1007                         } else if (is_known(next.cs(), known_font_families)) {
1008                                 // s will change the font family, so we must
1009                                 // reset it here
1010                                 os << s;
1011                                 if (!context.atParagraphStart())
1012                                         os << "\n\\family "
1013                                            << context.font.family << "\n";
1014                         } else if (is_known(next.cs(), known_font_series)) {
1015                                 // s will change the font series, so we must
1016                                 // reset it here
1017                                 os << s;
1018                                 if (!context.atParagraphStart())
1019                                         os << "\n\\series "
1020                                            << context.font.series << "\n";
1021                         } else if (is_known(next.cs(), known_font_shapes)) {
1022                                 // s will change the font shape, so we must
1023                                 // reset it here
1024                                 os << s;
1025                                 if (!context.atParagraphStart())
1026                                         os << "\n\\shape "
1027                                            << context.font.shape << "\n";
1028                         } else if (is_known(next.cs(), known_old_font_families) ||
1029                                    is_known(next.cs(), known_old_font_series) ||
1030                                    is_known(next.cs(), known_old_font_shapes)) {
1031                                 // s will change the font family, series
1032                                 // and shape, so we must reset it here
1033                                 os << s;
1034                                 if (!context.atParagraphStart())
1035                                         os <<  "\n\\family "
1036                                            << context.font.family
1037                                            << "\n\\series "
1038                                            << context.font.series
1039                                            << "\n\\shape "
1040                                            << context.font.shape << "\n";
1041                         } else {
1042                                 handle_ert(os, "{", context, false);
1043                                 // s will end the current layout and begin a
1044                                 // new one if necessary
1045                                 os << s;
1046                                 handle_ert(os, "}", context);
1047                         }
1048                 }
1049
1050                 else if (t.cat() == catEnd) {
1051                         if (flags & FLAG_BRACE_LAST) {
1052                                 return;
1053                         }
1054                         cerr << "stray '}' in text\n";
1055                         handle_ert(os, "}", context);
1056                 }
1057
1058                 else if (t.cat() == catComment)
1059                         parse_comment(p, os, t, context);
1060
1061                 //
1062                 // control sequences
1063                 //
1064
1065                 else if (t.cs() == "(") {
1066                         context.check_layout(os);
1067                         begin_inset(os, "Formula");
1068                         os << " \\(";
1069                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1070                         os << "\\)";
1071                         end_inset(os);
1072                 }
1073
1074                 else if (t.cs() == "[") {
1075                         context.check_layout(os);
1076                         begin_inset(os, "Formula");
1077                         os << " \\[";
1078                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1079                         os << "\\]";
1080                         end_inset(os);
1081                 }
1082
1083                 else if (t.cs() == "begin")
1084                         parse_environment(p, os, outer, context);
1085
1086                 else if (t.cs() == "end") {
1087                         if (flags & FLAG_END) {
1088                                 // eat environment name
1089                                 string const name = p.getArg('{', '}');
1090                                 if (name != active_environment())
1091                                         cerr << "\\end{" + name + "} does not match \\begin{"
1092                                                 + active_environment() + "}\n";
1093                                 return;
1094                         }
1095                         p.error("found 'end' unexpectedly");
1096                 }
1097
1098                 else if (t.cs() == "item") {
1099                         p.skip_spaces();
1100                         string s;
1101                         bool optarg = false;
1102                         if (p.next_token().character() == '[') {
1103                                 p.get_token(); // eat '['
1104                                 Context newcontext(false, context.textclass);
1105                                 newcontext.font = context.font;
1106                                 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
1107                                 optarg = true;
1108                         }
1109                         context.set_item();
1110                         context.check_layout(os);
1111                         if (optarg) {
1112                                 if (context.layout->labeltype != LABEL_MANUAL) {
1113                                         // lyx does not support \item[\mybullet]
1114                                         // in itemize environments
1115                                         handle_ert(os, "[", context);
1116                                         os << s;
1117                                         handle_ert(os, "]", context);
1118                                 } else if (!s.empty()) {
1119                                         // The space is needed to separate the
1120                                         // item from the rest of the sentence.
1121                                         os << s << ' ';
1122                                         eat_whitespace(p, os, context, false);
1123                                 }
1124                         }
1125                 }
1126
1127                 else if (t.cs() == "bibitem") {
1128                         context.set_item();
1129                         context.check_layout(os);
1130                         os << "\\bibitem ";
1131                         os << p.getOpt();
1132                         os << '{' << p.verbatim_item() << '}' << "\n";
1133                 }
1134
1135                 else if (t.cs() == "def") {
1136                         context.check_layout(os);
1137                         eat_whitespace(p, os, context, false);
1138                         string name = p.get_token().cs();
1139                         while (p.next_token().cat() != catBegin)
1140                                 name += p.get_token().asString();
1141                         handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1142                 }
1143
1144                 else if (t.cs() == "noindent") {
1145                         p.skip_spaces();
1146                         context.add_extra_stuff("\\noindent\n");
1147                 }
1148
1149                 else if (t.cs() == "appendix") {
1150                         p.skip_spaces();
1151                         context.add_extra_stuff("\\start_of_appendix\n");
1152                 }
1153
1154                 // Must attempt to parse "Section*" before "Section".
1155                 else if ((p.next_token().asInput() == "*") &&
1156                          // The single '=' is meant here.
1157                          (newlayout = findLayout(context.textclass,
1158                                                  t.cs() + '*')).get() &&
1159                          newlayout->isCommand()) {
1160                         p.get_token();
1161                         output_command_layout(os, p, outer, context, newlayout);
1162                         p.skip_spaces();
1163                 }
1164
1165                 // The single '=' is meant here.
1166                 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
1167                          newlayout->isCommand()) {
1168                         output_command_layout(os, p, outer, context, newlayout);
1169                         p.skip_spaces();
1170                 }
1171
1172                 else if (t.cs() == "includegraphics") {
1173                         bool const clip = p.next_token().asInput() == "*";
1174                         if (clip)
1175                                 p.get_token();
1176                         map<string, string> opts = split_map(p.getArg('[', ']'));
1177                         if (clip)
1178                                 opts["clip"] = string();
1179                         string name = subst(p.verbatim_item(), "\\lyxdot ", ".");
1180
1181                         string const path = getMasterFilePath();
1182                         // We want to preserve relative / absolute filenames,
1183                         // therefore path is only used for testing
1184                         if (!fs::exists(MakeAbsPath(name, path))) {
1185                                 // The file extension is probably missing.
1186                                 // Now try to find it out.
1187                                 string const dvips_name =
1188                                         find_file(name, path,
1189                                                   known_dvips_graphics_formats);
1190                                 string const pdftex_name =
1191                                         find_file(name, path,
1192                                                   known_pdftex_graphics_formats);
1193                                 if (!dvips_name.empty()) {
1194                                         if (!pdftex_name.empty()) {
1195                                                 cerr << "This file contains the "
1196                                                         "latex snippet\n"
1197                                                         "\"\\includegraphics{"
1198                                                      << name << "}\".\n"
1199                                                         "However, files\n\""
1200                                                      << dvips_name << "\" and\n\""
1201                                                      << pdftex_name << "\"\n"
1202                                                         "both exist, so I had to make a "
1203                                                         "choice and took the first one.\n"
1204                                                         "Please move the unwanted one "
1205                                                         "someplace else and try again\n"
1206                                                         "if my choice was wrong."
1207                                                      << endl;
1208                                         }
1209                                         name = dvips_name;
1210                                 } else if (!pdftex_name.empty())
1211                                         name = pdftex_name;
1212
1213                                 if (!fs::exists(MakeAbsPath(name, path)))
1214                                         cerr << "Warning: Could not find graphics file '"
1215                                              << name << "'." << endl;
1216                         }
1217
1218                         context.check_layout(os);
1219                         begin_inset(os, "Graphics ");
1220                         os << "\n\tfilename " << name << '\n';
1221                         if (opts.find("width") != opts.end())
1222                                 os << "\twidth "
1223                                    << translate_len(opts["width"]) << '\n';
1224                         if (opts.find("height") != opts.end())
1225                                 os << "\theight "
1226                                    << translate_len(opts["height"]) << '\n';
1227                         if (opts.find("scale") != opts.end()) {
1228                                 istringstream iss(opts["scale"]);
1229                                 double val;
1230                                 iss >> val;
1231                                 val = val*100;
1232                                 os << "\tscale " << val << '\n';
1233                         }
1234                         if (opts.find("angle") != opts.end())
1235                                 os << "\trotateAngle "
1236                                    << opts["angle"] << '\n';
1237                         if (opts.find("origin") != opts.end()) {
1238                                 ostringstream ss;
1239                                 string const opt = opts["origin"];
1240                                 if (opt.find('l') != string::npos) ss << "left";
1241                                 if (opt.find('r') != string::npos) ss << "right";
1242                                 if (opt.find('c') != string::npos) ss << "center";
1243                                 if (opt.find('t') != string::npos) ss << "Top";
1244                                 if (opt.find('b') != string::npos) ss << "Bottom";
1245                                 if (opt.find('B') != string::npos) ss << "Baseline";
1246                                 if (!ss.str().empty())
1247                                         os << "\trotateOrigin " << ss.str() << '\n';
1248                                 else
1249                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1250                         }
1251                         if (opts.find("keepaspectratio") != opts.end())
1252                                 os << "\tkeepAspectRatio\n";
1253                         if (opts.find("clip") != opts.end())
1254                                 os << "\tclip\n";
1255                         if (opts.find("draft") != opts.end())
1256                                 os << "\tdraft\n";
1257                         if (opts.find("bb") != opts.end())
1258                                 os << "\tBoundingBox "
1259                                    << opts["bb"] << '\n';
1260                         int numberOfbbOptions = 0;
1261                         if (opts.find("bbllx") != opts.end())
1262                                 numberOfbbOptions++;
1263                         if (opts.find("bblly") != opts.end())
1264                                 numberOfbbOptions++;
1265                         if (opts.find("bburx") != opts.end())
1266                                 numberOfbbOptions++;
1267                         if (opts.find("bbury") != opts.end())
1268                                 numberOfbbOptions++;
1269                         if (numberOfbbOptions == 4)
1270                                 os << "\tBoundingBox "
1271                                    << opts["bbllx"] << opts["bblly"]
1272                                    << opts["bburx"] << opts["bbury"] << '\n';
1273                         else if (numberOfbbOptions > 0)
1274                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1275                         numberOfbbOptions = 0;
1276                         if (opts.find("natwidth") != opts.end())
1277                                 numberOfbbOptions++;
1278                         if (opts.find("natheight") != opts.end())
1279                                 numberOfbbOptions++;
1280                         if (numberOfbbOptions == 2)
1281                                 os << "\tBoundingBox 0bp 0bp "
1282                                    << opts["natwidth"] << opts["natheight"] << '\n';
1283                         else if (numberOfbbOptions > 0)
1284                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1285                         ostringstream special;
1286                         if (opts.find("hiresbb") != opts.end())
1287                                 special << "hiresbb,";
1288                         if (opts.find("trim") != opts.end())
1289                                 special << "trim,";
1290                         if (opts.find("viewport") != opts.end())
1291                                 special << "viewport=" << opts["viewport"] << ',';
1292                         if (opts.find("totalheight") != opts.end())
1293                                 special << "totalheight=" << opts["totalheight"] << ',';
1294                         if (opts.find("type") != opts.end())
1295                                 special << "type=" << opts["type"] << ',';
1296                         if (opts.find("ext") != opts.end())
1297                                 special << "ext=" << opts["ext"] << ',';
1298                         if (opts.find("read") != opts.end())
1299                                 special << "read=" << opts["read"] << ',';
1300                         if (opts.find("command") != opts.end())
1301                                 special << "command=" << opts["command"] << ',';
1302                         string s_special = special.str();
1303                         if (!s_special.empty()) {
1304                                 // We had special arguments. Remove the trailing ','.
1305                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1306                         }
1307                         // TODO: Handle the unknown settings better.
1308                         // Warn about invalid options.
1309                         // Check whether some option was given twice.
1310                         end_inset(os);
1311                 }
1312
1313                 else if (t.cs() == "footnote" ||
1314                          (t.cs() == "thanks" && context.layout->intitle)) {
1315                         p.skip_spaces();
1316                         context.check_layout(os);
1317                         begin_inset(os, "Foot\n");
1318                         os << "status collapsed\n\n";
1319                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1320                         end_inset(os);
1321                 }
1322
1323                 else if (t.cs() == "marginpar") {
1324                         p.skip_spaces();
1325                         context.check_layout(os);
1326                         begin_inset(os, "Marginal\n");
1327                         os << "status collapsed\n\n";
1328                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1329                         end_inset(os);
1330                 }
1331
1332                 else if (t.cs() == "ensuremath") {
1333                         p.skip_spaces();
1334                         context.check_layout(os);
1335                         Context newcontext(false, context.textclass);
1336                         newcontext.font = context.font;
1337                         string s = parse_text(p, FLAG_ITEM, false, newcontext);
1338                         if (s == "±" || s == "³" || s == "²" || s == "µ")
1339                                 os << s;
1340                         else
1341                                 handle_ert(os, "\\ensuremath{" + s + "}",
1342                                            context);
1343                 }
1344
1345                 else if (t.cs() == "hfill") {
1346                         context.check_layout(os);
1347                         os << "\n\\hfill\n";
1348                         skip_braces(p);
1349                         p.skip_spaces();
1350                 }
1351
1352                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1353                         // FIXME: Somehow prevent title layouts if
1354                         // "maketitle" was not found
1355                         p.skip_spaces();
1356                         skip_braces(p); // swallow this
1357                 }
1358
1359                 else if (t.cs() == "tableofcontents") {
1360                         p.skip_spaces();
1361                         context.check_layout(os);
1362                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1363                         end_inset(os);
1364                         skip_braces(p); // swallow this
1365                 }
1366
1367                 else if (t.cs() == "listoffigures") {
1368                         p.skip_spaces();
1369                         context.check_layout(os);
1370                         begin_inset(os, "FloatList figure\n");
1371                         end_inset(os);
1372                         skip_braces(p); // swallow this
1373                 }
1374
1375                 else if (t.cs() == "listoftables") {
1376                         p.skip_spaces();
1377                         context.check_layout(os);
1378                         begin_inset(os, "FloatList table\n");
1379                         end_inset(os);
1380                         skip_braces(p); // swallow this
1381                 }
1382
1383                 else if (t.cs() == "listof") {
1384                         p.skip_spaces(true);
1385                         string const name = p.get_token().asString();
1386                         if (context.textclass.floats().typeExist(name)) {
1387                                 context.check_layout(os);
1388                                 begin_inset(os, "FloatList ");
1389                                 os << name << "\n";
1390                                 end_inset(os);
1391                                 p.get_token(); // swallow second arg
1392                         } else
1393                                 handle_ert(os, "\\listof{" + name + "}", context);
1394                 }
1395
1396                 else if (t.cs() == "textrm")
1397                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1398                                               context, "\\family",
1399                                               context.font.family, "roman");
1400
1401                 else if (t.cs() == "textsf")
1402                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1403                                               context, "\\family",
1404                                               context.font.family, "sans");
1405
1406                 else if (t.cs() == "texttt")
1407                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1408                                               context, "\\family",
1409                                               context.font.family, "typewriter");
1410
1411                 else if (t.cs() == "textmd")
1412                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1413                                               context, "\\series",
1414                                               context.font.series, "medium");
1415
1416                 else if (t.cs() == "textbf")
1417                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1418                                               context, "\\series",
1419                                               context.font.series, "bold");
1420
1421                 else if (t.cs() == "textup")
1422                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1423                                               context, "\\shape",
1424                                               context.font.shape, "up");
1425
1426                 else if (t.cs() == "textit")
1427                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1428                                               context, "\\shape",
1429                                               context.font.shape, "italic");
1430
1431                 else if (t.cs() == "textsl")
1432                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1433                                               context, "\\shape",
1434                                               context.font.shape, "slanted");
1435
1436                 else if (t.cs() == "textsc")
1437                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1438                                               context, "\\shape",
1439                                               context.font.shape, "smallcaps");
1440
1441                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1442                         context.check_layout(os);
1443                         Font oldFont = context.font;
1444                         context.font.init();
1445                         context.font.size = oldFont.size;
1446                         os << "\n\\family " << context.font.family << "\n";
1447                         os << "\n\\series " << context.font.series << "\n";
1448                         os << "\n\\shape " << context.font.shape << "\n";
1449                         if (t.cs() == "textnormal") {
1450                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1451                                 context.font = oldFont;
1452                                 os << "\n\\shape " << oldFont.shape << "\n";
1453                                 os << "\n\\series " << oldFont.series << "\n";
1454                                 os << "\n\\family " << oldFont.family << "\n";
1455                         } else
1456                                 eat_whitespace(p, os, context, false);
1457                 }
1458
1459                 else if (t.cs() == "underbar") {
1460                         // Do NOT handle \underline.
1461                         // \underbar cuts through y, g, q, p etc.,
1462                         // \underline does not.
1463                         context.check_layout(os);
1464                         os << "\n\\bar under\n";
1465                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1466                         os << "\n\\bar default\n";
1467                 }
1468
1469                 else if (t.cs() == "emph" || t.cs() == "noun") {
1470                         context.check_layout(os);
1471                         os << "\n\\" << t.cs() << " on\n";
1472                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1473                         os << "\n\\" << t.cs() << " default\n";
1474                 }
1475
1476                 else if (use_natbib &&
1477                          is_known(t.cs(), known_natbib_commands) &&
1478                          ((t.cs() != "citefullauthor" &&
1479                            t.cs() != "citeyear" &&
1480                            t.cs() != "citeyearpar") ||
1481                           p.next_token().asInput() != "*")) {
1482                         context.check_layout(os);
1483                         // tex                       lyx
1484                         // \citet[before][after]{a}  \citet[after][before]{a}
1485                         // \citet[before][]{a}       \citet[][before]{a}
1486                         // \citet[after]{a}          \citet[after]{a}
1487                         // \citet{a}                 \citet{a}
1488                         string command = '\\' + t.cs();
1489                         if (p.next_token().asInput() == "*") {
1490                                 command += '*';
1491                                 p.get_token();
1492                         }
1493                         if (command == "\\citefullauthor")
1494                                 // alternative name for "\\citeauthor*"
1495                                 command = "\\citeauthor*";
1496
1497                         // text before the citation
1498                         string before;
1499                         // text after the citation
1500                         string after;
1501
1502                         boost::tie(before, after) = getCiteArguments(p, true);
1503                         if (command == "\\cite") {
1504                                 // \cite without optional argument means
1505                                 // \citet, \cite with at least one optional
1506                                 // argument means \citep.
1507                                 if (before.empty() && after.empty())
1508                                         command = "\\citet";
1509                                 else
1510                                         command = "\\citep";
1511                         }
1512                         if (before.empty() && after == "[]")
1513                                 // avoid \citet[]{a}
1514                                 after.erase();
1515                         else if (before == "[]" && after == "[]") {
1516                                 // avoid \citet[][]{a}
1517                                 before.erase();
1518                                 after.erase();
1519                         }
1520                         begin_inset(os, "LatexCommand ");
1521                         os << command << after << before
1522                            << '{' << p.verbatim_item() << "}\n";
1523                         end_inset(os);
1524                 }
1525
1526                 else if (use_jurabib &&
1527                          is_known(t.cs(), known_jurabib_commands)) {
1528                         context.check_layout(os);
1529                         string const command = '\\' + t.cs();
1530                         char argumentOrder = '\0';
1531                         vector<string> const & options = used_packages["jurabib"];
1532                         if (std::find(options.begin(), options.end(),
1533                                       "natbiborder") != options.end())
1534                                 argumentOrder = 'n';
1535                         else if (std::find(options.begin(), options.end(),
1536                                            "jurabiborder") != options.end())
1537                                 argumentOrder = 'j';
1538
1539                         // text before the citation
1540                         string before;
1541                         // text after the citation
1542                         string after;
1543
1544                         boost::tie(before, after) =
1545                                 getCiteArguments(p, argumentOrder != 'j');
1546                         string const citation = p.verbatim_item();
1547                         if (!before.empty() && argumentOrder == '\0') {
1548                                 cerr << "Warning: Assuming argument order "
1549                                         "of jurabib version 0.6 for\n'"
1550                                      << command << before << after << '{'
1551                                      << citation << "}'.\n"
1552                                         "Add 'jurabiborder' to the jurabib "
1553                                         "package options if you used an\n"
1554                                         "earlier jurabib version." << endl;
1555                         }
1556                         begin_inset(os, "LatexCommand ");
1557                         os << command << after << before
1558                            << '{' << citation << "}\n";
1559                         end_inset(os);
1560                 }
1561
1562                 else if (is_known(t.cs(), known_latex_commands)) {
1563                         // This needs to be after the check for natbib and
1564                         // jurabib commands, because "cite" has different
1565                         // arguments with natbib and jurabib.
1566                         context.check_layout(os);
1567                         begin_inset(os, "LatexCommand ");
1568                         os << '\\' << t.cs();
1569                         // lyx cannot handle newlines in a latex command
1570                         // FIXME: Move the substitution into parser::getOpt()?
1571                         os << subst(p.getOpt(), "\n", " ");
1572                         os << subst(p.getOpt(), "\n", " ");
1573                         os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1574                         end_inset(os);
1575                 }
1576
1577                 else if (is_known(t.cs(), known_quotes)) {
1578                         char const * const * where = is_known(t.cs(), known_quotes);
1579                         context.check_layout(os);
1580                         begin_inset(os, "Quotes ");
1581                         os << known_coded_quotes[where - known_quotes];
1582                         end_inset(os);
1583                         // LyX adds {} after the quote, so we have to eat
1584                         // spaces here if there are any before a possible
1585                         // {} pair.
1586                         eat_whitespace(p, os, context, false);
1587                         skip_braces(p);
1588                 }
1589
1590                 else if (is_known(t.cs(), known_sizes)) {
1591                         char const * const * where = is_known(t.cs(), known_sizes);
1592                         context.check_layout(os);
1593                         context.font.size = known_coded_sizes[where - known_sizes];
1594                         os << "\n\\size " << context.font.size << '\n';
1595                         eat_whitespace(p, os, context, false);
1596                 }
1597
1598                 else if (is_known(t.cs(), known_font_families)) {
1599                         char const * const * where =
1600                                 is_known(t.cs(), known_font_families);
1601                         context.check_layout(os);
1602                         context.font.family =
1603                                 known_coded_font_families[where - known_font_families];
1604                         os << "\n\\family " << context.font.family << '\n';
1605                         eat_whitespace(p, os, context, false);
1606                 }
1607
1608                 else if (is_known(t.cs(), known_font_series)) {
1609                         char const * const * where =
1610                                 is_known(t.cs(), known_font_series);
1611                         context.check_layout(os);
1612                         context.font.series =
1613                                 known_coded_font_series[where - known_font_series];
1614                         os << "\n\\series " << context.font.series << '\n';
1615                         eat_whitespace(p, os, context, false);
1616                 }
1617
1618                 else if (is_known(t.cs(), known_font_shapes)) {
1619                         char const * const * where =
1620                                 is_known(t.cs(), known_font_shapes);
1621                         context.check_layout(os);
1622                         context.font.shape =
1623                                 known_coded_font_shapes[where - known_font_shapes];
1624                         os << "\n\\shape " << context.font.shape << '\n';
1625                         eat_whitespace(p, os, context, false);
1626                 }
1627                 else if (is_known(t.cs(), known_old_font_families)) {
1628                         char const * const * where =
1629                                 is_known(t.cs(), known_old_font_families);
1630                         context.check_layout(os);
1631                         string oldsize = context.font.size;
1632                         context.font.init();
1633                         context.font.size = oldsize;
1634                         context.font.family =
1635                                 known_coded_font_families[where - known_old_font_families];
1636                         os << "\n\\family " << context.font.family << "\n"
1637                            <<   "\\series " << context.font.series << "\n"
1638                            <<   "\\shape "  << context.font.shape  << "\n";
1639                         eat_whitespace(p, os, context, false);
1640                 }
1641
1642                 else if (is_known(t.cs(), known_old_font_series)) {
1643                         char const * const * where =
1644                                 is_known(t.cs(), known_old_font_series);
1645                         context.check_layout(os);
1646                         string oldsize = context.font.size;
1647                         context.font.init();
1648                         context.font.size = oldsize;
1649                         context.font.series =
1650                                 known_coded_font_series[where - known_old_font_series];
1651                         os << "\n\\family " << context.font.family << "\n"
1652                            <<   "\\series " << context.font.series << "\n"
1653                            <<   "\\shape "  << context.font.shape  << "\n";
1654                         eat_whitespace(p, os, context, false);
1655                 }
1656
1657                 else if (is_known(t.cs(), known_old_font_shapes)) {
1658                         char const * const * where =
1659                                 is_known(t.cs(), known_old_font_shapes);
1660                         context.check_layout(os);
1661                         string oldsize = context.font.size;
1662                         context.font.init();
1663                         context.font.size = oldsize;
1664                         context.font.shape =
1665                                 known_coded_font_shapes[where - known_old_font_shapes];
1666                         os << "\n\\family " << context.font.family << "\n"
1667                            <<   "\\series " << context.font.series << "\n"
1668                            <<   "\\shape "  << context.font.shape  << "\n";
1669                         eat_whitespace(p, os, context, false);
1670                 }
1671
1672                 else if (t.cs() == "LyX" || t.cs() == "TeX"
1673                          || t.cs() == "LaTeX") {
1674                         context.check_layout(os);
1675                         os << t.cs();
1676                         skip_braces(p); // eat {}
1677                 }
1678
1679                 else if (t.cs() == "LaTeXe") {
1680                         context.check_layout(os);
1681                         os << "LaTeX2e";
1682                         skip_braces(p); // eat {}
1683                 }
1684
1685                 else if (t.cs() == "ldots") {
1686                         context.check_layout(os);
1687                         skip_braces(p);
1688                         os << "\\SpecialChar \\ldots{}\n";
1689                 }
1690
1691                 else if (t.cs() == "lyxarrow") {
1692                         context.check_layout(os);
1693                         os << "\\SpecialChar \\menuseparator\n";
1694                         skip_braces(p);
1695                 }
1696
1697                 else if (t.cs() == "textcompwordmark") {
1698                         context.check_layout(os);
1699                         os << "\\SpecialChar \\textcompwordmark{}\n";
1700                         skip_braces(p);
1701                 }
1702
1703                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1704                         context.check_layout(os);
1705                         os << "\\SpecialChar \\@.\n";
1706                         p.get_token();
1707                 }
1708
1709                 else if (t.cs() == "-") {
1710                         context.check_layout(os);
1711                         os << "\\SpecialChar \\-\n";
1712                 }
1713
1714                 else if (t.cs() == "textasciitilde") {
1715                         context.check_layout(os);
1716                         os << '~';
1717                         skip_braces(p);
1718                 }
1719
1720                 else if (t.cs() == "textasciicircum") {
1721                         context.check_layout(os);
1722                         os << '^';
1723                         skip_braces(p);
1724                 }
1725
1726                 else if (t.cs() == "textbackslash") {
1727                         context.check_layout(os);
1728                         os << "\n\\backslash\n";
1729                         skip_braces(p);
1730                 }
1731
1732                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1733                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1734                             || t.cs() == "%") {
1735                         context.check_layout(os);
1736                         os << t.cs();
1737                 }
1738
1739                 else if (t.cs() == "char") {
1740                         context.check_layout(os);
1741                         if (p.next_token().character() == '`') {
1742                                 p.get_token();
1743                                 if (p.next_token().cs() == "\"") {
1744                                         p.get_token();
1745                                         os << '"';
1746                                         skip_braces(p);
1747                                 } else {
1748                                         handle_ert(os, "\\char`", context);
1749                                 }
1750                         } else {
1751                                 handle_ert(os, "\\char", context);
1752                         }
1753                 }
1754
1755                 else if (t.cs() == "\"") {
1756                         context.check_layout(os);
1757                         string const name = p.verbatim_item();
1758                              if (name == "a") os << 'ä';
1759                         else if (name == "o") os << 'ö';
1760                         else if (name == "u") os << 'ü';
1761                         else if (name == "A") os << 'Ä';
1762                         else if (name == "O") os << 'Ö';
1763                         else if (name == "U") os << 'Ü';
1764                         else handle_ert(os, "\"{" + name + "}", context);
1765                 }
1766
1767                 // Problem: \= creates a tabstop inside the tabbing environment
1768                 // and else an accent. In the latter case we really would want
1769                 // \={o} instead of \= o.
1770                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1771                         handle_ert(os, t.asInput(), context);
1772
1773                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1774                       || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1775                         // we need the trim as the LyX parser chokes on such spaces
1776                         context.check_layout(os);
1777                         os << "\n\\i \\" << t.cs() << "{"
1778                            << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1779                 }
1780
1781                 else if (t.cs() == "ss") {
1782                         context.check_layout(os);
1783                         os << "ß";
1784                 }
1785
1786                 else if (t.cs() == "i" || t.cs() == "j") {
1787                         context.check_layout(os);
1788                         os << "\\" << t.cs() << ' ';
1789                 }
1790
1791                 else if (t.cs() == "\\") {
1792                         context.check_layout(os);
1793                         string const next = p.next_token().asInput();
1794                         if (next == "[")
1795                                 handle_ert(os, "\\\\" + p.getOpt(), context);
1796                         else if (next == "*") {
1797                                 p.get_token();
1798                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
1799                         }
1800                         else {
1801                                 os << "\n\\newline\n";
1802                         }
1803                 }
1804
1805                 else if (t.cs() == "input" || t.cs() == "include"
1806                          || t.cs() == "verbatiminput") {
1807                         string name = '\\' + t.cs();
1808                         if (t.cs() == "verbatiminput"
1809                             && p.next_token().asInput() == "*")
1810                                 name += p.get_token().asInput();
1811                         context.check_layout(os);
1812                         begin_inset(os, "Include ");
1813                         string filename(p.getArg('{', '}'));
1814                         string lyxname(lyx::support::ChangeExtension(filename, ".lyx"));
1815                         if (tex2lyx(filename, lyxname)) {
1816                                 os << name << '{' << lyxname << "}\n";
1817                         } else {
1818                                 os << name << '{' << filename << "}\n";
1819                         }
1820                         os << "preview false\n";
1821                         end_inset(os);
1822                 }
1823
1824                 else if (t.cs() == "fancyhead") {
1825                         context.check_layout(os);
1826                         ostringstream ss;
1827                         ss << "\\fancyhead";
1828                         ss << p.getOpt();
1829                         ss << '{' << p.verbatim_item() << "}\n";
1830                         handle_ert(os, ss.str(), context);
1831                 }
1832
1833                 else if (t.cs() == "bibliographystyle") {
1834                         // store new bibliographystyle
1835                         bibliographystyle = p.verbatim_item();
1836                         // output new bibliographystyle.
1837                         // This is only necessary if used in some other macro than \bibliography.
1838                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1839                 }
1840
1841                 else if (t.cs() == "bibliography") {
1842                         context.check_layout(os);
1843                         begin_inset(os, "LatexCommand ");
1844                         os << "\\bibtex";
1845                         // Do we have a bibliographystyle set?
1846                         if (!bibliographystyle.empty()) {
1847                                 os << '[' << bibliographystyle << ']';
1848                         }
1849                         os << '{' << p.verbatim_item() << "}\n";
1850                         end_inset(os);
1851                 }
1852
1853                 else if (t.cs() == "parbox")
1854                         parse_box(p, os, FLAG_ITEM, outer, context, true);
1855
1856                 else if (t.cs() == "smallskip" ||
1857                          t.cs() == "medskip" ||
1858                          t.cs() == "bigskip" ||
1859                          t.cs() == "vfill") {
1860                         context.check_layout(os);
1861                         begin_inset(os, "VSpace ");
1862                         os << t.cs();
1863                         end_inset(os);
1864                         skip_braces(p);
1865                 }
1866
1867                 else if (t.cs() == "newcommand" ||
1868                          t.cs() == "providecommand" ||
1869                          t.cs() == "renewcommand") {
1870                         // these could be handled by parse_command(), but
1871                         // we need to call add_known_command() here.
1872                         string name = t.asInput();
1873                         if (p.next_token().asInput() == "*") {
1874                                 // Starred form. Eat '*'
1875                                 p.get_token();
1876                                 name += '*';
1877                         }
1878                         string const command = p.verbatim_item();
1879                         string const opt1 = p.getOpt();
1880                         string const opt2 = p.getFullOpt();
1881                         add_known_command(command, opt1, !opt2.empty());
1882                         string const ert = name + '{' + command + '}' +
1883                                            opt1 + opt2 +
1884                                            '{' + p.verbatim_item() + '}';
1885                         handle_ert(os, ert, context);
1886                 }
1887
1888                 else if (t.cs() == "vspace") {
1889                         bool starred = false;
1890                         if (p.next_token().asInput() == "*") {
1891                                 p.get_token();
1892                                 starred = true;
1893                         }
1894                         string const length = p.verbatim_item();
1895                         string unit;
1896                         string valstring;
1897                         bool valid = splitLatexLength(length, valstring, unit);
1898                         bool known_vspace = false;
1899                         bool known_unit = false;
1900                         double value;
1901                         if (valid) {
1902                                 istringstream iss(valstring);
1903                                 iss >> value;
1904                                 if (value == 1.0) {
1905                                         if (unit == "\\smallskipamount") {
1906                                                 unit = "smallskip";
1907                                                 known_vspace = true;
1908                                         } else if (unit == "\\medskipamount") {
1909                                                 unit = "medskip";
1910                                                 known_vspace = true;
1911                                         } else if (unit == "\\bigskipamount") {
1912                                                 unit = "bigskip";
1913                                                 known_vspace = true;
1914                                         } else if (unit == "\\fill") {
1915                                                 unit = "vfill";
1916                                                 known_vspace = true;
1917                                         }
1918                                 }
1919                                 if (!known_vspace) {
1920                                         switch (unitFromString(unit)) {
1921                                         case LyXLength::SP:
1922                                         case LyXLength::PT:
1923                                         case LyXLength::BP:
1924                                         case LyXLength::DD:
1925                                         case LyXLength::MM:
1926                                         case LyXLength::PC:
1927                                         case LyXLength::CC:
1928                                         case LyXLength::CM:
1929                                         case LyXLength::IN:
1930                                         case LyXLength::EX:
1931                                         case LyXLength::EM:
1932                                         case LyXLength::MU:
1933                                                 known_unit = true;
1934                                                 break;
1935                                         default:
1936                                                 break;
1937                                         }
1938                                 }
1939                         }
1940
1941                         if (known_unit || known_vspace) {
1942                                 // Literal length or known variable
1943                                 context.check_layout(os);
1944                                 begin_inset(os, "VSpace ");
1945                                 if (known_unit)
1946                                         os << value;
1947                                 os << unit;
1948                                 if (starred)
1949                                         os << '*';
1950                                 end_inset(os);
1951                         } else {
1952                                 // LyX can't handle other length variables in Inset VSpace
1953                                 string name = t.asInput();
1954                                 if (starred)
1955                                         name += '*';
1956                                 if (valid) {
1957                                         if (value == 1.0)
1958                                                 handle_ert(os, name + '{' + unit + '}', context);
1959                                         else if (value == -1.0)
1960                                                 handle_ert(os, name + "{-" + unit + '}', context);
1961                                         else
1962                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
1963                                 } else
1964                                         handle_ert(os, name + '{' + length + '}', context);
1965                         }
1966                 }
1967
1968                 else {
1969                         //cerr << "#: " << t << " mode: " << mode << endl;
1970                         // heuristic: read up to next non-nested space
1971                         /*
1972                         string s = t.asInput();
1973                         string z = p.verbatim_item();
1974                         while (p.good() && z != " " && z.size()) {
1975                                 //cerr << "read: " << z << endl;
1976                                 s += z;
1977                                 z = p.verbatim_item();
1978                         }
1979                         cerr << "found ERT: " << s << endl;
1980                         handle_ert(os, s + ' ', context);
1981                         */
1982                         string name = t.asInput();
1983                         if (p.next_token().asInput() == "*") {
1984                                 // Starred commands like \vspace*{}
1985                                 p.get_token();                          // Eat '*'
1986                                 name += '*';
1987                         }
1988                         if (! parse_command(name, p, os, outer, context))
1989                                 handle_ert(os, name, context);
1990                 }
1991
1992                 if (flags & FLAG_LEAVE) {
1993                         flags &= ~FLAG_LEAVE;
1994                         break;
1995                 }
1996         }
1997 }
1998
1999
2000 // }])