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