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