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