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