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