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