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