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