]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
tex2lyx/text.cpp: tex2lyx supports now fileformat 252
[lyx.git] / src / tex2lyx / text.cpp
1 /**
2  * \file tex2lyx/text.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Jean-Marc Lasgouttes
8  * \author Uwe Stöhr
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 // {[(
14
15 #include <config.h>
16
17 #include "tex2lyx.h"
18
19 #include "Context.h"
20 #include "Encoding.h"
21 #include "FloatList.h"
22 #include "Layout.h"
23 #include "Length.h"
24
25 #include "support/lassert.h"
26 #include "support/convert.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
30
31 #include <algorithm>
32 #include <iostream>
33 #include <map>
34 #include <sstream>
35 #include <vector>
36
37 using namespace std;
38 using namespace lyx::support;
39
40 namespace lyx {
41
42
43 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
44                 Context const & context)
45 {
46         Context newcontext(true, context.textclass);
47         newcontext.font = context.font;
48         parse_text(p, os, flags, outer, newcontext);
49         newcontext.check_end_layout(os);
50 }
51
52
53 namespace {
54
55 /// parses a paragraph snippet, useful for example for \\emph{...}
56 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
57                 Context & context)
58 {
59         Context newcontext(context);
60         // Don't inherit the paragraph-level extra stuff
61         newcontext.par_extra_stuff.clear();
62         parse_text(p, os, flags, outer, newcontext);
63         // Make sure that we don't create invalid .lyx files
64         context.need_layout = newcontext.need_layout;
65         context.need_end_layout = newcontext.need_end_layout;
66 }
67
68
69 /*!
70  * Thin wrapper around parse_text_snippet() using a string.
71  *
72  * We completely ignore \c context.need_layout and \c context.need_end_layout,
73  * because our return value is not used directly (otherwise the stream version
74  * of parse_text_snippet() could be used). That means that the caller needs
75  * to do layout management manually.
76  * This is intended to parse text that does not create any layout changes.
77  */
78 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
79                   Context & context)
80 {
81         Context newcontext(context);
82         newcontext.need_layout = false;
83         newcontext.need_end_layout = false;
84         newcontext.new_layout_allowed = false;
85         // Avoid warning by Context::~Context()
86         newcontext.par_extra_stuff.clear();
87         ostringstream os;
88         parse_text_snippet(p, os, flags, outer, newcontext);
89         return os.str();
90 }
91
92
93 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
94  "vpageref", "prettyref", "eqref", 0 };
95
96 /*!
97  * natbib commands.
98  * The starred forms are also known.
99  */
100 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
101 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
102 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
103
104 /*!
105  * jurabib commands.
106  * No starred form other than "cite*" known.
107  */
108 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
109 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
110 // jurabib commands not (yet) supported by LyX:
111 // "fullcite",
112 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
113 // "footciteauthor", "footciteyear", "footciteyearpar",
114 "citefield", "citetitle", "cite*", 0 };
115
116 /// LaTeX names for quotes
117 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
118 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
119 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
120 "guilsinglleft", "frq", "guilsinglright", 0};
121
122 /// the same as known_quotes with .lyx names
123 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
124 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
125 "gld", "grd", "gls", "ers", "fls",
126 "fls", "frs", "frs", 0};
127
128 /// LaTeX names for font sizes
129 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
130 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
131
132 /// the same as known_sizes with .lyx names plus a default entry
133 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
134 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
135
136 /// LaTeX 2.09 names for font families
137 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
138
139 /// LaTeX names for font families
140 char const * const known_font_families[] = { "rmfamily", "sffamily",
141 "ttfamily", 0};
142
143 /// the same as known_old_font_families and known_font_families with .lyx names
144 char const * const known_coded_font_families[] = { "roman", "sans",
145 "typewriter", 0};
146
147 /// LaTeX 2.09 names for font series
148 char const * const known_old_font_series[] = { "bf", 0};
149
150 /// LaTeX names for font series
151 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
152
153 /// the same as known_old_font_series and known_font_series with .lyx names
154 char const * const known_coded_font_series[] = { "bold", "medium", 0};
155
156 /// LaTeX 2.09 names for font shapes
157 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
158
159 /// LaTeX names for font shapes
160 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
161 "upshape", 0};
162
163 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
164 char const * const known_coded_font_shapes[] = { "italic", "slanted",
165 "smallcaps", "up", 0};
166
167 /*!
168  * Graphics file extensions known by the dvips driver of the graphics package.
169  * These extensions are used to complete the filename of an included
170  * graphics file if it does not contain an extension.
171  * The order must be the same that latex uses to find a file, because we
172  * will use the first extension that matches.
173  * This is only an approximation for the common cases. If we would want to
174  * do it right in all cases, we would need to know which graphics driver is
175  * used and know the extensions of every driver of the graphics package.
176  */
177 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
178 "ps.gz", "eps.Z", "ps.Z", 0};
179
180 /*!
181  * Graphics file extensions known by the pdftex driver of the graphics package.
182  * \sa known_dvips_graphics_formats
183  */
184 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
185 "mps", "tif", 0};
186
187 /*!
188  * Known file extensions for TeX files as used by \\include.
189  */
190 char const * const known_tex_extensions[] = {"tex", 0};
191
192 /// spaces known by InsetSpace
193 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
194 "qquad", "enspace", "enskip", "negthinspace", 0};
195
196 /// the same as known_spaces with .lyx names
197 char const * const known_coded_spaces[] = { "space{}", "space{}",
198 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
199 "negthinspace{}", 0};
200
201
202 /// splits "x=z, y=b" into a map
203 map<string, string> split_map(string const & s)
204 {
205         map<string, string> res;
206         vector<string> v;
207         split(s, v);
208         for (size_t i = 0; i < v.size(); ++i) {
209                 size_t const pos   = v[i].find('=');
210                 string const index = v[i].substr(0, pos);
211                 string const value = v[i].substr(pos + 1, string::npos);
212                 res[trim(index)] = trim(value);
213         }
214         return res;
215 }
216
217
218 /*!
219  * Split a LaTeX length into value and unit.
220  * The latter can be a real unit like "pt", or a latex length variable
221  * like "\textwidth". The unit may contain additional stuff like glue
222  * lengths, but we don't care, because such lengths are ERT anyway.
223  * \returns true if \p value and \p unit are valid.
224  */
225 bool splitLatexLength(string const & len, string & value, string & unit)
226 {
227         if (len.empty())
228                 return false;
229         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
230         //'4,5' is a valid LaTeX length number. Change it to '4.5'
231         string const length = subst(len, ',', '.');
232         if (i == string::npos)
233                 return false;
234         if (i == 0) {
235                 if (len[0] == '\\') {
236                         // We had something like \textwidth without a factor
237                         value = "1.0";
238                 } else {
239                         return false;
240                 }
241         } else {
242                 value = trim(string(length, 0, i));
243         }
244         if (value == "-")
245                 value = "-1.0";
246         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
247         if (contains(len, '\\'))
248                 unit = trim(string(len, i));
249         else
250                 unit = ascii_lowercase(trim(string(len, i)));
251         return true;
252 }
253
254
255 /// A simple function to translate a latex length to something lyx can
256 /// understand. Not perfect, but rather best-effort.
257 bool translate_len(string const & length, string & valstring, string & unit)
258 {
259         if (!splitLatexLength(length, valstring, unit))
260                 return false;
261         // LyX uses percent values
262         double value;
263         istringstream iss(valstring);
264         iss >> value;
265         value *= 100;
266         ostringstream oss;
267         oss << value;
268         string const percentval = oss.str();
269         // a normal length
270         if (unit.empty() || unit[0] != '\\')
271                 return true;
272         string::size_type const i = unit.find(' ');
273         string const endlen = (i == string::npos) ? string() : string(unit, i);
274         if (unit == "\\textwidth") {
275                 valstring = percentval;
276                 unit = "text%" + endlen;
277         } else if (unit == "\\columnwidth") {
278                 valstring = percentval;
279                 unit = "col%" + endlen;
280         } else if (unit == "\\paperwidth") {
281                 valstring = percentval;
282                 unit = "page%" + endlen;
283         } else if (unit == "\\linewidth") {
284                 valstring = percentval;
285                 unit = "line%" + endlen;
286         } else if (unit == "\\paperheight") {
287                 valstring = percentval;
288                 unit = "pheight%" + endlen;
289         } else if (unit == "\\textheight") {
290                 valstring = percentval;
291                 unit = "theight%" + endlen;
292         }
293         return true;
294 }
295
296 }
297
298
299 string translate_len(string const & length)
300 {
301         string unit;
302         string value;
303         if (translate_len(length, value, unit))
304                 return value + unit;
305         // If the input is invalid, return what we have.
306         return length;
307 }
308
309
310 namespace {
311
312 /*!
313  * Translates a LaTeX length into \p value, \p unit and
314  * \p special parts suitable for a box inset.
315  * The difference from translate_len() is that a box inset knows about
316  * some special "units" that are stored in \p special.
317  */
318 void translate_box_len(string const & length, string & value, string & unit, string & special)
319 {
320         if (translate_len(length, value, unit)) {
321                 if (unit == "\\height" || unit == "\\depth" ||
322                     unit == "\\totalheight" || unit == "\\width") {
323                         special = unit.substr(1);
324                         // The unit is not used, but LyX requires a dummy setting
325                         unit = "in";
326                 } else
327                         special = "none";
328         } else {
329                 value.clear();
330                 unit = length;
331                 special = "none";
332         }
333 }
334
335
336 /*!
337  * Find a file with basename \p name in path \p path and an extension
338  * in \p extensions.
339  */
340 string find_file(string const & name, string const & path,
341                  char const * const * extensions)
342 {
343         for (char const * const * what = extensions; *what; ++what) {
344                 string const trial = addExtension(name, *what);
345                 if (makeAbsPath(trial, path).exists())
346                         return trial;
347         }
348         return string();
349 }
350
351
352 void begin_inset(ostream & os, string const & name)
353 {
354         os << "\n\\begin_inset " << name;
355 }
356
357 void begin_Cinset(ostream & os, string const & name)
358 {
359         os << "\n\\begin_inset CommandInset " << name;
360 }
361
362
363 void end_inset(ostream & os)
364 {
365         os << "\n\\end_inset\n\n";
366 }
367
368 void LatexCommand(ostream & os, string const & name)
369 {
370         os << "\nLatexCommand " << name << "\n";
371 }
372
373
374 void skip_braces(Parser & p)
375 {
376         if (p.next_token().cat() != catBegin)
377                 return;
378         p.get_token();
379         if (p.next_token().cat() == catEnd) {
380                 p.get_token();
381                 return;
382         }
383         p.putback();
384 }
385
386
387 void handle_ert(ostream & os, string const & s, Context & context)
388 {
389         // We must have a valid layout before outputting the ERT inset.
390         context.check_layout(os);
391         Context newcontext(true, context.textclass);
392         begin_inset(os, "ERT");
393         os << "\nstatus collapsed\n";
394         newcontext.check_layout(os);
395         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
396                 if (*it == '\\')
397                         os << "\n\\backslash\n";
398                 else if (*it == '\n') {
399                         newcontext.new_paragraph(os);
400                         newcontext.check_layout(os);
401                 } else
402                         os << *it;
403         }
404         newcontext.check_end_layout(os);
405         end_inset(os);
406 }
407
408
409 void handle_comment(ostream & os, string const & s, Context & context)
410 {
411         // TODO: Handle this better
412         Context newcontext(true, context.textclass);
413         begin_inset(os, "ERT");
414         os << "\nstatus collapsed\n";
415         newcontext.check_layout(os);
416         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
417                 if (*it == '\\')
418                         os << "\n\\backslash\n";
419                 else
420                         os << *it;
421         }
422         // make sure that our comment is the last thing on the line
423         newcontext.new_paragraph(os);
424         newcontext.check_layout(os);
425         newcontext.check_end_layout(os);
426         end_inset(os);
427 }
428
429
430 Layout const * findLayout(TextClass const & textclass, string const & name)
431 {
432         DocumentClass::const_iterator lit = textclass.begin();
433         DocumentClass::const_iterator len = textclass.end();
434         for (; lit != len; ++lit)
435                 if (lit->latexname() == name)
436                         return &*lit;
437         return 0;
438 }
439
440
441 void eat_whitespace(Parser &, ostream &, Context &, bool);
442
443
444 Layout * captionlayout()
445 {
446         static Layout * lay = 0;
447         if (!lay) {
448                 lay = new Layout;
449                 lay->setName(from_ascii("Caption"));
450                 lay->setLatexName("caption");
451                 lay->latextype = LATEX_COMMAND;
452                 lay->optionalargs = 1;
453         }
454         return lay;
455 }
456
457
458 void output_command_layout(ostream & os, Parser & p, bool outer,
459                            Context & parent_context,
460                            Layout const * newlayout)
461 {
462         parent_context.check_end_layout(os);
463         Context context(true, parent_context.textclass, newlayout,
464                         parent_context.layout, parent_context.font);
465         if (parent_context.deeper_paragraph) {
466                 // We are beginning a nested environment after a
467                 // deeper paragraph inside the outer list environment.
468                 // Therefore we don't need to output a "begin deeper".
469                 context.need_end_deeper = true;
470         }
471         context.check_deeper(os);
472         context.check_layout(os);
473         if (context.layout->optionalargs > 0) {
474                 eat_whitespace(p, os, context, false);
475                 if (p.next_token().character() == '[') {
476                         p.get_token(); // eat '['
477                         begin_inset(os, "OptArg\n");
478                         os << "status collapsed\n\n";
479                         parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
480                         end_inset(os);
481                         eat_whitespace(p, os, context, false);
482                 }
483         }
484         parse_text(p, os, FLAG_ITEM, outer, context);
485         context.check_end_layout(os);
486         if (parent_context.deeper_paragraph) {
487                 // We must suppress the "end deeper" because we
488                 // suppressed the "begin deeper" above.
489                 context.need_end_deeper = false;
490         }
491         context.check_end_deeper(os);
492         // We don't need really a new paragraph, but
493         // we must make sure that the next item gets a \begin_layout.
494         parent_context.new_paragraph(os);
495 }
496
497
498 /*!
499  * Output a space if necessary.
500  * This function gets called for every whitespace token.
501  *
502  * We have three cases here:
503  * 1. A space must be suppressed. Example: The lyxcode case below
504  * 2. A space may be suppressed. Example: Spaces before "\par"
505  * 3. A space must not be suppressed. Example: A space between two words
506  *
507  * We currently handle only 1. and 3 and from 2. only the case of
508  * spaces before newlines as a side effect.
509  *
510  * 2. could be used to suppress as many spaces as possible. This has two effects:
511  * - Reimporting LyX generated LaTeX files changes almost no whitespace
512  * - Superflous whitespace from non LyX generated LaTeX files is removed.
513  * The drawback is that the logic inside the function becomes
514  * complicated, and that is the reason why it is not implemented.
515  */
516 void check_space(Parser & p, ostream & os, Context & context)
517 {
518         Token const next = p.next_token();
519         Token const curr = p.curr_token();
520         // A space before a single newline and vice versa must be ignored
521         // LyX emits a newline before \end{lyxcode}.
522         // This newline must be ignored,
523         // otherwise LyX will add an additional protected space.
524         if (next.cat() == catSpace ||
525             next.cat() == catNewline ||
526             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
527                 return;
528         }
529         context.check_layout(os);
530         os << ' ';
531 }
532
533
534 /*!
535  * Parse all arguments of \p command
536  */
537 void parse_arguments(string const & command,
538                      vector<ArgumentType> const & template_arguments,
539                      Parser & p, ostream & os, bool outer, Context & context)
540 {
541         string ert = command;
542         size_t no_arguments = template_arguments.size();
543         for (size_t i = 0; i < no_arguments; ++i) {
544                 switch (template_arguments[i]) {
545                 case required:
546                         // This argument contains regular LaTeX
547                         handle_ert(os, ert + '{', context);
548                         eat_whitespace(p, os, context, false);
549                         parse_text(p, os, FLAG_ITEM, outer, context);
550                         ert = "}";
551                         break;
552                 case verbatim:
553                         // This argument may contain special characters
554                         ert += '{' + p.verbatim_item() + '}';
555                         break;
556                 case optional:
557                         ert += p.getOpt();
558                         break;
559                 }
560         }
561         handle_ert(os, ert, context);
562 }
563
564
565 /*!
566  * Check whether \p command is a known command. If yes,
567  * handle the command with all arguments.
568  * \return true if the command was parsed, false otherwise.
569  */
570 bool parse_command(string const & command, Parser & p, ostream & os,
571                    bool outer, Context & context)
572 {
573         if (known_commands.find(command) != known_commands.end()) {
574                 parse_arguments(command, known_commands[command], p, os,
575                                 outer, context);
576                 return true;
577         }
578         return false;
579 }
580
581
582 /// Parses a minipage or parbox
583 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
584                Context & parent_context, bool use_parbox)
585 {
586         string position;
587         string inner_pos;
588         // We need to set the height to the LaTeX default of 1\\totalheight
589         // for the case when no height argument is given
590         string height_value = "1";
591         string height_unit = "in";
592         string height_special = "totalheight";
593         string latex_height;
594         if (p.next_token().asInput() == "[") {
595                 position = p.getArg('[', ']');
596                 if (position != "t" && position != "c" && position != "b") {
597                         position = "c";
598                         cerr << "invalid position for minipage/parbox" << endl;
599                 }
600                 if (p.next_token().asInput() == "[") {
601                         latex_height = p.getArg('[', ']');
602                         translate_box_len(latex_height, height_value, height_unit, height_special);
603
604                         if (p.next_token().asInput() == "[") {
605                                 inner_pos = p.getArg('[', ']');
606                                 if (inner_pos != "c" && inner_pos != "t" &&
607                                     inner_pos != "b" && inner_pos != "s") {
608                                         inner_pos = position;
609                                         cerr << "invalid inner_pos for minipage/parbox"
610                                              << endl;
611                                 }
612                         }
613                 }
614         }
615         string width_value;
616         string width_unit;
617         string const latex_width = p.verbatim_item();
618         translate_len(latex_width, width_value, width_unit);
619         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
620                 // LyX can't handle length variables
621                 ostringstream ss;
622                 if (use_parbox)
623                         ss << "\\parbox";
624                 else
625                         ss << "\\begin{minipage}";
626                 if (!position.empty())
627                         ss << '[' << position << ']';
628                 if (!latex_height.empty())
629                         ss << '[' << latex_height << ']';
630                 if (!inner_pos.empty())
631                         ss << '[' << inner_pos << ']';
632                 ss << "{" << latex_width << "}";
633                 if (use_parbox)
634                         ss << '{';
635                 handle_ert(os, ss.str(), parent_context);
636                 parent_context.new_paragraph(os);
637                 parse_text_in_inset(p, os, flags, outer, parent_context);
638                 if (use_parbox)
639                         handle_ert(os, "}", parent_context);
640                 else
641                         handle_ert(os, "\\end{minipage}", parent_context);
642         } else {
643                 // LyX does not like empty positions, so we have
644                 // to set them to the LaTeX default values here.
645                 if (position.empty())
646                         position = "c";
647                 if (inner_pos.empty())
648                         inner_pos = position;
649                 parent_context.check_layout(os);
650                 begin_inset(os, "Box Frameless\n");
651                 os << "position \"" << position << "\"\n";
652                 os << "hor_pos \"c\"\n";
653                 os << "has_inner_box 1\n";
654                 os << "inner_pos \"" << inner_pos << "\"\n";
655                 os << "use_parbox " << use_parbox << "\n";
656                 os << "width \"" << width_value << width_unit << "\"\n";
657                 os << "special \"none\"\n";
658                 os << "height \"" << height_value << height_unit << "\"\n";
659                 os << "height_special \"" << height_special << "\"\n";
660                 os << "status open\n\n";
661                 parse_text_in_inset(p, os, flags, outer, parent_context);
662                 end_inset(os);
663 #ifdef PRESERVE_LAYOUT
664                 // lyx puts a % after the end of the minipage
665                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
666                         // new paragraph
667                         //handle_comment(os, "%dummy", parent_context);
668                         p.get_token();
669                         p.skip_spaces();
670                         parent_context.new_paragraph(os);
671                 }
672                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
673                         //handle_comment(os, "%dummy", parent_context);
674                         p.get_token();
675                         p.skip_spaces();
676                         // We add a protected space if something real follows
677                         if (p.good() && p.next_token().cat() != catComment) {
678                                 os << "\\InsetSpace ~\n";
679                         }
680                 }
681 #endif
682         }
683 }
684
685
686 /// parse an unknown environment
687 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
688                                unsigned flags, bool outer,
689                                Context & parent_context)
690 {
691         if (name == "tabbing")
692                 // We need to remember that we have to handle '\=' specially
693                 flags |= FLAG_TABBING;
694
695         // We need to translate font changes and paragraphs inside the
696         // environment to ERT if we have a non standard font.
697         // Otherwise things like
698         // \large\begin{foo}\huge bar\end{foo}
699         // will not work.
700         bool const specialfont =
701                 (parent_context.font != parent_context.normalfont);
702         bool const new_layout_allowed = parent_context.new_layout_allowed;
703         if (specialfont)
704                 parent_context.new_layout_allowed = false;
705         handle_ert(os, "\\begin{" + name + "}", parent_context);
706         parse_text_snippet(p, os, flags, outer, parent_context);
707         handle_ert(os, "\\end{" + name + "}", parent_context);
708         if (specialfont)
709                 parent_context.new_layout_allowed = new_layout_allowed;
710 }
711
712
713 void parse_environment(Parser & p, ostream & os, bool outer,
714                        Context & parent_context)
715 {
716         Layout const * newlayout;
717         string const name = p.getArg('{', '}');
718         const bool is_starred = suffixIs(name, '*');
719         string const unstarred_name = rtrim(name, "*");
720         active_environments.push_back(name);
721
722         if (is_math_env(name)) {
723                 parent_context.check_layout(os);
724                 begin_inset(os, "Formula ");
725                 os << "\\begin{" << name << "}";
726                 parse_math(p, os, FLAG_END, MATH_MODE);
727                 os << "\\end{" << name << "}";
728                 end_inset(os);
729         }
730
731         else if (name == "tabular" || name == "longtable") {
732                 eat_whitespace(p, os, parent_context, false);
733                 parent_context.check_layout(os);
734                 begin_inset(os, "Tabular ");
735                 handle_tabular(p, os, name == "longtable", parent_context);
736                 end_inset(os);
737                 p.skip_spaces();
738         }
739
740         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
741                 eat_whitespace(p, os, parent_context, false);
742                 parent_context.check_layout(os);
743                 begin_inset(os, "Float " + unstarred_name + "\n");
744                 if (p.next_token().asInput() == "[") {
745                         os << "placement " << p.getArg('[', ']') << '\n';
746                 }
747                 os << "wide " << convert<string>(is_starred)
748                    << "\nsideways false"
749                    << "\nstatus open\n\n";
750                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
751                 end_inset(os);
752                 // We don't need really a new paragraph, but
753                 // we must make sure that the next item gets a \begin_layout.
754                 parent_context.new_paragraph(os);
755                 p.skip_spaces();
756         }
757
758         else if (name == "minipage") {
759                 eat_whitespace(p, os, parent_context, false);
760                 parse_box(p, os, FLAG_END, outer, parent_context, false);
761                 p.skip_spaces();
762         }
763
764         else if (name == "comment") {
765                 eat_whitespace(p, os, parent_context, false);
766                 parent_context.check_layout(os);
767                 begin_inset(os, "Note Comment\n");
768                 os << "status open\n";
769                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
770                 end_inset(os);
771                 p.skip_spaces();
772                 skip_braces(p); // eat {} that might by set by LyX behind comments
773         }
774
775         else if (name == "lyxgreyedout") {
776                 eat_whitespace(p, os, parent_context, false);
777                 parent_context.check_layout(os);
778                 begin_inset(os, "Note Greyedout\n");
779                 os << "status open\n";
780                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
781                 end_inset(os);
782                 p.skip_spaces();
783         }
784
785         else if (name == "framed") {
786                 eat_whitespace(p, os, parent_context, false);
787                 parent_context.check_layout(os);
788                 begin_inset(os, "Note Framed\n");
789                 os << "status open\n";
790                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
791                 end_inset(os);
792                 p.skip_spaces();
793         }
794
795         else if (name == "shaded") {
796                 eat_whitespace(p, os, parent_context, false);
797                 parent_context.check_layout(os);
798                 begin_inset(os, "Note Shaded\n");
799                 os << "status open\n";
800                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
801                 end_inset(os);
802                 p.skip_spaces();
803         }
804
805         else if (!parent_context.new_layout_allowed)
806                 parse_unknown_environment(p, name, os, FLAG_END, outer,
807                                           parent_context);
808
809         // Alignment and spacing settings
810         // FIXME (bug xxxx): These settings can span multiple paragraphs and
811         //                                       therefore are totally broken!
812         // Note that \centering, raggedright, and raggedleft cannot be handled, as
813         // they are commands not environments. They are furthermore switches that
814         // can be ended by another switches, but also by commands like \footnote or
815         // \parbox. So the only safe way is to leave them untouched.
816         else if (name == "center" || name == "centering" ||
817                  name == "flushleft" || name == "flushright" ||
818                  name == "singlespace" || name == "onehalfspace" ||
819                  name == "doublespace" || name == "spacing") {
820                 eat_whitespace(p, os, parent_context, false);
821                 // We must begin a new paragraph if not already done
822                 if (! parent_context.atParagraphStart()) {
823                         parent_context.check_end_layout(os);
824                         parent_context.new_paragraph(os);
825                 }
826                 if (name == "flushleft")
827                         parent_context.add_extra_stuff("\\align left\n");
828                 else if (name == "flushright")
829                         parent_context.add_extra_stuff("\\align right\n");
830                 else if (name == "center" || name == "centering")
831                         parent_context.add_extra_stuff("\\align center\n");
832                 else if (name == "singlespace")
833                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
834                 else if (name == "onehalfspace")
835                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
836                 else if (name == "doublespace")
837                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
838                 else if (name == "spacing")
839                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
840                 parse_text(p, os, FLAG_END, outer, parent_context);
841                 // Just in case the environment is empty
842                 parent_context.extra_stuff.erase();
843                 // We must begin a new paragraph to reset the alignment
844                 parent_context.new_paragraph(os);
845                 p.skip_spaces();
846         }
847
848         // The single '=' is meant here.
849         else if ((newlayout = findLayout(parent_context.textclass, name)) &&
850                   newlayout->isEnvironment()) {
851                 eat_whitespace(p, os, parent_context, false);
852                 Context context(true, parent_context.textclass, newlayout,
853                                 parent_context.layout, parent_context.font);
854                 if (parent_context.deeper_paragraph) {
855                         // We are beginning a nested environment after a
856                         // deeper paragraph inside the outer list environment.
857                         // Therefore we don't need to output a "begin deeper".
858                         context.need_end_deeper = true;
859                 }
860                 parent_context.check_end_layout(os);
861                 switch (context.layout->latextype) {
862                 case  LATEX_LIST_ENVIRONMENT:
863                         context.add_par_extra_stuff("\\labelwidthstring "
864                                                     + p.verbatim_item() + '\n');
865                         p.skip_spaces();
866                         break;
867                 case  LATEX_BIB_ENVIRONMENT:
868                         p.verbatim_item(); // swallow next arg
869                         p.skip_spaces();
870                         break;
871                 default:
872                         break;
873                 }
874                 context.check_deeper(os);
875                 parse_text(p, os, FLAG_END, outer, context);
876                 context.check_end_layout(os);
877                 if (parent_context.deeper_paragraph) {
878                         // We must suppress the "end deeper" because we
879                         // suppressed the "begin deeper" above.
880                         context.need_end_deeper = false;
881                 }
882                 context.check_end_deeper(os);
883                 parent_context.new_paragraph(os);
884                 p.skip_spaces();
885         }
886
887         else if (name == "appendix") {
888                 // This is no good latex style, but it works and is used in some documents...
889                 eat_whitespace(p, os, parent_context, false);
890                 parent_context.check_end_layout(os);
891                 Context context(true, parent_context.textclass, parent_context.layout,
892                                 parent_context.layout, parent_context.font);
893                 context.check_layout(os);
894                 os << "\\start_of_appendix\n";
895                 parse_text(p, os, FLAG_END, outer, context);
896                 context.check_end_layout(os);
897                 p.skip_spaces();
898         }
899
900         else if (known_environments.find(name) != known_environments.end()) {
901                 vector<ArgumentType> arguments = known_environments[name];
902                 // The last "argument" denotes wether we may translate the
903                 // environment contents to LyX
904                 // The default required if no argument is given makes us
905                 // compatible with the reLyXre environment.
906                 ArgumentType contents = arguments.empty() ?
907                         required :
908                         arguments.back();
909                 if (!arguments.empty())
910                         arguments.pop_back();
911                 // See comment in parse_unknown_environment()
912                 bool const specialfont =
913                         (parent_context.font != parent_context.normalfont);
914                 bool const new_layout_allowed =
915                         parent_context.new_layout_allowed;
916                 if (specialfont)
917                         parent_context.new_layout_allowed = false;
918                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
919                                 outer, parent_context);
920                 if (contents == verbatim)
921                         handle_ert(os, p.verbatimEnvironment(name),
922                                    parent_context);
923                 else
924                         parse_text_snippet(p, os, FLAG_END, outer,
925                                            parent_context);
926                 handle_ert(os, "\\end{" + name + "}", parent_context);
927                 if (specialfont)
928                         parent_context.new_layout_allowed = new_layout_allowed;
929         }
930
931         else
932                 parse_unknown_environment(p, name, os, FLAG_END, outer,
933                                           parent_context);
934
935         active_environments.pop_back();
936 }
937
938
939 /// parses a comment and outputs it to \p os.
940 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
941 {
942         LASSERT(t.cat() == catComment, return);
943         if (!t.cs().empty()) {
944                 context.check_layout(os);
945                 handle_comment(os, '%' + t.cs(), context);
946                 if (p.next_token().cat() == catNewline) {
947                         // A newline after a comment line starts a new
948                         // paragraph
949                         if (context.new_layout_allowed) {
950                                 if(!context.atParagraphStart())
951                                         // Only start a new paragraph if not already
952                                         // done (we might get called recursively)
953                                         context.new_paragraph(os);
954                         } else
955                                 handle_ert(os, "\n", context);
956                         eat_whitespace(p, os, context, true);
957                 }
958         } else {
959                 // "%\n" combination
960                 p.skip_spaces();
961         }
962 }
963
964
965 /*!
966  * Reads spaces and comments until the first non-space, non-comment token.
967  * New paragraphs (double newlines or \\par) are handled like simple spaces
968  * if \p eatParagraph is true.
969  * Spaces are skipped, but comments are written to \p os.
970  */
971 void eat_whitespace(Parser & p, ostream & os, Context & context,
972                     bool eatParagraph)
973 {
974         while (p.good()) {
975                 Token const & t = p.get_token();
976                 if (t.cat() == catComment)
977                         parse_comment(p, os, t, context);
978                 else if ((! eatParagraph && p.isParagraph()) ||
979                          (t.cat() != catSpace && t.cat() != catNewline)) {
980                         p.putback();
981                         return;
982                 }
983         }
984 }
985
986
987 /*!
988  * Set a font attribute, parse text and reset the font attribute.
989  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
990  * \param currentvalue Current value of the attribute. Is set to the new
991  * value during parsing.
992  * \param newvalue New value of the attribute
993  */
994 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
995                            Context & context, string const & attribute,
996                            string & currentvalue, string const & newvalue)
997 {
998         context.check_layout(os);
999         string const oldvalue = currentvalue;
1000         currentvalue = newvalue;
1001         os << '\n' << attribute << ' ' << newvalue << "\n";
1002         parse_text_snippet(p, os, flags, outer, context);
1003         context.check_layout(os);
1004         os << '\n' << attribute << ' ' << oldvalue << "\n";
1005         currentvalue = oldvalue;
1006 }
1007
1008
1009 /// get the arguments of a natbib or jurabib citation command
1010 void get_cite_arguments(Parser & p, bool natbibOrder,
1011         string & before, string & after)
1012 {
1013         // We need to distinguish "" and "[]", so we can't use p.getOpt().
1014
1015         // text before the citation
1016         before.clear();
1017         // text after the citation
1018         after = p.getFullOpt();
1019
1020         if (!after.empty()) {
1021                 before = p.getFullOpt();
1022                 if (natbibOrder && !before.empty())
1023                         swap(before, after);
1024         }
1025 }
1026
1027
1028 /// Convert filenames with TeX macros and/or quotes to something LyX
1029 /// can understand
1030 string const normalize_filename(string const & name)
1031 {
1032         Parser p(trim(name, "\""));
1033         ostringstream os;
1034         while (p.good()) {
1035                 Token const & t = p.get_token();
1036                 if (t.cat() != catEscape)
1037                         os << t.asInput();
1038                 else if (t.cs() == "lyxdot") {
1039                         // This is used by LyX for simple dots in relative
1040                         // names
1041                         os << '.';
1042                         p.skip_spaces();
1043                 } else if (t.cs() == "space") {
1044                         os << ' ';
1045                         p.skip_spaces();
1046                 } else
1047                         os << t.asInput();
1048         }
1049         return os.str();
1050 }
1051
1052
1053 /// Convert \p name from TeX convention (relative to master file) to LyX
1054 /// convention (relative to .lyx file) if it is relative
1055 void fix_relative_filename(string & name)
1056 {
1057         if (FileName::isAbsolute(name))
1058                 return;
1059
1060         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1061                                    from_utf8(getParentFilePath())));
1062 }
1063
1064
1065 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1066 void parse_noweb(Parser & p, ostream & os, Context & context)
1067 {
1068         // assemble the rest of the keyword
1069         string name("<<");
1070         bool scrap = false;
1071         while (p.good()) {
1072                 Token const & t = p.get_token();
1073                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1074                         name += ">>";
1075                         p.get_token();
1076                         scrap = (p.good() && p.next_token().asInput() == "=");
1077                         if (scrap)
1078                                 name += p.get_token().asInput();
1079                         break;
1080                 }
1081                 name += t.asInput();
1082         }
1083
1084         if (!scrap || !context.new_layout_allowed ||
1085             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1086                 cerr << "Warning: Could not interpret '" << name
1087                      << "'. Ignoring it." << endl;
1088                 return;
1089         }
1090
1091         // We use new_paragraph instead of check_end_layout because the stuff
1092         // following the noweb chunk needs to start with a \begin_layout.
1093         // This may create a new paragraph even if there was none in the
1094         // noweb file, but the alternative is an invalid LyX file. Since
1095         // noweb code chunks are implemented with a layout style in LyX they
1096         // always must be in an own paragraph.
1097         context.new_paragraph(os);
1098         Context newcontext(true, context.textclass,
1099                 &context.textclass[from_ascii("Scrap")]);
1100         newcontext.check_layout(os);
1101         os << name;
1102         while (p.good()) {
1103                 Token const & t = p.get_token();
1104                 // We abuse the parser a bit, because this is no TeX syntax
1105                 // at all.
1106                 if (t.cat() == catEscape)
1107                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1108                 else
1109                         os << subst(t.asInput(), "\n", "\n\\newline\n");
1110                 // The scrap chunk is ended by an @ at the beginning of a line.
1111                 // After the @ the line may contain a comment and/or
1112                 // whitespace, but nothing else.
1113                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1114                     (p.next_token().cat() == catSpace ||
1115                      p.next_token().cat() == catNewline ||
1116                      p.next_token().cat() == catComment)) {
1117                         while (p.good() && p.next_token().cat() == catSpace)
1118                                 os << p.get_token().asInput();
1119                         if (p.next_token().cat() == catComment)
1120                                 // The comment includes a final '\n'
1121                                 os << p.get_token().asInput();
1122                         else {
1123                                 if (p.next_token().cat() == catNewline)
1124                                         p.get_token();
1125                                 os << '\n';
1126                         }
1127                         break;
1128                 }
1129         }
1130         newcontext.check_end_layout(os);
1131 }
1132
1133 } // anonymous namespace
1134
1135
1136 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1137                 Context & context)
1138 {
1139         Layout const * newlayout = 0;
1140         // store the current selectlanguage to be used after \foreignlanguage
1141         string selectlang;
1142         // Store the latest bibliographystyle (needed for bibtex inset)
1143         string bibliographystyle;
1144         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1145         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1146         while (p.good()) {
1147                 Token const & t = p.get_token();
1148
1149 #ifdef FILEDEBUG
1150                 cerr << "t: " << t << " flags: " << flags << "\n";
1151 #endif
1152
1153                 if (flags & FLAG_ITEM) {
1154                         if (t.cat() == catSpace)
1155                                 continue;
1156
1157                         flags &= ~FLAG_ITEM;
1158                         if (t.cat() == catBegin) {
1159                                 // skip the brace and collect everything to the next matching
1160                                 // closing brace
1161                                 flags |= FLAG_BRACE_LAST;
1162                                 continue;
1163                         }
1164
1165                         // handle only this single token, leave the loop if done
1166                         flags |= FLAG_LEAVE;
1167                 }
1168
1169                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1170                         return;
1171
1172                 //
1173                 // cat codes
1174                 //
1175                 if (t.cat() == catMath) {
1176                         // we are inside some text mode thingy, so opening new math is allowed
1177                         context.check_layout(os);
1178                         begin_inset(os, "Formula ");
1179                         Token const & n = p.get_token();
1180                         if (n.cat() == catMath && outer) {
1181                                 // TeX's $$...$$ syntax for displayed math
1182                                 os << "\\[";
1183                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1184                                 os << "\\]";
1185                                 p.get_token(); // skip the second '$' token
1186                         } else {
1187                                 // simple $...$  stuff
1188                                 p.putback();
1189                                 os << '$';
1190                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1191                                 os << '$';
1192                         }
1193                         end_inset(os);
1194                 }
1195
1196                 else if (t.cat() == catSuper || t.cat() == catSub)
1197                         cerr << "catcode " << t << " illegal in text mode\n";
1198
1199                 // Basic support for english quotes. This should be
1200                 // extended to other quotes, but is not so easy (a
1201                 // left english quote is the same as a right german
1202                 // quote...)
1203                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1204                         context.check_layout(os);
1205                         begin_inset(os, "Quotes ");
1206                         os << "eld";
1207                         end_inset(os);
1208                         p.get_token();
1209                         skip_braces(p);
1210                 }
1211                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1212                         context.check_layout(os);
1213                         begin_inset(os, "Quotes ");
1214                         os << "erd";
1215                         end_inset(os);
1216                         p.get_token();
1217                         skip_braces(p);
1218                 }
1219
1220                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1221                         context.check_layout(os);
1222                         begin_inset(os, "Quotes ");
1223                         os << "ald";
1224                         end_inset(os);
1225                         p.get_token();
1226                         skip_braces(p);
1227                 }
1228
1229                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1230                         context.check_layout(os);
1231                         begin_inset(os, "Quotes ");
1232                         os << "ard";
1233                         end_inset(os);
1234                         p.get_token();
1235                         skip_braces(p);
1236                 }
1237
1238                 else if (t.asInput() == "<"
1239                          && p.next_token().asInput() == "<" && noweb_mode) {
1240                         p.get_token();
1241                         parse_noweb(p, os, context);
1242                 }
1243
1244                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1245                         check_space(p, os, context);
1246
1247                 else if (t.character() == '[' && noweb_mode &&
1248                          p.next_token().character() == '[') {
1249                         // These can contain underscores
1250                         p.putback();
1251                         string const s = p.getFullOpt() + ']';
1252                         if (p.next_token().character() == ']')
1253                                 p.get_token();
1254                         else
1255                                 cerr << "Warning: Inserting missing ']' in '"
1256                                      << s << "'." << endl;
1257                         handle_ert(os, s, context);
1258                 }
1259
1260                 else if (t.cat() == catLetter ||
1261                                t.cat() == catOther ||
1262                                t.cat() == catAlign ||
1263                                t.cat() == catParameter) {
1264                         // This translates "&" to "\\&" which may be wrong...
1265                         context.check_layout(os);
1266                         os << t.cs();
1267                 }
1268
1269                 else if (p.isParagraph()) {
1270                         if (context.new_layout_allowed)
1271                                 context.new_paragraph(os);
1272                         else
1273                                 handle_ert(os, "\\par ", context);
1274                         eat_whitespace(p, os, context, true);
1275                 }
1276
1277                 else if (t.cat() == catActive) {
1278                         context.check_layout(os);
1279                         if (t.character() == '~') {
1280                                 if (context.layout->free_spacing)
1281                                         os << ' ';
1282                                 else
1283                                         os << "\\InsetSpace ~\n";
1284                         } else
1285                                 os << t.cs();
1286                 }
1287
1288                 else if (t.cat() == catBegin &&
1289                          p.next_token().cat() == catEnd) {
1290                         // {}
1291                         Token const prev = p.prev_token();
1292                         p.get_token();
1293                         if (p.next_token().character() == '`' ||
1294                             (prev.character() == '-' &&
1295                              p.next_token().character() == '-'))
1296                                 ; // ignore it in {}`` or -{}-
1297                         else
1298                                 handle_ert(os, "{}", context);
1299
1300                 }
1301
1302                 else if (t.cat() == catBegin) {
1303                         context.check_layout(os);
1304                         // special handling of font attribute changes
1305                         Token const prev = p.prev_token();
1306                         Token const next = p.next_token();
1307                         TeXFont const oldFont = context.font;
1308                         if (next.character() == '[' ||
1309                             next.character() == ']' ||
1310                             next.character() == '*') {
1311                                 p.get_token();
1312                                 if (p.next_token().cat() == catEnd) {
1313                                         os << next.cs();
1314                                         p.get_token();
1315                                 } else {
1316                                         p.putback();
1317                                         handle_ert(os, "{", context);
1318                                         parse_text_snippet(p, os,
1319                                                         FLAG_BRACE_LAST,
1320                                                         outer, context);
1321                                         handle_ert(os, "}", context);
1322                                 }
1323                         } else if (! context.new_layout_allowed) {
1324                                 handle_ert(os, "{", context);
1325                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1326                                                    outer, context);
1327                                 handle_ert(os, "}", context);
1328                         } else if (is_known(next.cs(), known_sizes)) {
1329                                 // next will change the size, so we must
1330                                 // reset it here
1331                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1332                                                    outer, context);
1333                                 if (!context.atParagraphStart())
1334                                         os << "\n\\size "
1335                                            << context.font.size << "\n";
1336                         } else if (is_known(next.cs(), known_font_families)) {
1337                                 // next will change the font family, so we
1338                                 // must reset it here
1339                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1340                                                    outer, context);
1341                                 if (!context.atParagraphStart())
1342                                         os << "\n\\family "
1343                                            << context.font.family << "\n";
1344                         } else if (is_known(next.cs(), known_font_series)) {
1345                                 // next will change the font series, so we
1346                                 // must reset it here
1347                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1348                                                    outer, context);
1349                                 if (!context.atParagraphStart())
1350                                         os << "\n\\series "
1351                                            << context.font.series << "\n";
1352                         } else if (is_known(next.cs(), known_font_shapes)) {
1353                                 // next will change the font shape, so we
1354                                 // must reset it here
1355                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1356                                                    outer, context);
1357                                 if (!context.atParagraphStart())
1358                                         os << "\n\\shape "
1359                                            << context.font.shape << "\n";
1360                         } else if (is_known(next.cs(), known_old_font_families) ||
1361                                    is_known(next.cs(), known_old_font_series) ||
1362                                    is_known(next.cs(), known_old_font_shapes)) {
1363                                 // next will change the font family, series
1364                                 // and shape, so we must reset it here
1365                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1366                                                    outer, context);
1367                                 if (!context.atParagraphStart())
1368                                         os <<  "\n\\family "
1369                                            << context.font.family
1370                                            << "\n\\series "
1371                                            << context.font.series
1372                                            << "\n\\shape "
1373                                            << context.font.shape << "\n";
1374                         } else {
1375                                 handle_ert(os, "{", context);
1376                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1377                                                    outer, context);
1378                                 handle_ert(os, "}", context);
1379                         }
1380                 }
1381
1382                 else if (t.cat() == catEnd) {
1383                         if (flags & FLAG_BRACE_LAST) {
1384                                 return;
1385                         }
1386                         cerr << "stray '}' in text\n";
1387                         handle_ert(os, "}", context);
1388                 }
1389
1390                 else if (t.cat() == catComment)
1391                         parse_comment(p, os, t, context);
1392
1393                 //
1394                 // control sequences
1395                 //
1396
1397                 else if (t.cs() == "(") {
1398                         context.check_layout(os);
1399                         begin_inset(os, "Formula");
1400                         os << " \\(";
1401                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1402                         os << "\\)";
1403                         end_inset(os);
1404                 }
1405
1406                 else if (t.cs() == "[") {
1407                         context.check_layout(os);
1408                         begin_inset(os, "Formula");
1409                         os << " \\[";
1410                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1411                         os << "\\]";
1412                         end_inset(os);
1413                 }
1414
1415                 else if (t.cs() == "begin")
1416                         parse_environment(p, os, outer, context);
1417
1418                 else if (t.cs() == "end") {
1419                         if (flags & FLAG_END) {
1420                                 // eat environment name
1421                                 string const name = p.getArg('{', '}');
1422                                 if (name != active_environment())
1423                                         cerr << "\\end{" + name + "} does not match \\begin{"
1424                                                 + active_environment() + "}\n";
1425                                 return;
1426                         }
1427                         p.error("found 'end' unexpectedly");
1428                 }
1429
1430                 else if (t.cs() == "item") {
1431                         p.skip_spaces();
1432                         string s;
1433                         bool optarg = false;
1434                         if (p.next_token().character() == '[') {
1435                                 p.get_token(); // eat '['
1436                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1437                                                        outer, context);
1438                                 optarg = true;
1439                         }
1440                         context.set_item();
1441                         context.check_layout(os);
1442                         if (context.has_item) {
1443                                 // An item in an unknown list-like environment
1444                                 // FIXME: Do this in check_layout()!
1445                                 context.has_item = false;
1446                                 if (optarg)
1447                                         handle_ert(os, "\\item", context);
1448                                 else
1449                                         handle_ert(os, "\\item ", context);
1450                         }
1451                         if (optarg) {
1452                                 if (context.layout->labeltype != LABEL_MANUAL) {
1453                                         // lyx does not support \item[\mybullet]
1454                                         // in itemize environments
1455                                         handle_ert(os, "[", context);
1456                                         os << s;
1457                                         handle_ert(os, "]", context);
1458                                 } else if (!s.empty()) {
1459                                         // The space is needed to separate the
1460                                         // item from the rest of the sentence.
1461                                         os << s << ' ';
1462                                         eat_whitespace(p, os, context, false);
1463                                 }
1464                         }
1465                 }
1466
1467                 else if (t.cs() == "bibitem") {
1468                         context.set_item();
1469                         context.check_layout(os);
1470                         begin_Cinset(os, "bibitem");
1471                         LatexCommand(os, "bibitem");
1472                         os << p.getOpt();
1473                         os << "key " << '"' << p.verbatim_item() << '"' << "\n";
1474                         end_inset(os);
1475                 }
1476
1477                 else if (t.cs() == "def") {
1478                         context.check_layout(os);
1479                         eat_whitespace(p, os, context, false);
1480                         string name = p.get_token().cs();
1481                         eat_whitespace(p, os, context, false);
1482
1483                         // parameter text
1484                         bool simple = true;
1485                         string paramtext;
1486                         int arity = 0;
1487                         while (p.next_token().cat() != catBegin) {
1488                                 if (p.next_token().cat() == catParameter) {
1489                                         // # found
1490                                         p.get_token();
1491                                         paramtext += "#";
1492
1493                                         // followed by number?
1494                                         if (p.next_token().cat() == catOther) {
1495                                                 char c = p.getChar();
1496                                                 paramtext += c;
1497                                                 // number = current arity + 1?
1498                                                 if (c == arity + '0' + 1)
1499                                                         ++arity;
1500                                                 else
1501                                                         simple = false;
1502                                         } else
1503                                                 paramtext += p.get_token().asString();
1504                                 } else {
1505                                         paramtext += p.get_token().asString();
1506                                         simple = false;
1507                                 }
1508                         }
1509
1510                         // only output simple (i.e. compatible) macro as FormulaMacros
1511                         string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1512                         if (simple) {
1513                                 context.check_layout(os);
1514                                 begin_inset(os, "FormulaMacro");
1515                                 os << "\n" << ert;
1516                                 end_inset(os);
1517                         } else
1518                                 handle_ert(os, ert, context);
1519                 }
1520
1521                 else if (t.cs() == "noindent") {
1522                         p.skip_spaces();
1523                         context.add_par_extra_stuff("\\noindent\n");
1524                 }
1525
1526                 else if (t.cs() == "appendix") {
1527                         context.add_par_extra_stuff("\\start_of_appendix\n");
1528                         // We need to start a new paragraph. Otherwise the
1529                         // appendix in 'bla\appendix\chapter{' would start
1530                         // too late.
1531                         context.new_paragraph(os);
1532                         // We need to make sure that the paragraph is
1533                         // generated even if it is empty. Otherwise the
1534                         // appendix in '\par\appendix\par\chapter{' would
1535                         // start too late.
1536                         context.check_layout(os);
1537                         // FIXME: This is a hack to prevent paragraph
1538                         // deletion if it is empty. Handle this better!
1539                         handle_comment(os,
1540                                 "%dummy comment inserted by tex2lyx to "
1541                                 "ensure that this paragraph is not empty",
1542                                 context);
1543                         // Both measures above may generate an additional
1544                         // empty paragraph, but that does not hurt, because
1545                         // whitespace does not matter here.
1546                         eat_whitespace(p, os, context, true);
1547                 }
1548
1549                 // Starred section headings
1550                 // Must attempt to parse "Section*" before "Section".
1551                 else if ((p.next_token().asInput() == "*") &&
1552                          context.new_layout_allowed &&
1553                          (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1554                          newlayout->isCommand()) {
1555                         TeXFont const oldFont = context.font;
1556                         // save the current font size
1557                         string const size = oldFont.size;
1558                         // reset the font size to default, because the
1559                         // font size switches don't affect section
1560                         // headings and the like
1561                         context.font.size = known_coded_sizes[0];
1562                         output_font_change(os, oldFont, context.font);
1563                         // write the layout
1564                         p.get_token();
1565                         output_command_layout(os, p, outer, context, newlayout);
1566                         // set the font size to the original value
1567                         context.font.size = size;
1568                         output_font_change(os, oldFont, context.font);
1569                         p.skip_spaces();
1570                 }
1571
1572                 // Section headings and the like
1573                 else if (context.new_layout_allowed &&
1574                          (newlayout = findLayout(context.textclass, t.cs())) &&
1575                          newlayout->isCommand()) {
1576                         TeXFont const oldFont = context.font;
1577                         // save the current font size
1578                         string const size = oldFont.size;
1579                         // reset the font size to default, because the font size switches don't
1580                         // affect section headings and the like
1581                         context.font.size = known_coded_sizes[0];
1582                         output_font_change(os, oldFont, context.font);
1583                         // write the layout
1584                         output_command_layout(os, p, outer, context, newlayout);
1585                         // set the font size to the original value
1586                         context.font.size = size;
1587                         output_font_change(os, oldFont, context.font);
1588                         p.skip_spaces();
1589                 }
1590
1591                 // Special handling for \caption
1592                 // FIXME: remove this when InsetCaption is supported.
1593                 else if (context.new_layout_allowed &&
1594                          t.cs() == captionlayout()->latexname()) {
1595                         output_command_layout(os, p, outer, context, 
1596                                               captionlayout());
1597                         p.skip_spaces();
1598                 }
1599
1600                 else if (t.cs() == "includegraphics") {
1601                         bool const clip = p.next_token().asInput() == "*";
1602                         if (clip)
1603                                 p.get_token();
1604                         map<string, string> opts = split_map(p.getArg('[', ']'));
1605                         if (clip)
1606                                 opts["clip"] = string();
1607                         string name = normalize_filename(p.verbatim_item());
1608
1609                         string const path = getMasterFilePath();
1610                         // We want to preserve relative / absolute filenames,
1611                         // therefore path is only used for testing
1612                         if (!makeAbsPath(name, path).exists()) {
1613                                 // The file extension is probably missing.
1614                                 // Now try to find it out.
1615                                 string const dvips_name =
1616                                         find_file(name, path,
1617                                                   known_dvips_graphics_formats);
1618                                 string const pdftex_name =
1619                                         find_file(name, path,
1620                                                   known_pdftex_graphics_formats);
1621                                 if (!dvips_name.empty()) {
1622                                         if (!pdftex_name.empty()) {
1623                                                 cerr << "This file contains the "
1624                                                         "latex snippet\n"
1625                                                         "\"\\includegraphics{"
1626                                                      << name << "}\".\n"
1627                                                         "However, files\n\""
1628                                                      << dvips_name << "\" and\n\""
1629                                                      << pdftex_name << "\"\n"
1630                                                         "both exist, so I had to make a "
1631                                                         "choice and took the first one.\n"
1632                                                         "Please move the unwanted one "
1633                                                         "someplace else and try again\n"
1634                                                         "if my choice was wrong."
1635                                                      << endl;
1636                                         }
1637                                         name = dvips_name;
1638                                 } else if (!pdftex_name.empty())
1639                                         name = pdftex_name;
1640                         }
1641
1642                         if (makeAbsPath(name, path).exists())
1643                                 fix_relative_filename(name);
1644                         else
1645                                 cerr << "Warning: Could not find graphics file '"
1646                                      << name << "'." << endl;
1647
1648                         context.check_layout(os);
1649                         begin_inset(os, "Graphics ");
1650                         os << "\n\tfilename " << name << '\n';
1651                         if (opts.find("width") != opts.end())
1652                                 os << "\twidth "
1653                                    << translate_len(opts["width"]) << '\n';
1654                         if (opts.find("height") != opts.end())
1655                                 os << "\theight "
1656                                    << translate_len(opts["height"]) << '\n';
1657                         if (opts.find("scale") != opts.end()) {
1658                                 istringstream iss(opts["scale"]);
1659                                 double val;
1660                                 iss >> val;
1661                                 val = val*100;
1662                                 os << "\tscale " << val << '\n';
1663                         }
1664                         if (opts.find("angle") != opts.end())
1665                                 os << "\trotateAngle "
1666                                    << opts["angle"] << '\n';
1667                         if (opts.find("origin") != opts.end()) {
1668                                 ostringstream ss;
1669                                 string const opt = opts["origin"];
1670                                 if (opt.find('l') != string::npos) ss << "left";
1671                                 if (opt.find('r') != string::npos) ss << "right";
1672                                 if (opt.find('c') != string::npos) ss << "center";
1673                                 if (opt.find('t') != string::npos) ss << "Top";
1674                                 if (opt.find('b') != string::npos) ss << "Bottom";
1675                                 if (opt.find('B') != string::npos) ss << "Baseline";
1676                                 if (!ss.str().empty())
1677                                         os << "\trotateOrigin " << ss.str() << '\n';
1678                                 else
1679                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1680                         }
1681                         if (opts.find("keepaspectratio") != opts.end())
1682                                 os << "\tkeepAspectRatio\n";
1683                         if (opts.find("clip") != opts.end())
1684                                 os << "\tclip\n";
1685                         if (opts.find("draft") != opts.end())
1686                                 os << "\tdraft\n";
1687                         if (opts.find("bb") != opts.end())
1688                                 os << "\tBoundingBox "
1689                                    << opts["bb"] << '\n';
1690                         int numberOfbbOptions = 0;
1691                         if (opts.find("bbllx") != opts.end())
1692                                 numberOfbbOptions++;
1693                         if (opts.find("bblly") != opts.end())
1694                                 numberOfbbOptions++;
1695                         if (opts.find("bburx") != opts.end())
1696                                 numberOfbbOptions++;
1697                         if (opts.find("bbury") != opts.end())
1698                                 numberOfbbOptions++;
1699                         if (numberOfbbOptions == 4)
1700                                 os << "\tBoundingBox "
1701                                    << opts["bbllx"] << " " << opts["bblly"] << " "
1702                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
1703                         else if (numberOfbbOptions > 0)
1704                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1705                         numberOfbbOptions = 0;
1706                         if (opts.find("natwidth") != opts.end())
1707                                 numberOfbbOptions++;
1708                         if (opts.find("natheight") != opts.end())
1709                                 numberOfbbOptions++;
1710                         if (numberOfbbOptions == 2)
1711                                 os << "\tBoundingBox 0bp 0bp "
1712                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
1713                         else if (numberOfbbOptions > 0)
1714                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1715                         ostringstream special;
1716                         if (opts.find("hiresbb") != opts.end())
1717                                 special << "hiresbb,";
1718                         if (opts.find("trim") != opts.end())
1719                                 special << "trim,";
1720                         if (opts.find("viewport") != opts.end())
1721                                 special << "viewport=" << opts["viewport"] << ',';
1722                         if (opts.find("totalheight") != opts.end())
1723                                 special << "totalheight=" << opts["totalheight"] << ',';
1724                         if (opts.find("type") != opts.end())
1725                                 special << "type=" << opts["type"] << ',';
1726                         if (opts.find("ext") != opts.end())
1727                                 special << "ext=" << opts["ext"] << ',';
1728                         if (opts.find("read") != opts.end())
1729                                 special << "read=" << opts["read"] << ',';
1730                         if (opts.find("command") != opts.end())
1731                                 special << "command=" << opts["command"] << ',';
1732                         string s_special = special.str();
1733                         if (!s_special.empty()) {
1734                                 // We had special arguments. Remove the trailing ','.
1735                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1736                         }
1737                         // TODO: Handle the unknown settings better.
1738                         // Warn about invalid options.
1739                         // Check whether some option was given twice.
1740                         end_inset(os);
1741                 }
1742
1743                 else if (t.cs() == "footnote" ||
1744                          (t.cs() == "thanks" && context.layout->intitle)) {
1745                         p.skip_spaces();
1746                         context.check_layout(os);
1747                         begin_inset(os, "Foot\n");
1748                         os << "status collapsed\n\n";
1749                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1750                         end_inset(os);
1751                 }
1752
1753                 else if (t.cs() == "marginpar") {
1754                         p.skip_spaces();
1755                         context.check_layout(os);
1756                         begin_inset(os, "Marginal\n");
1757                         os << "status collapsed\n\n";
1758                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1759                         end_inset(os);
1760                 }
1761
1762                 else if (t.cs() == "ensuremath") {
1763                         p.skip_spaces();
1764                         context.check_layout(os);
1765                         string const s = p.verbatim_item();
1766                         //FIXME: this never triggers in UTF8
1767                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1768                                 os << s;
1769                         else
1770                                 handle_ert(os, "\\ensuremath{" + s + "}",
1771                                            context);
1772                 }
1773
1774                 else if (t.cs() == "hfill") {
1775                         context.check_layout(os);
1776                         os << "\n\\hfill\n";
1777                         skip_braces(p);
1778                         p.skip_spaces();
1779                 }
1780
1781                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1782                         // FIXME: Somehow prevent title layouts if
1783                         // "maketitle" was not found
1784                         p.skip_spaces();
1785                         skip_braces(p); // swallow this
1786                 }
1787
1788                 else if (t.cs() == "tableofcontents") {
1789                         p.skip_spaces();
1790                         context.check_layout(os);
1791                         begin_Cinset(os, "toc");
1792                         LatexCommand(os, "tableofcontents");
1793                         end_inset(os);
1794                         skip_braces(p); // swallow this
1795                 }
1796
1797                 else if (t.cs() == "listoffigures") {
1798                         p.skip_spaces();
1799                         context.check_layout(os);
1800                         begin_inset(os, "FloatList figure\n");
1801                         end_inset(os);
1802                         skip_braces(p); // swallow this
1803                 }
1804
1805                 else if (t.cs() == "listoftables") {
1806                         p.skip_spaces();
1807                         context.check_layout(os);
1808                         begin_inset(os, "FloatList table\n");
1809                         end_inset(os);
1810                         skip_braces(p); // swallow this
1811                 }
1812
1813                 else if (t.cs() == "listof") {
1814                         p.skip_spaces(true);
1815                         string const name = p.get_token().asString();
1816                         if (context.textclass.floats().typeExist(name)) {
1817                                 context.check_layout(os);
1818                                 begin_inset(os, "FloatList ");
1819                                 os << name << "\n";
1820                                 end_inset(os);
1821                                 p.get_token(); // swallow second arg
1822                         } else
1823                                 handle_ert(os, "\\listof{" + name + "}", context);
1824                 }
1825
1826                 else if (t.cs() == "textrm")
1827                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1828                                               context, "\\family",
1829                                               context.font.family, "roman");
1830
1831                 else if (t.cs() == "textsf")
1832                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1833                                               context, "\\family",
1834                                               context.font.family, "sans");
1835
1836                 else if (t.cs() == "texttt")
1837                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1838                                               context, "\\family",
1839                                               context.font.family, "typewriter");
1840
1841                 else if (t.cs() == "textmd")
1842                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1843                                               context, "\\series",
1844                                               context.font.series, "medium");
1845
1846                 else if (t.cs() == "textbf")
1847                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1848                                               context, "\\series",
1849                                               context.font.series, "bold");
1850
1851                 else if (t.cs() == "textup")
1852                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1853                                               context, "\\shape",
1854                                               context.font.shape, "up");
1855
1856                 else if (t.cs() == "textit")
1857                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1858                                               context, "\\shape",
1859                                               context.font.shape, "italic");
1860
1861                 else if (t.cs() == "textsl")
1862                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1863                                               context, "\\shape",
1864                                               context.font.shape, "slanted");
1865
1866                 else if (t.cs() == "textsc")
1867                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1868                                               context, "\\shape",
1869                                               context.font.shape, "smallcaps");
1870
1871                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1872                         context.check_layout(os);
1873                         TeXFont oldFont = context.font;
1874                         context.font.init();
1875                         context.font.size = oldFont.size;
1876                         os << "\n\\family " << context.font.family << "\n";
1877                         os << "\n\\series " << context.font.series << "\n";
1878                         os << "\n\\shape " << context.font.shape << "\n";
1879                         if (t.cs() == "textnormal") {
1880                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1881                                 output_font_change(os, context.font, oldFont);
1882                                 context.font = oldFont;
1883                         } else
1884                                 eat_whitespace(p, os, context, false);
1885                 }
1886
1887                 else if (t.cs() == "textcolor") {
1888                         // scheme is \textcolor{color name}{text}
1889                         string const color = p.verbatim_item();
1890                         // we only support the predefined colors of the color package
1891                         if (color == "black" || color == "blue" || color == "cyan"
1892                                 || color == "green" || color == "magenta" || color == "red"
1893                                 || color == "white" || color == "yellow") {
1894                                         context.check_layout(os);
1895                                         os << "\n\\color " << color << "\n";
1896                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1897                                         context.check_layout(os);
1898                                         os << "\n\\color inherit\n";
1899                         } else
1900                                 // for custom defined colors
1901                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
1902                 }
1903
1904                 else if (t.cs() == "underbar") {
1905                         // Do NOT handle \underline.
1906                         // \underbar cuts through y, g, q, p etc.,
1907                         // \underline does not.
1908                         context.check_layout(os);
1909                         os << "\n\\bar under\n";
1910                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1911                         context.check_layout(os);
1912                         os << "\n\\bar default\n";
1913                 }
1914
1915                 else if (t.cs() == "emph" || t.cs() == "noun") {
1916                         context.check_layout(os);
1917                         os << "\n\\" << t.cs() << " on\n";
1918                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1919                         context.check_layout(os);
1920                         os << "\n\\" << t.cs() << " default\n";
1921                 }
1922
1923                 else if (t.cs() == "lyxline") {
1924                         context.check_layout(os);
1925                         os << "\\lyxline";
1926                 }
1927
1928                 else if (is_known(t.cs(), known_ref_commands)) {
1929                         context.check_layout(os);
1930                         begin_Cinset(os, "ref");
1931                         LatexCommand(os, t.cs());
1932                         // lyx cannot handle newlines in a latex command
1933                         // FIXME: Move the substitution into parser::getOpt()?
1934                         os << subst(p.getOpt(), "\n", " ");
1935                         os << "reference " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
1936                         end_inset(os);
1937                 }
1938
1939                 else if (use_natbib &&
1940                          is_known(t.cs(), known_natbib_commands) &&
1941                          ((t.cs() != "citefullauthor" &&
1942                            t.cs() != "citeyear" &&
1943                            t.cs() != "citeyearpar") ||
1944                           p.next_token().asInput() != "*")) {
1945                         context.check_layout(os);
1946                         string command = t.cs();
1947                         if (p.next_token().asInput() == "*") {
1948                                 command += '*';
1949                                 p.get_token();
1950                         }
1951                         if (command == "citefullauthor")
1952                                 // alternative name for "\\citeauthor*"
1953                                 command = "citeauthor*";
1954
1955                         // text before the citation
1956                         string before;
1957                         // text after the citation
1958                         string after;
1959                         get_cite_arguments(p, true, before, after);
1960
1961                         if (command == "cite") {
1962                                 // \cite without optional argument means
1963                                 // \citet, \cite with at least one optional
1964                                 // argument means \citep.
1965                                 if (before.empty() && after.empty())
1966                                         command = "citet";
1967                                 else
1968                                         command = "citep";
1969                         }
1970                         if (before.empty() && after == "[]")
1971                                 // avoid \citet[]{a}
1972                                 after.erase();
1973                         else if (before == "[]" && after == "[]") {
1974                                 // avoid \citet[][]{a}
1975                                 before.erase();
1976                                 after.erase();
1977                         }
1978                         // remove the brackets around after and before
1979                         if (!after.empty()) {
1980                                 after.erase(0, 1);
1981                                 after.erase(after.length() - 1, 1);
1982                         }
1983                         if (!before.empty()) {
1984                                 before.erase(0, 1);
1985                                 before.erase(before.length() - 1, 1);
1986                         }
1987                         begin_Cinset(os, "citation");
1988                         LatexCommand(os, command);
1989                         os << "after " << '"' << after << '"' << "\n";
1990                         os << "before " << '"' << before << '"' << "\n";
1991                         os << "key " << '"' << p.verbatim_item() << '"' << "\n";
1992                         end_inset(os);
1993                 }
1994
1995                 else if (use_jurabib &&
1996                          is_known(t.cs(), known_jurabib_commands)) {
1997                         context.check_layout(os);
1998                         string const command = t.cs();
1999                         char argumentOrder = '\0';
2000                         vector<string> const & options = used_packages["jurabib"];
2001                         if (find(options.begin(), options.end(),
2002                                       "natbiborder") != options.end())
2003                                 argumentOrder = 'n';
2004                         else if (find(options.begin(), options.end(),
2005                                            "jurabiborder") != options.end())
2006                                 argumentOrder = 'j';
2007
2008                         // text before the citation
2009                         string before;
2010                         // text after the citation
2011                         string after;
2012                         get_cite_arguments(p, argumentOrder != 'j', before, after);
2013
2014                         string const citation = p.verbatim_item();
2015                         if (!before.empty() && argumentOrder == '\0') {
2016                                 cerr << "Warning: Assuming argument order "
2017                                         "of jurabib version 0.6 for\n'"
2018                                      << command << before << after << '{'
2019                                      << citation << "}'.\n"
2020                                         "Add 'jurabiborder' to the jurabib "
2021                                         "package options if you used an\n"
2022                                         "earlier jurabib version." << endl;
2023                         }
2024                         if (!after.empty()) {
2025                                 after.erase(0, 1);
2026                                 after.erase(after.length() - 1, 1);
2027                         }
2028                         if (!before.empty()) {
2029                                 before.erase(0, 1);
2030                                 before.erase(before.length() - 1, 1);
2031                         }
2032                         begin_Cinset(os, "citation");
2033                         LatexCommand(os, command);
2034                         os << "after " << '"' << after << '"' << "\n";
2035                         os << "before " << '"' << before << '"' << "\n";
2036                         os << "key " << '"' << citation << '"' << "\n";
2037                         end_inset(os);
2038                 }
2039
2040                 else if (t.cs() == "cite") {
2041                         context.check_layout(os);
2042                         // lyx cannot handle newlines in a latex command
2043                         string after = subst(p.getOpt(), "\n", " ");
2044                         if (!after.empty()) {
2045                                 after.erase(0, 1);
2046                                 after.erase(after.length() - 1, 1);
2047                         }
2048                         begin_Cinset(os, "citation");
2049                         LatexCommand(os, t.cs());
2050                         os << "after " << '"' << after << '"' << "\n";
2051                         os << "key " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2052                         end_inset(os);
2053                 }
2054
2055                 else if (t.cs() == "index") {
2056                         context.check_layout(os);
2057                         begin_inset(os, "LatexCommand ");
2058                         os << t.cs() << "\n";;
2059                         // lyx cannot handle newlines in a latex command
2060                         os << "name " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2061                         end_inset(os);
2062                 }
2063                 
2064                 else if (t.cs() == "label") {
2065                         context.check_layout(os);
2066                         begin_Cinset(os, t.cs());
2067                         LatexCommand(os, t.cs());
2068                         // lyx cannot handle newlines in a latex command
2069                         os << "name " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2070                         end_inset(os);
2071                 }
2072
2073                 else if (t.cs() == "printindex") {
2074                         context.check_layout(os);
2075                         begin_Cinset(os, "index_print");
2076                         LatexCommand(os, t.cs());
2077                         end_inset(os);
2078                         skip_braces(p);
2079                 }
2080
2081                 else if (t.cs() == "url") {
2082                         context.check_layout(os);
2083                         begin_inset(os, "LatexCommand ");
2084                         os << t.cs() << "\n";;
2085                         // lyx cannot handle newlines in a latex command
2086                         os << "target " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2087                         end_inset(os);
2088                 }
2089
2090                 else if (is_known(t.cs(), known_quotes)) {
2091                         char const * const * where = is_known(t.cs(), known_quotes);
2092                         context.check_layout(os);
2093                         begin_inset(os, "Quotes ");
2094                         os << known_coded_quotes[where - known_quotes];
2095                         end_inset(os);
2096                         // LyX adds {} after the quote, so we have to eat
2097                         // spaces here if there are any before a possible
2098                         // {} pair.
2099                         eat_whitespace(p, os, context, false);
2100                         skip_braces(p);
2101                 }
2102
2103                 else if (is_known(t.cs(), known_sizes) &&
2104                          context.new_layout_allowed) {
2105                         char const * const * where = is_known(t.cs(), known_sizes);
2106                         context.check_layout(os);
2107                         TeXFont const oldFont = context.font;
2108                         // the font size index differs by 1, because the known_coded_sizes
2109                         // has additionally a "default" entry
2110                         context.font.size = known_coded_sizes[where - known_sizes + 1];
2111                         output_font_change(os, oldFont, context.font);
2112                         eat_whitespace(p, os, context, false);
2113                 }
2114
2115                 else if (is_known(t.cs(), known_font_families) &&
2116                          context.new_layout_allowed) {
2117                         char const * const * where =
2118                                 is_known(t.cs(), known_font_families);
2119                         context.check_layout(os);
2120                         TeXFont const oldFont = context.font;
2121                         context.font.family =
2122                                 known_coded_font_families[where - known_font_families];
2123                         output_font_change(os, oldFont, context.font);
2124                         eat_whitespace(p, os, context, false);
2125                 }
2126
2127                 else if (is_known(t.cs(), known_font_series) &&
2128                          context.new_layout_allowed) {
2129                         char const * const * where =
2130                                 is_known(t.cs(), known_font_series);
2131                         context.check_layout(os);
2132                         TeXFont const oldFont = context.font;
2133                         context.font.series =
2134                                 known_coded_font_series[where - known_font_series];
2135                         output_font_change(os, oldFont, context.font);
2136                         eat_whitespace(p, os, context, false);
2137                 }
2138
2139                 else if (is_known(t.cs(), known_font_shapes) &&
2140                          context.new_layout_allowed) {
2141                         char const * const * where =
2142                                 is_known(t.cs(), known_font_shapes);
2143                         context.check_layout(os);
2144                         TeXFont const oldFont = context.font;
2145                         context.font.shape =
2146                                 known_coded_font_shapes[where - known_font_shapes];
2147                         output_font_change(os, oldFont, context.font);
2148                         eat_whitespace(p, os, context, false);
2149                 }
2150                 else if (is_known(t.cs(), known_old_font_families) &&
2151                          context.new_layout_allowed) {
2152                         char const * const * where =
2153                                 is_known(t.cs(), known_old_font_families);
2154                         context.check_layout(os);
2155                         TeXFont const oldFont = context.font;
2156                         context.font.init();
2157                         context.font.size = oldFont.size;
2158                         context.font.family =
2159                                 known_coded_font_families[where - known_old_font_families];
2160                         output_font_change(os, oldFont, context.font);
2161                         eat_whitespace(p, os, context, false);
2162                 }
2163
2164                 else if (is_known(t.cs(), known_old_font_series) &&
2165                          context.new_layout_allowed) {
2166                         char const * const * where =
2167                                 is_known(t.cs(), known_old_font_series);
2168                         context.check_layout(os);
2169                         TeXFont const oldFont = context.font;
2170                         context.font.init();
2171                         context.font.size = oldFont.size;
2172                         context.font.series =
2173                                 known_coded_font_series[where - known_old_font_series];
2174                         output_font_change(os, oldFont, context.font);
2175                         eat_whitespace(p, os, context, false);
2176                 }
2177
2178                 else if (is_known(t.cs(), known_old_font_shapes) &&
2179                          context.new_layout_allowed) {
2180                         char const * const * where =
2181                                 is_known(t.cs(), known_old_font_shapes);
2182                         context.check_layout(os);
2183                         TeXFont const oldFont = context.font;
2184                         context.font.init();
2185                         context.font.size = oldFont.size;
2186                         context.font.shape =
2187                                 known_coded_font_shapes[where - known_old_font_shapes];
2188                         output_font_change(os, oldFont, context.font);
2189                         eat_whitespace(p, os, context, false);
2190                 }
2191
2192                 else if (t.cs() == "selectlanguage") {
2193                         context.check_layout(os);
2194                         // save the language for the case that a
2195                         // \foreignlanguage is used 
2196
2197                         //FIXME: this is wrong, the language should
2198                         // be saved in the context. (JMarc)
2199                         selectlang = subst(p.verbatim_item(), "\n", " ");
2200                         os << "\\lang " << selectlang << "\n";
2201                 }
2202
2203                 else if (t.cs() == "foreignlanguage") {
2204                         context.check_layout(os);
2205                         os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2206                         os << subst(p.verbatim_item(), "\n", " ");
2207                         // FIXME: the second argument of selectlanguage
2208                         // has to be parsed (like for \textsf, for
2209                         // example). 
2210                         // set back to last selectlanguage
2211                         os << "\n\\lang " << selectlang << "\n";
2212                 }
2213
2214                 else if (t.cs() == "inputencoding") {
2215                         // nothing to write here
2216                         string const enc = subst(p.verbatim_item(), "\n", " ");
2217                         p.setEncoding(enc);
2218                 }
2219                 else if (t.cs() == "LyX" || t.cs() == "TeX"
2220                          || t.cs() == "LaTeX") {
2221                         context.check_layout(os);
2222                         os << t.cs();
2223                         skip_braces(p); // eat {}
2224                 }
2225
2226                 else if (t.cs() == "LaTeXe") {
2227                         context.check_layout(os);
2228                         os << "LaTeX2e";
2229                         skip_braces(p); // eat {}
2230                 }
2231
2232                 else if (t.cs() == "ldots") {
2233                         context.check_layout(os);
2234                         skip_braces(p);
2235                         os << "\\SpecialChar \\ldots{}\n";
2236                 }
2237
2238                 else if (t.cs() == "lyxarrow") {
2239                         context.check_layout(os);
2240                         os << "\\SpecialChar \\menuseparator\n";
2241                         skip_braces(p);
2242                 }
2243
2244                 else if (t.cs() == "textcompwordmark") {
2245                         context.check_layout(os);
2246                         os << "\\SpecialChar \\textcompwordmark{}\n";
2247                         skip_braces(p);
2248                 }
2249
2250                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2251                         context.check_layout(os);
2252                         os << "\\SpecialChar \\@.\n";
2253                         p.get_token();
2254                 }
2255
2256                 else if (t.cs() == "-") {
2257                         context.check_layout(os);
2258                         os << "\\SpecialChar \\-\n";
2259                 }
2260
2261                 else if (t.cs() == "textasciitilde") {
2262                         context.check_layout(os);
2263                         os << '~';
2264                         skip_braces(p);
2265                 }
2266
2267                 else if (t.cs() == "textasciicircum") {
2268                         context.check_layout(os);
2269                         os << '^';
2270                         skip_braces(p);
2271                 }
2272
2273                 else if (t.cs() == "textbackslash") {
2274                         context.check_layout(os);
2275                         os << "\n\\backslash\n";
2276                         skip_braces(p);
2277                 }
2278
2279                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2280                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2281                             || t.cs() == "%") {
2282                         context.check_layout(os);
2283                         os << t.cs();
2284                 }
2285
2286                 else if (t.cs() == "char") {
2287                         context.check_layout(os);
2288                         if (p.next_token().character() == '`') {
2289                                 p.get_token();
2290                                 if (p.next_token().cs() == "\"") {
2291                                         p.get_token();
2292                                         os << '"';
2293                                         skip_braces(p);
2294                                 } else {
2295                                         handle_ert(os, "\\char`", context);
2296                                 }
2297                         } else {
2298                                 handle_ert(os, "\\char", context);
2299                         }
2300                 }
2301
2302                 else if (t.cs() == "verb") {
2303                         context.check_layout(os);
2304                         char const delimiter = p.next_token().character();
2305                         string const arg = p.getArg(delimiter, delimiter);
2306                         ostringstream oss;
2307                         oss << "\\verb" << delimiter << arg << delimiter;
2308                         handle_ert(os, oss.str(), context);
2309                 }
2310
2311                 // Problem: \= creates a tabstop inside the tabbing environment
2312                 // and else an accent. In the latter case we really would want
2313                 // \={o} instead of \= o.
2314                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2315                         handle_ert(os, t.asInput(), context);
2316
2317                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2318                 else if (t.cs().size() == 1 
2319                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2320                         context.check_layout(os);
2321                         // try to see whether the string is in unicodesymbols
2322                         docstring rem;
2323                         string command = t.asInput() + "{" 
2324                                 + trim(p.verbatim_item())
2325                                 + "}";
2326                         docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2327                         if (!s.empty()) {
2328                                 if (!rem.empty())
2329                                         cerr << "When parsing " << command 
2330                                              << ", result is " << to_utf8(s)
2331                                              << "+" << to_utf8(rem) << endl;
2332                                 os << to_utf8(s);
2333                         } else
2334                                 // we did not find a non-ert version
2335                                 handle_ert(os, command, context);
2336                 }
2337
2338                 else if (t.cs() == "\\") {
2339                         context.check_layout(os);
2340                         string const next = p.next_token().asInput();
2341                         if (next == "[")
2342                                 handle_ert(os, "\\\\" + p.getOpt(), context);
2343                         else if (next == "*") {
2344                                 p.get_token();
2345                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
2346                         }
2347                         else {
2348                                 os << "\n\\newline\n";
2349                         }
2350                 }
2351
2352                 else if (t.cs() == "newline" ||
2353                         t.cs() == "linebreak") {
2354                         context.check_layout(os);
2355                         os << "\n\\" << t.cs() << "\n";
2356                         skip_braces(p); // eat {}
2357                 }
2358
2359                 else if (t.cs() == "input" || t.cs() == "include"
2360                          || t.cs() == "verbatiminput") {
2361                         string name = '\\' + t.cs();
2362                         if (t.cs() == "verbatiminput"
2363                             && p.next_token().asInput() == "*")
2364                                 name += p.get_token().asInput();
2365                         context.check_layout(os);
2366                         begin_inset(os, "Include ");
2367                         string filename(normalize_filename(p.getArg('{', '}')));
2368                         string const path = getMasterFilePath();
2369                         // We want to preserve relative / absolute filenames,
2370                         // therefore path is only used for testing
2371                         if ((t.cs() == "include" || t.cs() == "input") &&
2372                             !makeAbsPath(filename, path).exists()) {
2373                                 // The file extension is probably missing.
2374                                 // Now try to find it out.
2375                                 string const tex_name =
2376                                         find_file(filename, path,
2377                                                   known_tex_extensions);
2378                                 if (!tex_name.empty())
2379                                         filename = tex_name;
2380                         }
2381                         if (makeAbsPath(filename, path).exists()) {
2382                                 string const abstexname =
2383                                         makeAbsPath(filename, path).absFilename();
2384                                 string const abslyxname =
2385                                         changeExtension(abstexname, ".lyx");
2386                                 fix_relative_filename(filename);
2387                                 string const lyxname =
2388                                         changeExtension(filename, ".lyx");
2389                                 if (t.cs() != "verbatiminput" &&
2390                                     tex2lyx(abstexname, FileName(abslyxname),
2391                                             p.getEncoding())) {
2392                                         os << name << '{' << lyxname << "}\n";
2393                                 } else {
2394                                         os << name << '{' << filename << "}\n";
2395                                 }
2396                         } else {
2397                                 cerr << "Warning: Could not find included file '"
2398                                      << filename << "'." << endl;
2399                                 os << name << '{' << filename << "}\n";
2400                         }
2401                         os << "preview false\n";
2402                         end_inset(os);
2403                 }
2404
2405                 else if (t.cs() == "bibliographystyle") {
2406                         // store new bibliographystyle
2407                         bibliographystyle = p.verbatim_item();
2408                         // output new bibliographystyle.
2409                         // This is only necessary if used in some other macro than \bibliography.
2410                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2411                 }
2412
2413                 else if (t.cs() == "bibliography") {
2414                         context.check_layout(os);
2415                         begin_Cinset(os, "bibtex");
2416                         LatexCommand(os, "bibtex");
2417                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
2418                         // Do we have a bibliographystyle set?
2419                         if (!bibliographystyle.empty())
2420                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
2421                         end_inset(os);
2422                 }
2423
2424                 else if (t.cs() == "parbox")
2425                         parse_box(p, os, FLAG_ITEM, outer, context, true);
2426                 
2427                 //\makebox() is part of the picture environment and different from \makebox{}
2428                 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
2429                 else if (t.cs() == "makebox") {
2430                         string arg = t.asInput();
2431                         if (p.next_token().character() == '(')
2432                                 //the syntax is: \makebox(x,y)[position]{content}
2433                                 arg += p.getFullParentheseArg();
2434                         else
2435                                 //the syntax is: \makebox[width][position]{content}
2436                                 arg += p.getFullOpt();
2437                         handle_ert(os, arg + p.getFullOpt(), context);
2438                 }
2439
2440                 else if (t.cs() == "smallskip" ||
2441                          t.cs() == "medskip" ||
2442                          t.cs() == "bigskip" ||
2443                          t.cs() == "vfill") {
2444                         context.check_layout(os);
2445                         begin_inset(os, "VSpace ");
2446                         os << t.cs();
2447                         end_inset(os);
2448                         skip_braces(p);
2449                 }
2450
2451                 else if (is_known(t.cs(), known_spaces)) {
2452                         char const * const * where = is_known(t.cs(), known_spaces);
2453                         context.check_layout(os);
2454                         os << "\\InsetSpace ";
2455                         os << '\\' << known_coded_spaces[where - known_spaces]
2456                            << '\n';
2457                         // LaTeX swallows whitespace after all spaces except
2458                         // "\\,". We have to do that here, too, because LyX
2459                         // adds "{}" which would make the spaces significant.
2460                         if (t.cs() !=  ",")
2461                                 eat_whitespace(p, os, context, false);
2462                         // LyX adds "{}" after all spaces except "\\ " and
2463                         // "\\,", so we have to remove "{}".
2464                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
2465                         // remove the braces after "\\,", too.
2466                         if (t.cs() != " ")
2467                                 skip_braces(p);
2468                 }
2469
2470                 else if (t.cs() == "newpage" ||
2471                         t.cs() == "pagebreak" ||
2472                         t.cs() == "clearpage" ||
2473                         t.cs() == "cleardoublepage") {
2474                         context.check_layout(os);
2475                         os << "\n\\" << t.cs() << "\n";
2476                         skip_braces(p); // eat {}
2477                 }
2478
2479                 else if (t.cs() == "newcommand" ||
2480                          t.cs() == "providecommand" ||
2481                          t.cs() == "renewcommand") {
2482                         // these could be handled by parse_command(), but
2483                         // we need to call add_known_command() here.
2484                         string name = t.asInput();
2485                         if (p.next_token().asInput() == "*") {
2486                                 // Starred form. Eat '*'
2487                                 p.get_token();
2488                                 name += '*';
2489                         }
2490                         string const command = p.verbatim_item();
2491                         string const opt1 = p.getOpt();
2492                         string const opt2 = p.getFullOpt();
2493                         add_known_command(command, opt1, !opt2.empty());
2494                         string const ert = name + '{' + command + '}' +
2495                                            opt1 + opt2 +
2496                                            '{' + p.verbatim_item() + '}';
2497
2498                         context.check_layout(os);
2499                         begin_inset(os, "FormulaMacro");
2500                         os << "\n" << ert;
2501                         end_inset(os);
2502                 }
2503                 
2504                 else if (t.cs() == "vspace") {
2505                         bool starred = false;
2506                         if (p.next_token().asInput() == "*") {
2507                                 p.get_token();
2508                                 starred = true;
2509                         }
2510                         string const length = p.verbatim_item();
2511                         string unit;
2512                         string valstring;
2513                         bool valid = splitLatexLength(length, valstring, unit);
2514                         bool known_vspace = false;
2515                         bool known_unit = false;
2516                         double value;
2517                         if (valid) {
2518                                 istringstream iss(valstring);
2519                                 iss >> value;
2520                                 if (value == 1.0) {
2521                                         if (unit == "\\smallskipamount") {
2522                                                 unit = "smallskip";
2523                                                 known_vspace = true;
2524                                         } else if (unit == "\\medskipamount") {
2525                                                 unit = "medskip";
2526                                                 known_vspace = true;
2527                                         } else if (unit == "\\bigskipamount") {
2528                                                 unit = "bigskip";
2529                                                 known_vspace = true;
2530                                         } else if (unit == "\\fill") {
2531                                                 unit = "vfill";
2532                                                 known_vspace = true;
2533                                         }
2534                                 }
2535                                 if (!known_vspace) {
2536                                         switch (unitFromString(unit)) {
2537                                         case Length::SP:
2538                                         case Length::PT:
2539                                         case Length::BP:
2540                                         case Length::DD:
2541                                         case Length::MM:
2542                                         case Length::PC:
2543                                         case Length::CC:
2544                                         case Length::CM:
2545                                         case Length::IN:
2546                                         case Length::EX:
2547                                         case Length::EM:
2548                                         case Length::MU:
2549                                                 known_unit = true;
2550                                                 break;
2551                                         default:
2552                                                 break;
2553                                         }
2554                                 }
2555                         }
2556
2557                         if (known_unit || known_vspace) {
2558                                 // Literal length or known variable
2559                                 context.check_layout(os);
2560                                 begin_inset(os, "VSpace ");
2561                                 if (known_unit)
2562                                         os << value;
2563                                 os << unit;
2564                                 if (starred)
2565                                         os << '*';
2566                                 end_inset(os);
2567                         } else {
2568                                 // LyX can't handle other length variables in Inset VSpace
2569                                 string name = t.asInput();
2570                                 if (starred)
2571                                         name += '*';
2572                                 if (valid) {
2573                                         if (value == 1.0)
2574                                                 handle_ert(os, name + '{' + unit + '}', context);
2575                                         else if (value == -1.0)
2576                                                 handle_ert(os, name + "{-" + unit + '}', context);
2577                                         else
2578                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
2579                                 } else
2580                                         handle_ert(os, name + '{' + length + '}', context);
2581                         }
2582                 }
2583
2584                 else {
2585                         // try to see whether the string is in unicodesymbols
2586                         docstring rem;
2587                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()), rem);
2588                         if (!s.empty()) {
2589                                 if (!rem.empty())
2590                                         cerr << "When parsing " << t.cs() 
2591                                              << ", result is " << to_utf8(s)
2592                                              << "+" << to_utf8(rem) << endl;
2593                                 context.check_layout(os);
2594                                 os << to_utf8(s);
2595                                 p.skip_spaces();
2596                                 skip_braces(p); // eat {}
2597                         }
2598                         //cerr << "#: " << t << " mode: " << mode << endl;
2599                         // heuristic: read up to next non-nested space
2600                         /*
2601                         string s = t.asInput();
2602                         string z = p.verbatim_item();
2603                         while (p.good() && z != " " && z.size()) {
2604                                 //cerr << "read: " << z << endl;
2605                                 s += z;
2606                                 z = p.verbatim_item();
2607                         }
2608                         cerr << "found ERT: " << s << endl;
2609                         handle_ert(os, s + ' ', context);
2610                         */
2611                         else {
2612                                 string name = t.asInput();
2613                                 if (p.next_token().asInput() == "*") {
2614                                         // Starred commands like \vspace*{}
2615                                         p.get_token();  // Eat '*'
2616                                         name += '*';
2617                                 }
2618                                 if (!parse_command(name, p, os, outer, context))
2619                                         handle_ert(os, name, context);
2620                         }
2621                 }
2622
2623                 if (flags & FLAG_LEAVE) {
2624                         flags &= ~FLAG_LEAVE;
2625                         break;
2626                 }
2627         }
2628 }
2629
2630 // }])
2631
2632
2633 } // namespace lyx