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