]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.C
fix tex2lyx comment handling
[lyx.git] / src / tex2lyx / text.C
1 /**
2  * \file tex2lyx/text.C
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  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 // {[(
13
14 #include <config.h>
15
16 #include "tex2lyx.h"
17 #include "context.h"
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/convert.h"
22 #include "support/filetools.h"
23
24 #include <boost/filesystem/operations.hpp>
25 #include <boost/tuple/tuple.hpp>
26
27 #include <iostream>
28 #include <map>
29 #include <sstream>
30 #include <vector>
31
32 using lyx::support::ChangeExtension;
33 using lyx::support::MakeAbsPath;
34 using lyx::support::rtrim;
35 using lyx::support::suffixIs;
36 using lyx::support::contains;
37 using lyx::support::subst;
38
39 using std::cerr;
40 using std::endl;
41
42 using std::map;
43 using std::ostream;
44 using std::ostringstream;
45 using std::istringstream;
46 using std::string;
47 using std::vector;
48
49 namespace fs = boost::filesystem;
50
51
52 /// thin wrapper around parse_text using a string
53 string parse_text(Parser & p, unsigned flags, const bool outer,
54                   Context & context)
55 {
56         ostringstream os;
57         parse_text(p, os, flags, outer, context);
58         return os.str();
59 }
60
61
62 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
63                 Context & context)
64 {
65         Context newcontext(true, context.textclass);
66         newcontext.font = context.font;
67         parse_text(p, os, flags, outer, newcontext);
68         newcontext.check_end_layout(os);
69 }
70
71
72 /// parses a paragraph snippet, useful for example for \emph{...}
73 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
74                 Context & context)
75 {
76         Context newcontext(false, context.textclass);
77         newcontext.font = context.font;
78         parse_text(p, os, flags, outer, newcontext);
79         // should not be needed
80         newcontext.check_end_layout(os);
81 }
82
83
84 namespace {
85
86 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
87 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
88
89 /*!
90  * natbib commands.
91  * We can't put these into known_latex_commands because the argument order
92  * is reversed in lyx if there are 2 arguments.
93  * The starred forms are also known.
94  */
95 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
96 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
97 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
98
99 /*!
100  * jurabib commands.
101  * We can't put these into known_latex_commands because the argument order
102  * is reversed in lyx if there are 2 arguments.
103  * No starred form other than "cite*" known.
104  */
105 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
106 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar", "fullcite",
107 // jurabib commands not (yet) supported by LyX:
108 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
109 // "footciteauthor", "footciteyear", "footciteyearpar",
110 "citefield", "citetitle", "cite*", 0 };
111
112 /// LaTeX names for quotes
113 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
114 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
115
116 /// the same as known_quotes with .lyx names
117 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
118 "grd", "gls", "fls", "frd", 0};
119
120 /// LaTeX names for font sizes
121 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
122 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
123
124 /// the same as known_sizes with .lyx names
125 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
126 "small", "normal", "large", "larger", "largest",  "huge", "giant", 0};
127
128 /// LaTeX 2.09 names for font families
129 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
130
131 /// LaTeX names for font families
132 char const * const known_font_families[] = { "rmfamily", "sffamily",
133 "ttfamily", 0};
134
135 /// the same as known_old_font_families and known_font_families with .lyx names
136 char const * const known_coded_font_families[] = { "roman", "sans",
137 "typewriter", 0};
138
139 /// LaTeX 2.09 names for font series
140 char const * const known_old_font_series[] = { "bf", 0};
141
142 /// LaTeX names for font series
143 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
144
145 /// the same as known_old_font_series and known_font_series with .lyx names
146 char const * const known_coded_font_series[] = { "bold", "medium", 0};
147
148 /// LaTeX 2.09 names for font shapes
149 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
150
151 /// LaTeX names for font shapes
152 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
153 "upshape", 0};
154
155 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
156 char const * const known_coded_font_shapes[] = { "italic", "slanted",
157 "smallcaps", "up", 0};
158
159 /*!
160  * Graphics file extensions known by the dvips driver of the graphics package.
161  * These extensions are used to complete the filename of an included
162  * graphics file if it does not contain an extension.
163  * The order must be the same that latex uses to find a file, because we
164  * will use the first extension that matches.
165  * This is only an approximation for the common cases. If we would want to
166  * do it right in all cases, we would need to know which graphics driver is
167  * used and know the extensions of every driver of the graphics package.
168  */
169 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
170 "ps.gz", "eps.Z", "ps.Z", 0};
171
172 /*!
173  * Graphics file extensions known by the pdftex driver of the graphics package.
174  * \sa known_dvips_graphics_formats
175  */
176 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
177 "mps", "tif", 0};
178
179 /*!
180  * Known file extensions for TeX files as used by \\include.
181  */
182 char const * const known_tex_extensions[] = {"tex", 0};
183
184
185 /// splits "x=z, y=b" into a map
186 map<string, string> split_map(string const & s)
187 {
188         map<string, string> res;
189         vector<string> v;
190         split(s, v);
191         for (size_t i = 0; i < v.size(); ++i) {
192                 size_t const pos   = v[i].find('=');
193                 string const index = v[i].substr(0, pos);
194                 string const value = v[i].substr(pos + 1, string::npos);
195                 res[trim(index)] = trim(value);
196         }
197         return res;
198 }
199
200
201 /*!
202  * Split a LaTeX length into value and unit.
203  * The latter can be a real unit like "pt", or a latex length variable
204  * like "\textwidth". The unit may contain additional stuff like glue
205  * lengths, but we don't care, because such lengths are ERT anyway.
206  * \returns true if \p value and \p unit are valid.
207  */
208 bool splitLatexLength(string const & len, string & value, string & unit)
209 {
210         if (len.empty())
211                 return false;
212         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
213         //'4,5' is a valid LaTeX length number. Change it to '4.5'
214         string const length = subst(len, ',', '.');
215         if (i == string::npos)
216                 return false;
217         if (i == 0) {
218                 if (len[0] == '\\') {
219                         // We had something like \textwidth without a factor
220                         value = "1.0";
221                 } else {
222                         return false;
223                 }
224         } else {
225                 value = trim(string(length, 0, i));
226         }
227         if (value == "-")
228                 value = "-1.0";
229         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
230         if (contains(len, '\\'))
231                 unit = trim(string(len, i));
232         else
233                 unit = lyx::support::lowercase(trim(string(len, i)));
234         return true;
235 }
236
237
238 /// A simple function to translate a latex length to something lyx can
239 /// understand. Not perfect, but rather best-effort.
240 bool translate_len(string const & length, string & valstring, string & unit)
241 {
242         if (!splitLatexLength(length, valstring, unit))
243                 return false;
244         // LyX uses percent values
245         double value;
246         istringstream iss(valstring);
247         iss >> value;
248         value *= 100;
249         ostringstream oss;
250         oss << value;
251         string const percentval = oss.str();
252         // a normal length
253         if (unit.empty() || unit[0] != '\\')
254                 return true;
255         string::size_type const i = unit.find(' ');
256         string const endlen = (i == string::npos) ? string() : string(unit, i);
257         if (unit == "\\textwidth") {
258                 valstring = percentval;
259                 unit = "text%" + endlen;
260         } else if (unit == "\\columnwidth") {
261                 valstring = percentval;
262                 unit = "col%" + endlen;
263         } else if (unit == "\\paperwidth") {
264                 valstring = percentval;
265                 unit = "page%" + endlen;
266         } else if (unit == "\\linewidth") {
267                 valstring = percentval;
268                 unit = "line%" + endlen;
269         } else if (unit == "\\paperheight") {
270                 valstring = percentval;
271                 unit = "pheight%" + endlen;
272         } else if (unit == "\\textheight") {
273                 valstring = percentval;
274                 unit = "theight%" + endlen;
275         }
276         return true;
277 }
278
279
280 string translate_len(string const & length)
281 {
282         string unit;
283         string value;
284         if (translate_len(length, value, unit))
285                 return value + unit;
286         // If the input is invalid, return what we have.
287         return length;
288 }
289
290
291 /*!
292  * Translates a LaTeX length into \p value, \p unit and
293  * \p special parts suitable for a box inset.
294  * The difference from translate_len() is that a box inset knows about
295  * some special "units" that are stored in \p special.
296  */
297 void translate_box_len(string const & length, string & value, string & unit, string & special)
298 {
299         if (translate_len(length, value, unit)) {
300                 if (unit == "\\height" || unit == "\\depth" ||
301                     unit == "\\totalheight" || unit == "\\width") {
302                         special = unit.substr(1);
303                         // The unit is not used, but LyX requires a dummy setting
304                         unit = "in";
305                 } else
306                         special = "none";
307         } else {
308                 value.clear();
309                 unit = length;
310                 special = "none";
311         }
312 }
313
314
315 /*!
316  * Find a file with basename \p name in path \p path and an extension
317  * in \p extensions.
318  */
319 string find_file(string const & name, string const & path,
320                  char const * const * extensions)
321 {
322         for (char const * const * what = extensions; *what; ++what) {
323                 // We don't use ChangeExtension() because it does the wrong
324                 // thing if name contains a dot.
325                 string const trial = name + '.' + (*what);
326                 if (fs::exists(MakeAbsPath(trial, path)))
327                         return trial;
328         }
329         return string();
330 }
331
332
333 void begin_inset(ostream & os, string const & name)
334 {
335         os << "\n\\begin_inset " << name;
336 }
337
338
339 void end_inset(ostream & os)
340 {
341         os << "\n\\end_inset\n\n";
342 }
343
344
345 void skip_braces(Parser & p)
346 {
347         if (p.next_token().cat() != catBegin)
348                 return;
349         p.get_token();
350         if (p.next_token().cat() == catEnd) {
351                 p.get_token();
352                 return;
353         }
354         p.putback();
355 }
356
357
358 void handle_ert(ostream & os, string const & s, Context & context, bool check_layout = true)
359 {
360         if (check_layout) {
361                 // We must have a valid layout before outputting the ERT inset.
362                 context.check_layout(os);
363         }
364         Context newcontext(true, context.textclass);
365         begin_inset(os, "ERT");
366         os << "\nstatus collapsed\n";
367         newcontext.check_layout(os);
368         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
369                 if (*it == '\\')
370                         os << "\n\\backslash\n";
371                 else if (*it == '\n') {
372                         newcontext.new_paragraph(os);
373                         newcontext.check_layout(os);
374                 } else
375                         os << *it;
376         }
377         newcontext.check_end_layout(os);
378         end_inset(os);
379 }
380
381
382 void handle_comment(ostream & os, string const & s, Context & context)
383 {
384         // TODO: Handle this better
385         Context newcontext(true, context.textclass);
386         begin_inset(os, "ERT");
387         os << "\nstatus collapsed\n";
388         newcontext.check_layout(os);
389         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
390                 if (*it == '\\')
391                         os << "\n\\backslash\n";
392                 else
393                         os << *it;
394         }
395         // make sure that our comment is the last thing on the line
396         newcontext.new_paragraph(os);
397         newcontext.check_layout(os);
398         newcontext.check_end_layout(os);
399         end_inset(os);
400 }
401
402
403 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
404 public:
405         isLayout(string const name) : name_(name) {}
406         bool operator()(LyXLayout_ptr const & ptr) const {
407                 return ptr->latexname() == name_;
408         }
409 private:
410         string const name_;
411 };
412
413
414 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
415                          string const & name)
416 {
417         LyXTextClass::const_iterator beg  = textclass.begin();
418         LyXTextClass::const_iterator end = textclass.end();
419
420         LyXTextClass::const_iterator
421                 it = std::find_if(beg, end, isLayout(name));
422
423         return (it == end) ? LyXLayout_ptr() : *it;
424 }
425
426
427 void eat_whitespace(Parser &, ostream &, Context &, bool);
428
429
430 void output_command_layout(ostream & os, Parser & p, bool outer,
431                            Context & parent_context,
432                            LyXLayout_ptr newlayout)
433 {
434         parent_context.check_end_layout(os);
435         Context context(true, parent_context.textclass, newlayout,
436                         parent_context.layout, parent_context.font);
437         if (parent_context.deeper_paragraph) {
438                 // We are beginning a nested environment after a
439                 // deeper paragraph inside the outer list environment.
440                 // Therefore we don't need to output a "begin deeper".
441                 context.need_end_deeper = true;
442         }
443         context.check_deeper(os);
444         context.check_layout(os);
445         if (context.layout->optionalargs > 0) {
446                 eat_whitespace(p, os, context, false);
447                 if (p.next_token().character() == '[') {
448                         p.get_token(); // eat '['
449                         begin_inset(os, "OptArg\n");
450                         os << "status collapsed\n\n";
451                         parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
452                         end_inset(os);
453                         eat_whitespace(p, os, context, false);
454                 }
455         }
456         parse_text(p, os, FLAG_ITEM, outer, context);
457         context.check_end_layout(os);
458         if (parent_context.deeper_paragraph) {
459                 // We must suppress the "end deeper" because we
460                 // suppressed the "begin deeper" above.
461                 context.need_end_deeper = false;
462         }
463         context.check_end_deeper(os);
464         // We don't need really a new paragraph, but
465         // we must make sure that the next item gets a \begin_layout.
466         parent_context.new_paragraph(os);
467 }
468
469
470 /*!
471  * Output a space if necessary.
472  * This function gets called for every whitespace token.
473  *
474  * We have three cases here:
475  * 1. A space must be suppressed. Example: The lyxcode case below
476  * 2. A space may be suppressed. Example: Spaces before "\par"
477  * 3. A space must not be suppressed. Example: A space between two words
478  *
479  * We currently handle only 1. and 3 and from 2. only the case of
480  * spaces before newlines as a side effect.
481  *
482  * 2. could be used to suppress as many spaces as possible. This has two effects:
483  * - Reimporting LyX generated LaTeX files changes almost no whitespace
484  * - Superflous whitespace from non LyX generated LaTeX files is removed.
485  * The drawback is that the logic inside the function becomes
486  * complicated, and that is the reason why it is not implemented.
487  */
488 void check_space(Parser const & p, ostream & os, Context & context)
489 {
490         Token const next = p.next_token();
491         Token const curr = p.curr_token();
492         // A space before a single newline and vice versa must be ignored
493         // LyX emits a newline before \end{lyxcode}.
494         // This newline must be ignored,
495         // otherwise LyX will add an additional protected space.
496         if (next.cat() == catSpace ||
497             next.cat() == catNewline ||
498             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
499                 return;
500         }
501         context.check_layout(os);
502         os << ' ';
503 }
504
505
506 /*!
507  * Check whether \p command is a known command. If yes,
508  * handle the command with all arguments.
509  * \return true if the command was parsed, false otherwise.
510  */
511 bool parse_command(string const & command, Parser & p, ostream & os,
512                    bool outer, Context & context)
513 {
514         if (known_commands.find(command) != known_commands.end()) {
515                 vector<ArgumentType> const & template_arguments = known_commands[command];
516                 string ert = command;
517                 size_t no_arguments = template_arguments.size();
518                 for (size_t i = 0; i < no_arguments; ++i) {
519                         switch (template_arguments[i]) {
520                         case required:
521                                 // This argument contains regular LaTeX
522                                 handle_ert(os, ert + '{', context);
523                                 parse_text(p, os, FLAG_ITEM, outer, context);
524                                 ert = "}";
525                                 break;
526                         case verbatim:
527                                 // This argument may contain special characters
528                                 ert += '{' + p.verbatim_item() + '}';
529                                 break;
530                         case optional:
531                                 ert += p.getOpt();
532                                 break;
533                         }
534                 }
535                 handle_ert(os, ert, context);
536                 return true;
537         }
538         return false;
539 }
540
541
542 /// Parses a minipage or parbox
543 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
544                Context & parent_context, bool use_parbox)
545 {
546         string position;
547         string inner_pos;
548         string height_value = "0";
549         string height_unit = "pt";
550         string height_special = "none";
551         string latex_height;
552         if (p.next_token().asInput() == "[") {
553                 position = p.getArg('[', ']');
554                 if (position != "t" && position != "c" && position != "b") {
555                         position = "c";
556                         cerr << "invalid position for minipage/parbox" << endl;
557                 }
558                 if (p.next_token().asInput() == "[") {
559                         latex_height = p.getArg('[', ']');
560                         translate_box_len(latex_height, height_value, height_unit, height_special);
561
562                         if (p.next_token().asInput() == "[") {
563                                 inner_pos = p.getArg('[', ']');
564                                 if (inner_pos != "c" && inner_pos != "t" &&
565                                     inner_pos != "b" && inner_pos != "s") {
566                                         inner_pos = position;
567                                         cerr << "invalid inner_pos for minipage/parbox"
568                                              << endl;
569                                 }
570                         }
571                 }
572         }
573         string width_value;
574         string width_unit;
575         string const latex_width = p.verbatim_item();
576         translate_len(latex_width, width_value, width_unit);
577         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
578                 // LyX can't handle length variables
579                 ostringstream ss;
580                 if (use_parbox)
581                         ss << "\\parbox";
582                 else
583                         ss << "\\begin{minipage}";
584                 if (!position.empty())
585                         ss << '[' << position << ']';
586                 if (!latex_height.empty())
587                         ss << '[' << latex_height << ']';
588                 if (!inner_pos.empty())
589                         ss << '[' << inner_pos << ']';
590                 ss << "{" << latex_width << "}";
591                 if (use_parbox)
592                         ss << '{';
593                 handle_ert(os, ss.str(), parent_context);
594                 parent_context.new_paragraph(os);
595                 parse_text_in_inset(p, os, flags, outer, parent_context);
596                 if (use_parbox)
597                         handle_ert(os, "}", parent_context);
598                 else
599                         handle_ert(os, "\\end{minipage}", parent_context);
600         } else {
601                 // LyX does not like empty positions, so we have
602                 // to set them to the LaTeX default values here.
603                 if (position.empty())
604                         position = "c";
605                 if (inner_pos.empty())
606                         inner_pos = position;
607                 parent_context.check_layout(os);
608                 begin_inset(os, "Box Frameless\n");
609                 os << "position \"" << position << "\"\n";
610                 os << "hor_pos \"c\"\n";
611                 os << "has_inner_box 1\n";
612                 os << "inner_pos \"" << inner_pos << "\"\n";
613                 os << "use_parbox " << use_parbox << "\n";
614                 os << "width \"" << width_value << width_unit << "\"\n";
615                 os << "special \"none\"\n";
616                 os << "height \"" << height_value << height_unit << "\"\n";
617                 os << "height_special \"" << height_special << "\"\n";
618                 os << "status open\n\n";
619                 parse_text_in_inset(p, os, flags, outer, parent_context);
620                 end_inset(os);
621 #ifdef PRESERVE_LAYOUT
622                 // lyx puts a % after the end of the minipage
623                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
624                         // new paragraph
625                         //handle_comment(os, "%dummy", parent_context);
626                         p.get_token();
627                         p.skip_spaces();
628                         parent_context.new_paragraph(os);
629                 }
630                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
631                         //handle_comment(os, "%dummy", parent_context);
632                         p.get_token();
633                         p.skip_spaces();
634                         // We add a protected space if something real follows
635                         if (p.good() && p.next_token().cat() != catComment) {
636                                 os << "\\InsetSpace ~\n";
637                         }
638                 }
639 #endif
640         }
641 }
642
643
644 void parse_environment(Parser & p, ostream & os, bool outer,
645                        Context & parent_context)
646 {
647         LyXLayout_ptr newlayout;
648         string const name = p.getArg('{', '}');
649         const bool is_starred = suffixIs(name, '*');
650         string const unstarred_name = rtrim(name, "*");
651         eat_whitespace(p, os, parent_context, false);
652         active_environments.push_back(name);
653
654         if (is_math_env(name)) {
655                 parent_context.check_layout(os);
656                 begin_inset(os, "Formula ");
657                 os << "\\begin{" << name << "}";
658                 parse_math(p, os, FLAG_END, MATH_MODE);
659                 os << "\\end{" << name << "}";
660                 end_inset(os);
661         }
662
663         else if (name == "tabular" || name == "longtable") {
664                 parent_context.check_layout(os);
665                 begin_inset(os, "Tabular ");
666                 handle_tabular(p, os, name == "longtable", parent_context);
667                 end_inset(os);
668         }
669
670         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
671                 parent_context.check_layout(os);
672                 begin_inset(os, "Float " + unstarred_name + "\n");
673                 if (p.next_token().asInput() == "[") {
674                         os << "placement " << p.getArg('[', ']') << '\n';
675                 }
676                 os << "wide " << convert<string>(is_starred)
677                    << "\nsideways false"
678                    << "\nstatus open\n\n";
679                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
680                 end_inset(os);
681                 // We don't need really a new paragraph, but
682                 // we must make sure that the next item gets a \begin_layout.
683                 parent_context.new_paragraph(os);
684         }
685
686         else if (name == "minipage")
687                 parse_box(p, os, FLAG_END, outer, parent_context, false);
688
689         // Alignment settings
690         else if (name == "center" || name == "flushleft" || name == "flushright" ||
691                  name == "centering" || name == "raggedright" || name == "raggedleft") {
692                 // We must begin a new paragraph if not already done
693                 if (! parent_context.atParagraphStart()) {
694                         parent_context.check_end_layout(os);
695                         parent_context.new_paragraph(os);
696                 }
697                 if (name == "flushleft" || name == "raggedright")
698                         parent_context.add_extra_stuff("\\align left\n");
699                 else if (name == "flushright" || name == "raggedleft")
700                         parent_context.add_extra_stuff("\\align right\n");
701                 else
702                         parent_context.add_extra_stuff("\\align center\n");
703                 parse_text(p, os, FLAG_END, outer, parent_context);
704                 // Just in case the environment is empty ..
705                 parent_context.extra_stuff.erase();
706                 // We must begin a new paragraph to reset the alignment
707                 parent_context.new_paragraph(os);
708         }
709
710         // The single '=' is meant here.
711         else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
712                    newlayout->isEnvironment()) {
713                 Context context(true, parent_context.textclass, newlayout,
714                                 parent_context.layout, parent_context.font);
715                 if (parent_context.deeper_paragraph) {
716                         // We are beginning a nested environment after a
717                         // deeper paragraph inside the outer list environment.
718                         // Therefore we don't need to output a "begin deeper".
719                         context.need_end_deeper = true;
720                 }
721                 parent_context.check_end_layout(os);
722                 switch (context.layout->latextype) {
723                 case  LATEX_LIST_ENVIRONMENT:
724                         context.extra_stuff = "\\labelwidthstring "
725                                 + p.verbatim_item() + '\n';
726                         p.skip_spaces();
727                         break;
728                 case  LATEX_BIB_ENVIRONMENT:
729                         p.verbatim_item(); // swallow next arg
730                         p.skip_spaces();
731                         break;
732                 default:
733                         break;
734                 }
735                 context.check_deeper(os);
736                 parse_text(p, os, FLAG_END, outer, context);
737                 context.check_end_layout(os);
738                 if (parent_context.deeper_paragraph) {
739                         // We must suppress the "end deeper" because we
740                         // suppressed the "begin deeper" above.
741                         context.need_end_deeper = false;
742                 }
743                 context.check_end_deeper(os);
744                 parent_context.new_paragraph(os);
745         }
746
747         else if (name == "appendix") {
748                 // This is no good latex style, but it works and is used in some documents...
749                 parent_context.check_end_layout(os);
750                 Context context(true, parent_context.textclass, parent_context.layout,
751                                 parent_context.layout, parent_context.font);
752                 context.check_layout(os);
753                 os << "\\start_of_appendix\n";
754                 parse_text(p, os, FLAG_END, outer, context);
755                 context.check_end_layout(os);
756         }
757
758         else if (name == "comment") {
759                 parent_context.check_layout(os);
760                 begin_inset(os, "Note Comment\n");
761                 os << "status open\n";
762                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
763                 end_inset(os);
764         }
765
766         else if (name == "lyxgreyedout") {
767                 parent_context.check_layout(os);
768                 begin_inset(os, "Note Greyedout\n");
769                 os << "status open\n";
770                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
771                 end_inset(os);
772         }
773
774         else if (name == "tabbing") {
775                 // We need to remember that we have to handle '\=' specially
776                 handle_ert(os, "\\begin{" + name + "}", parent_context);
777                 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer, parent_context);
778                 handle_ert(os, "\\end{" + name + "}", parent_context);
779         }
780
781         else {
782                 handle_ert(os, "\\begin{" + name + "}", parent_context);
783                 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
784                 handle_ert(os, "\\end{" + name + "}", parent_context);
785         }
786
787         active_environments.pop_back();
788         if (name != "math")
789                 p.skip_spaces();
790 }
791
792
793 /// parses a comment and outputs it to \p os.
794 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
795 {
796         BOOST_ASSERT(t.cat() == catComment);
797         if (!t.cs().empty()) {
798                 context.check_layout(os);
799                 handle_comment(os, '%' + t.cs(), context);
800                 if (p.next_token().cat() == catNewline) {
801                         // A newline after a comment line starts a new
802                         // paragraph
803                         if(!context.atParagraphStart()) {
804                                 // Only start a new paragraph if not already
805                                 // done (we might get called recursively)
806                                 context.new_paragraph(os);
807                         }
808                         eat_whitespace(p, os, context, true);
809                 }
810         } else {
811                 // "%\n" combination
812                 p.skip_spaces();
813         }
814 }
815
816
817 /*!
818  * Reads spaces and comments until the first non-space, non-comment token.
819  * New paragraphs (double newlines or \\par) are handled like simple spaces
820  * if \p eatParagraph is true.
821  * Spaces are skipped, but comments are written to \p os.
822  */
823 void eat_whitespace(Parser & p, ostream & os, Context & context,
824                     bool eatParagraph)
825 {
826         while (p.good()) {
827                 Token const & t = p.get_token();
828                 if (t.cat() == catComment)
829                         parse_comment(p, os, t, context);
830                 else if ((! eatParagraph && p.isParagraph()) ||
831                          (t.cat() != catSpace && t.cat() != catNewline)) {
832                         p.putback();
833                         return;
834                 }
835         }
836 }
837
838
839 /*!
840  * Set a font attribute, parse text and reset the font attribute.
841  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
842  * \param currentvalue Current value of the attribute. Is set to the new
843  * value during parsing.
844  * \param newvalue New value of the attribute
845  */
846 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
847                            Context & context, string const & attribute,
848                            string & currentvalue, string const & newvalue)
849 {
850         context.check_layout(os);
851         string oldvalue = currentvalue;
852         currentvalue = newvalue;
853         os << '\n' << attribute << ' ' << newvalue << "\n";
854         parse_text_snippet(p, os, flags, outer, context);
855         currentvalue = oldvalue;
856         os << '\n' << attribute << ' ' << oldvalue << "\n";
857 }
858
859
860 /// get the arguments of a natbib or jurabib citation command
861 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
862 {
863         // We need to distinguish "" and "[]", so we can't use p.getOpt().
864
865         // text before the citation
866         string before;
867         // text after the citation
868         string after = p.getFullOpt();
869
870         if (!after.empty()) {
871                 before = p.getFullOpt();
872                 if (natbibOrder && !before.empty())
873                         std::swap(before, after);
874         }
875         return std::make_pair(before, after);
876 }
877
878
879 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
880 string const normalize_filename(string const & name)
881 {
882         Parser p(trim(name, "\""));
883         ostringstream os;
884         while (p.good()) {
885                 Token const & t = p.get_token();
886                 if (t.cat() != catEscape)
887                         os << t.asInput();
888                 else if (t.cs() == "lyxdot") {
889                         // This is used by LyX for simple dots in relative
890                         // names
891                         os << '.';
892                         p.skip_spaces();
893                 } else if (t.cs() == "space") {
894                         os << ' ';
895                         p.skip_spaces();
896                 } else
897                         os << t.asInput();
898         }
899         return os.str();
900 }
901
902 } // anonymous namespace
903
904
905 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
906                 Context & context)
907 {
908         LyXLayout_ptr newlayout;
909         // Store the latest bibliographystyle (needed for bibtex inset)
910         string bibliographystyle;
911         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
912         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
913         while (p.good()) {
914                 Token const & t = p.get_token();
915
916 #ifdef FILEDEBUG
917                 cerr << "t: " << t << " flags: " << flags << "\n";
918 #endif
919
920                 if (flags & FLAG_ITEM) {
921                         if (t.cat() == catSpace)
922                                 continue;
923
924                         flags &= ~FLAG_ITEM;
925                         if (t.cat() == catBegin) {
926                                 // skip the brace and collect everything to the next matching
927                                 // closing brace
928                                 flags |= FLAG_BRACE_LAST;
929                                 continue;
930                         }
931
932                         // handle only this single token, leave the loop if done
933                         flags |= FLAG_LEAVE;
934                 }
935
936                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
937                         return;
938
939                 //
940                 // cat codes
941                 //
942                 if (t.cat() == catMath) {
943                         // we are inside some text mode thingy, so opening new math is allowed
944                         context.check_layout(os);
945                         begin_inset(os, "Formula ");
946                         Token const & n = p.get_token();
947                         if (n.cat() == catMath && outer) {
948                                 // TeX's $$...$$ syntax for displayed math
949                                 os << "\\[";
950                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
951                                 os << "\\]";
952                                 p.get_token(); // skip the second '$' token
953                         } else {
954                                 // simple $...$  stuff
955                                 p.putback();
956                                 os << '$';
957                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
958                                 os << '$';
959                         }
960                         end_inset(os);
961                 }
962
963                 else if (t.cat() == catSuper || t.cat() == catSub)
964                         cerr << "catcode " << t << " illegal in text mode\n";
965
966                 // Basic support for english quotes. This should be
967                 // extended to other quotes, but is not so easy (a
968                 // left english quote is the same as a right german
969                 // quote...)
970                 else if (t.asInput() == "`"
971                          && p.next_token().asInput() == "`") {
972                         context.check_layout(os);
973                         begin_inset(os, "Quotes ");
974                         os << "eld";
975                         end_inset(os);
976                         p.get_token();
977                         skip_braces(p);
978                 }
979                 else if (t.asInput() == "'"
980                          && p.next_token().asInput() == "'") {
981                         context.check_layout(os);
982                         begin_inset(os, "Quotes ");
983                         os << "erd";
984                         end_inset(os);
985                         p.get_token();
986                         skip_braces(p);
987                 }
988
989                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
990                         check_space(p, os, context);
991
992                 else if (t.cat() == catLetter ||
993                                t.cat() == catOther ||
994                                t.cat() == catAlign ||
995                                t.cat() == catParameter) {
996                         // This translates "&" to "\\&" which may be wrong...
997                         context.check_layout(os);
998                         os << t.character();
999                 }
1000
1001                 else if (p.isParagraph()) {
1002                         context.new_paragraph(os);
1003                         eat_whitespace(p, os, context, true);
1004                 }
1005
1006                 else if (t.cat() == catActive) {
1007                         context.check_layout(os);
1008                         if (t.character() == '~') {
1009                                 if (context.layout->free_spacing)
1010                                         os << ' ';
1011                                 else
1012                                         os << "\\InsetSpace ~\n";
1013                         } else
1014                                 os << t.character();
1015                 }
1016
1017                 else if (t.cat() == catBegin) {
1018                         context.check_layout(os);
1019                         // special handling of font attribute changes
1020                         Token const prev = p.prev_token();
1021                         Token const next = p.next_token();
1022                         Font const oldFont = context.font;
1023                         string const s = parse_text(p, FLAG_BRACE_LAST, outer,
1024                                                     context);
1025                         context.font = oldFont;
1026                         if (s.empty() && (p.next_token().character() == '`' ||
1027                                           (prev.character() == '-' &&
1028                                            p.next_token().character() == '-')))
1029                                 ; // ignore it in {}`` or -{}-
1030                         else if (s == "[" || s == "]" || s == "*")
1031                                 os << s;
1032                         else if (is_known(next.cs(), known_sizes)) {
1033                                 // s will change the size, so we must reset
1034                                 // it here
1035                                 os << s;
1036                                 if (!context.atParagraphStart())
1037                                         os << "\n\\size "
1038                                            << context.font.size << "\n";
1039                         } else if (is_known(next.cs(), known_font_families)) {
1040                                 // s will change the font family, so we must
1041                                 // reset it here
1042                                 os << s;
1043                                 if (!context.atParagraphStart())
1044                                         os << "\n\\family "
1045                                            << context.font.family << "\n";
1046                         } else if (is_known(next.cs(), known_font_series)) {
1047                                 // s will change the font series, so we must
1048                                 // reset it here
1049                                 os << s;
1050                                 if (!context.atParagraphStart())
1051                                         os << "\n\\series "
1052                                            << context.font.series << "\n";
1053                         } else if (is_known(next.cs(), known_font_shapes)) {
1054                                 // s will change the font shape, so we must
1055                                 // reset it here
1056                                 os << s;
1057                                 if (!context.atParagraphStart())
1058                                         os << "\n\\shape "
1059                                            << context.font.shape << "\n";
1060                         } else if (is_known(next.cs(), known_old_font_families) ||
1061                                    is_known(next.cs(), known_old_font_series) ||
1062                                    is_known(next.cs(), known_old_font_shapes)) {
1063                                 // s will change the font family, series
1064                                 // and shape, so we must reset it here
1065                                 os << s;
1066                                 if (!context.atParagraphStart())
1067                                         os <<  "\n\\family "
1068                                            << context.font.family
1069                                            << "\n\\series "
1070                                            << context.font.series
1071                                            << "\n\\shape "
1072                                            << context.font.shape << "\n";
1073                         } else {
1074                                 handle_ert(os, "{", context, false);
1075                                 // s will end the current layout and begin a
1076                                 // new one if necessary
1077                                 os << s;
1078                                 handle_ert(os, "}", context);
1079                         }
1080                 }
1081
1082                 else if (t.cat() == catEnd) {
1083                         if (flags & FLAG_BRACE_LAST) {
1084                                 return;
1085                         }
1086                         cerr << "stray '}' in text\n";
1087                         handle_ert(os, "}", context);
1088                 }
1089
1090                 else if (t.cat() == catComment)
1091                         parse_comment(p, os, t, context);
1092
1093                 //
1094                 // control sequences
1095                 //
1096
1097                 else if (t.cs() == "(") {
1098                         context.check_layout(os);
1099                         begin_inset(os, "Formula");
1100                         os << " \\(";
1101                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1102                         os << "\\)";
1103                         end_inset(os);
1104                 }
1105
1106                 else if (t.cs() == "[") {
1107                         context.check_layout(os);
1108                         begin_inset(os, "Formula");
1109                         os << " \\[";
1110                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1111                         os << "\\]";
1112                         end_inset(os);
1113                 }
1114
1115                 else if (t.cs() == "begin")
1116                         parse_environment(p, os, outer, context);
1117
1118                 else if (t.cs() == "end") {
1119                         if (flags & FLAG_END) {
1120                                 // eat environment name
1121                                 string const name = p.getArg('{', '}');
1122                                 if (name != active_environment())
1123                                         cerr << "\\end{" + name + "} does not match \\begin{"
1124                                                 + active_environment() + "}\n";
1125                                 return;
1126                         }
1127                         p.error("found 'end' unexpectedly");
1128                 }
1129
1130                 else if (t.cs() == "item") {
1131                         p.skip_spaces();
1132                         string s;
1133                         bool optarg = false;
1134                         if (p.next_token().character() == '[') {
1135                                 p.get_token(); // eat '['
1136                                 Context newcontext(false, context.textclass);
1137                                 newcontext.font = context.font;
1138                                 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
1139                                 optarg = true;
1140                         }
1141                         context.set_item();
1142                         context.check_layout(os);
1143                         if (optarg) {
1144                                 if (context.layout->labeltype != LABEL_MANUAL) {
1145                                         // lyx does not support \item[\mybullet]
1146                                         // in itemize environments
1147                                         handle_ert(os, "[", context);
1148                                         os << s;
1149                                         handle_ert(os, "]", context);
1150                                 } else if (!s.empty()) {
1151                                         // The space is needed to separate the
1152                                         // item from the rest of the sentence.
1153                                         os << s << ' ';
1154                                         eat_whitespace(p, os, context, false);
1155                                 }
1156                         }
1157                 }
1158
1159                 else if (t.cs() == "bibitem") {
1160                         context.set_item();
1161                         context.check_layout(os);
1162                         os << "\\bibitem ";
1163                         os << p.getOpt();
1164                         os << '{' << p.verbatim_item() << '}' << "\n";
1165                 }
1166
1167                 else if (t.cs() == "def") {
1168                         context.check_layout(os);
1169                         eat_whitespace(p, os, context, false);
1170                         string name = p.get_token().cs();
1171                         while (p.next_token().cat() != catBegin)
1172                                 name += p.get_token().asString();
1173                         handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1174                 }
1175
1176                 else if (t.cs() == "noindent") {
1177                         p.skip_spaces();
1178                         context.add_extra_stuff("\\noindent\n");
1179                 }
1180
1181                 else if (t.cs() == "appendix") {
1182                         context.add_extra_stuff("\\start_of_appendix\n");
1183                         // We need to start a new paragraph. Otherwise the
1184                         // appendix in 'bla\appendix\chapter{' would start
1185                         // too late.
1186                         context.new_paragraph(os);
1187                         // We need to make sure that the paragraph is
1188                         // generated even if it is empty. Otherwise the
1189                         // appendix in '\par\appendix\par\chapter{' would
1190                         // start too late.
1191                         context.check_layout(os);
1192                         // FIXME: This is a hack to prevent paragraph
1193                         // deletion if it is empty. Handle this better!
1194                         handle_comment(os,
1195                                 "%dummy comment inserted by tex2lyx to "
1196                                 "ensure that this paragraph is not empty",
1197                                 context);
1198                         // Both measures above may generate an additional
1199                         // empty paragraph, but that does not hurt, because
1200                         // whitespace does not matter here.
1201                         eat_whitespace(p, os, context, true);
1202                 }
1203
1204                 // Must attempt to parse "Section*" before "Section".
1205                 else if ((p.next_token().asInput() == "*") &&
1206                          // The single '=' is meant here.
1207                          (newlayout = findLayout(context.textclass,
1208                                                  t.cs() + '*')).get() &&
1209                          newlayout->isCommand()) {
1210                         p.get_token();
1211                         output_command_layout(os, p, outer, context, newlayout);
1212                         p.skip_spaces();
1213                 }
1214
1215                 // The single '=' is meant here.
1216                 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
1217                          newlayout->isCommand()) {
1218                         output_command_layout(os, p, outer, context, newlayout);
1219                         p.skip_spaces();
1220                 }
1221
1222                 else if (t.cs() == "includegraphics") {
1223                         bool const clip = p.next_token().asInput() == "*";
1224                         if (clip)
1225                                 p.get_token();
1226                         map<string, string> opts = split_map(p.getArg('[', ']'));
1227                         if (clip)
1228                                 opts["clip"] = string();
1229                         string name = normalize_filename(p.verbatim_item());
1230
1231                         string const path = getMasterFilePath();
1232                         // We want to preserve relative / absolute filenames,
1233                         // therefore path is only used for testing
1234                         if (!fs::exists(MakeAbsPath(name, path))) {
1235                                 // The file extension is probably missing.
1236                                 // Now try to find it out.
1237                                 string const dvips_name =
1238                                         find_file(name, path,
1239                                                   known_dvips_graphics_formats);
1240                                 string const pdftex_name =
1241                                         find_file(name, path,
1242                                                   known_pdftex_graphics_formats);
1243                                 if (!dvips_name.empty()) {
1244                                         if (!pdftex_name.empty()) {
1245                                                 cerr << "This file contains the "
1246                                                         "latex snippet\n"
1247                                                         "\"\\includegraphics{"
1248                                                      << name << "}\".\n"
1249                                                         "However, files\n\""
1250                                                      << dvips_name << "\" and\n\""
1251                                                      << pdftex_name << "\"\n"
1252                                                         "both exist, so I had to make a "
1253                                                         "choice and took the first one.\n"
1254                                                         "Please move the unwanted one "
1255                                                         "someplace else and try again\n"
1256                                                         "if my choice was wrong."
1257                                                      << endl;
1258                                         }
1259                                         name = dvips_name;
1260                                 } else if (!pdftex_name.empty())
1261                                         name = pdftex_name;
1262
1263                                 if (!fs::exists(MakeAbsPath(name, path)))
1264                                         cerr << "Warning: Could not find graphics file '"
1265                                              << name << "'." << endl;
1266                         }
1267
1268                         context.check_layout(os);
1269                         begin_inset(os, "Graphics ");
1270                         os << "\n\tfilename " << name << '\n';
1271                         if (opts.find("width") != opts.end())
1272                                 os << "\twidth "
1273                                    << translate_len(opts["width"]) << '\n';
1274                         if (opts.find("height") != opts.end())
1275                                 os << "\theight "
1276                                    << translate_len(opts["height"]) << '\n';
1277                         if (opts.find("scale") != opts.end()) {
1278                                 istringstream iss(opts["scale"]);
1279                                 double val;
1280                                 iss >> val;
1281                                 val = val*100;
1282                                 os << "\tscale " << val << '\n';
1283                         }
1284                         if (opts.find("angle") != opts.end())
1285                                 os << "\trotateAngle "
1286                                    << opts["angle"] << '\n';
1287                         if (opts.find("origin") != opts.end()) {
1288                                 ostringstream ss;
1289                                 string const opt = opts["origin"];
1290                                 if (opt.find('l') != string::npos) ss << "left";
1291                                 if (opt.find('r') != string::npos) ss << "right";
1292                                 if (opt.find('c') != string::npos) ss << "center";
1293                                 if (opt.find('t') != string::npos) ss << "Top";
1294                                 if (opt.find('b') != string::npos) ss << "Bottom";
1295                                 if (opt.find('B') != string::npos) ss << "Baseline";
1296                                 if (!ss.str().empty())
1297                                         os << "\trotateOrigin " << ss.str() << '\n';
1298                                 else
1299                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1300                         }
1301                         if (opts.find("keepaspectratio") != opts.end())
1302                                 os << "\tkeepAspectRatio\n";
1303                         if (opts.find("clip") != opts.end())
1304                                 os << "\tclip\n";
1305                         if (opts.find("draft") != opts.end())
1306                                 os << "\tdraft\n";
1307                         if (opts.find("bb") != opts.end())
1308                                 os << "\tBoundingBox "
1309                                    << opts["bb"] << '\n';
1310                         int numberOfbbOptions = 0;
1311                         if (opts.find("bbllx") != opts.end())
1312                                 numberOfbbOptions++;
1313                         if (opts.find("bblly") != opts.end())
1314                                 numberOfbbOptions++;
1315                         if (opts.find("bburx") != opts.end())
1316                                 numberOfbbOptions++;
1317                         if (opts.find("bbury") != opts.end())
1318                                 numberOfbbOptions++;
1319                         if (numberOfbbOptions == 4)
1320                                 os << "\tBoundingBox "
1321                                    << opts["bbllx"] << opts["bblly"]
1322                                    << opts["bburx"] << opts["bbury"] << '\n';
1323                         else if (numberOfbbOptions > 0)
1324                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1325                         numberOfbbOptions = 0;
1326                         if (opts.find("natwidth") != opts.end())
1327                                 numberOfbbOptions++;
1328                         if (opts.find("natheight") != opts.end())
1329                                 numberOfbbOptions++;
1330                         if (numberOfbbOptions == 2)
1331                                 os << "\tBoundingBox 0bp 0bp "
1332                                    << opts["natwidth"] << opts["natheight"] << '\n';
1333                         else if (numberOfbbOptions > 0)
1334                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1335                         ostringstream special;
1336                         if (opts.find("hiresbb") != opts.end())
1337                                 special << "hiresbb,";
1338                         if (opts.find("trim") != opts.end())
1339                                 special << "trim,";
1340                         if (opts.find("viewport") != opts.end())
1341                                 special << "viewport=" << opts["viewport"] << ',';
1342                         if (opts.find("totalheight") != opts.end())
1343                                 special << "totalheight=" << opts["totalheight"] << ',';
1344                         if (opts.find("type") != opts.end())
1345                                 special << "type=" << opts["type"] << ',';
1346                         if (opts.find("ext") != opts.end())
1347                                 special << "ext=" << opts["ext"] << ',';
1348                         if (opts.find("read") != opts.end())
1349                                 special << "read=" << opts["read"] << ',';
1350                         if (opts.find("command") != opts.end())
1351                                 special << "command=" << opts["command"] << ',';
1352                         string s_special = special.str();
1353                         if (!s_special.empty()) {
1354                                 // We had special arguments. Remove the trailing ','.
1355                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1356                         }
1357                         // TODO: Handle the unknown settings better.
1358                         // Warn about invalid options.
1359                         // Check whether some option was given twice.
1360                         end_inset(os);
1361                 }
1362
1363                 else if (t.cs() == "footnote" ||
1364                          (t.cs() == "thanks" && context.layout->intitle)) {
1365                         p.skip_spaces();
1366                         context.check_layout(os);
1367                         begin_inset(os, "Foot\n");
1368                         os << "status collapsed\n\n";
1369                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1370                         end_inset(os);
1371                 }
1372
1373                 else if (t.cs() == "marginpar") {
1374                         p.skip_spaces();
1375                         context.check_layout(os);
1376                         begin_inset(os, "Marginal\n");
1377                         os << "status collapsed\n\n";
1378                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1379                         end_inset(os);
1380                 }
1381
1382                 else if (t.cs() == "ensuremath") {
1383                         p.skip_spaces();
1384                         context.check_layout(os);
1385                         Context newcontext(false, context.textclass);
1386                         newcontext.font = context.font;
1387                         string s = parse_text(p, FLAG_ITEM, false, newcontext);
1388                         if (s == "±" || s == "³" || s == "²" || s == "µ")
1389                                 os << s;
1390                         else
1391                                 handle_ert(os, "\\ensuremath{" + s + "}",
1392                                            context);
1393                 }
1394
1395                 else if (t.cs() == "hfill") {
1396                         context.check_layout(os);
1397                         os << "\n\\hfill\n";
1398                         skip_braces(p);
1399                         p.skip_spaces();
1400                 }
1401
1402                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1403                         // FIXME: Somehow prevent title layouts if
1404                         // "maketitle" was not found
1405                         p.skip_spaces();
1406                         skip_braces(p); // swallow this
1407                 }
1408
1409                 else if (t.cs() == "tableofcontents") {
1410                         p.skip_spaces();
1411                         context.check_layout(os);
1412                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1413                         end_inset(os);
1414                         skip_braces(p); // swallow this
1415                 }
1416
1417                 else if (t.cs() == "listoffigures") {
1418                         p.skip_spaces();
1419                         context.check_layout(os);
1420                         begin_inset(os, "FloatList figure\n");
1421                         end_inset(os);
1422                         skip_braces(p); // swallow this
1423                 }
1424
1425                 else if (t.cs() == "listoftables") {
1426                         p.skip_spaces();
1427                         context.check_layout(os);
1428                         begin_inset(os, "FloatList table\n");
1429                         end_inset(os);
1430                         skip_braces(p); // swallow this
1431                 }
1432
1433                 else if (t.cs() == "listof") {
1434                         p.skip_spaces(true);
1435                         string const name = p.get_token().asString();
1436                         if (context.textclass.floats().typeExist(name)) {
1437                                 context.check_layout(os);
1438                                 begin_inset(os, "FloatList ");
1439                                 os << name << "\n";
1440                                 end_inset(os);
1441                                 p.get_token(); // swallow second arg
1442                         } else
1443                                 handle_ert(os, "\\listof{" + name + "}", context);
1444                 }
1445
1446                 else if (t.cs() == "textrm")
1447                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1448                                               context, "\\family",
1449                                               context.font.family, "roman");
1450
1451                 else if (t.cs() == "textsf")
1452                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1453                                               context, "\\family",
1454                                               context.font.family, "sans");
1455
1456                 else if (t.cs() == "texttt")
1457                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1458                                               context, "\\family",
1459                                               context.font.family, "typewriter");
1460
1461                 else if (t.cs() == "textmd")
1462                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1463                                               context, "\\series",
1464                                               context.font.series, "medium");
1465
1466                 else if (t.cs() == "textbf")
1467                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1468                                               context, "\\series",
1469                                               context.font.series, "bold");
1470
1471                 else if (t.cs() == "textup")
1472                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1473                                               context, "\\shape",
1474                                               context.font.shape, "up");
1475
1476                 else if (t.cs() == "textit")
1477                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1478                                               context, "\\shape",
1479                                               context.font.shape, "italic");
1480
1481                 else if (t.cs() == "textsl")
1482                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1483                                               context, "\\shape",
1484                                               context.font.shape, "slanted");
1485
1486                 else if (t.cs() == "textsc")
1487                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1488                                               context, "\\shape",
1489                                               context.font.shape, "smallcaps");
1490
1491                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1492                         context.check_layout(os);
1493                         Font oldFont = context.font;
1494                         context.font.init();
1495                         context.font.size = oldFont.size;
1496                         os << "\n\\family " << context.font.family << "\n";
1497                         os << "\n\\series " << context.font.series << "\n";
1498                         os << "\n\\shape " << context.font.shape << "\n";
1499                         if (t.cs() == "textnormal") {
1500                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1501                                 context.font = oldFont;
1502                                 os << "\n\\shape " << oldFont.shape << "\n";
1503                                 os << "\n\\series " << oldFont.series << "\n";
1504                                 os << "\n\\family " << oldFont.family << "\n";
1505                         } else
1506                                 eat_whitespace(p, os, context, false);
1507                 }
1508
1509                 else if (t.cs() == "underbar") {
1510                         // Do NOT handle \underline.
1511                         // \underbar cuts through y, g, q, p etc.,
1512                         // \underline does not.
1513                         context.check_layout(os);
1514                         os << "\n\\bar under\n";
1515                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1516                         os << "\n\\bar default\n";
1517                 }
1518
1519                 else if (t.cs() == "emph" || t.cs() == "noun") {
1520                         context.check_layout(os);
1521                         os << "\n\\" << t.cs() << " on\n";
1522                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1523                         os << "\n\\" << t.cs() << " default\n";
1524                 }
1525
1526                 else if (use_natbib &&
1527                          is_known(t.cs(), known_natbib_commands) &&
1528                          ((t.cs() != "citefullauthor" &&
1529                            t.cs() != "citeyear" &&
1530                            t.cs() != "citeyearpar") ||
1531                           p.next_token().asInput() != "*")) {
1532                         context.check_layout(os);
1533                         // tex                       lyx
1534                         // \citet[before][after]{a}  \citet[after][before]{a}
1535                         // \citet[before][]{a}       \citet[][before]{a}
1536                         // \citet[after]{a}          \citet[after]{a}
1537                         // \citet{a}                 \citet{a}
1538                         string command = '\\' + t.cs();
1539                         if (p.next_token().asInput() == "*") {
1540                                 command += '*';
1541                                 p.get_token();
1542                         }
1543                         if (command == "\\citefullauthor")
1544                                 // alternative name for "\\citeauthor*"
1545                                 command = "\\citeauthor*";
1546
1547                         // text before the citation
1548                         string before;
1549                         // text after the citation
1550                         string after;
1551
1552                         boost::tie(before, after) = getCiteArguments(p, true);
1553                         if (command == "\\cite") {
1554                                 // \cite without optional argument means
1555                                 // \citet, \cite with at least one optional
1556                                 // argument means \citep.
1557                                 if (before.empty() && after.empty())
1558                                         command = "\\citet";
1559                                 else
1560                                         command = "\\citep";
1561                         }
1562                         if (before.empty() && after == "[]")
1563                                 // avoid \citet[]{a}
1564                                 after.erase();
1565                         else if (before == "[]" && after == "[]") {
1566                                 // avoid \citet[][]{a}
1567                                 before.erase();
1568                                 after.erase();
1569                         }
1570                         begin_inset(os, "LatexCommand ");
1571                         os << command << after << before
1572                            << '{' << p.verbatim_item() << "}\n";
1573                         end_inset(os);
1574                 }
1575
1576                 else if (use_jurabib &&
1577                          is_known(t.cs(), known_jurabib_commands)) {
1578                         context.check_layout(os);
1579                         string const command = '\\' + t.cs();
1580                         char argumentOrder = '\0';
1581                         vector<string> const & options = used_packages["jurabib"];
1582                         if (std::find(options.begin(), options.end(),
1583                                       "natbiborder") != options.end())
1584                                 argumentOrder = 'n';
1585                         else if (std::find(options.begin(), options.end(),
1586                                            "jurabiborder") != options.end())
1587                                 argumentOrder = 'j';
1588
1589                         // text before the citation
1590                         string before;
1591                         // text after the citation
1592                         string after;
1593
1594                         boost::tie(before, after) =
1595                                 getCiteArguments(p, argumentOrder != 'j');
1596                         string const citation = p.verbatim_item();
1597                         if (!before.empty() && argumentOrder == '\0') {
1598                                 cerr << "Warning: Assuming argument order "
1599                                         "of jurabib version 0.6 for\n'"
1600                                      << command << before << after << '{'
1601                                      << citation << "}'.\n"
1602                                         "Add 'jurabiborder' to the jurabib "
1603                                         "package options if you used an\n"
1604                                         "earlier jurabib version." << endl;
1605                         }
1606                         begin_inset(os, "LatexCommand ");
1607                         os << command << after << before
1608                            << '{' << citation << "}\n";
1609                         end_inset(os);
1610                 }
1611
1612                 else if (is_known(t.cs(), known_latex_commands)) {
1613                         // This needs to be after the check for natbib and
1614                         // jurabib commands, because "cite" has different
1615                         // arguments with natbib and jurabib.
1616                         context.check_layout(os);
1617                         begin_inset(os, "LatexCommand ");
1618                         os << '\\' << t.cs();
1619                         // lyx cannot handle newlines in a latex command
1620                         // FIXME: Move the substitution into parser::getOpt()?
1621                         os << subst(p.getOpt(), "\n", " ");
1622                         os << subst(p.getOpt(), "\n", " ");
1623                         os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1624                         end_inset(os);
1625                 }
1626
1627                 else if (is_known(t.cs(), known_quotes)) {
1628                         char const * const * where = is_known(t.cs(), known_quotes);
1629                         context.check_layout(os);
1630                         begin_inset(os, "Quotes ");
1631                         os << known_coded_quotes[where - known_quotes];
1632                         end_inset(os);
1633                         // LyX adds {} after the quote, so we have to eat
1634                         // spaces here if there are any before a possible
1635                         // {} pair.
1636                         eat_whitespace(p, os, context, false);
1637                         skip_braces(p);
1638                 }
1639
1640                 else if (is_known(t.cs(), known_sizes)) {
1641                         char const * const * where = is_known(t.cs(), known_sizes);
1642                         context.check_layout(os);
1643                         context.font.size = known_coded_sizes[where - known_sizes];
1644                         os << "\n\\size " << context.font.size << '\n';
1645                         eat_whitespace(p, os, context, false);
1646                 }
1647
1648                 else if (is_known(t.cs(), known_font_families)) {
1649                         char const * const * where =
1650                                 is_known(t.cs(), known_font_families);
1651                         context.check_layout(os);
1652                         context.font.family =
1653                                 known_coded_font_families[where - known_font_families];
1654                         os << "\n\\family " << context.font.family << '\n';
1655                         eat_whitespace(p, os, context, false);
1656                 }
1657
1658                 else if (is_known(t.cs(), known_font_series)) {
1659                         char const * const * where =
1660                                 is_known(t.cs(), known_font_series);
1661                         context.check_layout(os);
1662                         context.font.series =
1663                                 known_coded_font_series[where - known_font_series];
1664                         os << "\n\\series " << context.font.series << '\n';
1665                         eat_whitespace(p, os, context, false);
1666                 }
1667
1668                 else if (is_known(t.cs(), known_font_shapes)) {
1669                         char const * const * where =
1670                                 is_known(t.cs(), known_font_shapes);
1671                         context.check_layout(os);
1672                         context.font.shape =
1673                                 known_coded_font_shapes[where - known_font_shapes];
1674                         os << "\n\\shape " << context.font.shape << '\n';
1675                         eat_whitespace(p, os, context, false);
1676                 }
1677                 else if (is_known(t.cs(), known_old_font_families)) {
1678                         char const * const * where =
1679                                 is_known(t.cs(), known_old_font_families);
1680                         context.check_layout(os);
1681                         string oldsize = context.font.size;
1682                         context.font.init();
1683                         context.font.size = oldsize;
1684                         context.font.family =
1685                                 known_coded_font_families[where - known_old_font_families];
1686                         os << "\n\\family " << context.font.family << "\n"
1687                            <<   "\\series " << context.font.series << "\n"
1688                            <<   "\\shape "  << context.font.shape  << "\n";
1689                         eat_whitespace(p, os, context, false);
1690                 }
1691
1692                 else if (is_known(t.cs(), known_old_font_series)) {
1693                         char const * const * where =
1694                                 is_known(t.cs(), known_old_font_series);
1695                         context.check_layout(os);
1696                         string oldsize = context.font.size;
1697                         context.font.init();
1698                         context.font.size = oldsize;
1699                         context.font.series =
1700                                 known_coded_font_series[where - known_old_font_series];
1701                         os << "\n\\family " << context.font.family << "\n"
1702                            <<   "\\series " << context.font.series << "\n"
1703                            <<   "\\shape "  << context.font.shape  << "\n";
1704                         eat_whitespace(p, os, context, false);
1705                 }
1706
1707                 else if (is_known(t.cs(), known_old_font_shapes)) {
1708                         char const * const * where =
1709                                 is_known(t.cs(), known_old_font_shapes);
1710                         context.check_layout(os);
1711                         string oldsize = context.font.size;
1712                         context.font.init();
1713                         context.font.size = oldsize;
1714                         context.font.shape =
1715                                 known_coded_font_shapes[where - known_old_font_shapes];
1716                         os << "\n\\family " << context.font.family << "\n"
1717                            <<   "\\series " << context.font.series << "\n"
1718                            <<   "\\shape "  << context.font.shape  << "\n";
1719                         eat_whitespace(p, os, context, false);
1720                 }
1721
1722                 else if (t.cs() == "LyX" || t.cs() == "TeX"
1723                          || t.cs() == "LaTeX") {
1724                         context.check_layout(os);
1725                         os << t.cs();
1726                         skip_braces(p); // eat {}
1727                 }
1728
1729                 else if (t.cs() == "LaTeXe") {
1730                         context.check_layout(os);
1731                         os << "LaTeX2e";
1732                         skip_braces(p); // eat {}
1733                 }
1734
1735                 else if (t.cs() == "ldots") {
1736                         context.check_layout(os);
1737                         skip_braces(p);
1738                         os << "\\SpecialChar \\ldots{}\n";
1739                 }
1740
1741                 else if (t.cs() == "lyxarrow") {
1742                         context.check_layout(os);
1743                         os << "\\SpecialChar \\menuseparator\n";
1744                         skip_braces(p);
1745                 }
1746
1747                 else if (t.cs() == "textcompwordmark") {
1748                         context.check_layout(os);
1749                         os << "\\SpecialChar \\textcompwordmark{}\n";
1750                         skip_braces(p);
1751                 }
1752
1753                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1754                         context.check_layout(os);
1755                         os << "\\SpecialChar \\@.\n";
1756                         p.get_token();
1757                 }
1758
1759                 else if (t.cs() == "-") {
1760                         context.check_layout(os);
1761                         os << "\\SpecialChar \\-\n";
1762                 }
1763
1764                 else if (t.cs() == "textasciitilde") {
1765                         context.check_layout(os);
1766                         os << '~';
1767                         skip_braces(p);
1768                 }
1769
1770                 else if (t.cs() == "textasciicircum") {
1771                         context.check_layout(os);
1772                         os << '^';
1773                         skip_braces(p);
1774                 }
1775
1776                 else if (t.cs() == "textbackslash") {
1777                         context.check_layout(os);
1778                         os << "\n\\backslash\n";
1779                         skip_braces(p);
1780                 }
1781
1782                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1783                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1784                             || t.cs() == "%") {
1785                         context.check_layout(os);
1786                         os << t.cs();
1787                 }
1788
1789                 else if (t.cs() == "char") {
1790                         context.check_layout(os);
1791                         if (p.next_token().character() == '`') {
1792                                 p.get_token();
1793                                 if (p.next_token().cs() == "\"") {
1794                                         p.get_token();
1795                                         os << '"';
1796                                         skip_braces(p);
1797                                 } else {
1798                                         handle_ert(os, "\\char`", context);
1799                                 }
1800                         } else {
1801                                 handle_ert(os, "\\char", context);
1802                         }
1803                 }
1804
1805                 else if (t.cs() == "\"") {
1806                         context.check_layout(os);
1807                         string const name = p.verbatim_item();
1808                              if (name == "a") os << 'ä';
1809                         else if (name == "o") os << 'ö';
1810                         else if (name == "u") os << 'ü';
1811                         else if (name == "A") os << 'Ä';
1812                         else if (name == "O") os << 'Ö';
1813                         else if (name == "U") os << 'Ü';
1814                         else handle_ert(os, "\"{" + name + "}", context);
1815                 }
1816
1817                 // Problem: \= creates a tabstop inside the tabbing environment
1818                 // and else an accent. In the latter case we really would want
1819                 // \={o} instead of \= o.
1820                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1821                         handle_ert(os, t.asInput(), context);
1822
1823                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1824                       || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1825                         // we need the trim as the LyX parser chokes on such spaces
1826                         context.check_layout(os);
1827                         os << "\n\\i \\" << t.cs() << "{"
1828                            << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1829                 }
1830
1831                 else if (t.cs() == "ss") {
1832                         context.check_layout(os);
1833                         os << "ß";
1834                 }
1835
1836                 else if (t.cs() == "i" || t.cs() == "j") {
1837                         context.check_layout(os);
1838                         os << "\\" << t.cs() << ' ';
1839                 }
1840
1841                 else if (t.cs() == "\\") {
1842                         context.check_layout(os);
1843                         string const next = p.next_token().asInput();
1844                         if (next == "[")
1845                                 handle_ert(os, "\\\\" + p.getOpt(), context);
1846                         else if (next == "*") {
1847                                 p.get_token();
1848                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
1849                         }
1850                         else {
1851                                 os << "\n\\newline\n";
1852                         }
1853                 }
1854
1855                 else if (t.cs() == "input" || t.cs() == "include"
1856                          || t.cs() == "verbatiminput") {
1857                         string name = '\\' + t.cs();
1858                         if (t.cs() == "verbatiminput"
1859                             && p.next_token().asInput() == "*")
1860                                 name += p.get_token().asInput();
1861                         context.check_layout(os);
1862                         begin_inset(os, "Include ");
1863                         string filename(normalize_filename(p.getArg('{', '}')));
1864                         string const path = getMasterFilePath();
1865                         // We want to preserve relative / absolute filenames,
1866                         // therefore path is only used for testing
1867                         if (t.cs() == "include" &&
1868                             !fs::exists(MakeAbsPath(filename, path))) {
1869                                 // The file extension is probably missing.
1870                                 // Now try to find it out.
1871                                 string const tex_name =
1872                                         find_file(filename, path,
1873                                                   known_tex_extensions);
1874                                 if (!tex_name.empty())
1875                                         filename = tex_name;
1876                         }
1877                         if (fs::exists(MakeAbsPath(filename, path))) {
1878                                 string const abstexname =
1879                                         MakeAbsPath(filename, path);
1880                                 string const abslyxname =
1881                                         ChangeExtension(abstexname, ".lyx");
1882                                 string const lyxname =
1883                                         ChangeExtension(filename, ".lyx");
1884                                 if (t.cs() != "verbatiminput" &&
1885                                     tex2lyx(abstexname, abslyxname)) {
1886                                         os << name << '{' << lyxname << "}\n";
1887                                 } else {
1888                                         os << name << '{' << filename << "}\n";
1889                                 }
1890                         } else {
1891                                 cerr << "Warning: Could not find included file '"
1892                                      << filename << "'." << endl;
1893                                 os << name << '{' << filename << "}\n";
1894                         }
1895                         os << "preview false\n";
1896                         end_inset(os);
1897                 }
1898
1899                 else if (t.cs() == "fancyhead") {
1900                         context.check_layout(os);
1901                         ostringstream ss;
1902                         ss << "\\fancyhead";
1903                         ss << p.getOpt();
1904                         ss << '{' << p.verbatim_item() << "}\n";
1905                         handle_ert(os, ss.str(), context);
1906                 }
1907
1908                 else if (t.cs() == "bibliographystyle") {
1909                         // store new bibliographystyle
1910                         bibliographystyle = p.verbatim_item();
1911                         // output new bibliographystyle.
1912                         // This is only necessary if used in some other macro than \bibliography.
1913                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1914                 }
1915
1916                 else if (t.cs() == "bibliography") {
1917                         context.check_layout(os);
1918                         begin_inset(os, "LatexCommand ");
1919                         os << "\\bibtex";
1920                         // Do we have a bibliographystyle set?
1921                         if (!bibliographystyle.empty()) {
1922                                 os << '[' << bibliographystyle << ']';
1923                         }
1924                         os << '{' << p.verbatim_item() << "}\n";
1925                         end_inset(os);
1926                 }
1927
1928                 else if (t.cs() == "parbox")
1929                         parse_box(p, os, FLAG_ITEM, outer, context, true);
1930
1931                 else if (t.cs() == "smallskip" ||
1932                          t.cs() == "medskip" ||
1933                          t.cs() == "bigskip" ||
1934                          t.cs() == "vfill") {
1935                         context.check_layout(os);
1936                         begin_inset(os, "VSpace ");
1937                         os << t.cs();
1938                         end_inset(os);
1939                         skip_braces(p);
1940                 }
1941
1942                 else if (t.cs() == "newcommand" ||
1943                          t.cs() == "providecommand" ||
1944                          t.cs() == "renewcommand") {
1945                         // these could be handled by parse_command(), but
1946                         // we need to call add_known_command() here.
1947                         string name = t.asInput();
1948                         if (p.next_token().asInput() == "*") {
1949                                 // Starred form. Eat '*'
1950                                 p.get_token();
1951                                 name += '*';
1952                         }
1953                         string const command = p.verbatim_item();
1954                         string const opt1 = p.getOpt();
1955                         string const opt2 = p.getFullOpt();
1956                         add_known_command(command, opt1, !opt2.empty());
1957                         string const ert = name + '{' + command + '}' +
1958                                            opt1 + opt2 +
1959                                            '{' + p.verbatim_item() + '}';
1960                         handle_ert(os, ert, context);
1961                 }
1962
1963                 else if (t.cs() == "vspace") {
1964                         bool starred = false;
1965                         if (p.next_token().asInput() == "*") {
1966                                 p.get_token();
1967                                 starred = true;
1968                         }
1969                         string const length = p.verbatim_item();
1970                         string unit;
1971                         string valstring;
1972                         bool valid = splitLatexLength(length, valstring, unit);
1973                         bool known_vspace = false;
1974                         bool known_unit = false;
1975                         double value;
1976                         if (valid) {
1977                                 istringstream iss(valstring);
1978                                 iss >> value;
1979                                 if (value == 1.0) {
1980                                         if (unit == "\\smallskipamount") {
1981                                                 unit = "smallskip";
1982                                                 known_vspace = true;
1983                                         } else if (unit == "\\medskipamount") {
1984                                                 unit = "medskip";
1985                                                 known_vspace = true;
1986                                         } else if (unit == "\\bigskipamount") {
1987                                                 unit = "bigskip";
1988                                                 known_vspace = true;
1989                                         } else if (unit == "\\fill") {
1990                                                 unit = "vfill";
1991                                                 known_vspace = true;
1992                                         }
1993                                 }
1994                                 if (!known_vspace) {
1995                                         switch (unitFromString(unit)) {
1996                                         case LyXLength::SP:
1997                                         case LyXLength::PT:
1998                                         case LyXLength::BP:
1999                                         case LyXLength::DD:
2000                                         case LyXLength::MM:
2001                                         case LyXLength::PC:
2002                                         case LyXLength::CC:
2003                                         case LyXLength::CM:
2004                                         case LyXLength::IN:
2005                                         case LyXLength::EX:
2006                                         case LyXLength::EM:
2007                                         case LyXLength::MU:
2008                                                 known_unit = true;
2009                                                 break;
2010                                         default:
2011                                                 break;
2012                                         }
2013                                 }
2014                         }
2015
2016                         if (known_unit || known_vspace) {
2017                                 // Literal length or known variable
2018                                 context.check_layout(os);
2019                                 begin_inset(os, "VSpace ");
2020                                 if (known_unit)
2021                                         os << value;
2022                                 os << unit;
2023                                 if (starred)
2024                                         os << '*';
2025                                 end_inset(os);
2026                         } else {
2027                                 // LyX can't handle other length variables in Inset VSpace
2028                                 string name = t.asInput();
2029                                 if (starred)
2030                                         name += '*';
2031                                 if (valid) {
2032                                         if (value == 1.0)
2033                                                 handle_ert(os, name + '{' + unit + '}', context);
2034                                         else if (value == -1.0)
2035                                                 handle_ert(os, name + "{-" + unit + '}', context);
2036                                         else
2037                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
2038                                 } else
2039                                         handle_ert(os, name + '{' + length + '}', context);
2040                         }
2041                 }
2042
2043                 else {
2044                         //cerr << "#: " << t << " mode: " << mode << endl;
2045                         // heuristic: read up to next non-nested space
2046                         /*
2047                         string s = t.asInput();
2048                         string z = p.verbatim_item();
2049                         while (p.good() && z != " " && z.size()) {
2050                                 //cerr << "read: " << z << endl;
2051                                 s += z;
2052                                 z = p.verbatim_item();
2053                         }
2054                         cerr << "found ERT: " << s << endl;
2055                         handle_ert(os, s + ' ', context);
2056                         */
2057                         string name = t.asInput();
2058                         if (p.next_token().asInput() == "*") {
2059                                 // Starred commands like \vspace*{}
2060                                 p.get_token();                          // Eat '*'
2061                                 name += '*';
2062                         }
2063                         if (! parse_command(name, p, os, outer, context))
2064                                 handle_ert(os, name, context);
2065                 }
2066
2067                 if (flags & FLAG_LEAVE) {
2068                         flags &= ~FLAG_LEAVE;
2069                         break;
2070                 }
2071         }
2072 }
2073
2074
2075 // }])