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