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