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