]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
tex2lyx/text.cpp: code simplification
[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 == "sidewaysfigure"
1079                 || unstarred_name == "sidewaystable") {
1080                 eat_whitespace(p, os, parent_context, false);
1081                 parent_context.check_layout(os);
1082                 if (unstarred_name == "sidewaysfigure")
1083                         begin_inset(os, "Float figure\n");
1084                 else
1085                         begin_inset(os, "Float table\n");
1086                 os << "wide " << convert<string>(is_starred)
1087                    << "\nsideways true"
1088                    << "\nstatus open\n\n";
1089                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1090                 end_inset(os);
1091                 // We don't need really a new paragraph, but
1092                 // we must make sure that the next item gets a \begin_layout.
1093                 parent_context.new_paragraph(os);
1094                 p.skip_spaces();
1095         }
1096
1097         else if (name == "minipage") {
1098                 eat_whitespace(p, os, parent_context, false);
1099                 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1100                 p.skip_spaces();
1101         }
1102
1103         else if (name == "comment") {
1104                 eat_whitespace(p, os, parent_context, false);
1105                 parent_context.check_layout(os);
1106                 begin_inset(os, "Note Comment\n");
1107                 os << "status open\n";
1108                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1109                 end_inset(os);
1110                 p.skip_spaces();
1111                 skip_braces(p); // eat {} that might by set by LyX behind comments
1112         }
1113
1114         else if (name == "lyxgreyedout") {
1115                 eat_whitespace(p, os, parent_context, false);
1116                 parent_context.check_layout(os);
1117                 begin_inset(os, "Note Greyedout\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         }
1123
1124         else if (name == "framed" || name == "shaded") {
1125                 eat_whitespace(p, os, parent_context, false);
1126                 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1127                 p.skip_spaces();
1128         }
1129
1130         else if (name == "lstlisting") {
1131                 eat_whitespace(p, os, parent_context, false);
1132                 // FIXME handle listings with parameters
1133                 if (p.hasOpt())
1134                         parse_unknown_environment(p, name, os, FLAG_END,
1135                                                   outer, parent_context);
1136                 else
1137                         parse_listings(p, os, parent_context);
1138                 p.skip_spaces();
1139         }
1140
1141         else if (!parent_context.new_layout_allowed)
1142                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1143                                           parent_context);
1144
1145         // Alignment and spacing settings
1146         // FIXME (bug xxxx): These settings can span multiple paragraphs and
1147         //                                       therefore are totally broken!
1148         // Note that \centering, raggedright, and raggedleft cannot be handled, as
1149         // they are commands not environments. They are furthermore switches that
1150         // can be ended by another switches, but also by commands like \footnote or
1151         // \parbox. So the only safe way is to leave them untouched.
1152         else if (name == "center" || name == "centering" ||
1153                  name == "flushleft" || name == "flushright" ||
1154                  name == "singlespace" || name == "onehalfspace" ||
1155                  name == "doublespace" || name == "spacing") {
1156                 eat_whitespace(p, os, parent_context, false);
1157                 // We must begin a new paragraph if not already done
1158                 if (! parent_context.atParagraphStart()) {
1159                         parent_context.check_end_layout(os);
1160                         parent_context.new_paragraph(os);
1161                 }
1162                 if (name == "flushleft")
1163                         parent_context.add_extra_stuff("\\align left\n");
1164                 else if (name == "flushright")
1165                         parent_context.add_extra_stuff("\\align right\n");
1166                 else if (name == "center" || name == "centering")
1167                         parent_context.add_extra_stuff("\\align center\n");
1168                 else if (name == "singlespace")
1169                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1170                 else if (name == "onehalfspace")
1171                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1172                 else if (name == "doublespace")
1173                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1174                 else if (name == "spacing")
1175                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1176                 parse_text(p, os, FLAG_END, outer, parent_context);
1177                 // Just in case the environment is empty
1178                 parent_context.extra_stuff.erase();
1179                 // We must begin a new paragraph to reset the alignment
1180                 parent_context.new_paragraph(os);
1181                 p.skip_spaces();
1182         }
1183
1184         // The single '=' is meant here.
1185         else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1186                 eat_whitespace(p, os, parent_context, false);
1187                 Context context(true, parent_context.textclass, newlayout,
1188                                 parent_context.layout, parent_context.font);
1189                 if (parent_context.deeper_paragraph) {
1190                         // We are beginning a nested environment after a
1191                         // deeper paragraph inside the outer list environment.
1192                         // Therefore we don't need to output a "begin deeper".
1193                         context.need_end_deeper = true;
1194                 }
1195                 parent_context.check_end_layout(os);
1196                 if (last_env == name) {
1197                         // we need to output a separator since LyX would export
1198                         // the two environments as one otherwise (bug 5716)
1199                         docstring const sep = from_ascii("--Separator--");
1200                         TeX2LyXDocClass const & textclass(parent_context.textclass);
1201                         if (textclass.hasLayout(sep)) {
1202                                 Context newcontext(parent_context);
1203                                 newcontext.layout = &(textclass[sep]);
1204                                 newcontext.check_layout(os);
1205                                 newcontext.check_end_layout(os);
1206                         } else {
1207                                 parent_context.check_layout(os);
1208                                 begin_inset(os, "Note Note\n");
1209                                 os << "status closed\n";
1210                                 Context newcontext(true, textclass,
1211                                                 &(textclass.defaultLayout()));
1212                                 newcontext.check_layout(os);
1213                                 newcontext.check_end_layout(os);
1214                                 end_inset(os);
1215                                 parent_context.check_end_layout(os);
1216                         }
1217                 }
1218                 switch (context.layout->latextype) {
1219                 case  LATEX_LIST_ENVIRONMENT:
1220                         context.add_par_extra_stuff("\\labelwidthstring "
1221                                                     + p.verbatim_item() + '\n');
1222                         p.skip_spaces();
1223                         break;
1224                 case  LATEX_BIB_ENVIRONMENT:
1225                         p.verbatim_item(); // swallow next arg
1226                         p.skip_spaces();
1227                         break;
1228                 default:
1229                         break;
1230                 }
1231                 context.check_deeper(os);
1232                 // handle known optional and required arguments
1233                 // layouts require all optional arguments before the required ones
1234                 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1235                 // It is impossible to place anything after the environment name,
1236                 // but before the first \\item.
1237                 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1238                         bool need_layout = true;
1239                         unsigned int optargs = 0;
1240                         while (optargs < context.layout->optargs) {
1241                                 eat_whitespace(p, os, context, false);
1242                                 if (p.next_token().cat() == catEscape ||
1243                                     p.next_token().character() != '[') 
1244                                         break;
1245                                 p.get_token(); // eat '['
1246                                 if (need_layout) {
1247                                         context.check_layout(os);
1248                                         need_layout = false;
1249                                 }
1250                                 begin_inset(os, "Argument\n");
1251                                 os << "status collapsed\n\n";
1252                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1253                                 end_inset(os);
1254                                 eat_whitespace(p, os, context, false);
1255                                 ++optargs;
1256                         }
1257                         unsigned int reqargs = 0;
1258                         while (reqargs < context.layout->reqargs) {
1259                                 eat_whitespace(p, os, context, false);
1260                                 if (p.next_token().cat() != catBegin)
1261                                         break;
1262                                 p.get_token(); // eat '{'
1263                                 if (need_layout) {
1264                                         context.check_layout(os);
1265                                         need_layout = false;
1266                                 }
1267                                 begin_inset(os, "Argument\n");
1268                                 os << "status collapsed\n\n";
1269                                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1270                                 end_inset(os);
1271                                 eat_whitespace(p, os, context, false);
1272                                 ++reqargs;
1273                         }
1274                 }
1275                 parse_text(p, os, FLAG_END, outer, context);
1276                 context.check_end_layout(os);
1277                 if (parent_context.deeper_paragraph) {
1278                         // We must suppress the "end deeper" because we
1279                         // suppressed the "begin deeper" above.
1280                         context.need_end_deeper = false;
1281                 }
1282                 context.check_end_deeper(os);
1283                 parent_context.new_paragraph(os);
1284                 p.skip_spaces();
1285         }
1286
1287         // The single '=' is meant here.
1288         else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1289                 eat_whitespace(p, os, parent_context, false);
1290                 parent_context.check_layout(os);
1291                 begin_inset(os, "Flex ");
1292                 os << to_utf8(newinsetlayout->name()) << '\n'
1293                    << "status collapsed\n";
1294                 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1295                 end_inset(os);
1296         }
1297
1298         else if (name == "appendix") {
1299                 // This is no good latex style, but it works and is used in some documents...
1300                 eat_whitespace(p, os, parent_context, false);
1301                 parent_context.check_end_layout(os);
1302                 Context context(true, parent_context.textclass, parent_context.layout,
1303                                 parent_context.layout, parent_context.font);
1304                 context.check_layout(os);
1305                 os << "\\start_of_appendix\n";
1306                 parse_text(p, os, FLAG_END, outer, context);
1307                 context.check_end_layout(os);
1308                 p.skip_spaces();
1309         }
1310
1311         else if (known_environments.find(name) != known_environments.end()) {
1312                 vector<ArgumentType> arguments = known_environments[name];
1313                 // The last "argument" denotes wether we may translate the
1314                 // environment contents to LyX
1315                 // The default required if no argument is given makes us
1316                 // compatible with the reLyXre environment.
1317                 ArgumentType contents = arguments.empty() ?
1318                         required :
1319                         arguments.back();
1320                 if (!arguments.empty())
1321                         arguments.pop_back();
1322                 // See comment in parse_unknown_environment()
1323                 bool const specialfont =
1324                         (parent_context.font != parent_context.normalfont);
1325                 bool const new_layout_allowed =
1326                         parent_context.new_layout_allowed;
1327                 if (specialfont)
1328                         parent_context.new_layout_allowed = false;
1329                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1330                                 outer, parent_context);
1331                 if (contents == verbatim)
1332                         handle_ert(os, p.verbatimEnvironment(name),
1333                                    parent_context);
1334                 else
1335                         parse_text_snippet(p, os, FLAG_END, outer,
1336                                            parent_context);
1337                 handle_ert(os, "\\end{" + name + "}", parent_context);
1338                 if (specialfont)
1339                         parent_context.new_layout_allowed = new_layout_allowed;
1340         }
1341
1342         else
1343                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1344                                           parent_context);
1345
1346         last_env = name;
1347         active_environments.pop_back();
1348 }
1349
1350
1351 /// parses a comment and outputs it to \p os.
1352 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1353 {
1354         LASSERT(t.cat() == catComment, return);
1355         if (!t.cs().empty()) {
1356                 context.check_layout(os);
1357                 handle_comment(os, '%' + t.cs(), context);
1358                 if (p.next_token().cat() == catNewline) {
1359                         // A newline after a comment line starts a new
1360                         // paragraph
1361                         if (context.new_layout_allowed) {
1362                                 if(!context.atParagraphStart())
1363                                         // Only start a new paragraph if not already
1364                                         // done (we might get called recursively)
1365                                         context.new_paragraph(os);
1366                         } else
1367                                 handle_ert(os, "\n", context);
1368                         eat_whitespace(p, os, context, true);
1369                 }
1370         } else {
1371                 // "%\n" combination
1372                 p.skip_spaces();
1373         }
1374 }
1375
1376
1377 /*!
1378  * Reads spaces and comments until the first non-space, non-comment token.
1379  * New paragraphs (double newlines or \\par) are handled like simple spaces
1380  * if \p eatParagraph is true.
1381  * Spaces are skipped, but comments are written to \p os.
1382  */
1383 void eat_whitespace(Parser & p, ostream & os, Context & context,
1384                     bool eatParagraph)
1385 {
1386         while (p.good()) {
1387                 Token const & t = p.get_token();
1388                 if (t.cat() == catComment)
1389                         parse_comment(p, os, t, context);
1390                 else if ((! eatParagraph && p.isParagraph()) ||
1391                          (t.cat() != catSpace && t.cat() != catNewline)) {
1392                         p.putback();
1393                         return;
1394                 }
1395         }
1396 }
1397
1398
1399 /*!
1400  * Set a font attribute, parse text and reset the font attribute.
1401  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1402  * \param currentvalue Current value of the attribute. Is set to the new
1403  * value during parsing.
1404  * \param newvalue New value of the attribute
1405  */
1406 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1407                            Context & context, string const & attribute,
1408                            string & currentvalue, string const & newvalue)
1409 {
1410         context.check_layout(os);
1411         string const oldvalue = currentvalue;
1412         currentvalue = newvalue;
1413         os << '\n' << attribute << ' ' << newvalue << "\n";
1414         parse_text_snippet(p, os, flags, outer, context);
1415         context.check_layout(os);
1416         os << '\n' << attribute << ' ' << oldvalue << "\n";
1417         currentvalue = oldvalue;
1418 }
1419
1420
1421 /// get the arguments of a natbib or jurabib citation command
1422 void get_cite_arguments(Parser & p, bool natbibOrder,
1423         string & before, string & after)
1424 {
1425         // We need to distinguish "" and "[]", so we can't use p.getOpt().
1426
1427         // text before the citation
1428         before.clear();
1429         // text after the citation
1430         after = p.getFullOpt();
1431
1432         if (!after.empty()) {
1433                 before = p.getFullOpt();
1434                 if (natbibOrder && !before.empty())
1435                         swap(before, after);
1436         }
1437 }
1438
1439
1440 /// Convert filenames with TeX macros and/or quotes to something LyX
1441 /// can understand
1442 string const normalize_filename(string const & name)
1443 {
1444         Parser p(trim(name, "\""));
1445         ostringstream os;
1446         while (p.good()) {
1447                 Token const & t = p.get_token();
1448                 if (t.cat() != catEscape)
1449                         os << t.asInput();
1450                 else if (t.cs() == "lyxdot") {
1451                         // This is used by LyX for simple dots in relative
1452                         // names
1453                         os << '.';
1454                         p.skip_spaces();
1455                 } else if (t.cs() == "space") {
1456                         os << ' ';
1457                         p.skip_spaces();
1458                 } else
1459                         os << t.asInput();
1460         }
1461         return os.str();
1462 }
1463
1464
1465 /// Convert \p name from TeX convention (relative to master file) to LyX
1466 /// convention (relative to .lyx file) if it is relative
1467 void fix_relative_filename(string & name)
1468 {
1469         if (FileName::isAbsolute(name))
1470                 return;
1471
1472         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1473                                    from_utf8(getParentFilePath())));
1474 }
1475
1476
1477 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1478 void parse_noweb(Parser & p, ostream & os, Context & context)
1479 {
1480         // assemble the rest of the keyword
1481         string name("<<");
1482         bool scrap = false;
1483         while (p.good()) {
1484                 Token const & t = p.get_token();
1485                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1486                         name += ">>";
1487                         p.get_token();
1488                         scrap = (p.good() && p.next_token().asInput() == "=");
1489                         if (scrap)
1490                                 name += p.get_token().asInput();
1491                         break;
1492                 }
1493                 name += t.asInput();
1494         }
1495
1496         if (!scrap || !context.new_layout_allowed ||
1497             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1498                 cerr << "Warning: Could not interpret '" << name
1499                      << "'. Ignoring it." << endl;
1500                 return;
1501         }
1502
1503         // We use new_paragraph instead of check_end_layout because the stuff
1504         // following the noweb chunk needs to start with a \begin_layout.
1505         // This may create a new paragraph even if there was none in the
1506         // noweb file, but the alternative is an invalid LyX file. Since
1507         // noweb code chunks are implemented with a layout style in LyX they
1508         // always must be in an own paragraph.
1509         context.new_paragraph(os);
1510         Context newcontext(true, context.textclass,
1511                 &context.textclass[from_ascii("Scrap")]);
1512         newcontext.check_layout(os);
1513         os << name;
1514         while (p.good()) {
1515                 Token const & t = p.get_token();
1516                 // We abuse the parser a bit, because this is no TeX syntax
1517                 // at all.
1518                 if (t.cat() == catEscape)
1519                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1520                 else {
1521                         ostringstream oss;
1522                         Context tmp(false, context.textclass,
1523                                     &context.textclass[from_ascii("Scrap")]);
1524                         tmp.need_end_layout = true;
1525                         tmp.check_layout(oss);
1526                         os << subst(t.asInput(), "\n", oss.str());
1527                 }
1528                 // The scrap chunk is ended by an @ at the beginning of a line.
1529                 // After the @ the line may contain a comment and/or
1530                 // whitespace, but nothing else.
1531                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1532                     (p.next_token().cat() == catSpace ||
1533                      p.next_token().cat() == catNewline ||
1534                      p.next_token().cat() == catComment)) {
1535                         while (p.good() && p.next_token().cat() == catSpace)
1536                                 os << p.get_token().asInput();
1537                         if (p.next_token().cat() == catComment)
1538                                 // The comment includes a final '\n'
1539                                 os << p.get_token().asInput();
1540                         else {
1541                                 if (p.next_token().cat() == catNewline)
1542                                         p.get_token();
1543                                 os << '\n';
1544                         }
1545                         break;
1546                 }
1547         }
1548         newcontext.check_end_layout(os);
1549 }
1550
1551
1552 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1553 bool is_macro(Parser & p)
1554 {
1555         Token first = p.curr_token();
1556         if (first.cat() != catEscape || !p.good())
1557                 return false;
1558         if (first.cs() == "def")
1559                 return true;
1560         if (first.cs() != "global" && first.cs() != "long")
1561                 return false;
1562         Token second = p.get_token();
1563         int pos = 1;
1564         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1565                second.cat() == catNewline || second.cat() == catComment)) {
1566                 second = p.get_token();
1567                 pos++;
1568         }
1569         bool secondvalid = second.cat() == catEscape;
1570         Token third;
1571         bool thirdvalid = false;
1572         if (p.good() && first.cs() == "global" && secondvalid &&
1573             second.cs() == "long") {
1574                 third = p.get_token();
1575                 pos++;
1576                 while (p.good() && !p.isParagraph() &&
1577                        (third.cat() == catSpace ||
1578                         third.cat() == catNewline ||
1579                         third.cat() == catComment)) {
1580                         third = p.get_token();
1581                         pos++;
1582                 }
1583                 thirdvalid = third.cat() == catEscape;
1584         }
1585         for (int i = 0; i < pos; ++i)
1586                 p.putback();
1587         if (!secondvalid)
1588                 return false;
1589         if (!thirdvalid)
1590                 return (first.cs() == "global" || first.cs() == "long") &&
1591                        second.cs() == "def";
1592         return first.cs() == "global" && second.cs() == "long" &&
1593                third.cs() == "def";
1594 }
1595
1596
1597 /// Parse a macro definition (assumes that is_macro() returned true)
1598 void parse_macro(Parser & p, ostream & os, Context & context)
1599 {
1600         context.check_layout(os);
1601         Token first = p.curr_token();
1602         Token second;
1603         Token third;
1604         string command = first.asInput();
1605         if (first.cs() != "def") {
1606                 p.get_token();
1607                 eat_whitespace(p, os, context, false);
1608                 second = p.curr_token();
1609                 command += second.asInput();
1610                 if (second.cs() != "def") {
1611                         p.get_token();
1612                         eat_whitespace(p, os, context, false);
1613                         third = p.curr_token();
1614                         command += third.asInput();
1615                 }
1616         }
1617         eat_whitespace(p, os, context, false);
1618         string const name = p.get_token().cs();
1619         eat_whitespace(p, os, context, false);
1620
1621         // parameter text
1622         bool simple = true;
1623         string paramtext;
1624         int arity = 0;
1625         while (p.next_token().cat() != catBegin) {
1626                 if (p.next_token().cat() == catParameter) {
1627                         // # found
1628                         p.get_token();
1629                         paramtext += "#";
1630
1631                         // followed by number?
1632                         if (p.next_token().cat() == catOther) {
1633                                 char c = p.getChar();
1634                                 paramtext += c;
1635                                 // number = current arity + 1?
1636                                 if (c == arity + '0' + 1)
1637                                         ++arity;
1638                                 else
1639                                         simple = false;
1640                         } else
1641                                 paramtext += p.get_token().cs();
1642                 } else {
1643                         paramtext += p.get_token().cs();
1644                         simple = false;
1645                 }
1646         }
1647
1648         // only output simple (i.e. compatible) macro as FormulaMacros
1649         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1650         if (simple) {
1651                 context.check_layout(os);
1652                 begin_inset(os, "FormulaMacro");
1653                 os << "\n\\def" << ert;
1654                 end_inset(os);
1655         } else
1656                 handle_ert(os, command + ert, context);
1657 }
1658
1659 } // anonymous namespace
1660
1661
1662 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1663                 Context & context)
1664 {
1665         Layout const * newlayout = 0;
1666         InsetLayout const * newinsetlayout = 0;
1667         // Store the latest bibliographystyle and nocite{*} option
1668         // (needed for bibtex inset)
1669         string btprint;
1670         string bibliographystyle;
1671         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1672         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1673         string last_env;
1674         while (p.good()) {
1675                 Token const & t = p.get_token();
1676
1677 #ifdef FILEDEBUG
1678                 debugToken(cerr, t, flags);
1679 #endif
1680
1681                 if (flags & FLAG_ITEM) {
1682                         if (t.cat() == catSpace)
1683                                 continue;
1684
1685                         flags &= ~FLAG_ITEM;
1686                         if (t.cat() == catBegin) {
1687                                 // skip the brace and collect everything to the next matching
1688                                 // closing brace
1689                                 flags |= FLAG_BRACE_LAST;
1690                                 continue;
1691                         }
1692
1693                         // handle only this single token, leave the loop if done
1694                         flags |= FLAG_LEAVE;
1695                 }
1696
1697                 if (t.cat() != catEscape && t.character() == ']' &&
1698                     (flags & FLAG_BRACK_LAST))
1699                         return;
1700                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1701                         return;
1702
1703                 // If there is anything between \end{env} and \begin{env} we
1704                 // don't need to output a separator.
1705                 if (t.cat() != catSpace && t.cat() != catNewline &&
1706                     t.asInput() != "\\begin")
1707                         last_env = "";
1708
1709                 //
1710                 // cat codes
1711                 //
1712                 if (t.cat() == catMath) {
1713                         // we are inside some text mode thingy, so opening new math is allowed
1714                         context.check_layout(os);
1715                         begin_inset(os, "Formula ");
1716                         Token const & n = p.get_token();
1717                         if (n.cat() == catMath && outer) {
1718                                 // TeX's $$...$$ syntax for displayed math
1719                                 os << "\\[";
1720                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1721                                 os << "\\]";
1722                                 p.get_token(); // skip the second '$' token
1723                         } else {
1724                                 // simple $...$  stuff
1725                                 p.putback();
1726                                 os << '$';
1727                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1728                                 os << '$';
1729                         }
1730                         end_inset(os);
1731                 }
1732
1733                 else if (t.cat() == catSuper || t.cat() == catSub)
1734                         cerr << "catcode " << t << " illegal in text mode\n";
1735
1736                 // Basic support for english quotes. This should be
1737                 // extended to other quotes, but is not so easy (a
1738                 // left english quote is the same as a right german
1739                 // quote...)
1740                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1741                         context.check_layout(os);
1742                         begin_inset(os, "Quotes ");
1743                         os << "eld";
1744                         end_inset(os);
1745                         p.get_token();
1746                         skip_braces(p);
1747                 }
1748                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1749                         context.check_layout(os);
1750                         begin_inset(os, "Quotes ");
1751                         os << "erd";
1752                         end_inset(os);
1753                         p.get_token();
1754                         skip_braces(p);
1755                 }
1756
1757                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1758                         context.check_layout(os);
1759                         begin_inset(os, "Quotes ");
1760                         os << "ald";
1761                         end_inset(os);
1762                         p.get_token();
1763                         skip_braces(p);
1764                 }
1765
1766                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1767                         context.check_layout(os);
1768                         begin_inset(os, "Quotes ");
1769                         os << "ard";
1770                         end_inset(os);
1771                         p.get_token();
1772                         skip_braces(p);
1773                 }
1774
1775                 else if (t.asInput() == "<"
1776                          && p.next_token().asInput() == "<" && noweb_mode) {
1777                         p.get_token();
1778                         parse_noweb(p, os, context);
1779                 }
1780
1781                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1782                         check_space(p, os, context);
1783
1784                 else if (t.character() == '[' && noweb_mode &&
1785                          p.next_token().character() == '[') {
1786                         // These can contain underscores
1787                         p.putback();
1788                         string const s = p.getFullOpt() + ']';
1789                         if (p.next_token().character() == ']')
1790                                 p.get_token();
1791                         else
1792                                 cerr << "Warning: Inserting missing ']' in '"
1793                                      << s << "'." << endl;
1794                         handle_ert(os, s, context);
1795                 }
1796
1797                 else if (t.cat() == catLetter) {
1798                         context.check_layout(os);
1799                         // Workaround for bug 4752.
1800                         // FIXME: This whole code block needs to be removed
1801                         //        when the bug is fixed and tex2lyx produces
1802                         //        the updated file format.
1803                         // The replacement algorithm in LyX is so stupid that
1804                         // it even translates a phrase if it is part of a word.
1805                         bool handled = false;
1806                         for (int const * l = known_phrase_lengths; *l; ++l) {
1807                                 string phrase = t.cs();
1808                                 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1809                                         phrase += p.get_token().cs();
1810                                 if (is_known(phrase, known_coded_phrases)) {
1811                                         handle_ert(os, phrase, context);
1812                                         handled = true;
1813                                         break;
1814                                 } else {
1815                                         for (size_t i = 1; i < phrase.length(); ++i)
1816                                                 p.putback();
1817                                 }
1818                         }
1819                         if (!handled)
1820                                 os << t.cs();
1821                 }
1822
1823                 else if (t.cat() == catOther ||
1824                                t.cat() == catAlign ||
1825                                t.cat() == catParameter) {
1826                         // This translates "&" to "\\&" which may be wrong...
1827                         context.check_layout(os);
1828                         os << t.cs();
1829                 }
1830
1831                 else if (p.isParagraph()) {
1832                         if (context.new_layout_allowed)
1833                                 context.new_paragraph(os);
1834                         else
1835                                 handle_ert(os, "\\par ", context);
1836                         eat_whitespace(p, os, context, true);
1837                 }
1838
1839                 else if (t.cat() == catActive) {
1840                         context.check_layout(os);
1841                         if (t.character() == '~') {
1842                                 if (context.layout->free_spacing)
1843                                         os << ' ';
1844                                 else {
1845                                         begin_inset(os, "space ~\n");
1846                                         end_inset(os);
1847                                 }
1848                         } else
1849                                 os << t.cs();
1850                 }
1851
1852                 else if (t.cat() == catBegin &&
1853                          p.next_token().cat() == catEnd) {
1854                         // {}
1855                         Token const prev = p.prev_token();
1856                         p.get_token();
1857                         if (p.next_token().character() == '`' ||
1858                             (prev.character() == '-' &&
1859                              p.next_token().character() == '-'))
1860                                 ; // ignore it in {}`` or -{}-
1861                         else
1862                                 handle_ert(os, "{}", context);
1863
1864                 }
1865
1866                 else if (t.cat() == catBegin) {
1867                         context.check_layout(os);
1868                         // special handling of font attribute changes
1869                         Token const prev = p.prev_token();
1870                         Token const next = p.next_token();
1871                         TeXFont const oldFont = context.font;
1872                         if (next.character() == '[' ||
1873                             next.character() == ']' ||
1874                             next.character() == '*') {
1875                                 p.get_token();
1876                                 if (p.next_token().cat() == catEnd) {
1877                                         os << next.cs();
1878                                         p.get_token();
1879                                 } else {
1880                                         p.putback();
1881                                         handle_ert(os, "{", context);
1882                                         parse_text_snippet(p, os,
1883                                                         FLAG_BRACE_LAST,
1884                                                         outer, context);
1885                                         handle_ert(os, "}", context);
1886                                 }
1887                         } else if (! context.new_layout_allowed) {
1888                                 handle_ert(os, "{", context);
1889                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1890                                                    outer, context);
1891                                 handle_ert(os, "}", context);
1892                         } else if (is_known(next.cs(), known_sizes)) {
1893                                 // next will change the size, so we must
1894                                 // reset it here
1895                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1896                                                    outer, context);
1897                                 if (!context.atParagraphStart())
1898                                         os << "\n\\size "
1899                                            << context.font.size << "\n";
1900                         } else if (is_known(next.cs(), known_font_families)) {
1901                                 // next will change the font family, so we
1902                                 // must reset it here
1903                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1904                                                    outer, context);
1905                                 if (!context.atParagraphStart())
1906                                         os << "\n\\family "
1907                                            << context.font.family << "\n";
1908                         } else if (is_known(next.cs(), known_font_series)) {
1909                                 // next will change the font series, so we
1910                                 // must reset it here
1911                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1912                                                    outer, context);
1913                                 if (!context.atParagraphStart())
1914                                         os << "\n\\series "
1915                                            << context.font.series << "\n";
1916                         } else if (is_known(next.cs(), known_font_shapes)) {
1917                                 // next will change the font shape, so we
1918                                 // must reset it here
1919                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1920                                                    outer, context);
1921                                 if (!context.atParagraphStart())
1922                                         os << "\n\\shape "
1923                                            << context.font.shape << "\n";
1924                         } else if (is_known(next.cs(), known_old_font_families) ||
1925                                    is_known(next.cs(), known_old_font_series) ||
1926                                    is_known(next.cs(), known_old_font_shapes)) {
1927                                 // next will change the font family, series
1928                                 // and shape, so we must reset it here
1929                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1930                                                    outer, context);
1931                                 if (!context.atParagraphStart())
1932                                         os <<  "\n\\family "
1933                                            << context.font.family
1934                                            << "\n\\series "
1935                                            << context.font.series
1936                                            << "\n\\shape "
1937                                            << context.font.shape << "\n";
1938                         } else {
1939                                 handle_ert(os, "{", context);
1940                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1941                                                    outer, context);
1942                                 handle_ert(os, "}", context);
1943                         }
1944                 }
1945
1946                 else if (t.cat() == catEnd) {
1947                         if (flags & FLAG_BRACE_LAST) {
1948                                 return;
1949                         }
1950                         cerr << "stray '}' in text\n";
1951                         handle_ert(os, "}", context);
1952                 }
1953
1954                 else if (t.cat() == catComment)
1955                         parse_comment(p, os, t, context);
1956
1957                 //
1958                 // control sequences
1959                 //
1960
1961                 else if (t.cs() == "(") {
1962                         context.check_layout(os);
1963                         begin_inset(os, "Formula");
1964                         os << " \\(";
1965                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1966                         os << "\\)";
1967                         end_inset(os);
1968                 }
1969
1970                 else if (t.cs() == "[") {
1971                         context.check_layout(os);
1972                         begin_inset(os, "Formula");
1973                         os << " \\[";
1974                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1975                         os << "\\]";
1976                         end_inset(os);
1977                 }
1978
1979                 else if (t.cs() == "begin")
1980                         parse_environment(p, os, outer, last_env, context);
1981
1982                 else if (t.cs() == "end") {
1983                         if (flags & FLAG_END) {
1984                                 // eat environment name
1985                                 string const name = p.getArg('{', '}');
1986                                 if (name != active_environment())
1987                                         cerr << "\\end{" + name + "} does not match \\begin{"
1988                                                 + active_environment() + "}\n";
1989                                 return;
1990                         }
1991                         p.error("found 'end' unexpectedly");
1992                 }
1993
1994                 else if (t.cs() == "item") {
1995                         p.skip_spaces();
1996                         string s;
1997                         bool optarg = false;
1998                         if (p.next_token().cat() != catEscape &&
1999                             p.next_token().character() == '[') {
2000                                 p.get_token(); // eat '['
2001                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2002                                                        outer, context);
2003                                 optarg = true;
2004                         }
2005                         context.set_item();
2006                         context.check_layout(os);
2007                         if (context.has_item) {
2008                                 // An item in an unknown list-like environment
2009                                 // FIXME: Do this in check_layout()!
2010                                 context.has_item = false;
2011                                 if (optarg)
2012                                         handle_ert(os, "\\item", context);
2013                                 else
2014                                         handle_ert(os, "\\item ", context);
2015                         }
2016                         if (optarg) {
2017                                 if (context.layout->labeltype != LABEL_MANUAL) {
2018                                         // LyX does not support \item[\mybullet]
2019                                         // in itemize environments
2020                                         handle_ert(os, "[", context);
2021                                         os << s;
2022                                         handle_ert(os, "]", context);
2023                                 } else if (!s.empty()) {
2024                                         // The space is needed to separate the
2025                                         // item from the rest of the sentence.
2026                                         os << s << ' ';
2027                                         eat_whitespace(p, os, context, false);
2028                                 }
2029                         }
2030                 }
2031
2032                 else if (t.cs() == "bibitem") {
2033                         context.set_item();
2034                         context.check_layout(os);
2035                         string label = convert_command_inset_arg(p.getArg('[', ']'));
2036                         string key = convert_command_inset_arg(p.verbatim_item());
2037                         if (contains(label, '\\') || contains(key, '\\')) {
2038                                 // LyX can't handle LaTeX commands in labels or keys
2039                                 handle_ert(os, t.asInput() + '[' + label +
2040                                                "]{" + p.verbatim_item() + '}',
2041                                            context);
2042                         } else {
2043                                 begin_command_inset(os, "bibitem", "bibitem");
2044                                 os << "label \"" << label << "\"\n"
2045                                       "key \"" << key << "\"\n";
2046                                 end_inset(os);
2047                         }
2048                 }
2049
2050                 else if (is_macro(p))
2051                         parse_macro(p, os, context);
2052
2053                 else if (t.cs() == "noindent") {
2054                         p.skip_spaces();
2055                         context.add_par_extra_stuff("\\noindent\n");
2056                 }
2057
2058                 else if (t.cs() == "appendix") {
2059                         context.add_par_extra_stuff("\\start_of_appendix\n");
2060                         // We need to start a new paragraph. Otherwise the
2061                         // appendix in 'bla\appendix\chapter{' would start
2062                         // too late.
2063                         context.new_paragraph(os);
2064                         // We need to make sure that the paragraph is
2065                         // generated even if it is empty. Otherwise the
2066                         // appendix in '\par\appendix\par\chapter{' would
2067                         // start too late.
2068                         context.check_layout(os);
2069                         // FIXME: This is a hack to prevent paragraph
2070                         // deletion if it is empty. Handle this better!
2071                         handle_comment(os,
2072                                 "%dummy comment inserted by tex2lyx to "
2073                                 "ensure that this paragraph is not empty",
2074                                 context);
2075                         // Both measures above may generate an additional
2076                         // empty paragraph, but that does not hurt, because
2077                         // whitespace does not matter here.
2078                         eat_whitespace(p, os, context, true);
2079                 }
2080
2081                 // Starred section headings
2082                 // Must attempt to parse "Section*" before "Section".
2083                 else if ((p.next_token().asInput() == "*") &&
2084                          context.new_layout_allowed &&
2085                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2086                         // write the layout
2087                         p.get_token();
2088                         output_command_layout(os, p, outer, context, newlayout);
2089                         p.skip_spaces();
2090                 }
2091
2092                 // Section headings and the like
2093                 else if (context.new_layout_allowed &&
2094                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2095                         // write the layout
2096                         output_command_layout(os, p, outer, context, newlayout);
2097                         p.skip_spaces();
2098                 }
2099
2100                 else if (t.cs() == "caption") {
2101                         p.skip_spaces();
2102                         context.check_layout(os);
2103                         p.skip_spaces();
2104                         begin_inset(os, "Caption\n\n");
2105                         Context newcontext(true, context.textclass);
2106                         newcontext.font = context.font;
2107                         newcontext.check_layout(os);
2108                         if (p.next_token().cat() != catEscape &&
2109                             p.next_token().character() == '[') {
2110                                 p.get_token(); // eat '['
2111                                 begin_inset(os, "Argument\n");
2112                                 os << "status collapsed\n";
2113                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2114                                 end_inset(os);
2115                                 eat_whitespace(p, os, context, false);
2116                         }
2117                         parse_text(p, os, FLAG_ITEM, outer, context);
2118                         context.check_end_layout(os);
2119                         // We don't need really a new paragraph, but
2120                         // we must make sure that the next item gets a \begin_layout.
2121                         context.new_paragraph(os);
2122                         end_inset(os);
2123                         p.skip_spaces();
2124                         newcontext.check_end_layout(os);
2125                 }
2126
2127                 else if (t.cs() == "includegraphics") {
2128                         bool const clip = p.next_token().asInput() == "*";
2129                         if (clip)
2130                                 p.get_token();
2131                         string const arg = p.getArg('[', ']');
2132                         map<string, string> opts;
2133                         vector<string> keys;
2134                         split_map(arg, opts, keys);
2135                         if (clip)
2136                                 opts["clip"] = string();
2137                         string name = normalize_filename(p.verbatim_item());
2138
2139                         string const path = getMasterFilePath();
2140                         // We want to preserve relative / absolute filenames,
2141                         // therefore path is only used for testing
2142                         if (!makeAbsPath(name, path).exists()) {
2143                                 // The file extension is probably missing.
2144                                 // Now try to find it out.
2145                                 string const dvips_name =
2146                                         find_file(name, path,
2147                                                   known_dvips_graphics_formats);
2148                                 string const pdftex_name =
2149                                         find_file(name, path,
2150                                                   known_pdftex_graphics_formats);
2151                                 if (!dvips_name.empty()) {
2152                                         if (!pdftex_name.empty()) {
2153                                                 cerr << "This file contains the "
2154                                                         "latex snippet\n"
2155                                                         "\"\\includegraphics{"
2156                                                      << name << "}\".\n"
2157                                                         "However, files\n\""
2158                                                      << dvips_name << "\" and\n\""
2159                                                      << pdftex_name << "\"\n"
2160                                                         "both exist, so I had to make a "
2161                                                         "choice and took the first one.\n"
2162                                                         "Please move the unwanted one "
2163                                                         "someplace else and try again\n"
2164                                                         "if my choice was wrong."
2165                                                      << endl;
2166                                         }
2167                                         name = dvips_name;
2168                                 } else if (!pdftex_name.empty()) {
2169                                         name = pdftex_name;
2170                                         pdflatex = true;
2171                                 }
2172                         }
2173
2174                         if (makeAbsPath(name, path).exists())
2175                                 fix_relative_filename(name);
2176                         else
2177                                 cerr << "Warning: Could not find graphics file '"
2178                                      << name << "'." << endl;
2179
2180                         context.check_layout(os);
2181                         begin_inset(os, "Graphics ");
2182                         os << "\n\tfilename " << name << '\n';
2183                         if (opts.find("width") != opts.end())
2184                                 os << "\twidth "
2185                                    << translate_len(opts["width"]) << '\n';
2186                         if (opts.find("height") != opts.end())
2187                                 os << "\theight "
2188                                    << translate_len(opts["height"]) << '\n';
2189                         if (opts.find("scale") != opts.end()) {
2190                                 istringstream iss(opts["scale"]);
2191                                 double val;
2192                                 iss >> val;
2193                                 val = val*100;
2194                                 os << "\tscale " << val << '\n';
2195                         }
2196                         if (opts.find("angle") != opts.end()) {
2197                                 os << "\trotateAngle "
2198                                    << opts["angle"] << '\n';
2199                                 vector<string>::const_iterator a =
2200                                         find(keys.begin(), keys.end(), "angle");
2201                                 vector<string>::const_iterator s =
2202                                         find(keys.begin(), keys.end(), "width");
2203                                 if (s == keys.end())
2204                                         s = find(keys.begin(), keys.end(), "height");
2205                                 if (s == keys.end())
2206                                         s = find(keys.begin(), keys.end(), "scale");
2207                                 if (s != keys.end() && distance(s, a) > 0)
2208                                         os << "\tscaleBeforeRotation\n";
2209                         }
2210                         if (opts.find("origin") != opts.end()) {
2211                                 ostringstream ss;
2212                                 string const opt = opts["origin"];
2213                                 if (opt.find('l') != string::npos) ss << "left";
2214                                 if (opt.find('r') != string::npos) ss << "right";
2215                                 if (opt.find('c') != string::npos) ss << "center";
2216                                 if (opt.find('t') != string::npos) ss << "Top";
2217                                 if (opt.find('b') != string::npos) ss << "Bottom";
2218                                 if (opt.find('B') != string::npos) ss << "Baseline";
2219                                 if (!ss.str().empty())
2220                                         os << "\trotateOrigin " << ss.str() << '\n';
2221                                 else
2222                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2223                         }
2224                         if (opts.find("keepaspectratio") != opts.end())
2225                                 os << "\tkeepAspectRatio\n";
2226                         if (opts.find("clip") != opts.end())
2227                                 os << "\tclip\n";
2228                         if (opts.find("draft") != opts.end())
2229                                 os << "\tdraft\n";
2230                         if (opts.find("bb") != opts.end())
2231                                 os << "\tBoundingBox "
2232                                    << opts["bb"] << '\n';
2233                         int numberOfbbOptions = 0;
2234                         if (opts.find("bbllx") != opts.end())
2235                                 numberOfbbOptions++;
2236                         if (opts.find("bblly") != opts.end())
2237                                 numberOfbbOptions++;
2238                         if (opts.find("bburx") != opts.end())
2239                                 numberOfbbOptions++;
2240                         if (opts.find("bbury") != opts.end())
2241                                 numberOfbbOptions++;
2242                         if (numberOfbbOptions == 4)
2243                                 os << "\tBoundingBox "
2244                                    << opts["bbllx"] << " " << opts["bblly"] << " "
2245                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
2246                         else if (numberOfbbOptions > 0)
2247                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2248                         numberOfbbOptions = 0;
2249                         if (opts.find("natwidth") != opts.end())
2250                                 numberOfbbOptions++;
2251                         if (opts.find("natheight") != opts.end())
2252                                 numberOfbbOptions++;
2253                         if (numberOfbbOptions == 2)
2254                                 os << "\tBoundingBox 0bp 0bp "
2255                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
2256                         else if (numberOfbbOptions > 0)
2257                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2258                         ostringstream special;
2259                         if (opts.find("hiresbb") != opts.end())
2260                                 special << "hiresbb,";
2261                         if (opts.find("trim") != opts.end())
2262                                 special << "trim,";
2263                         if (opts.find("viewport") != opts.end())
2264                                 special << "viewport=" << opts["viewport"] << ',';
2265                         if (opts.find("totalheight") != opts.end())
2266                                 special << "totalheight=" << opts["totalheight"] << ',';
2267                         if (opts.find("type") != opts.end())
2268                                 special << "type=" << opts["type"] << ',';
2269                         if (opts.find("ext") != opts.end())
2270                                 special << "ext=" << opts["ext"] << ',';
2271                         if (opts.find("read") != opts.end())
2272                                 special << "read=" << opts["read"] << ',';
2273                         if (opts.find("command") != opts.end())
2274                                 special << "command=" << opts["command"] << ',';
2275                         string s_special = special.str();
2276                         if (!s_special.empty()) {
2277                                 // We had special arguments. Remove the trailing ','.
2278                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2279                         }
2280                         // TODO: Handle the unknown settings better.
2281                         // Warn about invalid options.
2282                         // Check whether some option was given twice.
2283                         end_inset(os);
2284                 }
2285
2286                 else if (t.cs() == "footnote" ||
2287                          (t.cs() == "thanks" && context.layout->intitle)) {
2288                         p.skip_spaces();
2289                         context.check_layout(os);
2290                         begin_inset(os, "Foot\n");
2291                         os << "status collapsed\n\n";
2292                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2293                         end_inset(os);
2294                 }
2295
2296                 else if (t.cs() == "marginpar") {
2297                         p.skip_spaces();
2298                         context.check_layout(os);
2299                         begin_inset(os, "Marginal\n");
2300                         os << "status collapsed\n\n";
2301                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2302                         end_inset(os);
2303                 }
2304
2305                 else if (t.cs() == "ensuremath") {
2306                         p.skip_spaces();
2307                         context.check_layout(os);
2308                         string const s = p.verbatim_item();
2309                         //FIXME: this never triggers in UTF8
2310                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2311                                 os << s;
2312                         else
2313                                 handle_ert(os, "\\ensuremath{" + s + "}",
2314                                            context);
2315                 }
2316
2317                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2318                         // FIXME: Somehow prevent title layouts if
2319                         // "maketitle" was not found
2320                         // swallow this
2321                         skip_spaces_braces(p);
2322                 }
2323
2324                 else if (t.cs() == "tableofcontents") {
2325                         context.check_layout(os);
2326                         begin_command_inset(os, "toc", "tableofcontents");
2327                         end_inset(os);
2328                         skip_spaces_braces(p);
2329                 }
2330
2331                 else if (t.cs() == "listoffigures") {
2332                         context.check_layout(os);
2333                         begin_inset(os, "FloatList figure\n");
2334                         end_inset(os);
2335                         skip_spaces_braces(p);
2336                 }
2337
2338                 else if (t.cs() == "listoftables") {
2339                         context.check_layout(os);
2340                         begin_inset(os, "FloatList table\n");
2341                         end_inset(os);
2342                         skip_spaces_braces(p);
2343                 }
2344
2345                 else if (t.cs() == "listof") {
2346                         p.skip_spaces(true);
2347                         string const name = p.get_token().cs();
2348                         if (context.textclass.floats().typeExist(name)) {
2349                                 context.check_layout(os);
2350                                 begin_inset(os, "FloatList ");
2351                                 os << name << "\n";
2352                                 end_inset(os);
2353                                 p.get_token(); // swallow second arg
2354                         } else
2355                                 handle_ert(os, "\\listof{" + name + "}", context);
2356                 }
2357
2358                 else if (t.cs() == "textrm")
2359                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2360                                               context, "\\family",
2361                                               context.font.family, "roman");
2362
2363                 else if (t.cs() == "textsf")
2364                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2365                                               context, "\\family",
2366                                               context.font.family, "sans");
2367
2368                 else if (t.cs() == "texttt")
2369                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2370                                               context, "\\family",
2371                                               context.font.family, "typewriter");
2372
2373                 else if (t.cs() == "textmd")
2374                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2375                                               context, "\\series",
2376                                               context.font.series, "medium");
2377
2378                 else if (t.cs() == "textbf")
2379                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2380                                               context, "\\series",
2381                                               context.font.series, "bold");
2382
2383                 else if (t.cs() == "textup")
2384                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2385                                               context, "\\shape",
2386                                               context.font.shape, "up");
2387
2388                 else if (t.cs() == "textit")
2389                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2390                                               context, "\\shape",
2391                                               context.font.shape, "italic");
2392
2393                 else if (t.cs() == "textsl")
2394                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2395                                               context, "\\shape",
2396                                               context.font.shape, "slanted");
2397
2398                 else if (t.cs() == "textsc")
2399                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2400                                               context, "\\shape",
2401                                               context.font.shape, "smallcaps");
2402
2403                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2404                         context.check_layout(os);
2405                         TeXFont oldFont = context.font;
2406                         context.font.init();
2407                         context.font.size = oldFont.size;
2408                         os << "\n\\family " << context.font.family << "\n";
2409                         os << "\n\\series " << context.font.series << "\n";
2410                         os << "\n\\shape " << context.font.shape << "\n";
2411                         if (t.cs() == "textnormal") {
2412                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2413                                 output_font_change(os, context.font, oldFont);
2414                                 context.font = oldFont;
2415                         } else
2416                                 eat_whitespace(p, os, context, false);
2417                 }
2418
2419                 else if (t.cs() == "textcolor") {
2420                         // scheme is \textcolor{color name}{text}
2421                         string const color = p.verbatim_item();
2422                         // we only support the predefined colors of the color package
2423                         if (color == "black" || color == "blue" || color == "cyan"
2424                                 || color == "green" || color == "magenta" || color == "red"
2425                                 || color == "white" || color == "yellow") {
2426                                         context.check_layout(os);
2427                                         os << "\n\\color " << color << "\n";
2428                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2429                                         context.check_layout(os);
2430                                         os << "\n\\color inherit\n";
2431                         } else
2432                                 // for custom defined colors
2433                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
2434                 }
2435
2436                 else if (t.cs() == "underbar" || t.cs() == "uline") {
2437                         // \underbar is not 100% correct (LyX outputs \uline
2438                         // of ulem.sty). The difference is that \ulem allows
2439                         // line breaks, and \underbar does not.
2440                         // Do NOT handle \underline.
2441                         // \underbar cuts through y, g, q, p etc.,
2442                         // \underline does not.
2443                         context.check_layout(os);
2444                         os << "\n\\bar under\n";
2445                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2446                         context.check_layout(os);
2447                         os << "\n\\bar default\n";
2448                 }
2449
2450                 else if (t.cs() == "sout") {
2451                         context.check_layout(os);
2452                         os << "\n\\strikeout on\n";
2453                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2454                         context.check_layout(os);
2455                         os << "\n\\strikeout default\n";
2456                 }
2457
2458                 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2459                          t.cs() == "emph" || t.cs() == "noun") {
2460                         context.check_layout(os);
2461                         os << "\n\\" << t.cs() << " on\n";
2462                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2463                         context.check_layout(os);
2464                         os << "\n\\" << t.cs() << " default\n";
2465                 }
2466
2467                 // FIXME, the inset layout should be plain, not standard, see bug #7846
2468                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2469                              t.cs() == "vphantom") {
2470                         context.check_layout(os);
2471                         if (t.cs() == "phantom")
2472                                 begin_inset(os, "Phantom Phantom\n");
2473                         if (t.cs() == "hphantom")
2474                                 begin_inset(os, "Phantom Hhantom\n");
2475                         if (t.cs() == "vphantom")
2476                                 begin_inset(os, "Phantom Vhantom\n");
2477                         os << "status open\n";
2478                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2479                         end_inset(os);
2480                 }
2481                 
2482                 else if (t.cs() == "lyxline") {
2483                         // swallow size argument (it is not used anyway)
2484                         p.getArg('{', '}');
2485                         if (!context.atParagraphStart()) {
2486                                 // so our line is in the middle of a paragraph
2487                                 // we need to add a new line, lest this line
2488                                 // follow the other content on that line and
2489                                 // run off the side of the page
2490                                 // FIXME: This may create an empty paragraph,
2491                                 //        but without that it would not be
2492                                 //        possible to set noindent below.
2493                                 //        Fortunately LaTeX does not care
2494                                 //        about the empty paragraph.
2495                                 context.new_paragraph(os);
2496                         }
2497                         if (h_paragraph_separation == "indent") {
2498                                 // we need to unindent, lest the line be too long
2499                                 context.add_par_extra_stuff("\\noindent\n");
2500                         }
2501                         context.check_layout(os);
2502                         begin_command_inset(os, "line", "rule");
2503                         os << "offset \"0.5ex\"\n"
2504                               "width \"100line%\"\n"
2505                               "height \"1pt\"\n";
2506                         end_inset(os);
2507                 }
2508
2509                 else if (t.cs() == "rule") {
2510                         string offset = "";
2511                         string width;
2512                         string thickness;
2513                         if (p.hasOpt())
2514                                 offset = p.getArg('[', ']');
2515                         width = p.getArg('{', '}');
2516                         thickness = p.getArg('{', '}');
2517                                         
2518                         context.check_layout(os);
2519                         begin_command_inset(os, "line", "rule");
2520                         if (!offset.empty())
2521                                 os << "offset \"" << translate_len(offset) << "\"\n";
2522                         os << "width \"" << translate_len(width) << "\"\n"
2523                                   "height \"" << translate_len(thickness) << "\"\n";
2524                         end_inset(os);
2525                 }
2526
2527                 else if (is_known(t.cs(), known_phrases) ||
2528                          (t.cs() == "protect" &&
2529                           p.next_token().cat() == catEscape &&
2530                           is_known(p.next_token().cs(), known_phrases))) {
2531                         // LyX sometimes puts a \protect in front, so we have to ignore it
2532                         // FIXME: This needs to be changed when bug 4752 is fixed.
2533                         char const * const * where = is_known(
2534                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2535                                 known_phrases);
2536                         context.check_layout(os);
2537                         os << known_coded_phrases[where - known_phrases];
2538                         skip_spaces_braces(p);
2539                 }
2540
2541                 else if (is_known(t.cs(), known_ref_commands)) {
2542                         string const opt = p.getOpt();
2543                         if (opt.empty()) {
2544                                 context.check_layout(os);
2545                                 char const * const * where = is_known(t.cs(),
2546                                         known_ref_commands);
2547                                 begin_command_inset(os, "ref",
2548                                         known_coded_ref_commands[where - known_ref_commands]);
2549                                 os << "reference \""
2550                                    << convert_command_inset_arg(p.verbatim_item())
2551                                    << "\"\n";
2552                                 end_inset(os);
2553                         } else {
2554                                 // LyX does not support optional arguments of ref commands
2555                                 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2556                                                p.verbatim_item() + "}", context);
2557                         }
2558                 }
2559
2560                 else if (use_natbib &&
2561                          is_known(t.cs(), known_natbib_commands) &&
2562                          ((t.cs() != "citefullauthor" &&
2563                            t.cs() != "citeyear" &&
2564                            t.cs() != "citeyearpar") ||
2565                           p.next_token().asInput() != "*")) {
2566                         context.check_layout(os);
2567                         string command = t.cs();
2568                         if (p.next_token().asInput() == "*") {
2569                                 command += '*';
2570                                 p.get_token();
2571                         }
2572                         if (command == "citefullauthor")
2573                                 // alternative name for "\\citeauthor*"
2574                                 command = "citeauthor*";
2575
2576                         // text before the citation
2577                         string before;
2578                         // text after the citation
2579                         string after;
2580                         get_cite_arguments(p, true, before, after);
2581
2582                         if (command == "cite") {
2583                                 // \cite without optional argument means
2584                                 // \citet, \cite with at least one optional
2585                                 // argument means \citep.
2586                                 if (before.empty() && after.empty())
2587                                         command = "citet";
2588                                 else
2589                                         command = "citep";
2590                         }
2591                         if (before.empty() && after == "[]")
2592                                 // avoid \citet[]{a}
2593                                 after.erase();
2594                         else if (before == "[]" && after == "[]") {
2595                                 // avoid \citet[][]{a}
2596                                 before.erase();
2597                                 after.erase();
2598                         }
2599                         // remove the brackets around after and before
2600                         if (!after.empty()) {
2601                                 after.erase(0, 1);
2602                                 after.erase(after.length() - 1, 1);
2603                                 after = convert_command_inset_arg(after);
2604                         }
2605                         if (!before.empty()) {
2606                                 before.erase(0, 1);
2607                                 before.erase(before.length() - 1, 1);
2608                                 before = convert_command_inset_arg(before);
2609                         }
2610                         begin_command_inset(os, "citation", command);
2611                         os << "after " << '"' << after << '"' << "\n";
2612                         os << "before " << '"' << before << '"' << "\n";
2613                         os << "key \""
2614                            << convert_command_inset_arg(p.verbatim_item())
2615                            << "\"\n";
2616                         end_inset(os);
2617                 }
2618
2619                 else if (use_jurabib &&
2620                          is_known(t.cs(), known_jurabib_commands) &&
2621                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2622                         context.check_layout(os);
2623                         string command = t.cs();
2624                         if (p.next_token().asInput() == "*") {
2625                                 command += '*';
2626                                 p.get_token();
2627                         }
2628                         char argumentOrder = '\0';
2629                         vector<string> const & options = used_packages["jurabib"];
2630                         if (find(options.begin(), options.end(),
2631                                       "natbiborder") != options.end())
2632                                 argumentOrder = 'n';
2633                         else if (find(options.begin(), options.end(),
2634                                            "jurabiborder") != options.end())
2635                                 argumentOrder = 'j';
2636
2637                         // text before the citation
2638                         string before;
2639                         // text after the citation
2640                         string after;
2641                         get_cite_arguments(p, argumentOrder != 'j', before, after);
2642
2643                         string const citation = p.verbatim_item();
2644                         if (!before.empty() && argumentOrder == '\0') {
2645                                 cerr << "Warning: Assuming argument order "
2646                                         "of jurabib version 0.6 for\n'"
2647                                      << command << before << after << '{'
2648                                      << citation << "}'.\n"
2649                                         "Add 'jurabiborder' to the jurabib "
2650                                         "package options if you used an\n"
2651                                         "earlier jurabib version." << endl;
2652                         }
2653                         if (!after.empty()) {
2654                                 after.erase(0, 1);
2655                                 after.erase(after.length() - 1, 1);
2656                         }
2657                         if (!before.empty()) {
2658                                 before.erase(0, 1);
2659                                 before.erase(before.length() - 1, 1);
2660                         }
2661                         begin_command_inset(os, "citation", command);
2662                         os << "after " << '"' << after << '"' << "\n";
2663                         os << "before " << '"' << before << '"' << "\n";
2664                         os << "key " << '"' << citation << '"' << "\n";
2665                         end_inset(os);
2666                 }
2667
2668                 else if (t.cs() == "cite"
2669                         || t.cs() == "nocite") {
2670                         context.check_layout(os);
2671                         string after = convert_command_inset_arg(p.getArg('[', ']'));
2672                         string key = convert_command_inset_arg(p.verbatim_item());
2673                         // store the case that it is "\nocite{*}" to use it later for
2674                         // the BibTeX inset
2675                         if (key != "*") {
2676                                 begin_command_inset(os, "citation", t.cs());
2677                                 os << "after " << '"' << after << '"' << "\n";
2678                                 os << "key " << '"' << key << '"' << "\n";
2679                                 end_inset(os);
2680                         } else if (t.cs() == "nocite")
2681                                 btprint = key;
2682                 }
2683
2684                 else if (t.cs() == "index") {
2685                         context.check_layout(os);
2686                         begin_inset(os, "Index idx\n");
2687                         os << "status collapsed\n";
2688                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2689                         end_inset(os);
2690                 }
2691
2692                 else if (t.cs() == "nomenclature") {
2693                         context.check_layout(os);
2694                         begin_command_inset(os, "nomenclature", "nomenclature");
2695                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2696                         if (!prefix.empty())
2697                                 os << "prefix " << '"' << prefix << '"' << "\n";
2698                         os << "symbol " << '"'
2699                            << convert_command_inset_arg(p.verbatim_item());
2700                         os << "\"\ndescription \""
2701                            << convert_command_inset_arg(p.verbatim_item())
2702                            << "\"\n";
2703                         end_inset(os);
2704                 }
2705                 
2706                 else if (t.cs() == "label") {
2707                         context.check_layout(os);
2708                         begin_command_inset(os, "label", "label");
2709                         os << "name \""
2710                            << convert_command_inset_arg(p.verbatim_item())
2711                            << "\"\n";
2712                         end_inset(os);
2713                 }
2714
2715                 else if (t.cs() == "printindex") {
2716                         context.check_layout(os);
2717                         begin_command_inset(os, "index_print", "printindex");
2718                         os << "type \"idx\"\n";
2719                         end_inset(os);
2720                         skip_spaces_braces(p);
2721                 }
2722
2723                 else if (t.cs() == "printnomenclature") {
2724                         string width = "";
2725                         string width_type = "";
2726                         context.check_layout(os);
2727                         begin_command_inset(os, "nomencl_print", "printnomenclature");
2728                         // case of a custom width
2729                         if (p.hasOpt()) {
2730                                 width = p.getArg('[', ']');
2731                                 width = translate_len(width);
2732                                 width_type = "custom";
2733                         }
2734                         // case of no custom width
2735                         // the case of no custom width but the width set
2736                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
2737                         // because the user could have set anything, not only the width
2738                         // of the longest label (which would be width_type = "auto")
2739                         string label = convert_command_inset_arg(p.getArg('{', '}'));
2740                         if (label.empty() && width_type.empty())
2741                                 width_type = "none";
2742                         os << "set_width \"" << width_type << "\"\n";
2743                         if (width_type == "custom")
2744                                 os << "width \"" << width << '\"';
2745                         end_inset(os);
2746                         skip_spaces_braces(p);
2747                 }
2748
2749                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2750                         context.check_layout(os);
2751                         begin_inset(os, "script ");
2752                         os << t.cs().substr(4) << '\n';
2753                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2754                         end_inset(os);
2755                 }
2756
2757                 else if (is_known(t.cs(), known_quotes)) {
2758                         char const * const * where = is_known(t.cs(), known_quotes);
2759                         context.check_layout(os);
2760                         begin_inset(os, "Quotes ");
2761                         os << known_coded_quotes[where - known_quotes];
2762                         end_inset(os);
2763                         // LyX adds {} after the quote, so we have to eat
2764                         // spaces here if there are any before a possible
2765                         // {} pair.
2766                         eat_whitespace(p, os, context, false);
2767                         skip_braces(p);
2768                 }
2769
2770                 else if (is_known(t.cs(), known_sizes) &&
2771                          context.new_layout_allowed) {
2772                         char const * const * where = is_known(t.cs(), known_sizes);
2773                         context.check_layout(os);
2774                         TeXFont const oldFont = context.font;
2775                         context.font.size = known_coded_sizes[where - known_sizes];
2776                         output_font_change(os, oldFont, context.font);
2777                         eat_whitespace(p, os, context, false);
2778                 }
2779
2780                 else if (is_known(t.cs(), known_font_families) &&
2781                          context.new_layout_allowed) {
2782                         char const * const * where =
2783                                 is_known(t.cs(), known_font_families);
2784                         context.check_layout(os);
2785                         TeXFont const oldFont = context.font;
2786                         context.font.family =
2787                                 known_coded_font_families[where - known_font_families];
2788                         output_font_change(os, oldFont, context.font);
2789                         eat_whitespace(p, os, context, false);
2790                 }
2791
2792                 else if (is_known(t.cs(), known_font_series) &&
2793                          context.new_layout_allowed) {
2794                         char const * const * where =
2795                                 is_known(t.cs(), known_font_series);
2796                         context.check_layout(os);
2797                         TeXFont const oldFont = context.font;
2798                         context.font.series =
2799                                 known_coded_font_series[where - known_font_series];
2800                         output_font_change(os, oldFont, context.font);
2801                         eat_whitespace(p, os, context, false);
2802                 }
2803
2804                 else if (is_known(t.cs(), known_font_shapes) &&
2805                          context.new_layout_allowed) {
2806                         char const * const * where =
2807                                 is_known(t.cs(), known_font_shapes);
2808                         context.check_layout(os);
2809                         TeXFont const oldFont = context.font;
2810                         context.font.shape =
2811                                 known_coded_font_shapes[where - known_font_shapes];
2812                         output_font_change(os, oldFont, context.font);
2813                         eat_whitespace(p, os, context, false);
2814                 }
2815                 else if (is_known(t.cs(), known_old_font_families) &&
2816                          context.new_layout_allowed) {
2817                         char const * const * where =
2818                                 is_known(t.cs(), known_old_font_families);
2819                         context.check_layout(os);
2820                         TeXFont const oldFont = context.font;
2821                         context.font.init();
2822                         context.font.size = oldFont.size;
2823                         context.font.family =
2824                                 known_coded_font_families[where - known_old_font_families];
2825                         output_font_change(os, oldFont, context.font);
2826                         eat_whitespace(p, os, context, false);
2827                 }
2828
2829                 else if (is_known(t.cs(), known_old_font_series) &&
2830                          context.new_layout_allowed) {
2831                         char const * const * where =
2832                                 is_known(t.cs(), known_old_font_series);
2833                         context.check_layout(os);
2834                         TeXFont const oldFont = context.font;
2835                         context.font.init();
2836                         context.font.size = oldFont.size;
2837                         context.font.series =
2838                                 known_coded_font_series[where - known_old_font_series];
2839                         output_font_change(os, oldFont, context.font);
2840                         eat_whitespace(p, os, context, false);
2841                 }
2842
2843                 else if (is_known(t.cs(), known_old_font_shapes) &&
2844                          context.new_layout_allowed) {
2845                         char const * const * where =
2846                                 is_known(t.cs(), known_old_font_shapes);
2847                         context.check_layout(os);
2848                         TeXFont const oldFont = context.font;
2849                         context.font.init();
2850                         context.font.size = oldFont.size;
2851                         context.font.shape =
2852                                 known_coded_font_shapes[where - known_old_font_shapes];
2853                         output_font_change(os, oldFont, context.font);
2854                         eat_whitespace(p, os, context, false);
2855                 }
2856
2857                 else if (t.cs() == "selectlanguage") {
2858                         context.check_layout(os);
2859                         // save the language for the case that a
2860                         // \foreignlanguage is used 
2861
2862                         context.font.language = babel2lyx(p.verbatim_item());
2863                         os << "\n\\lang " << context.font.language << "\n";
2864                 }
2865
2866                 else if (t.cs() == "foreignlanguage") {
2867                         string const lang = babel2lyx(p.verbatim_item());
2868                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2869                                               context, "\\lang",
2870                                               context.font.language, lang);
2871                 }
2872
2873                 else if (t.cs() == "inputencoding") {
2874                         // nothing to write here
2875                         string const enc = subst(p.verbatim_item(), "\n", " ");
2876                         p.setEncoding(enc);
2877                 }
2878
2879                 else if (t.cs() == "ldots") {
2880                         context.check_layout(os);
2881                         os << "\\SpecialChar \\ldots{}\n";
2882                         skip_spaces_braces(p);
2883                 }
2884
2885                 else if (t.cs() == "lyxarrow") {
2886                         context.check_layout(os);
2887                         os << "\\SpecialChar \\menuseparator\n";
2888                         skip_spaces_braces(p);
2889                 }
2890
2891                 else if (t.cs() == "textcompwordmark") {
2892                         context.check_layout(os);
2893                         os << "\\SpecialChar \\textcompwordmark{}\n";
2894                         skip_spaces_braces(p);
2895                 }
2896
2897                 else if (t.cs() == "slash") {
2898                         context.check_layout(os);
2899                         os << "\\SpecialChar \\slash{}\n";
2900                         skip_spaces_braces(p);
2901                 }
2902
2903                 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2904                         context.check_layout(os);
2905                         os << "\\SpecialChar \\nobreakdash-\n";
2906                         p.get_token();
2907                 }
2908
2909                 else if (t.cs() == "textquotedbl") {
2910                         context.check_layout(os);
2911                         os << "\"";
2912                         skip_braces(p);
2913                 }
2914
2915                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2916                         context.check_layout(os);
2917                         os << "\\SpecialChar \\@.\n";
2918                         p.get_token();
2919                 }
2920
2921                 else if (t.cs() == "-") {
2922                         context.check_layout(os);
2923                         os << "\\SpecialChar \\-\n";
2924                 }
2925
2926                 else if (t.cs() == "textasciitilde") {
2927                         context.check_layout(os);
2928                         os << '~';
2929                         skip_spaces_braces(p);
2930                 }
2931
2932                 else if (t.cs() == "textasciicircum") {
2933                         context.check_layout(os);
2934                         os << '^';
2935                         skip_spaces_braces(p);
2936                 }
2937
2938                 else if (t.cs() == "textbackslash") {
2939                         context.check_layout(os);
2940                         os << "\n\\backslash\n";
2941                         skip_spaces_braces(p);
2942                 }
2943
2944                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2945                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2946                             || t.cs() == "%") {
2947                         context.check_layout(os);
2948                         os << t.cs();
2949                 }
2950
2951                 else if (t.cs() == "char") {
2952                         context.check_layout(os);
2953                         if (p.next_token().character() == '`') {
2954                                 p.get_token();
2955                                 if (p.next_token().cs() == "\"") {
2956                                         p.get_token();
2957                                         os << '"';
2958                                         skip_braces(p);
2959                                 } else {
2960                                         handle_ert(os, "\\char`", context);
2961                                 }
2962                         } else {
2963                                 handle_ert(os, "\\char", context);
2964                         }
2965                 }
2966
2967                 else if (t.cs() == "verb") {
2968                         context.check_layout(os);
2969                         char const delimiter = p.next_token().character();
2970                         string const arg = p.getArg(delimiter, delimiter);
2971                         ostringstream oss;
2972                         oss << "\\verb" << delimiter << arg << delimiter;
2973                         handle_ert(os, oss.str(), context);
2974                 }
2975
2976                 // Problem: \= creates a tabstop inside the tabbing environment
2977                 // and else an accent. In the latter case we really would want
2978                 // \={o} instead of \= o.
2979                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2980                         handle_ert(os, t.asInput(), context);
2981
2982                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2983                 else if (t.cs().size() == 1 
2984                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2985                         context.check_layout(os);
2986                         // try to see whether the string is in unicodesymbols
2987                         docstring rem;
2988                         string command = t.asInput() + "{" 
2989                                 + trimSpaceAndEol(p.verbatim_item())
2990                                 + "}";
2991                         docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2992                         if (!s.empty()) {
2993                                 if (!rem.empty())
2994                                         cerr << "When parsing " << command 
2995                                              << ", result is " << to_utf8(s)
2996                                              << "+" << to_utf8(rem) << endl;
2997                                 os << to_utf8(s);
2998                         } else
2999                                 // we did not find a non-ert version
3000                                 handle_ert(os, command, context);
3001                 }
3002
3003                 else if (t.cs() == "\\") {
3004                         context.check_layout(os);
3005                         if (p.hasOpt())
3006                                 handle_ert(os, "\\\\" + p.getOpt(), context);
3007                         else if (p.next_token().asInput() == "*") {
3008                                 p.get_token();
3009                                 // getOpt() eats the following space if there
3010                                 // is no optional argument, but that is OK
3011                                 // here since it has no effect in the output.
3012                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
3013                         }
3014                         else {
3015                                 begin_inset(os, "Newline newline");
3016                                 end_inset(os);
3017                         }
3018                 }
3019
3020                 else if (t.cs() == "newline" ||
3021                          (t.cs() == "linebreak" && !p.hasOpt())) {
3022                         context.check_layout(os);
3023                         begin_inset(os, "Newline ");
3024                         os << t.cs();
3025                         end_inset(os);
3026                         skip_spaces_braces(p);
3027                 }
3028
3029                 else if (t.cs() == "input" || t.cs() == "include"
3030                          || t.cs() == "verbatiminput") {
3031                         string name = t.cs();
3032                         if (t.cs() == "verbatiminput"
3033                             && p.next_token().asInput() == "*")
3034                                 name += p.get_token().asInput();
3035                         context.check_layout(os);
3036                         string filename(normalize_filename(p.getArg('{', '}')));
3037                         string const path = getMasterFilePath();
3038                         // We want to preserve relative / absolute filenames,
3039                         // therefore path is only used for testing
3040                         if ((t.cs() == "include" || t.cs() == "input") &&
3041                             !makeAbsPath(filename, path).exists()) {
3042                                 // The file extension is probably missing.
3043                                 // Now try to find it out.
3044                                 string const tex_name =
3045                                         find_file(filename, path,
3046                                                   known_tex_extensions);
3047                                 if (!tex_name.empty())
3048                                         filename = tex_name;
3049                         }
3050                         bool external = false;
3051                         string outname;
3052                         if (makeAbsPath(filename, path).exists()) {
3053                                 string const abstexname =
3054                                         makeAbsPath(filename, path).absFileName();
3055                                 string const abslyxname =
3056                                         changeExtension(abstexname, ".lyx");
3057                                 string const absfigname =
3058                                         changeExtension(abstexname, ".fig");
3059                                 fix_relative_filename(filename);
3060                                 string const lyxname =
3061                                         changeExtension(filename, ".lyx");
3062                                 bool xfig = false;
3063                                 external = FileName(absfigname).exists();
3064                                 if (t.cs() == "input") {
3065                                         string const ext = getExtension(abstexname);
3066
3067                                         // Combined PS/LaTeX:
3068                                         // x.eps, x.pstex_t (old xfig)
3069                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3070                                         FileName const absepsname(
3071                                                 changeExtension(abstexname, ".eps"));
3072                                         FileName const abspstexname(
3073                                                 changeExtension(abstexname, ".pstex"));
3074                                         bool const xfigeps =
3075                                                 (absepsname.exists() ||
3076                                                  abspstexname.exists()) &&
3077                                                 ext == "pstex_t";
3078
3079                                         // Combined PDF/LaTeX:
3080                                         // x.pdf, x.pdftex_t (old xfig)
3081                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3082                                         FileName const abspdfname(
3083                                                 changeExtension(abstexname, ".pdf"));
3084                                         bool const xfigpdf =
3085                                                 abspdfname.exists() &&
3086                                                 (ext == "pdftex_t" || ext == "pdf_t");
3087                                         if (xfigpdf)
3088                                                 pdflatex = true;
3089
3090                                         // Combined PS/PDF/LaTeX:
3091                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3092                                         string const absbase2(
3093                                                 removeExtension(abstexname) + "_pspdftex");
3094                                         FileName const abseps2name(
3095                                                 addExtension(absbase2, ".eps"));
3096                                         FileName const abspdf2name(
3097                                                 addExtension(absbase2, ".pdf"));
3098                                         bool const xfigboth =
3099                                                 abspdf2name.exists() &&
3100                                                 abseps2name.exists() && ext == "pspdftex";
3101
3102                                         xfig = xfigpdf || xfigeps || xfigboth;
3103                                         external = external && xfig;
3104                                 }
3105                                 if (external) {
3106                                         outname = changeExtension(filename, ".fig");
3107                                 } else if (xfig) {
3108                                         // Don't try to convert, the result
3109                                         // would be full of ERT.
3110                                         outname = filename;
3111                                 } else if (t.cs() != "verbatiminput" &&
3112                                     tex2lyx(abstexname, FileName(abslyxname),
3113                                             p.getEncoding())) {
3114                                         outname = lyxname;
3115                                 } else {
3116                                         outname = filename;
3117                                 }
3118                         } else {
3119                                 cerr << "Warning: Could not find included file '"
3120                                      << filename << "'." << endl;
3121                                 outname = filename;
3122                         }
3123                         if (external) {
3124                                 begin_inset(os, "External\n");
3125                                 os << "\ttemplate XFig\n"
3126                                    << "\tfilename " << outname << '\n';
3127                         } else {
3128                                 begin_command_inset(os, "include", name);
3129                                 os << "preview false\n"
3130                                       "filename \"" << outname << "\"\n";
3131                         }
3132                         end_inset(os);
3133                 }
3134
3135                 else if (t.cs() == "bibliographystyle") {
3136                         // store new bibliographystyle
3137                         bibliographystyle = p.verbatim_item();
3138                         // If any other command than \bibliography and
3139                         // \nocite{*} follows, we need to output the style
3140                         // (because it might be used by that command).
3141                         // Otherwise, it will automatically be output by LyX.
3142                         p.pushPosition();
3143                         bool output = true;
3144                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3145                                 if (t2.cat() == catBegin)
3146                                         break;
3147                                 if (t2.cat() != catEscape)
3148                                         continue;
3149                                 if (t2.cs() == "nocite") {
3150                                         if (p.getArg('{', '}') == "*")
3151                                                 continue;
3152                                 } else if (t2.cs() == "bibliography")
3153                                         output = false;
3154                                 break;
3155                         }
3156                         p.popPosition();
3157                         if (output) {
3158                                 handle_ert(os,
3159                                         "\\bibliographystyle{" + bibliographystyle + '}',
3160                                         context);
3161                         }
3162                 }
3163
3164                 else if (t.cs() == "bibliography") {
3165                         context.check_layout(os);
3166                         begin_command_inset(os, "bibtex", "bibtex");
3167                         if (!btprint.empty()) {
3168                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3169                                 // clear the string because the next BibTeX inset can be without the
3170                                 // \nocite{*} option
3171                                 btprint.clear();
3172                         }
3173                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3174                         // Do we have a bibliographystyle set?
3175                         if (!bibliographystyle.empty())
3176                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
3177                         end_inset(os);
3178                 }
3179
3180                 else if (t.cs() == "parbox")
3181                         parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3182
3183                 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3184                          t.cs() == "shadowbox" || t.cs() == "doublebox")
3185                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3186
3187                 else if (t.cs() == "framebox") {
3188                         string special = p.getFullOpt();
3189                         special += p.getOpt();
3190                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3191                 }
3192
3193                 //\makebox() is part of the picture environment and different from \makebox{}
3194                 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3195                 else if (t.cs() == "makebox") {
3196                         string arg = t.asInput();
3197                         if (p.next_token().character() == '(')
3198                                 //the syntax is: \makebox(x,y)[position]{content}
3199                                 arg += p.getFullParentheseArg();
3200                         else
3201                                 //the syntax is: \makebox[width][position]{content}
3202                                 arg += p.getFullOpt();
3203                         handle_ert(os, arg + p.getFullOpt(), context);
3204                 }
3205
3206                 else if (t.cs() == "smallskip" ||
3207                          t.cs() == "medskip" ||
3208                          t.cs() == "bigskip" ||
3209                          t.cs() == "vfill") {
3210                         context.check_layout(os);
3211                         begin_inset(os, "VSpace ");
3212                         os << t.cs();
3213                         end_inset(os);
3214                         skip_spaces_braces(p);
3215                 }
3216
3217                 else if (is_known(t.cs(), known_spaces)) {
3218                         char const * const * where = is_known(t.cs(), known_spaces);
3219                         context.check_layout(os);
3220                         begin_inset(os, "space ");
3221                         os << '\\' << known_coded_spaces[where - known_spaces]
3222                            << '\n';
3223                         end_inset(os);
3224                         // LaTeX swallows whitespace after all spaces except
3225                         // "\\,". We have to do that here, too, because LyX
3226                         // adds "{}" which would make the spaces significant.
3227                         if (t.cs() !=  ",")
3228                                 eat_whitespace(p, os, context, false);
3229                         // LyX adds "{}" after all spaces except "\\ " and
3230                         // "\\,", so we have to remove "{}".
3231                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
3232                         // remove the braces after "\\,", too.
3233                         if (t.cs() != " ")
3234                                 skip_braces(p);
3235                 }
3236
3237                 else if (t.cs() == "newpage" ||
3238                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
3239                          t.cs() == "clearpage" ||
3240                          t.cs() == "cleardoublepage") {
3241                         context.check_layout(os);
3242                         begin_inset(os, "Newpage ");
3243                         os << t.cs();
3244                         end_inset(os);
3245                         skip_spaces_braces(p);
3246                 }
3247
3248                 else if (t.cs() == "DeclareRobustCommand" ||
3249                          t.cs() == "DeclareRobustCommandx" ||
3250                          t.cs() == "newcommand" ||
3251                          t.cs() == "newcommandx" ||
3252                          t.cs() == "providecommand" ||
3253                          t.cs() == "providecommandx" ||
3254                          t.cs() == "renewcommand" ||
3255                          t.cs() == "renewcommandx") {
3256                         // DeclareRobustCommand, DeclareRobustCommandx,
3257                         // providecommand and providecommandx could be handled
3258                         // by parse_command(), but we need to call
3259                         // add_known_command() here.
3260                         string name = t.asInput();
3261                         if (p.next_token().asInput() == "*") {
3262                                 // Starred form. Eat '*'
3263                                 p.get_token();
3264                                 name += '*';
3265                         }
3266                         string const command = p.verbatim_item();
3267                         string const opt1 = p.getFullOpt();
3268                         string const opt2 = p.getFullOpt();
3269                         add_known_command(command, opt1, !opt2.empty());
3270                         string const ert = name + '{' + command + '}' +
3271                                            opt1 + opt2 +
3272                                            '{' + p.verbatim_item() + '}';
3273
3274                         if (t.cs() == "DeclareRobustCommand" ||
3275                             t.cs() == "DeclareRobustCommandx" ||
3276                             t.cs() == "providecommand" ||
3277                             t.cs() == "providecommandx" ||
3278                             name[name.length()-1] == '*')
3279                                 handle_ert(os, ert, context);
3280                         else {
3281                                 context.check_layout(os);
3282                                 begin_inset(os, "FormulaMacro");
3283                                 os << "\n" << ert;
3284                                 end_inset(os);
3285                         }
3286                 }
3287
3288                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3289                         // let could be handled by parse_command(),
3290                         // but we need to call add_known_command() here.
3291                         string ert = t.asInput();
3292                         string name;
3293                         p.skip_spaces();
3294                         if (p.next_token().cat() == catBegin) {
3295                                 name = p.verbatim_item();
3296                                 ert += '{' + name + '}';
3297                         } else {
3298                                 name = p.verbatim_item();
3299                                 ert += name;
3300                         }
3301                         string command;
3302                         p.skip_spaces();
3303                         if (p.next_token().cat() == catBegin) {
3304                                 command = p.verbatim_item();
3305                                 ert += '{' + command + '}';
3306                         } else {
3307                                 command = p.verbatim_item();
3308                                 ert += command;
3309                         }
3310                         // If command is known, make name known too, to parse
3311                         // its arguments correctly. For this reason we also
3312                         // have commands in syntax.default that are hardcoded.
3313                         CommandMap::iterator it = known_commands.find(command);
3314                         if (it != known_commands.end())
3315                                 known_commands[t.asInput()] = it->second;
3316                         handle_ert(os, ert, context);
3317                 }
3318
3319                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3320                         bool starred = false;
3321                         if (p.next_token().asInput() == "*") {
3322                                 p.get_token();
3323                                 starred = true;
3324                         }
3325                         string name = t.asInput();
3326                         string const length = p.verbatim_item();
3327                         string unit;
3328                         string valstring;
3329                         bool valid = splitLatexLength(length, valstring, unit);
3330                         bool known_hspace = false;
3331                         bool known_vspace = false;
3332                         bool known_unit = false;
3333                         double value;
3334                         if (valid) {
3335                                 istringstream iss(valstring);
3336                                 iss >> value;
3337                                 if (value == 1.0) {
3338                                         if (t.cs()[0] == 'h') {
3339                                                 if (unit == "\\fill") {
3340                                                         if (!starred) {
3341                                                                 unit = "";
3342                                                                 name = "\\hfill";
3343                                                         }
3344                                                         known_hspace = true;
3345                                                 }
3346                                         } else {
3347                                                 if (unit == "\\smallskipamount") {
3348                                                         unit = "smallskip";
3349                                                         known_vspace = true;
3350                                                 } else if (unit == "\\medskipamount") {
3351                                                         unit = "medskip";
3352                                                         known_vspace = true;
3353                                                 } else if (unit == "\\bigskipamount") {
3354                                                         unit = "bigskip";
3355                                                         known_vspace = true;
3356                                                 } else if (unit == "\\fill") {
3357                                                         unit = "vfill";
3358                                                         known_vspace = true;
3359                                                 }
3360                                         }
3361                                 }
3362                                 if (!known_hspace && !known_vspace) {
3363                                         switch (unitFromString(unit)) {
3364                                         case Length::SP:
3365                                         case Length::PT:
3366                                         case Length::BP:
3367                                         case Length::DD:
3368                                         case Length::MM:
3369                                         case Length::PC:
3370                                         case Length::CC:
3371                                         case Length::CM:
3372                                         case Length::IN:
3373                                         case Length::EX:
3374                                         case Length::EM:
3375                                         case Length::MU:
3376                                                 known_unit = true;
3377                                                 break;
3378                                         default:
3379                                                 break;
3380                                         }
3381                                 }
3382                         }
3383
3384                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3385                                 // Literal horizontal length or known variable
3386                                 context.check_layout(os);
3387                                 begin_inset(os, "space ");
3388                                 os << name;
3389                                 if (starred)
3390                                         os << '*';
3391                                 os << '{';
3392                                 if (known_hspace)
3393                                         os << unit;
3394                                 os << "}";
3395                                 if (known_unit && !known_hspace)
3396                                         os << "\n\\length "
3397                                            << translate_len(length);
3398                                 end_inset(os);
3399                         } else if (known_unit || known_vspace) {
3400                                 // Literal vertical length or known variable
3401                                 context.check_layout(os);
3402                                 begin_inset(os, "VSpace ");
3403                                 if (known_unit)
3404                                         os << value;
3405                                 os << unit;
3406                                 if (starred)
3407                                         os << '*';
3408                                 end_inset(os);
3409                         } else {
3410                                 // LyX can't handle other length variables in Inset VSpace/space
3411                                 if (starred)
3412                                         name += '*';
3413                                 if (valid) {
3414                                         if (value == 1.0)
3415                                                 handle_ert(os, name + '{' + unit + '}', context);
3416                                         else if (value == -1.0)
3417                                                 handle_ert(os, name + "{-" + unit + '}', context);
3418                                         else
3419                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
3420                                 } else
3421                                         handle_ert(os, name + '{' + length + '}', context);
3422                         }
3423                 }
3424
3425                 // The single '=' is meant here.
3426                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3427                         p.skip_spaces();
3428                         context.check_layout(os);
3429                         begin_inset(os, "Flex ");
3430                         os << to_utf8(newinsetlayout->name()) << '\n'
3431                            << "status collapsed\n";
3432                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3433                         end_inset(os);
3434                 }
3435
3436                 else {
3437                         // try to see whether the string is in unicodesymbols
3438                         // Only use text mode commands, since we are in text mode here,
3439                         // and math commands may be invalid (bug 6797)
3440                         docstring rem;
3441                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3442                                                                  rem, Encodings::TEXT_CMD);
3443                         if (!s.empty()) {
3444                                 if (!rem.empty())
3445                                         cerr << "When parsing " << t.cs() 
3446                                              << ", result is " << to_utf8(s)
3447                                              << "+" << to_utf8(rem) << endl;
3448                                 context.check_layout(os);
3449                                 os << to_utf8(s);
3450                                 skip_spaces_braces(p);
3451                         }
3452                         //cerr << "#: " << t << " mode: " << mode << endl;
3453                         // heuristic: read up to next non-nested space
3454                         /*
3455                         string s = t.asInput();
3456                         string z = p.verbatim_item();
3457                         while (p.good() && z != " " && z.size()) {
3458                                 //cerr << "read: " << z << endl;
3459                                 s += z;
3460                                 z = p.verbatim_item();
3461                         }
3462                         cerr << "found ERT: " << s << endl;
3463                         handle_ert(os, s + ' ', context);
3464                         */
3465                         else {
3466                                 string name = t.asInput();
3467                                 if (p.next_token().asInput() == "*") {
3468                                         // Starred commands like \vspace*{}
3469                                         p.get_token();  // Eat '*'
3470                                         name += '*';
3471                                 }
3472                                 if (!parse_command(name, p, os, outer, context))
3473                                         handle_ert(os, name, context);
3474                         }
3475                 }
3476
3477                 if (flags & FLAG_LEAVE) {
3478                         flags &= ~FLAG_LEAVE;
3479                         break;
3480                 }
3481         }
3482 }
3483
3484 // }])
3485
3486
3487 } // namespace lyx