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