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