]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
Fix bug #3016: tex2lyx fails to convert xfig figures to Xfig insets
[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)
45 {
46         Context newcontext(true, context.textclass);
47         newcontext.font = context.font;
48         parse_text(p, os, flags, outer, newcontext);
49         newcontext.check_end_layout(os);
50 }
51
52
53 namespace {
54
55 /// parses a paragraph snippet, useful for example for \\emph{...}
56 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
57                 Context & context)
58 {
59         Context newcontext(context);
60         // Don't inherit the paragraph-level extra stuff
61         newcontext.par_extra_stuff.clear();
62         parse_text(p, os, flags, outer, newcontext);
63         // Make sure that we don't create invalid .lyx files
64         context.need_layout = newcontext.need_layout;
65         context.need_end_layout = newcontext.need_end_layout;
66 }
67
68
69 /*!
70  * Thin wrapper around parse_text_snippet() using a string.
71  *
72  * We completely ignore \c context.need_layout and \c context.need_end_layout,
73  * because our return value is not used directly (otherwise the stream version
74  * of parse_text_snippet() could be used). That means that the caller needs
75  * to do layout management manually.
76  * This is intended to parse text that does not create any layout changes.
77  */
78 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
79                   Context & context)
80 {
81         Context newcontext(context);
82         newcontext.need_layout = false;
83         newcontext.need_end_layout = false;
84         newcontext.new_layout_allowed = false;
85         // Avoid warning by Context::~Context()
86         newcontext.par_extra_stuff.clear();
87         ostringstream os;
88         parse_text_snippet(p, os, flags, outer, newcontext);
89         return os.str();
90 }
91
92
93 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
94  "vpageref", "prettyref", "eqref", 0 };
95
96 /*!
97  * natbib commands.
98  * The starred forms are also known.
99  */
100 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
101 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
102 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
103
104 /*!
105  * jurabib commands.
106  * No starred form other than "cite*" known.
107  */
108 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
109 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
110 // jurabib commands not (yet) supported by LyX:
111 // "fullcite",
112 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
113 // "footciteauthor", "footciteyear", "footciteyearpar",
114 "citefield", "citetitle", "cite*", 0 };
115
116 /// LaTeX names for quotes
117 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
118 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
119 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
120 "guilsinglleft", "frq", "guilsinglright", 0};
121
122 /// the same as known_quotes with .lyx names
123 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
124 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
125 "gld", "grd", "gls", "ers", "fls",
126 "fls", "frs", "frs", 0};
127
128 /// LaTeX names for font sizes
129 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
130 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
131
132 /// the same as known_sizes with .lyx names plus a default entry
133 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
134 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
135
136 /// LaTeX 2.09 names for font families
137 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
138
139 /// LaTeX names for font families
140 char const * const known_font_families[] = { "rmfamily", "sffamily",
141 "ttfamily", 0};
142
143 /// the same as known_old_font_families and known_font_families with .lyx names
144 char const * const known_coded_font_families[] = { "roman", "sans",
145 "typewriter", 0};
146
147 /// LaTeX 2.09 names for font series
148 char const * const known_old_font_series[] = { "bf", 0};
149
150 /// LaTeX names for font series
151 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
152
153 /// the same as known_old_font_series and known_font_series with .lyx names
154 char const * const known_coded_font_series[] = { "bold", "medium", 0};
155
156 /// LaTeX 2.09 names for font shapes
157 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
158
159 /// LaTeX names for font shapes
160 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
161 "upshape", 0};
162
163 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
164 char const * const known_coded_font_shapes[] = { "italic", "slanted",
165 "smallcaps", "up", 0};
166
167 /*!
168  * Graphics file extensions known by the dvips driver of the graphics package.
169  * These extensions are used to complete the filename of an included
170  * graphics file if it does not contain an extension.
171  * The order must be the same that latex uses to find a file, because we
172  * will use the first extension that matches.
173  * This is only an approximation for the common cases. If we would want to
174  * do it right in all cases, we would need to know which graphics driver is
175  * used and know the extensions of every driver of the graphics package.
176  */
177 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
178 "ps.gz", "eps.Z", "ps.Z", 0};
179
180 /*!
181  * Graphics file extensions known by the pdftex driver of the graphics package.
182  * \sa known_dvips_graphics_formats
183  */
184 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
185 "mps", "tif", 0};
186
187 /*!
188  * Known file extensions for TeX files as used by \\include.
189  */
190 char const * const known_tex_extensions[] = {"tex", 0};
191
192 /// spaces known by InsetSpace
193 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
194 "qquad", "enspace", "enskip", "negthinspace", 0};
195
196 /// the same as known_spaces with .lyx names
197 char const * const known_coded_spaces[] = { "space{}", "space{}",
198 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
199 "negthinspace{}", 0};
200
201
202 /// splits "x=z, y=b" into a map
203 map<string, string> split_map(string const & s)
204 {
205         map<string, string> res;
206         vector<string> v;
207         split(s, v);
208         for (size_t i = 0; i < v.size(); ++i) {
209                 size_t const pos   = v[i].find('=');
210                 string const index = v[i].substr(0, pos);
211                 string const value = v[i].substr(pos + 1, string::npos);
212                 res[trim(index)] = trim(value);
213         }
214         return res;
215 }
216
217
218 /*!
219  * Split a LaTeX length into value and unit.
220  * The latter can be a real unit like "pt", or a latex length variable
221  * like "\textwidth". The unit may contain additional stuff like glue
222  * lengths, but we don't care, because such lengths are ERT anyway.
223  * \returns true if \p value and \p unit are valid.
224  */
225 bool splitLatexLength(string const & len, string & value, string & unit)
226 {
227         if (len.empty())
228                 return false;
229         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
230         //'4,5' is a valid LaTeX length number. Change it to '4.5'
231         string const length = subst(len, ',', '.');
232         if (i == string::npos)
233                 return false;
234         if (i == 0) {
235                 if (len[0] == '\\') {
236                         // We had something like \textwidth without a factor
237                         value = "1.0";
238                 } else {
239                         return false;
240                 }
241         } else {
242                 value = trim(string(length, 0, i));
243         }
244         if (value == "-")
245                 value = "-1.0";
246         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
247         if (contains(len, '\\'))
248                 unit = trim(string(len, i));
249         else
250                 unit = ascii_lowercase(trim(string(len, i)));
251         return true;
252 }
253
254
255 /// A simple function to translate a latex length to something LyX can
256 /// understand. Not perfect, but rather best-effort.
257 bool translate_len(string const & length, string & valstring, string & unit)
258 {
259         if (!splitLatexLength(length, valstring, unit))
260                 return false;
261         // LyX uses percent values
262         double value;
263         istringstream iss(valstring);
264         iss >> value;
265         value *= 100;
266         ostringstream oss;
267         oss << value;
268         string const percentval = oss.str();
269         // a normal length
270         if (unit.empty() || unit[0] != '\\')
271                 return true;
272         string::size_type const i = unit.find(' ');
273         string const endlen = (i == string::npos) ? string() : string(unit, i);
274         if (unit == "\\textwidth") {
275                 valstring = percentval;
276                 unit = "text%" + endlen;
277         } else if (unit == "\\columnwidth") {
278                 valstring = percentval;
279                 unit = "col%" + endlen;
280         } else if (unit == "\\paperwidth") {
281                 valstring = percentval;
282                 unit = "page%" + endlen;
283         } else if (unit == "\\linewidth") {
284                 valstring = percentval;
285                 unit = "line%" + endlen;
286         } else if (unit == "\\paperheight") {
287                 valstring = percentval;
288                 unit = "pheight%" + endlen;
289         } else if (unit == "\\textheight") {
290                 valstring = percentval;
291                 unit = "theight%" + endlen;
292         }
293         return true;
294 }
295
296 }
297
298
299 string translate_len(string const & length)
300 {
301         string unit;
302         string value;
303         if (translate_len(length, value, unit))
304                 return value + unit;
305         // If the input is invalid, return what we have.
306         return length;
307 }
308
309
310 namespace {
311
312 /*!
313  * Translates a LaTeX length into \p value, \p unit and
314  * \p special parts suitable for a box inset.
315  * The difference from translate_len() is that a box inset knows about
316  * some special "units" that are stored in \p special.
317  */
318 void translate_box_len(string const & length, string & value, string & unit, string & special)
319 {
320         if (translate_len(length, value, unit)) {
321                 if (unit == "\\height" || unit == "\\depth" ||
322                     unit == "\\totalheight" || unit == "\\width") {
323                         special = unit.substr(1);
324                         // The unit is not used, but LyX requires a dummy setting
325                         unit = "in";
326                 } else
327                         special = "none";
328         } else {
329                 value.clear();
330                 unit = length;
331                 special = "none";
332         }
333 }
334
335
336 /*!
337  * Find a file with basename \p name in path \p path and an extension
338  * in \p extensions.
339  */
340 string find_file(string const & name, string const & path,
341                  char const * const * extensions)
342 {
343         for (char const * const * what = extensions; *what; ++what) {
344                 string const trial = addExtension(name, *what);
345                 if (makeAbsPath(trial, path).exists())
346                         return trial;
347         }
348         return string();
349 }
350
351
352 void begin_inset(ostream & os, string const & name)
353 {
354         os << "\n\\begin_inset " << name;
355 }
356
357 /*// use this void when format 288 is supported
358 void begin_command_inset(ostream & os, string const & name,
359                                                  string const & latexname)
360 {
361         os << "\n\\begin_inset CommandInset " << name;
362         os << "\nLatexCommand " << latexname << "\n";
363 }*/
364
365
366 void end_inset(ostream & os)
367 {
368         os << "\n\\end_inset\n\n";
369 }
370
371
372 void skip_braces(Parser & p)
373 {
374         if (p.next_token().cat() != catBegin)
375                 return;
376         p.get_token();
377         if (p.next_token().cat() == catEnd) {
378                 p.get_token();
379                 return;
380         }
381         p.putback();
382 }
383
384
385 void handle_ert(ostream & os, string const & s, Context & context)
386 {
387         // We must have a valid layout before outputting the ERT inset.
388         context.check_layout(os);
389         Context newcontext(true, context.textclass);
390         begin_inset(os, "ERT");
391         os << "\nstatus collapsed\n";
392         newcontext.check_layout(os);
393         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
394                 if (*it == '\\')
395                         os << "\n\\backslash\n";
396                 else if (*it == '\n') {
397                         newcontext.new_paragraph(os);
398                         newcontext.check_layout(os);
399                 } else
400                         os << *it;
401         }
402         newcontext.check_end_layout(os);
403         end_inset(os);
404 }
405
406
407 void handle_comment(ostream & os, string const & s, Context & context)
408 {
409         // TODO: Handle this better
410         Context newcontext(true, context.textclass);
411         begin_inset(os, "ERT");
412         os << "\nstatus collapsed\n";
413         newcontext.check_layout(os);
414         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
415                 if (*it == '\\')
416                         os << "\n\\backslash\n";
417                 else
418                         os << *it;
419         }
420         // make sure that our comment is the last thing on the line
421         newcontext.new_paragraph(os);
422         newcontext.check_layout(os);
423         newcontext.check_end_layout(os);
424         end_inset(os);
425 }
426
427
428 Layout const * findLayout(TextClass const & textclass, string const & name)
429 {
430         DocumentClass::const_iterator lit = textclass.begin();
431         DocumentClass::const_iterator len = textclass.end();
432         for (; lit != len; ++lit)
433                 if (lit->latexname() == name)
434                         return &*lit;
435         return 0;
436 }
437
438
439 void eat_whitespace(Parser &, ostream &, Context &, bool);
440
441
442 void output_command_layout(ostream & os, Parser & p, bool outer,
443                            Context & parent_context,
444                            Layout const * newlayout)
445 {
446         parent_context.check_end_layout(os);
447         Context context(true, parent_context.textclass, newlayout,
448                         parent_context.layout, parent_context.font);
449         if (parent_context.deeper_paragraph) {
450                 // We are beginning a nested environment after a
451                 // deeper paragraph inside the outer list environment.
452                 // Therefore we don't need to output a "begin deeper".
453                 context.need_end_deeper = true;
454         }
455         context.check_deeper(os);
456         context.check_layout(os);
457         unsigned int optargs = 0;
458         while (optargs < context.layout->optargs) {
459                 eat_whitespace(p, os, context, false);
460                 if (p.next_token().character() != '[') 
461                         break;
462                 p.get_token(); // eat '['
463                 begin_inset(os, "OptArg\n");
464                 os << "status collapsed\n\n";
465                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
466                 end_inset(os);
467                 eat_whitespace(p, os, context, false);
468                 ++optargs;
469         }
470 #if 0
471         // This is the code needed to parse required arguments, but 
472         // required arguments come into being only much later than the
473         // file format tex2lyx is presently outputting.
474         unsigned int reqargs = 0;
475         while (reqargs < context.layout->reqargs) {
476                 eat_whitespace(p, os, context, false);
477                 if (p.next_token().character() != '{') 
478                         break;
479                 p.get_token(); // eat '{'
480                 begin_inset(os, "OptArg\n");
481                 os << "status collapsed\n\n";
482                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
483                 end_inset(os);
484                 eat_whitespace(p, os, context, false);
485                 ++reqargs;
486         }
487 #endif
488         parse_text(p, os, FLAG_ITEM, outer, context);
489         context.check_end_layout(os);
490         if (parent_context.deeper_paragraph) {
491                 // We must suppress the "end deeper" because we
492                 // suppressed the "begin deeper" above.
493                 context.need_end_deeper = false;
494         }
495         context.check_end_deeper(os);
496         // We don't need really a new paragraph, but
497         // we must make sure that the next item gets a \begin_layout.
498         parent_context.new_paragraph(os);
499 }
500
501
502 /*!
503  * Output a space if necessary.
504  * This function gets called for every whitespace token.
505  *
506  * We have three cases here:
507  * 1. A space must be suppressed. Example: The lyxcode case below
508  * 2. A space may be suppressed. Example: Spaces before "\par"
509  * 3. A space must not be suppressed. Example: A space between two words
510  *
511  * We currently handle only 1. and 3 and from 2. only the case of
512  * spaces before newlines as a side effect.
513  *
514  * 2. could be used to suppress as many spaces as possible. This has two effects:
515  * - Reimporting LyX generated LaTeX files changes almost no whitespace
516  * - Superflous whitespace from non LyX generated LaTeX files is removed.
517  * The drawback is that the logic inside the function becomes
518  * complicated, and that is the reason why it is not implemented.
519  */
520 void check_space(Parser & p, ostream & os, Context & context)
521 {
522         Token const next = p.next_token();
523         Token const curr = p.curr_token();
524         // A space before a single newline and vice versa must be ignored
525         // LyX emits a newline before \end{lyxcode}.
526         // This newline must be ignored,
527         // otherwise LyX will add an additional protected space.
528         if (next.cat() == catSpace ||
529             next.cat() == catNewline ||
530             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
531                 return;
532         }
533         context.check_layout(os);
534         os << ' ';
535 }
536
537
538 /*!
539  * Parse all arguments of \p command
540  */
541 void parse_arguments(string const & command,
542                      vector<ArgumentType> const & template_arguments,
543                      Parser & p, ostream & os, bool outer, Context & context)
544 {
545         string ert = command;
546         size_t no_arguments = template_arguments.size();
547         for (size_t i = 0; i < no_arguments; ++i) {
548                 switch (template_arguments[i]) {
549                 case required:
550                         // This argument contains regular LaTeX
551                         handle_ert(os, ert + '{', context);
552                         eat_whitespace(p, os, context, false);
553                         parse_text(p, os, FLAG_ITEM, outer, context);
554                         ert = "}";
555                         break;
556                 case verbatim:
557                         // This argument may contain special characters
558                         ert += '{' + p.verbatim_item() + '}';
559                         break;
560                 case optional:
561                         ert += p.getOpt();
562                         break;
563                 }
564         }
565         handle_ert(os, ert, context);
566 }
567
568
569 /*!
570  * Check whether \p command is a known command. If yes,
571  * handle the command with all arguments.
572  * \return true if the command was parsed, false otherwise.
573  */
574 bool parse_command(string const & command, Parser & p, ostream & os,
575                    bool outer, Context & context)
576 {
577         if (known_commands.find(command) != known_commands.end()) {
578                 parse_arguments(command, known_commands[command], p, os,
579                                 outer, context);
580                 return true;
581         }
582         return false;
583 }
584
585
586 /// Parses a minipage or parbox
587 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
588                Context & parent_context, bool use_parbox)
589 {
590         string position;
591         string inner_pos;
592         // We need to set the height to the LaTeX default of 1\\totalheight
593         // for the case when no height argument is given
594         string height_value = "1";
595         string height_unit = "in";
596         string height_special = "totalheight";
597         string latex_height;
598         if (p.next_token().asInput() == "[") {
599                 position = p.getArg('[', ']');
600                 if (position != "t" && position != "c" && position != "b") {
601                         position = "c";
602                         cerr << "invalid position for minipage/parbox" << endl;
603                 }
604                 if (p.next_token().asInput() == "[") {
605                         latex_height = p.getArg('[', ']');
606                         translate_box_len(latex_height, height_value, height_unit, height_special);
607
608                         if (p.next_token().asInput() == "[") {
609                                 inner_pos = p.getArg('[', ']');
610                                 if (inner_pos != "c" && inner_pos != "t" &&
611                                     inner_pos != "b" && inner_pos != "s") {
612                                         inner_pos = position;
613                                         cerr << "invalid inner_pos for minipage/parbox"
614                                              << endl;
615                                 }
616                         }
617                 }
618         }
619         string width_value;
620         string width_unit;
621         string const latex_width = p.verbatim_item();
622         translate_len(latex_width, width_value, width_unit);
623         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
624                 // LyX can't handle length variables
625                 ostringstream ss;
626                 if (use_parbox)
627                         ss << "\\parbox";
628                 else
629                         ss << "\\begin{minipage}";
630                 if (!position.empty())
631                         ss << '[' << position << ']';
632                 if (!latex_height.empty())
633                         ss << '[' << latex_height << ']';
634                 if (!inner_pos.empty())
635                         ss << '[' << inner_pos << ']';
636                 ss << "{" << latex_width << "}";
637                 if (use_parbox)
638                         ss << '{';
639                 handle_ert(os, ss.str(), parent_context);
640                 parent_context.new_paragraph(os);
641                 parse_text_in_inset(p, os, flags, outer, parent_context);
642                 if (use_parbox)
643                         handle_ert(os, "}", parent_context);
644                 else
645                         handle_ert(os, "\\end{minipage}", parent_context);
646         } else {
647                 // LyX does not like empty positions, so we have
648                 // to set them to the LaTeX default values here.
649                 if (position.empty())
650                         position = "c";
651                 if (inner_pos.empty())
652                         inner_pos = position;
653                 parent_context.check_layout(os);
654                 begin_inset(os, "Box Frameless\n");
655                 os << "position \"" << position << "\"\n";
656                 os << "hor_pos \"c\"\n";
657                 os << "has_inner_box 1\n";
658                 os << "inner_pos \"" << inner_pos << "\"\n";
659                 os << "use_parbox " << use_parbox << "\n";
660                 os << "width \"" << width_value << width_unit << "\"\n";
661                 os << "special \"none\"\n";
662                 os << "height \"" << height_value << height_unit << "\"\n";
663                 os << "height_special \"" << height_special << "\"\n";
664                 os << "status open\n\n";
665                 parse_text_in_inset(p, os, flags, outer, parent_context);
666                 end_inset(os);
667 #ifdef PRESERVE_LAYOUT
668                 // LyX puts a % after the end of the minipage
669                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
670                         // new paragraph
671                         //handle_comment(os, "%dummy", parent_context);
672                         p.get_token();
673                         p.skip_spaces();
674                         parent_context.new_paragraph(os);
675                 }
676                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
677                         //handle_comment(os, "%dummy", parent_context);
678                         p.get_token();
679                         p.skip_spaces();
680                         // We add a protected space if something real follows
681                         if (p.good() && p.next_token().cat() != catComment) {
682                                 os << "\\InsetSpace ~\n";
683                         }
684                 }
685 #endif
686         }
687 }
688
689
690 /// parse an unknown environment
691 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
692                                unsigned flags, bool outer,
693                                Context & parent_context)
694 {
695         if (name == "tabbing")
696                 // We need to remember that we have to handle '\=' specially
697                 flags |= FLAG_TABBING;
698
699         // We need to translate font changes and paragraphs inside the
700         // environment to ERT if we have a non standard font.
701         // Otherwise things like
702         // \large\begin{foo}\huge bar\end{foo}
703         // will not work.
704         bool const specialfont =
705                 (parent_context.font != parent_context.normalfont);
706         bool const new_layout_allowed = parent_context.new_layout_allowed;
707         if (specialfont)
708                 parent_context.new_layout_allowed = false;
709         handle_ert(os, "\\begin{" + name + "}", parent_context);
710         parse_text_snippet(p, os, flags, outer, parent_context);
711         handle_ert(os, "\\end{" + name + "}", parent_context);
712         if (specialfont)
713                 parent_context.new_layout_allowed = new_layout_allowed;
714 }
715
716
717 void parse_environment(Parser & p, ostream & os, bool outer,
718                        Context & parent_context)
719 {
720         Layout const * newlayout;
721         string const name = p.getArg('{', '}');
722         const bool is_starred = suffixIs(name, '*');
723         string const unstarred_name = rtrim(name, "*");
724         active_environments.push_back(name);
725
726         if (is_math_env(name)) {
727                 parent_context.check_layout(os);
728                 begin_inset(os, "Formula ");
729                 os << "\\begin{" << name << "}";
730                 parse_math(p, os, FLAG_END, MATH_MODE);
731                 os << "\\end{" << name << "}";
732                 end_inset(os);
733         }
734
735         else if (name == "tabular" || name == "longtable") {
736                 eat_whitespace(p, os, parent_context, false);
737                 parent_context.check_layout(os);
738                 begin_inset(os, "Tabular ");
739                 handle_tabular(p, os, name == "longtable", parent_context);
740                 end_inset(os);
741                 p.skip_spaces();
742         }
743
744         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
745                 eat_whitespace(p, os, parent_context, false);
746                 parent_context.check_layout(os);
747                 begin_inset(os, "Float " + unstarred_name + "\n");
748                 if (p.next_token().asInput() == "[") {
749                         os << "placement " << p.getArg('[', ']') << '\n';
750                 }
751                 os << "wide " << convert<string>(is_starred)
752                    << "\nsideways false"
753                    << "\nstatus open\n\n";
754                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
755                 end_inset(os);
756                 // We don't need really a new paragraph, but
757                 // we must make sure that the next item gets a \begin_layout.
758                 parent_context.new_paragraph(os);
759                 p.skip_spaces();
760         }
761
762         else if (name == "minipage") {
763                 eat_whitespace(p, os, parent_context, false);
764                 parse_box(p, os, FLAG_END, outer, parent_context, false);
765                 p.skip_spaces();
766         }
767
768         else if (name == "comment") {
769                 eat_whitespace(p, os, parent_context, false);
770                 parent_context.check_layout(os);
771                 begin_inset(os, "Note Comment\n");
772                 os << "status open\n";
773                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
774                 end_inset(os);
775                 p.skip_spaces();
776                 skip_braces(p); // eat {} that might by set by LyX behind comments
777         }
778
779         else if (name == "lyxgreyedout") {
780                 eat_whitespace(p, os, parent_context, false);
781                 parent_context.check_layout(os);
782                 begin_inset(os, "Note Greyedout\n");
783                 os << "status open\n";
784                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
785                 end_inset(os);
786                 p.skip_spaces();
787         }
788
789         else if (name == "framed") {
790                 eat_whitespace(p, os, parent_context, false);
791                 parent_context.check_layout(os);
792                 begin_inset(os, "Note Framed\n");
793                 os << "status open\n";
794                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
795                 end_inset(os);
796                 p.skip_spaces();
797         }
798
799         else if (name == "shaded") {
800                 eat_whitespace(p, os, parent_context, false);
801                 parent_context.check_layout(os);
802                 begin_inset(os, "Note Shaded\n");
803                 os << "status open\n";
804                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
805                 end_inset(os);
806                 p.skip_spaces();
807         }
808
809         else if (!parent_context.new_layout_allowed)
810                 parse_unknown_environment(p, name, os, FLAG_END, outer,
811                                           parent_context);
812
813         // Alignment and spacing settings
814         // FIXME (bug xxxx): These settings can span multiple paragraphs and
815         //                                       therefore are totally broken!
816         // Note that \centering, raggedright, and raggedleft cannot be handled, as
817         // they are commands not environments. They are furthermore switches that
818         // can be ended by another switches, but also by commands like \footnote or
819         // \parbox. So the only safe way is to leave them untouched.
820         else if (name == "center" || name == "centering" ||
821                  name == "flushleft" || name == "flushright" ||
822                  name == "singlespace" || name == "onehalfspace" ||
823                  name == "doublespace" || name == "spacing") {
824                 eat_whitespace(p, os, parent_context, false);
825                 // We must begin a new paragraph if not already done
826                 if (! parent_context.atParagraphStart()) {
827                         parent_context.check_end_layout(os);
828                         parent_context.new_paragraph(os);
829                 }
830                 if (name == "flushleft")
831                         parent_context.add_extra_stuff("\\align left\n");
832                 else if (name == "flushright")
833                         parent_context.add_extra_stuff("\\align right\n");
834                 else if (name == "center" || name == "centering")
835                         parent_context.add_extra_stuff("\\align center\n");
836                 else if (name == "singlespace")
837                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
838                 else if (name == "onehalfspace")
839                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
840                 else if (name == "doublespace")
841                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
842                 else if (name == "spacing")
843                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
844                 parse_text(p, os, FLAG_END, outer, parent_context);
845                 // Just in case the environment is empty
846                 parent_context.extra_stuff.erase();
847                 // We must begin a new paragraph to reset the alignment
848                 parent_context.new_paragraph(os);
849                 p.skip_spaces();
850         }
851
852         // The single '=' is meant here.
853         else if ((newlayout = findLayout(parent_context.textclass, name)) &&
854                   newlayout->isEnvironment()) {
855                 eat_whitespace(p, os, parent_context, false);
856                 Context context(true, parent_context.textclass, newlayout,
857                                 parent_context.layout, parent_context.font);
858                 if (parent_context.deeper_paragraph) {
859                         // We are beginning a nested environment after a
860                         // deeper paragraph inside the outer list environment.
861                         // Therefore we don't need to output a "begin deeper".
862                         context.need_end_deeper = true;
863                 }
864                 parent_context.check_end_layout(os);
865                 switch (context.layout->latextype) {
866                 case  LATEX_LIST_ENVIRONMENT:
867                         context.add_par_extra_stuff("\\labelwidthstring "
868                                                     + p.verbatim_item() + '\n');
869                         p.skip_spaces();
870                         break;
871                 case  LATEX_BIB_ENVIRONMENT:
872                         p.verbatim_item(); // swallow next arg
873                         p.skip_spaces();
874                         break;
875                 default:
876                         break;
877                 }
878                 context.check_deeper(os);
879                 parse_text(p, os, FLAG_END, outer, context);
880                 context.check_end_layout(os);
881                 if (parent_context.deeper_paragraph) {
882                         // We must suppress the "end deeper" because we
883                         // suppressed the "begin deeper" above.
884                         context.need_end_deeper = false;
885                 }
886                 context.check_end_deeper(os);
887                 parent_context.new_paragraph(os);
888                 p.skip_spaces();
889         }
890
891         else if (name == "appendix") {
892                 // This is no good latex style, but it works and is used in some documents...
893                 eat_whitespace(p, os, parent_context, false);
894                 parent_context.check_end_layout(os);
895                 Context context(true, parent_context.textclass, parent_context.layout,
896                                 parent_context.layout, parent_context.font);
897                 context.check_layout(os);
898                 os << "\\start_of_appendix\n";
899                 parse_text(p, os, FLAG_END, outer, context);
900                 context.check_end_layout(os);
901                 p.skip_spaces();
902         }
903
904         else if (known_environments.find(name) != known_environments.end()) {
905                 vector<ArgumentType> arguments = known_environments[name];
906                 // The last "argument" denotes wether we may translate the
907                 // environment contents to LyX
908                 // The default required if no argument is given makes us
909                 // compatible with the reLyXre environment.
910                 ArgumentType contents = arguments.empty() ?
911                         required :
912                         arguments.back();
913                 if (!arguments.empty())
914                         arguments.pop_back();
915                 // See comment in parse_unknown_environment()
916                 bool const specialfont =
917                         (parent_context.font != parent_context.normalfont);
918                 bool const new_layout_allowed =
919                         parent_context.new_layout_allowed;
920                 if (specialfont)
921                         parent_context.new_layout_allowed = false;
922                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
923                                 outer, parent_context);
924                 if (contents == verbatim)
925                         handle_ert(os, p.verbatimEnvironment(name),
926                                    parent_context);
927                 else
928                         parse_text_snippet(p, os, FLAG_END, outer,
929                                            parent_context);
930                 handle_ert(os, "\\end{" + name + "}", parent_context);
931                 if (specialfont)
932                         parent_context.new_layout_allowed = new_layout_allowed;
933         }
934
935         else
936                 parse_unknown_environment(p, name, os, FLAG_END, outer,
937                                           parent_context);
938
939         active_environments.pop_back();
940 }
941
942
943 /// parses a comment and outputs it to \p os.
944 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
945 {
946         LASSERT(t.cat() == catComment, return);
947         if (!t.cs().empty()) {
948                 context.check_layout(os);
949                 handle_comment(os, '%' + t.cs(), context);
950                 if (p.next_token().cat() == catNewline) {
951                         // A newline after a comment line starts a new
952                         // paragraph
953                         if (context.new_layout_allowed) {
954                                 if(!context.atParagraphStart())
955                                         // Only start a new paragraph if not already
956                                         // done (we might get called recursively)
957                                         context.new_paragraph(os);
958                         } else
959                                 handle_ert(os, "\n", context);
960                         eat_whitespace(p, os, context, true);
961                 }
962         } else {
963                 // "%\n" combination
964                 p.skip_spaces();
965         }
966 }
967
968
969 /*!
970  * Reads spaces and comments until the first non-space, non-comment token.
971  * New paragraphs (double newlines or \\par) are handled like simple spaces
972  * if \p eatParagraph is true.
973  * Spaces are skipped, but comments are written to \p os.
974  */
975 void eat_whitespace(Parser & p, ostream & os, Context & context,
976                     bool eatParagraph)
977 {
978         while (p.good()) {
979                 Token const & t = p.get_token();
980                 if (t.cat() == catComment)
981                         parse_comment(p, os, t, context);
982                 else if ((! eatParagraph && p.isParagraph()) ||
983                          (t.cat() != catSpace && t.cat() != catNewline)) {
984                         p.putback();
985                         return;
986                 }
987         }
988 }
989
990
991 /*!
992  * Set a font attribute, parse text and reset the font attribute.
993  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
994  * \param currentvalue Current value of the attribute. Is set to the new
995  * value during parsing.
996  * \param newvalue New value of the attribute
997  */
998 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
999                            Context & context, string const & attribute,
1000                            string & currentvalue, string const & newvalue)
1001 {
1002         context.check_layout(os);
1003         string const oldvalue = currentvalue;
1004         currentvalue = newvalue;
1005         os << '\n' << attribute << ' ' << newvalue << "\n";
1006         parse_text_snippet(p, os, flags, outer, context);
1007         context.check_layout(os);
1008         os << '\n' << attribute << ' ' << oldvalue << "\n";
1009         currentvalue = oldvalue;
1010 }
1011
1012
1013 /// get the arguments of a natbib or jurabib citation command
1014 void get_cite_arguments(Parser & p, bool natbibOrder,
1015         string & before, string & after)
1016 {
1017         // We need to distinguish "" and "[]", so we can't use p.getOpt().
1018
1019         // text before the citation
1020         before.clear();
1021         // text after the citation
1022         after = p.getFullOpt();
1023
1024         if (!after.empty()) {
1025                 before = p.getFullOpt();
1026                 if (natbibOrder && !before.empty())
1027                         swap(before, after);
1028         }
1029 }
1030
1031
1032 /// Convert filenames with TeX macros and/or quotes to something LyX
1033 /// can understand
1034 string const normalize_filename(string const & name)
1035 {
1036         Parser p(trim(name, "\""));
1037         ostringstream os;
1038         while (p.good()) {
1039                 Token const & t = p.get_token();
1040                 if (t.cat() != catEscape)
1041                         os << t.asInput();
1042                 else if (t.cs() == "lyxdot") {
1043                         // This is used by LyX for simple dots in relative
1044                         // names
1045                         os << '.';
1046                         p.skip_spaces();
1047                 } else if (t.cs() == "space") {
1048                         os << ' ';
1049                         p.skip_spaces();
1050                 } else
1051                         os << t.asInput();
1052         }
1053         return os.str();
1054 }
1055
1056
1057 /// Convert \p name from TeX convention (relative to master file) to LyX
1058 /// convention (relative to .lyx file) if it is relative
1059 void fix_relative_filename(string & name)
1060 {
1061         if (FileName::isAbsolute(name))
1062                 return;
1063
1064         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1065                                    from_utf8(getParentFilePath())));
1066 }
1067
1068
1069 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1070 void parse_noweb(Parser & p, ostream & os, Context & context)
1071 {
1072         // assemble the rest of the keyword
1073         string name("<<");
1074         bool scrap = false;
1075         while (p.good()) {
1076                 Token const & t = p.get_token();
1077                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1078                         name += ">>";
1079                         p.get_token();
1080                         scrap = (p.good() && p.next_token().asInput() == "=");
1081                         if (scrap)
1082                                 name += p.get_token().asInput();
1083                         break;
1084                 }
1085                 name += t.asInput();
1086         }
1087
1088         if (!scrap || !context.new_layout_allowed ||
1089             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1090                 cerr << "Warning: Could not interpret '" << name
1091                      << "'. Ignoring it." << endl;
1092                 return;
1093         }
1094
1095         // We use new_paragraph instead of check_end_layout because the stuff
1096         // following the noweb chunk needs to start with a \begin_layout.
1097         // This may create a new paragraph even if there was none in the
1098         // noweb file, but the alternative is an invalid LyX file. Since
1099         // noweb code chunks are implemented with a layout style in LyX they
1100         // always must be in an own paragraph.
1101         context.new_paragraph(os);
1102         Context newcontext(true, context.textclass,
1103                 &context.textclass[from_ascii("Scrap")]);
1104         newcontext.check_layout(os);
1105         os << name;
1106         while (p.good()) {
1107                 Token const & t = p.get_token();
1108                 // We abuse the parser a bit, because this is no TeX syntax
1109                 // at all.
1110                 if (t.cat() == catEscape)
1111                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1112                 else
1113                         os << subst(t.asInput(), "\n", "\n\\newline\n");
1114                 // The scrap chunk is ended by an @ at the beginning of a line.
1115                 // After the @ the line may contain a comment and/or
1116                 // whitespace, but nothing else.
1117                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1118                     (p.next_token().cat() == catSpace ||
1119                      p.next_token().cat() == catNewline ||
1120                      p.next_token().cat() == catComment)) {
1121                         while (p.good() && p.next_token().cat() == catSpace)
1122                                 os << p.get_token().asInput();
1123                         if (p.next_token().cat() == catComment)
1124                                 // The comment includes a final '\n'
1125                                 os << p.get_token().asInput();
1126                         else {
1127                                 if (p.next_token().cat() == catNewline)
1128                                         p.get_token();
1129                                 os << '\n';
1130                         }
1131                         break;
1132                 }
1133         }
1134         newcontext.check_end_layout(os);
1135 }
1136
1137 } // anonymous namespace
1138
1139
1140 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1141                 Context & context)
1142 {
1143         Layout const * newlayout = 0;
1144         // Store the latest bibliographystyle (needed for bibtex inset)
1145         string bibliographystyle;
1146         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1147         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1148         while (p.good()) {
1149                 Token const & t = p.get_token();
1150
1151 #ifdef FILEDEBUG
1152                 cerr << "t: " << t << " flags: " << flags << "\n";
1153 #endif
1154
1155                 if (flags & FLAG_ITEM) {
1156                         if (t.cat() == catSpace)
1157                                 continue;
1158
1159                         flags &= ~FLAG_ITEM;
1160                         if (t.cat() == catBegin) {
1161                                 // skip the brace and collect everything to the next matching
1162                                 // closing brace
1163                                 flags |= FLAG_BRACE_LAST;
1164                                 continue;
1165                         }
1166
1167                         // handle only this single token, leave the loop if done
1168                         flags |= FLAG_LEAVE;
1169                 }
1170
1171                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1172                         return;
1173                 if (t.character() == '}' && (flags & FLAG_BRACE_LAST))
1174                         return;
1175
1176                 //
1177                 // cat codes
1178                 //
1179                 if (t.cat() == catMath) {
1180                         // we are inside some text mode thingy, so opening new math is allowed
1181                         context.check_layout(os);
1182                         begin_inset(os, "Formula ");
1183                         Token const & n = p.get_token();
1184                         if (n.cat() == catMath && outer) {
1185                                 // TeX's $$...$$ syntax for displayed math
1186                                 os << "\\[";
1187                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1188                                 os << "\\]";
1189                                 p.get_token(); // skip the second '$' token
1190                         } else {
1191                                 // simple $...$  stuff
1192                                 p.putback();
1193                                 os << '$';
1194                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1195                                 os << '$';
1196                         }
1197                         end_inset(os);
1198                 }
1199
1200                 else if (t.cat() == catSuper || t.cat() == catSub)
1201                         cerr << "catcode " << t << " illegal in text mode\n";
1202
1203                 // Basic support for english quotes. This should be
1204                 // extended to other quotes, but is not so easy (a
1205                 // left english quote is the same as a right german
1206                 // quote...)
1207                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1208                         context.check_layout(os);
1209                         begin_inset(os, "Quotes ");
1210                         os << "eld";
1211                         end_inset(os);
1212                         p.get_token();
1213                         skip_braces(p);
1214                 }
1215                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1216                         context.check_layout(os);
1217                         begin_inset(os, "Quotes ");
1218                         os << "erd";
1219                         end_inset(os);
1220                         p.get_token();
1221                         skip_braces(p);
1222                 }
1223
1224                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1225                         context.check_layout(os);
1226                         begin_inset(os, "Quotes ");
1227                         os << "ald";
1228                         end_inset(os);
1229                         p.get_token();
1230                         skip_braces(p);
1231                 }
1232
1233                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1234                         context.check_layout(os);
1235                         begin_inset(os, "Quotes ");
1236                         os << "ard";
1237                         end_inset(os);
1238                         p.get_token();
1239                         skip_braces(p);
1240                 }
1241
1242                 else if (t.asInput() == "<"
1243                          && p.next_token().asInput() == "<" && noweb_mode) {
1244                         p.get_token();
1245                         parse_noweb(p, os, context);
1246                 }
1247
1248                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1249                         check_space(p, os, context);
1250
1251                 else if (t.character() == '[' && noweb_mode &&
1252                          p.next_token().character() == '[') {
1253                         // These can contain underscores
1254                         p.putback();
1255                         string const s = p.getFullOpt() + ']';
1256                         if (p.next_token().character() == ']')
1257                                 p.get_token();
1258                         else
1259                                 cerr << "Warning: Inserting missing ']' in '"
1260                                      << s << "'." << endl;
1261                         handle_ert(os, s, context);
1262                 }
1263
1264                 else if (t.cat() == catLetter ||
1265                                t.cat() == catOther ||
1266                                t.cat() == catAlign ||
1267                                t.cat() == catParameter) {
1268                         // This translates "&" to "\\&" which may be wrong...
1269                         context.check_layout(os);
1270                         os << t.cs();
1271                 }
1272
1273                 else if (p.isParagraph()) {
1274                         if (context.new_layout_allowed)
1275                                 context.new_paragraph(os);
1276                         else
1277                                 handle_ert(os, "\\par ", context);
1278                         eat_whitespace(p, os, context, true);
1279                 }
1280
1281                 else if (t.cat() == catActive) {
1282                         context.check_layout(os);
1283                         if (t.character() == '~') {
1284                                 if (context.layout->free_spacing)
1285                                         os << ' ';
1286                                 else
1287                                         os << "\\InsetSpace ~\n";
1288                         } else
1289                                 os << t.cs();
1290                 }
1291
1292                 else if (t.cat() == catBegin &&
1293                          p.next_token().cat() == catEnd) {
1294                         // {}
1295                         Token const prev = p.prev_token();
1296                         p.get_token();
1297                         if (p.next_token().character() == '`' ||
1298                             (prev.character() == '-' &&
1299                              p.next_token().character() == '-'))
1300                                 ; // ignore it in {}`` or -{}-
1301                         else
1302                                 handle_ert(os, "{}", context);
1303
1304                 }
1305
1306                 else if (t.cat() == catBegin) {
1307                         context.check_layout(os);
1308                         // special handling of font attribute changes
1309                         Token const prev = p.prev_token();
1310                         Token const next = p.next_token();
1311                         TeXFont const oldFont = context.font;
1312                         if (next.character() == '[' ||
1313                             next.character() == ']' ||
1314                             next.character() == '*') {
1315                                 p.get_token();
1316                                 if (p.next_token().cat() == catEnd) {
1317                                         os << next.cs();
1318                                         p.get_token();
1319                                 } else {
1320                                         p.putback();
1321                                         handle_ert(os, "{", context);
1322                                         parse_text_snippet(p, os,
1323                                                         FLAG_BRACE_LAST,
1324                                                         outer, context);
1325                                         handle_ert(os, "}", context);
1326                                 }
1327                         } else if (! context.new_layout_allowed) {
1328                                 handle_ert(os, "{", context);
1329                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1330                                                    outer, context);
1331                                 handle_ert(os, "}", context);
1332                         } else if (is_known(next.cs(), known_sizes)) {
1333                                 // next will change the size, so we must
1334                                 // reset it here
1335                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1336                                                    outer, context);
1337                                 if (!context.atParagraphStart())
1338                                         os << "\n\\size "
1339                                            << context.font.size << "\n";
1340                         } else if (is_known(next.cs(), known_font_families)) {
1341                                 // next will change the font family, so we
1342                                 // must reset it here
1343                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1344                                                    outer, context);
1345                                 if (!context.atParagraphStart())
1346                                         os << "\n\\family "
1347                                            << context.font.family << "\n";
1348                         } else if (is_known(next.cs(), known_font_series)) {
1349                                 // next will change the font series, so we
1350                                 // must reset it here
1351                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1352                                                    outer, context);
1353                                 if (!context.atParagraphStart())
1354                                         os << "\n\\series "
1355                                            << context.font.series << "\n";
1356                         } else if (is_known(next.cs(), known_font_shapes)) {
1357                                 // next will change the font shape, so we
1358                                 // must reset it here
1359                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1360                                                    outer, context);
1361                                 if (!context.atParagraphStart())
1362                                         os << "\n\\shape "
1363                                            << context.font.shape << "\n";
1364                         } else if (is_known(next.cs(), known_old_font_families) ||
1365                                    is_known(next.cs(), known_old_font_series) ||
1366                                    is_known(next.cs(), known_old_font_shapes)) {
1367                                 // next will change the font family, series
1368                                 // and shape, so we must reset it here
1369                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1370                                                    outer, context);
1371                                 if (!context.atParagraphStart())
1372                                         os <<  "\n\\family "
1373                                            << context.font.family
1374                                            << "\n\\series "
1375                                            << context.font.series
1376                                            << "\n\\shape "
1377                                            << context.font.shape << "\n";
1378                         } else {
1379                                 handle_ert(os, "{", context);
1380                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1381                                                    outer, context);
1382                                 handle_ert(os, "}", context);
1383                         }
1384                 }
1385
1386                 else if (t.cat() == catEnd) {
1387                         if (flags & FLAG_BRACE_LAST) {
1388                                 return;
1389                         }
1390                         cerr << "stray '}' in text\n";
1391                         handle_ert(os, "}", context);
1392                 }
1393
1394                 else if (t.cat() == catComment)
1395                         parse_comment(p, os, t, context);
1396
1397                 //
1398                 // control sequences
1399                 //
1400
1401                 else if (t.cs() == "(") {
1402                         context.check_layout(os);
1403                         begin_inset(os, "Formula");
1404                         os << " \\(";
1405                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1406                         os << "\\)";
1407                         end_inset(os);
1408                 }
1409
1410                 else if (t.cs() == "[") {
1411                         context.check_layout(os);
1412                         begin_inset(os, "Formula");
1413                         os << " \\[";
1414                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1415                         os << "\\]";
1416                         end_inset(os);
1417                 }
1418
1419                 else if (t.cs() == "begin")
1420                         parse_environment(p, os, outer, context);
1421
1422                 else if (t.cs() == "end") {
1423                         if (flags & FLAG_END) {
1424                                 // eat environment name
1425                                 string const name = p.getArg('{', '}');
1426                                 if (name != active_environment())
1427                                         cerr << "\\end{" + name + "} does not match \\begin{"
1428                                                 + active_environment() + "}\n";
1429                                 return;
1430                         }
1431                         p.error("found 'end' unexpectedly");
1432                 }
1433
1434                 else if (t.cs() == "item") {
1435                         p.skip_spaces();
1436                         string s;
1437                         bool optarg = false;
1438                         if (p.next_token().character() == '[') {
1439                                 p.get_token(); // eat '['
1440                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1441                                                        outer, context);
1442                                 optarg = true;
1443                         }
1444                         context.set_item();
1445                         context.check_layout(os);
1446                         if (context.has_item) {
1447                                 // An item in an unknown list-like environment
1448                                 // FIXME: Do this in check_layout()!
1449                                 context.has_item = false;
1450                                 if (optarg)
1451                                         handle_ert(os, "\\item", context);
1452                                 else
1453                                         handle_ert(os, "\\item ", context);
1454                         }
1455                         if (optarg) {
1456                                 if (context.layout->labeltype != LABEL_MANUAL) {
1457                                         // LyX does not support \item[\mybullet]
1458                                         // in itemize environments
1459                                         handle_ert(os, "[", context);
1460                                         os << s;
1461                                         handle_ert(os, "]", context);
1462                                 } else if (!s.empty()) {
1463                                         // The space is needed to separate the
1464                                         // item from the rest of the sentence.
1465                                         os << s << ' ';
1466                                         eat_whitespace(p, os, context, false);
1467                                 }
1468                         }
1469                 }
1470
1471                 else if (t.cs() == "bibitem") {
1472                         context.set_item();
1473                         context.check_layout(os);
1474                         begin_inset(os, "LatexCommand ");
1475                         os << t.cs() << "\n";
1476                         os << "label \"" << p.getOptContent() << "\"\n";
1477                         os << "key \"" << p.verbatim_item() << "\"\n";
1478                         end_inset(os);
1479                 }
1480
1481                 else if (t.cs() == "def") {
1482                         context.check_layout(os);
1483                         eat_whitespace(p, os, context, false);
1484                         string name = p.get_token().cs();
1485                         eat_whitespace(p, os, context, false);
1486
1487                         // parameter text
1488                         bool simple = true;
1489                         string paramtext;
1490                         int arity = 0;
1491                         while (p.next_token().cat() != catBegin) {
1492                                 if (p.next_token().cat() == catParameter) {
1493                                         // # found
1494                                         p.get_token();
1495                                         paramtext += "#";
1496
1497                                         // followed by number?
1498                                         if (p.next_token().cat() == catOther) {
1499                                                 char c = p.getChar();
1500                                                 paramtext += c;
1501                                                 // number = current arity + 1?
1502                                                 if (c == arity + '0' + 1)
1503                                                         ++arity;
1504                                                 else
1505                                                         simple = false;
1506                                         } else
1507                                                 paramtext += p.get_token().cs();
1508                                 } else {
1509                                         paramtext += p.get_token().cs();
1510                                         simple = false;
1511                                 }
1512                         }
1513
1514                         // only output simple (i.e. compatible) macro as FormulaMacros
1515                         string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1516                         if (simple) {
1517                                 context.check_layout(os);
1518                                 begin_inset(os, "FormulaMacro");
1519                                 os << "\n" << ert;
1520                                 end_inset(os);
1521                         } else
1522                                 handle_ert(os, ert, context);
1523                 }
1524
1525                 else if (t.cs() == "noindent") {
1526                         p.skip_spaces();
1527                         context.add_par_extra_stuff("\\noindent\n");
1528                 }
1529
1530                 else if (t.cs() == "appendix") {
1531                         context.add_par_extra_stuff("\\start_of_appendix\n");
1532                         // We need to start a new paragraph. Otherwise the
1533                         // appendix in 'bla\appendix\chapter{' would start
1534                         // too late.
1535                         context.new_paragraph(os);
1536                         // We need to make sure that the paragraph is
1537                         // generated even if it is empty. Otherwise the
1538                         // appendix in '\par\appendix\par\chapter{' would
1539                         // start too late.
1540                         context.check_layout(os);
1541                         // FIXME: This is a hack to prevent paragraph
1542                         // deletion if it is empty. Handle this better!
1543                         handle_comment(os,
1544                                 "%dummy comment inserted by tex2lyx to "
1545                                 "ensure that this paragraph is not empty",
1546                                 context);
1547                         // Both measures above may generate an additional
1548                         // empty paragraph, but that does not hurt, because
1549                         // whitespace does not matter here.
1550                         eat_whitespace(p, os, context, true);
1551                 }
1552
1553                 // Starred section headings
1554                 // Must attempt to parse "Section*" before "Section".
1555                 else if ((p.next_token().asInput() == "*") &&
1556                          context.new_layout_allowed &&
1557                          (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1558                          newlayout->isCommand()) {
1559                         TeXFont const oldFont = context.font;
1560                         // save the current font size
1561                         string const size = oldFont.size;
1562                         // reset the font size to default, because the
1563                         // font size switches don't affect section
1564                         // headings and the like
1565                         context.font.size = known_coded_sizes[0];
1566                         output_font_change(os, oldFont, context.font);
1567                         // write the layout
1568                         p.get_token();
1569                         output_command_layout(os, p, outer, context, newlayout);
1570                         // set the font size to the original value
1571                         context.font.size = size;
1572                         output_font_change(os, oldFont, context.font);
1573                         p.skip_spaces();
1574                 }
1575
1576                 // Section headings and the like
1577                 else if (context.new_layout_allowed &&
1578                          (newlayout = findLayout(context.textclass, t.cs())) &&
1579                          newlayout->isCommand()) {
1580                         TeXFont const oldFont = context.font;
1581                         // save the current font size
1582                         string const size = oldFont.size;
1583                         // reset the font size to default, because the font size switches don't
1584                         // affect section headings and the like
1585                         context.font.size = known_coded_sizes[0];
1586                         output_font_change(os, oldFont, context.font);
1587                         // write the layout
1588                         output_command_layout(os, p, outer, context, newlayout);
1589                         // set the font size to the original value
1590                         context.font.size = size;
1591                         output_font_change(os, oldFont, context.font);
1592                         p.skip_spaces();
1593                 }
1594
1595                 else if (t.cs() == "caption") {
1596                         // FIXME: this should get some cleanup. All
1597                         // the \begin_layout:s are output by the
1598                         // Context class!
1599                         p.skip_spaces();
1600                         context.check_layout(os);
1601                         p.skip_spaces();
1602                         begin_inset(os, "Caption\n\n");
1603                         os << "\\begin_layout " 
1604                            << to_utf8(context.textclass.defaultLayout().name()) 
1605                            << '\n';
1606                         if (p.next_token().character() == '[') {
1607                                 p.get_token(); // eat '['
1608                                 begin_inset(os, "OptArg\n");
1609                                 os << "status collapsed\n";
1610                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1611                                 end_inset(os);
1612                                 eat_whitespace(p, os, context, false);
1613                         }
1614                         parse_text(p, os, FLAG_ITEM, outer, context);
1615                         context.check_end_layout(os);
1616                         // We don't need really a new paragraph, but
1617                         // we must make sure that the next item gets a \begin_layout.
1618                         context.new_paragraph(os);
1619                         end_inset(os);
1620                         p.skip_spaces();
1621                         os << "\\end_layout\n";
1622                 }
1623
1624                 else if (t.cs() == "includegraphics") {
1625                         bool const clip = p.next_token().asInput() == "*";
1626                         if (clip)
1627                                 p.get_token();
1628                         map<string, string> opts = split_map(p.getArg('[', ']'));
1629                         if (clip)
1630                                 opts["clip"] = string();
1631                         string name = normalize_filename(p.verbatim_item());
1632
1633                         string const path = getMasterFilePath();
1634                         // We want to preserve relative / absolute filenames,
1635                         // therefore path is only used for testing
1636                         if (!makeAbsPath(name, path).exists()) {
1637                                 // The file extension is probably missing.
1638                                 // Now try to find it out.
1639                                 string const dvips_name =
1640                                         find_file(name, path,
1641                                                   known_dvips_graphics_formats);
1642                                 string const pdftex_name =
1643                                         find_file(name, path,
1644                                                   known_pdftex_graphics_formats);
1645                                 if (!dvips_name.empty()) {
1646                                         if (!pdftex_name.empty()) {
1647                                                 cerr << "This file contains the "
1648                                                         "latex snippet\n"
1649                                                         "\"\\includegraphics{"
1650                                                      << name << "}\".\n"
1651                                                         "However, files\n\""
1652                                                      << dvips_name << "\" and\n\""
1653                                                      << pdftex_name << "\"\n"
1654                                                         "both exist, so I had to make a "
1655                                                         "choice and took the first one.\n"
1656                                                         "Please move the unwanted one "
1657                                                         "someplace else and try again\n"
1658                                                         "if my choice was wrong."
1659                                                      << endl;
1660                                         }
1661                                         name = dvips_name;
1662                                 } else if (!pdftex_name.empty())
1663                                         name = pdftex_name;
1664                         }
1665
1666                         if (makeAbsPath(name, path).exists())
1667                                 fix_relative_filename(name);
1668                         else
1669                                 cerr << "Warning: Could not find graphics file '"
1670                                      << name << "'." << endl;
1671
1672                         context.check_layout(os);
1673                         begin_inset(os, "Graphics ");
1674                         os << "\n\tfilename " << name << '\n';
1675                         if (opts.find("width") != opts.end())
1676                                 os << "\twidth "
1677                                    << translate_len(opts["width"]) << '\n';
1678                         if (opts.find("height") != opts.end())
1679                                 os << "\theight "
1680                                    << translate_len(opts["height"]) << '\n';
1681                         if (opts.find("scale") != opts.end()) {
1682                                 istringstream iss(opts["scale"]);
1683                                 double val;
1684                                 iss >> val;
1685                                 val = val*100;
1686                                 os << "\tscale " << val << '\n';
1687                         }
1688                         if (opts.find("angle") != opts.end())
1689                                 os << "\trotateAngle "
1690                                    << opts["angle"] << '\n';
1691                         if (opts.find("origin") != opts.end()) {
1692                                 ostringstream ss;
1693                                 string const opt = opts["origin"];
1694                                 if (opt.find('l') != string::npos) ss << "left";
1695                                 if (opt.find('r') != string::npos) ss << "right";
1696                                 if (opt.find('c') != string::npos) ss << "center";
1697                                 if (opt.find('t') != string::npos) ss << "Top";
1698                                 if (opt.find('b') != string::npos) ss << "Bottom";
1699                                 if (opt.find('B') != string::npos) ss << "Baseline";
1700                                 if (!ss.str().empty())
1701                                         os << "\trotateOrigin " << ss.str() << '\n';
1702                                 else
1703                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1704                         }
1705                         if (opts.find("keepaspectratio") != opts.end())
1706                                 os << "\tkeepAspectRatio\n";
1707                         if (opts.find("clip") != opts.end())
1708                                 os << "\tclip\n";
1709                         if (opts.find("draft") != opts.end())
1710                                 os << "\tdraft\n";
1711                         if (opts.find("bb") != opts.end())
1712                                 os << "\tBoundingBox "
1713                                    << opts["bb"] << '\n';
1714                         int numberOfbbOptions = 0;
1715                         if (opts.find("bbllx") != opts.end())
1716                                 numberOfbbOptions++;
1717                         if (opts.find("bblly") != opts.end())
1718                                 numberOfbbOptions++;
1719                         if (opts.find("bburx") != opts.end())
1720                                 numberOfbbOptions++;
1721                         if (opts.find("bbury") != opts.end())
1722                                 numberOfbbOptions++;
1723                         if (numberOfbbOptions == 4)
1724                                 os << "\tBoundingBox "
1725                                    << opts["bbllx"] << " " << opts["bblly"] << " "
1726                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
1727                         else if (numberOfbbOptions > 0)
1728                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1729                         numberOfbbOptions = 0;
1730                         if (opts.find("natwidth") != opts.end())
1731                                 numberOfbbOptions++;
1732                         if (opts.find("natheight") != opts.end())
1733                                 numberOfbbOptions++;
1734                         if (numberOfbbOptions == 2)
1735                                 os << "\tBoundingBox 0bp 0bp "
1736                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
1737                         else if (numberOfbbOptions > 0)
1738                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1739                         ostringstream special;
1740                         if (opts.find("hiresbb") != opts.end())
1741                                 special << "hiresbb,";
1742                         if (opts.find("trim") != opts.end())
1743                                 special << "trim,";
1744                         if (opts.find("viewport") != opts.end())
1745                                 special << "viewport=" << opts["viewport"] << ',';
1746                         if (opts.find("totalheight") != opts.end())
1747                                 special << "totalheight=" << opts["totalheight"] << ',';
1748                         if (opts.find("type") != opts.end())
1749                                 special << "type=" << opts["type"] << ',';
1750                         if (opts.find("ext") != opts.end())
1751                                 special << "ext=" << opts["ext"] << ',';
1752                         if (opts.find("read") != opts.end())
1753                                 special << "read=" << opts["read"] << ',';
1754                         if (opts.find("command") != opts.end())
1755                                 special << "command=" << opts["command"] << ',';
1756                         string s_special = special.str();
1757                         if (!s_special.empty()) {
1758                                 // We had special arguments. Remove the trailing ','.
1759                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1760                         }
1761                         // TODO: Handle the unknown settings better.
1762                         // Warn about invalid options.
1763                         // Check whether some option was given twice.
1764                         end_inset(os);
1765                 }
1766
1767                 else if (t.cs() == "footnote" ||
1768                          (t.cs() == "thanks" && context.layout->intitle)) {
1769                         p.skip_spaces();
1770                         context.check_layout(os);
1771                         begin_inset(os, "Foot\n");
1772                         os << "status collapsed\n\n";
1773                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1774                         end_inset(os);
1775                 }
1776
1777                 else if (t.cs() == "marginpar") {
1778                         p.skip_spaces();
1779                         context.check_layout(os);
1780                         begin_inset(os, "Marginal\n");
1781                         os << "status collapsed\n\n";
1782                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1783                         end_inset(os);
1784                 }
1785
1786                 else if (t.cs() == "ensuremath") {
1787                         p.skip_spaces();
1788                         context.check_layout(os);
1789                         string const s = p.verbatim_item();
1790                         //FIXME: this never triggers in UTF8
1791                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1792                                 os << s;
1793                         else
1794                                 handle_ert(os, "\\ensuremath{" + s + "}",
1795                                            context);
1796                 }
1797
1798                 else if (t.cs() == "hfill") {
1799                         context.check_layout(os);
1800                         os << "\n\\hfill\n";
1801                         skip_braces(p);
1802                         p.skip_spaces();
1803                 }
1804
1805                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1806                         // FIXME: Somehow prevent title layouts if
1807                         // "maketitle" was not found
1808                         p.skip_spaces();
1809                         skip_braces(p); // swallow this
1810                 }
1811
1812                 else if (t.cs() == "tableofcontents") {
1813                         p.skip_spaces();
1814                         context.check_layout(os);
1815                         begin_inset(os, "LatexCommand ");
1816                         os << t.cs() << "\n";
1817                         end_inset(os);
1818                         skip_braces(p); // swallow this
1819                 }
1820
1821                 else if (t.cs() == "listoffigures") {
1822                         p.skip_spaces();
1823                         context.check_layout(os);
1824                         begin_inset(os, "FloatList figure\n");
1825                         end_inset(os);
1826                         skip_braces(p); // swallow this
1827                 }
1828
1829                 else if (t.cs() == "listoftables") {
1830                         p.skip_spaces();
1831                         context.check_layout(os);
1832                         begin_inset(os, "FloatList table\n");
1833                         end_inset(os);
1834                         skip_braces(p); // swallow this
1835                 }
1836
1837                 else if (t.cs() == "listof") {
1838                         p.skip_spaces(true);
1839                         string const name = p.get_token().cs();
1840                         if (context.textclass.floats().typeExist(name)) {
1841                                 context.check_layout(os);
1842                                 begin_inset(os, "FloatList ");
1843                                 os << name << "\n";
1844                                 end_inset(os);
1845                                 p.get_token(); // swallow second arg
1846                         } else
1847                                 handle_ert(os, "\\listof{" + name + "}", context);
1848                 }
1849
1850                 else if (t.cs() == "textrm")
1851                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1852                                               context, "\\family",
1853                                               context.font.family, "roman");
1854
1855                 else if (t.cs() == "textsf")
1856                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1857                                               context, "\\family",
1858                                               context.font.family, "sans");
1859
1860                 else if (t.cs() == "texttt")
1861                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1862                                               context, "\\family",
1863                                               context.font.family, "typewriter");
1864
1865                 else if (t.cs() == "textmd")
1866                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1867                                               context, "\\series",
1868                                               context.font.series, "medium");
1869
1870                 else if (t.cs() == "textbf")
1871                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1872                                               context, "\\series",
1873                                               context.font.series, "bold");
1874
1875                 else if (t.cs() == "textup")
1876                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1877                                               context, "\\shape",
1878                                               context.font.shape, "up");
1879
1880                 else if (t.cs() == "textit")
1881                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1882                                               context, "\\shape",
1883                                               context.font.shape, "italic");
1884
1885                 else if (t.cs() == "textsl")
1886                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1887                                               context, "\\shape",
1888                                               context.font.shape, "slanted");
1889
1890                 else if (t.cs() == "textsc")
1891                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1892                                               context, "\\shape",
1893                                               context.font.shape, "smallcaps");
1894
1895                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1896                         context.check_layout(os);
1897                         TeXFont oldFont = context.font;
1898                         context.font.init();
1899                         context.font.size = oldFont.size;
1900                         os << "\n\\family " << context.font.family << "\n";
1901                         os << "\n\\series " << context.font.series << "\n";
1902                         os << "\n\\shape " << context.font.shape << "\n";
1903                         if (t.cs() == "textnormal") {
1904                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1905                                 output_font_change(os, context.font, oldFont);
1906                                 context.font = oldFont;
1907                         } else
1908                                 eat_whitespace(p, os, context, false);
1909                 }
1910
1911                 else if (t.cs() == "textcolor") {
1912                         // scheme is \textcolor{color name}{text}
1913                         string const color = p.verbatim_item();
1914                         // we only support the predefined colors of the color package
1915                         if (color == "black" || color == "blue" || color == "cyan"
1916                                 || color == "green" || color == "magenta" || color == "red"
1917                                 || color == "white" || color == "yellow") {
1918                                         context.check_layout(os);
1919                                         os << "\n\\color " << color << "\n";
1920                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1921                                         context.check_layout(os);
1922                                         os << "\n\\color inherit\n";
1923                         } else
1924                                 // for custom defined colors
1925                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
1926                 }
1927
1928                 else if (t.cs() == "underbar") {
1929                         // Do NOT handle \underline.
1930                         // \underbar cuts through y, g, q, p etc.,
1931                         // \underline does not.
1932                         context.check_layout(os);
1933                         os << "\n\\bar under\n";
1934                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1935                         context.check_layout(os);
1936                         os << "\n\\bar default\n";
1937                 }
1938
1939                 else if (t.cs() == "emph" || t.cs() == "noun") {
1940                         context.check_layout(os);
1941                         os << "\n\\" << t.cs() << " on\n";
1942                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1943                         context.check_layout(os);
1944                         os << "\n\\" << t.cs() << " default\n";
1945                 }
1946
1947                 else if (t.cs() == "lyxline") {
1948                         context.check_layout(os);
1949                         os << "\\lyxline";
1950                 }
1951
1952                 else if (is_known(t.cs(), known_ref_commands)) {
1953                         context.check_layout(os);
1954                         begin_inset(os, "LatexCommand ");
1955                         os << t.cs() << "\n";
1956                         // LyX cannot handle newlines in a latex command
1957                         // FIXME: Move the substitution into parser::getOpt()?
1958                         os << subst(p.getOpt(), "\n", " ");
1959                         os << "reference " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
1960                         end_inset(os);
1961                 }
1962
1963                 else if (use_natbib &&
1964                          is_known(t.cs(), known_natbib_commands) &&
1965                          ((t.cs() != "citefullauthor" &&
1966                            t.cs() != "citeyear" &&
1967                            t.cs() != "citeyearpar") ||
1968                           p.next_token().asInput() != "*")) {
1969                         context.check_layout(os);
1970                         string command = t.cs();
1971                         if (p.next_token().asInput() == "*") {
1972                                 command += '*';
1973                                 p.get_token();
1974                         }
1975                         if (command == "citefullauthor")
1976                                 // alternative name for "\\citeauthor*"
1977                                 command = "citeauthor*";
1978
1979                         // text before the citation
1980                         string before;
1981                         // text after the citation
1982                         string after;
1983                         get_cite_arguments(p, true, before, after);
1984
1985                         if (command == "cite") {
1986                                 // \cite without optional argument means
1987                                 // \citet, \cite with at least one optional
1988                                 // argument means \citep.
1989                                 if (before.empty() && after.empty())
1990                                         command = "citet";
1991                                 else
1992                                         command = "citep";
1993                         }
1994                         if (before.empty() && after == "[]")
1995                                 // avoid \citet[]{a}
1996                                 after.erase();
1997                         else if (before == "[]" && after == "[]") {
1998                                 // avoid \citet[][]{a}
1999                                 before.erase();
2000                                 after.erase();
2001                         }
2002                         // remove the brackets around after and before
2003                         if (!after.empty()) {
2004                                 after.erase(0, 1);
2005                                 after.erase(after.length() - 1, 1);
2006                                 // LyX cannot handle newlines in the parameter
2007                                 after = subst(after, "\n", " ");
2008                         }
2009                         if (!before.empty()) {
2010                                 before.erase(0, 1);
2011                                 before.erase(before.length() - 1, 1);
2012                                 // LyX cannot handle newlines in the parameter
2013                                 before = subst(before, "\n", " ");
2014                         }
2015                         begin_inset(os, "LatexCommand ");
2016                         os << t.cs() << "\n";
2017                         os << "after " << '"' << after << '"' << "\n";
2018                         os << "before " << '"' << before << '"' << "\n";
2019                         os << "key " << '"' << p.verbatim_item() << '"' << "\n";
2020                         end_inset(os);
2021                 }
2022
2023                 else if (use_jurabib &&
2024                          is_known(t.cs(), known_jurabib_commands)) {
2025                         context.check_layout(os);
2026                         string const command = t.cs();
2027                         char argumentOrder = '\0';
2028                         vector<string> const & options = used_packages["jurabib"];
2029                         if (find(options.begin(), options.end(),
2030                                       "natbiborder") != options.end())
2031                                 argumentOrder = 'n';
2032                         else if (find(options.begin(), options.end(),
2033                                            "jurabiborder") != options.end())
2034                                 argumentOrder = 'j';
2035
2036                         // text before the citation
2037                         string before;
2038                         // text after the citation
2039                         string after;
2040                         get_cite_arguments(p, argumentOrder != 'j', before, after);
2041
2042                         string const citation = p.verbatim_item();
2043                         if (!before.empty() && argumentOrder == '\0') {
2044                                 cerr << "Warning: Assuming argument order "
2045                                         "of jurabib version 0.6 for\n'"
2046                                      << command << before << after << '{'
2047                                      << citation << "}'.\n"
2048                                         "Add 'jurabiborder' to the jurabib "
2049                                         "package options if you used an\n"
2050                                         "earlier jurabib version." << endl;
2051                         }
2052                         if (!after.empty()) {
2053                                 after.erase(0, 1);
2054                                 after.erase(after.length() - 1, 1);
2055                         }
2056                         if (!before.empty()) {
2057                                 before.erase(0, 1);
2058                                 before.erase(before.length() - 1, 1);
2059                         }
2060                         begin_inset(os, "LatexCommand ");
2061                         os << t.cs() << "\n";
2062                         os << "after " << '"' << after << '"' << "\n";
2063                         os << "before " << '"' << before << '"' << "\n";
2064                         os << "key " << '"' << citation << '"' << "\n";
2065                         end_inset(os);
2066                 }
2067
2068                 else if (t.cs() == "cite") {
2069                         context.check_layout(os);
2070                         // LyX cannot handle newlines in a latex command
2071                         string after = subst(p.getOptContent(), "\n", " ");
2072                         begin_inset(os, "LatexCommand ");
2073                         os << t.cs() << "\n";
2074                         os << "after " << '"' << after << '"' << "\n";
2075                         os << "key " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2076                         end_inset(os);
2077                 }
2078
2079                 else if (t.cs() == "index") {
2080                         context.check_layout(os);
2081                         begin_inset(os, "LatexCommand ");
2082                         os << t.cs() << "\n";
2083                         // LyX cannot handle newlines in a latex command
2084                         os << "name " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2085                         end_inset(os);
2086                 }
2087
2088                 else if (t.cs() == "nomenclature") {
2089                         context.check_layout(os);
2090                         begin_inset(os, "LatexCommand ");
2091                         os << t.cs() << "\n";
2092                         // LyX cannot handle newlines in a latex command
2093                         string prefix = subst(p.getOptContent(), "\n", " ");
2094                         if (!prefix.empty())
2095                                 os << "prefix " << '"' << prefix << '"' << "\n";
2096                         os << "symbol " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2097                         os << "description " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2098                         end_inset(os);
2099                 }
2100                 
2101                 else if (t.cs() == "label") {
2102                         context.check_layout(os);
2103                         begin_inset(os, "LatexCommand ");
2104                         os << t.cs() << "\n";
2105                         // LyX cannot handle newlines in a latex command
2106                         os << "name " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2107                         end_inset(os);
2108                 }
2109
2110                 else if (t.cs() == "printindex") {
2111                         context.check_layout(os);
2112                         begin_inset(os, "LatexCommand ");
2113                         os << t.cs() << "\n";
2114                         end_inset(os);
2115                         skip_braces(p);
2116                 }
2117
2118                 else if (t.cs() == "printnomenclature") {
2119                         context.check_layout(os);
2120                         begin_inset(os, "LatexCommand ");
2121                         os << t.cs() << "\n";
2122                         end_inset(os);
2123                         skip_braces(p);
2124                 }
2125
2126                 else if (t.cs() == "url") {
2127                         context.check_layout(os);
2128                         begin_inset(os, "LatexCommand ");
2129                         os << t.cs() << "\n";
2130                         // LyX cannot handle newlines in a latex command
2131                         os << "target " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2132                         end_inset(os);
2133                 }
2134
2135                 else if (is_known(t.cs(), known_quotes)) {
2136                         char const * const * where = is_known(t.cs(), known_quotes);
2137                         context.check_layout(os);
2138                         begin_inset(os, "Quotes ");
2139                         os << known_coded_quotes[where - known_quotes];
2140                         end_inset(os);
2141                         // LyX adds {} after the quote, so we have to eat
2142                         // spaces here if there are any before a possible
2143                         // {} pair.
2144                         eat_whitespace(p, os, context, false);
2145                         skip_braces(p);
2146                 }
2147
2148                 else if (is_known(t.cs(), known_sizes) &&
2149                          context.new_layout_allowed) {
2150                         char const * const * where = is_known(t.cs(), known_sizes);
2151                         context.check_layout(os);
2152                         TeXFont const oldFont = context.font;
2153                         // the font size index differs by 1, because the known_coded_sizes
2154                         // has additionally a "default" entry
2155                         context.font.size = known_coded_sizes[where - known_sizes + 1];
2156                         output_font_change(os, oldFont, context.font);
2157                         eat_whitespace(p, os, context, false);
2158                 }
2159
2160                 else if (is_known(t.cs(), known_font_families) &&
2161                          context.new_layout_allowed) {
2162                         char const * const * where =
2163                                 is_known(t.cs(), known_font_families);
2164                         context.check_layout(os);
2165                         TeXFont const oldFont = context.font;
2166                         context.font.family =
2167                                 known_coded_font_families[where - known_font_families];
2168                         output_font_change(os, oldFont, context.font);
2169                         eat_whitespace(p, os, context, false);
2170                 }
2171
2172                 else if (is_known(t.cs(), known_font_series) &&
2173                          context.new_layout_allowed) {
2174                         char const * const * where =
2175                                 is_known(t.cs(), known_font_series);
2176                         context.check_layout(os);
2177                         TeXFont const oldFont = context.font;
2178                         context.font.series =
2179                                 known_coded_font_series[where - known_font_series];
2180                         output_font_change(os, oldFont, context.font);
2181                         eat_whitespace(p, os, context, false);
2182                 }
2183
2184                 else if (is_known(t.cs(), known_font_shapes) &&
2185                          context.new_layout_allowed) {
2186                         char const * const * where =
2187                                 is_known(t.cs(), known_font_shapes);
2188                         context.check_layout(os);
2189                         TeXFont const oldFont = context.font;
2190                         context.font.shape =
2191                                 known_coded_font_shapes[where - known_font_shapes];
2192                         output_font_change(os, oldFont, context.font);
2193                         eat_whitespace(p, os, context, false);
2194                 }
2195                 else if (is_known(t.cs(), known_old_font_families) &&
2196                          context.new_layout_allowed) {
2197                         char const * const * where =
2198                                 is_known(t.cs(), known_old_font_families);
2199                         context.check_layout(os);
2200                         TeXFont const oldFont = context.font;
2201                         context.font.init();
2202                         context.font.size = oldFont.size;
2203                         context.font.family =
2204                                 known_coded_font_families[where - known_old_font_families];
2205                         output_font_change(os, oldFont, context.font);
2206                         eat_whitespace(p, os, context, false);
2207                 }
2208
2209                 else if (is_known(t.cs(), known_old_font_series) &&
2210                          context.new_layout_allowed) {
2211                         char const * const * where =
2212                                 is_known(t.cs(), known_old_font_series);
2213                         context.check_layout(os);
2214                         TeXFont const oldFont = context.font;
2215                         context.font.init();
2216                         context.font.size = oldFont.size;
2217                         context.font.series =
2218                                 known_coded_font_series[where - known_old_font_series];
2219                         output_font_change(os, oldFont, context.font);
2220                         eat_whitespace(p, os, context, false);
2221                 }
2222
2223                 else if (is_known(t.cs(), known_old_font_shapes) &&
2224                          context.new_layout_allowed) {
2225                         char const * const * where =
2226                                 is_known(t.cs(), known_old_font_shapes);
2227                         context.check_layout(os);
2228                         TeXFont const oldFont = context.font;
2229                         context.font.init();
2230                         context.font.size = oldFont.size;
2231                         context.font.shape =
2232                                 known_coded_font_shapes[where - known_old_font_shapes];
2233                         output_font_change(os, oldFont, context.font);
2234                         eat_whitespace(p, os, context, false);
2235                 }
2236
2237                 else if (t.cs() == "selectlanguage") {
2238                         context.check_layout(os);
2239                         // save the language for the case that a
2240                         // \foreignlanguage is used 
2241
2242                         context.font.language = subst(p.verbatim_item(), "\n", " ");
2243                         os << "\\lang " << context.font.language << "\n";
2244                 }
2245
2246                 else if (t.cs() == "foreignlanguage") {
2247                         context.check_layout(os);
2248                         os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2249                         os << subst(p.verbatim_item(), "\n", " ");
2250                         // FIXME: the second argument of selectlanguage
2251                         // has to be parsed (like for \textsf, for
2252                         // example). 
2253                         // set back to last selectlanguage
2254                         os << "\n\\lang " << context.font.language << "\n";
2255                 }
2256
2257                 else if (t.cs() == "inputencoding") {
2258                         // nothing to write here
2259                         string const enc = subst(p.verbatim_item(), "\n", " ");
2260                         p.setEncoding(enc);
2261                 }
2262
2263                 else if (t.cs() == "LyX" || t.cs() == "TeX"
2264                          || t.cs() == "LaTeX") {
2265                         context.check_layout(os);
2266                         os << t.cs();
2267                         skip_braces(p); // eat {}
2268                 }
2269
2270                 else if (t.cs() == "LaTeXe") {
2271                         context.check_layout(os);
2272                         os << "LaTeX2e";
2273                         skip_braces(p); // eat {}
2274                 }
2275
2276                 else if (t.cs() == "ldots") {
2277                         context.check_layout(os);
2278                         skip_braces(p);
2279                         os << "\\SpecialChar \\ldots{}\n";
2280                 }
2281
2282                 else if (t.cs() == "lyxarrow") {
2283                         context.check_layout(os);
2284                         os << "\\SpecialChar \\menuseparator\n";
2285                         skip_braces(p);
2286                 }
2287
2288                 else if (t.cs() == "textcompwordmark") {
2289                         context.check_layout(os);
2290                         os << "\\SpecialChar \\textcompwordmark{}\n";
2291                         skip_braces(p);
2292                 }
2293
2294                 else if (t.cs() == "textquotedbl") {
2295                         context.check_layout(os);
2296                         os << "\"";
2297                         skip_braces(p);
2298                 }
2299
2300                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2301                         context.check_layout(os);
2302                         os << "\\SpecialChar \\@.\n";
2303                         p.get_token();
2304                 }
2305
2306                 else if (t.cs() == "-") {
2307                         context.check_layout(os);
2308                         os << "\\SpecialChar \\-\n";
2309                 }
2310
2311                 else if (t.cs() == "textasciitilde") {
2312                         context.check_layout(os);
2313                         os << '~';
2314                         skip_braces(p);
2315                 }
2316
2317                 else if (t.cs() == "textasciicircum") {
2318                         context.check_layout(os);
2319                         os << '^';
2320                         skip_braces(p);
2321                 }
2322
2323                 else if (t.cs() == "textbackslash") {
2324                         context.check_layout(os);
2325                         os << "\n\\backslash\n";
2326                         skip_braces(p);
2327                 }
2328
2329                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2330                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2331                             || t.cs() == "%") {
2332                         context.check_layout(os);
2333                         os << t.cs();
2334                 }
2335
2336                 else if (t.cs() == "char") {
2337                         context.check_layout(os);
2338                         if (p.next_token().character() == '`') {
2339                                 p.get_token();
2340                                 if (p.next_token().cs() == "\"") {
2341                                         p.get_token();
2342                                         os << '"';
2343                                         skip_braces(p);
2344                                 } else {
2345                                         handle_ert(os, "\\char`", context);
2346                                 }
2347                         } else {
2348                                 handle_ert(os, "\\char", context);
2349                         }
2350                 }
2351
2352                 else if (t.cs() == "verb") {
2353                         context.check_layout(os);
2354                         char const delimiter = p.next_token().character();
2355                         string const arg = p.getArg(delimiter, delimiter);
2356                         ostringstream oss;
2357                         oss << "\\verb" << delimiter << arg << delimiter;
2358                         handle_ert(os, oss.str(), context);
2359                 }
2360
2361                 // Problem: \= creates a tabstop inside the tabbing environment
2362                 // and else an accent. In the latter case we really would want
2363                 // \={o} instead of \= o.
2364                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2365                         handle_ert(os, t.asInput(), context);
2366
2367                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2368                 else if (t.cs().size() == 1 
2369                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2370                         context.check_layout(os);
2371                         // try to see whether the string is in unicodesymbols
2372                         docstring rem;
2373                         string command = t.asInput() + "{" 
2374                                 + trim(p.verbatim_item())
2375                                 + "}";
2376                         docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2377                         if (!s.empty()) {
2378                                 if (!rem.empty())
2379                                         cerr << "When parsing " << command 
2380                                              << ", result is " << to_utf8(s)
2381                                              << "+" << to_utf8(rem) << endl;
2382                                 os << to_utf8(s);
2383                         } else
2384                                 // we did not find a non-ert version
2385                                 handle_ert(os, command, context);
2386                 }
2387
2388                 else if (t.cs() == "\\") {
2389                         context.check_layout(os);
2390                         string const next = p.next_token().asInput();
2391                         if (next == "[")
2392                                 handle_ert(os, "\\\\" + p.getOpt(), context);
2393                         else if (next == "*") {
2394                                 p.get_token();
2395                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
2396                         }
2397                         else {
2398                                 os << "\n\\newline\n";
2399                         }
2400                 }
2401
2402                 else if (t.cs() == "newline") {
2403                         context.check_layout(os);
2404                         os << "\n\\" << t.cs() << "\n";
2405                         skip_braces(p); // eat {}
2406                 }
2407
2408                 else if (t.cs() == "input" || t.cs() == "include"
2409                          || t.cs() == "verbatiminput") {
2410                         string name = '\\' + t.cs();
2411                         if (t.cs() == "verbatiminput"
2412                             && p.next_token().asInput() == "*")
2413                                 name += p.get_token().asInput();
2414                         context.check_layout(os);
2415                         string filename(normalize_filename(p.getArg('{', '}')));
2416                         string const path = getMasterFilePath();
2417                         // We want to preserve relative / absolute filenames,
2418                         // therefore path is only used for testing
2419                         if ((t.cs() == "include" || t.cs() == "input") &&
2420                             !makeAbsPath(filename, path).exists()) {
2421                                 // The file extension is probably missing.
2422                                 // Now try to find it out.
2423                                 string const tex_name =
2424                                         find_file(filename, path,
2425                                                   known_tex_extensions);
2426                                 if (!tex_name.empty())
2427                                         filename = tex_name;
2428                         }
2429                         bool xfig = false;
2430                         string outname;
2431                         if (makeAbsPath(filename, path).exists()) {
2432                                 string const abstexname =
2433                                         makeAbsPath(filename, path).absFileName();
2434                                 string const abslyxname =
2435                                         changeExtension(abstexname, ".lyx");
2436                                 string const absfigname =
2437                                         changeExtension(abstexname, ".fig");
2438                                 fix_relative_filename(filename);
2439                                 string const lyxname =
2440                                         changeExtension(filename, ".lyx");
2441                                 if (t.cs() == "input" && FileName(absfigname).exists()) {
2442                                         FileName const absepsname(
2443                                                 changeExtension(abstexname, ".eps"));
2444                                         FileName const abspdfname(
2445                                                 changeExtension(abstexname, ".pdf"));
2446                                         string const ext = getExtension(abstexname);
2447                                         bool const xfigpdf =
2448                                                 abspdfname.exists() && ext == "pdftex_t";
2449                                         bool const xfigeps  =
2450                                                 absepsname.exists() && ext == "pstex_t";
2451                                         xfig = xfigpdf || xfigeps;
2452                                 }
2453                                 if (xfig) {
2454                                         outname = changeExtension(filename, ".fig");
2455                                 } else if (t.cs() != "verbatiminput" &&
2456                                     tex2lyx(abstexname, FileName(abslyxname),
2457                                             p.getEncoding())) {
2458                                         outname = lyxname;
2459                                 } else {
2460                                         outname = filename;
2461                                 }
2462                         } else {
2463                                 cerr << "Warning: Could not find included file '"
2464                                      << filename << "'." << endl;
2465                                 outname = filename;
2466                         }
2467                         if (xfig) {
2468                                 begin_inset(os, "External\n");
2469                                 os << "\ttemplate XFig\n"
2470                                    << "\tfilename " << outname << '\n';
2471                         } else {
2472                                 begin_inset(os, "Include ");
2473                                 os << name << '{' << outname
2474                                    << "}\npreview false\n";
2475                         }
2476                         end_inset(os);
2477                 }
2478
2479                 else if (t.cs() == "bibliographystyle") {
2480                         // store new bibliographystyle
2481                         bibliographystyle = p.verbatim_item();
2482                         // output new bibliographystyle.
2483                         // This is only necessary if used in some other macro than \bibliography.
2484                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2485                 }
2486
2487                 else if (t.cs() == "bibliography") {
2488                         context.check_layout(os);
2489                         begin_inset(os, "LatexCommand ");
2490                         os << "bibtex" << "\n";
2491                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
2492                         // Do we have a bibliographystyle set?
2493                         if (!bibliographystyle.empty())
2494                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
2495                         end_inset(os);
2496                 }
2497
2498                 else if (t.cs() == "parbox")
2499                         parse_box(p, os, FLAG_ITEM, outer, context, true);
2500                 
2501                 //\makebox() is part of the picture environment and different from \makebox{}
2502                 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
2503                 else if (t.cs() == "makebox") {
2504                         string arg = t.asInput();
2505                         if (p.next_token().character() == '(')
2506                                 //the syntax is: \makebox(x,y)[position]{content}
2507                                 arg += p.getFullParentheseArg();
2508                         else
2509                                 //the syntax is: \makebox[width][position]{content}
2510                                 arg += p.getFullOpt();
2511                         handle_ert(os, arg + p.getFullOpt(), context);
2512                 }
2513
2514                 else if (t.cs() == "smallskip" ||
2515                          t.cs() == "medskip" ||
2516                          t.cs() == "bigskip" ||
2517                          t.cs() == "vfill") {
2518                         context.check_layout(os);
2519                         begin_inset(os, "VSpace ");
2520                         os << t.cs();
2521                         end_inset(os);
2522                         skip_braces(p);
2523                 }
2524
2525                 else if (is_known(t.cs(), known_spaces)) {
2526                         char const * const * where = is_known(t.cs(), known_spaces);
2527                         context.check_layout(os);
2528                         os << "\\InsetSpace ";
2529                         os << '\\' << known_coded_spaces[where - known_spaces]
2530                            << '\n';
2531                         // LaTeX swallows whitespace after all spaces except
2532                         // "\\,". We have to do that here, too, because LyX
2533                         // adds "{}" which would make the spaces significant.
2534                         if (t.cs() !=  ",")
2535                                 eat_whitespace(p, os, context, false);
2536                         // LyX adds "{}" after all spaces except "\\ " and
2537                         // "\\,", so we have to remove "{}".
2538                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
2539                         // remove the braces after "\\,", too.
2540                         if (t.cs() != " ")
2541                                 skip_braces(p);
2542                 }
2543
2544                 else if (t.cs() == "newpage" ||
2545                         t.cs() == "clearpage" ||
2546                         t.cs() == "cleardoublepage") {
2547                         context.check_layout(os);
2548                         os << "\n\\" << t.cs() << "\n";
2549                         skip_braces(p); // eat {}
2550                 }
2551
2552                 else if (t.cs() == "newcommand" ||
2553                          t.cs() == "providecommand" ||
2554                          t.cs() == "renewcommand") {
2555                         // these could be handled by parse_command(), but
2556                         // we need to call add_known_command() here.
2557                         string name = t.asInput();
2558                         if (p.next_token().asInput() == "*") {
2559                                 // Starred form. Eat '*'
2560                                 p.get_token();
2561                                 name += '*';
2562                         }
2563                         string const command = p.verbatim_item();
2564                         string const opt1 = p.getOpt();
2565                         string const opt2 = p.getFullOpt();
2566                         add_known_command(command, opt1, !opt2.empty());
2567                         string const ert = name + '{' + command + '}' +
2568                                            opt1 + opt2 +
2569                                            '{' + p.verbatim_item() + '}';
2570
2571                         context.check_layout(os);
2572                         begin_inset(os, "FormulaMacro");
2573                         os << "\n" << ert;
2574                         end_inset(os);
2575                 }
2576                 
2577                 else if (t.cs() == "vspace") {
2578                         bool starred = false;
2579                         if (p.next_token().asInput() == "*") {
2580                                 p.get_token();
2581                                 starred = true;
2582                         }
2583                         string const length = p.verbatim_item();
2584                         string unit;
2585                         string valstring;
2586                         bool valid = splitLatexLength(length, valstring, unit);
2587                         bool known_vspace = false;
2588                         bool known_unit = false;
2589                         double value;
2590                         if (valid) {
2591                                 istringstream iss(valstring);
2592                                 iss >> value;
2593                                 if (value == 1.0) {
2594                                         if (unit == "\\smallskipamount") {
2595                                                 unit = "smallskip";
2596                                                 known_vspace = true;
2597                                         } else if (unit == "\\medskipamount") {
2598                                                 unit = "medskip";
2599                                                 known_vspace = true;
2600                                         } else if (unit == "\\bigskipamount") {
2601                                                 unit = "bigskip";
2602                                                 known_vspace = true;
2603                                         } else if (unit == "\\fill") {
2604                                                 unit = "vfill";
2605                                                 known_vspace = true;
2606                                         }
2607                                 }
2608                                 if (!known_vspace) {
2609                                         switch (unitFromString(unit)) {
2610                                         case Length::SP:
2611                                         case Length::PT:
2612                                         case Length::BP:
2613                                         case Length::DD:
2614                                         case Length::MM:
2615                                         case Length::PC:
2616                                         case Length::CC:
2617                                         case Length::CM:
2618                                         case Length::IN:
2619                                         case Length::EX:
2620                                         case Length::EM:
2621                                         case Length::MU:
2622                                                 known_unit = true;
2623                                                 break;
2624                                         default:
2625                                                 break;
2626                                         }
2627                                 }
2628                         }
2629
2630                         if (known_unit || known_vspace) {
2631                                 // Literal length or known variable
2632                                 context.check_layout(os);
2633                                 begin_inset(os, "VSpace ");
2634                                 if (known_unit)
2635                                         os << value;
2636                                 os << unit;
2637                                 if (starred)
2638                                         os << '*';
2639                                 end_inset(os);
2640                         } else {
2641                                 // LyX can't handle other length variables in Inset VSpace
2642                                 string name = t.asInput();
2643                                 if (starred)
2644                                         name += '*';
2645                                 if (valid) {
2646                                         if (value == 1.0)
2647                                                 handle_ert(os, name + '{' + unit + '}', context);
2648                                         else if (value == -1.0)
2649                                                 handle_ert(os, name + "{-" + unit + '}', context);
2650                                         else
2651                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
2652                                 } else
2653                                         handle_ert(os, name + '{' + length + '}', context);
2654                         }
2655                 }
2656
2657                 else {
2658                         // try to see whether the string is in unicodesymbols
2659                         docstring rem;
2660                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()), rem);
2661                         if (!s.empty()) {
2662                                 if (!rem.empty())
2663                                         cerr << "When parsing " << t.cs() 
2664                                              << ", result is " << to_utf8(s)
2665                                              << "+" << to_utf8(rem) << endl;
2666                                 context.check_layout(os);
2667                                 os << to_utf8(s);
2668                                 p.skip_spaces();
2669                                 skip_braces(p); // eat {}
2670                         }
2671                         //cerr << "#: " << t << " mode: " << mode << endl;
2672                         // heuristic: read up to next non-nested space
2673                         /*
2674                         string s = t.asInput();
2675                         string z = p.verbatim_item();
2676                         while (p.good() && z != " " && z.size()) {
2677                                 //cerr << "read: " << z << endl;
2678                                 s += z;
2679                                 z = p.verbatim_item();
2680                         }
2681                         cerr << "found ERT: " << s << endl;
2682                         handle_ert(os, s + ' ', context);
2683                         */
2684                         else {
2685                                 string name = t.asInput();
2686                                 if (p.next_token().asInput() == "*") {
2687                                         // Starred commands like \vspace*{}
2688                                         p.get_token();  // Eat '*'
2689                                         name += '*';
2690                                 }
2691                                 if (!parse_command(name, p, os, outer, context))
2692                                         handle_ert(os, name, context);
2693                         }
2694                 }
2695
2696                 if (flags & FLAG_LEAVE) {
2697                         flags &= ~FLAG_LEAVE;
2698                         break;
2699                 }
2700         }
2701 }
2702
2703 // }])
2704
2705
2706 } // namespace lyx