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