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