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