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