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