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