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