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