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