]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
tex2lyx/text.cpp: take care of the brace pair after comment environments that are...
[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                 skip_braces(p); // eat {} that might by set by LyX behind comments
769         }
770
771         else if (name == "lyxgreyedout") {
772                 eat_whitespace(p, os, parent_context, false);
773                 parent_context.check_layout(os);
774                 begin_inset(os, "Note Greyedout\n");
775                 os << "status open\n";
776                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
777                 end_inset(os);
778                 p.skip_spaces();
779         }
780
781         else if (name == "framed") {
782                 eat_whitespace(p, os, parent_context, false);
783                 parent_context.check_layout(os);
784                 begin_inset(os, "Note Framed\n");
785                 os << "status open\n";
786                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
787                 end_inset(os);
788                 p.skip_spaces();
789         }
790
791         else if (name == "shaded") {
792                 eat_whitespace(p, os, parent_context, false);
793                 parent_context.check_layout(os);
794                 begin_inset(os, "Note Shaded\n");
795                 os << "status open\n";
796                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
797                 end_inset(os);
798                 p.skip_spaces();
799         }
800
801         else if (!parent_context.new_layout_allowed)
802                 parse_unknown_environment(p, name, os, FLAG_END, outer,
803                                           parent_context);
804
805         // Alignment settings
806         else if (name == "center" || name == "flushleft" || name == "flushright" ||
807                  name == "centering" || name == "raggedright" || name == "raggedleft") {
808                 eat_whitespace(p, os, parent_context, false);
809                 // We must begin a new paragraph if not already done
810                 if (! parent_context.atParagraphStart()) {
811                         parent_context.check_end_layout(os);
812                         parent_context.new_paragraph(os);
813                 }
814                 if (name == "flushleft" || name == "raggedright")
815                         parent_context.add_extra_stuff("\\align left\n");
816                 else if (name == "flushright" || name == "raggedleft")
817                         parent_context.add_extra_stuff("\\align right\n");
818                 else
819                         parent_context.add_extra_stuff("\\align center\n");
820                 parse_text(p, os, FLAG_END, outer, parent_context);
821                 // Just in case the environment is empty ..
822                 parent_context.extra_stuff.erase();
823                 // We must begin a new paragraph to reset the alignment
824                 parent_context.new_paragraph(os);
825                 p.skip_spaces();
826         }
827
828         // The single '=' is meant here.
829         else if ((newlayout = findLayout(parent_context.textclass, name)) &&
830                   newlayout->isEnvironment()) {
831                 eat_whitespace(p, os, parent_context, false);
832                 Context context(true, parent_context.textclass, newlayout,
833                                 parent_context.layout, parent_context.font);
834                 if (parent_context.deeper_paragraph) {
835                         // We are beginning a nested environment after a
836                         // deeper paragraph inside the outer list environment.
837                         // Therefore we don't need to output a "begin deeper".
838                         context.need_end_deeper = true;
839                 }
840                 parent_context.check_end_layout(os);
841                 switch (context.layout->latextype) {
842                 case  LATEX_LIST_ENVIRONMENT:
843                         context.extra_stuff = "\\labelwidthstring "
844                                 + p.verbatim_item() + '\n';
845                         p.skip_spaces();
846                         break;
847                 case  LATEX_BIB_ENVIRONMENT:
848                         p.verbatim_item(); // swallow next arg
849                         p.skip_spaces();
850                         break;
851                 default:
852                         break;
853                 }
854                 context.check_deeper(os);
855                 parse_text(p, os, FLAG_END, outer, context);
856                 context.check_end_layout(os);
857                 if (parent_context.deeper_paragraph) {
858                         // We must suppress the "end deeper" because we
859                         // suppressed the "begin deeper" above.
860                         context.need_end_deeper = false;
861                 }
862                 context.check_end_deeper(os);
863                 parent_context.new_paragraph(os);
864                 p.skip_spaces();
865         }
866
867         else if (name == "appendix") {
868                 // This is no good latex style, but it works and is used in some documents...
869                 eat_whitespace(p, os, parent_context, false);
870                 parent_context.check_end_layout(os);
871                 Context context(true, parent_context.textclass, parent_context.layout,
872                                 parent_context.layout, parent_context.font);
873                 context.check_layout(os);
874                 os << "\\start_of_appendix\n";
875                 parse_text(p, os, FLAG_END, outer, context);
876                 context.check_end_layout(os);
877                 p.skip_spaces();
878         }
879
880         else if (known_environments.find(name) != known_environments.end()) {
881                 vector<ArgumentType> arguments = known_environments[name];
882                 // The last "argument" denotes wether we may translate the
883                 // environment contents to LyX
884                 // The default required if no argument is given makes us
885                 // compatible with the reLyXre environment.
886                 ArgumentType contents = arguments.empty() ?
887                         required :
888                         arguments.back();
889                 if (!arguments.empty())
890                         arguments.pop_back();
891                 // See comment in parse_unknown_environment()
892                 bool const specialfont =
893                         (parent_context.font != parent_context.normalfont);
894                 bool const new_layout_allowed =
895                         parent_context.new_layout_allowed;
896                 if (specialfont)
897                         parent_context.new_layout_allowed = false;
898                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
899                                 outer, parent_context);
900                 if (contents == verbatim)
901                         handle_ert(os, p.verbatimEnvironment(name),
902                                    parent_context);
903                 else
904                         parse_text_snippet(p, os, FLAG_END, outer,
905                                            parent_context);
906                 handle_ert(os, "\\end{" + name + "}", parent_context);
907                 if (specialfont)
908                         parent_context.new_layout_allowed = new_layout_allowed;
909         }
910
911         else
912                 parse_unknown_environment(p, name, os, FLAG_END, outer,
913                                           parent_context);
914
915         active_environments.pop_back();
916 }
917
918
919 /// parses a comment and outputs it to \p os.
920 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
921 {
922         LASSERT(t.cat() == catComment, return);
923         if (!t.cs().empty()) {
924                 context.check_layout(os);
925                 handle_comment(os, '%' + t.cs(), context);
926                 if (p.next_token().cat() == catNewline) {
927                         // A newline after a comment line starts a new
928                         // paragraph
929                         if (context.new_layout_allowed) {
930                                 if(!context.atParagraphStart())
931                                         // Only start a new paragraph if not already
932                                         // done (we might get called recursively)
933                                         context.new_paragraph(os);
934                         } else
935                                 handle_ert(os, "\n", context);
936                         eat_whitespace(p, os, context, true);
937                 }
938         } else {
939                 // "%\n" combination
940                 p.skip_spaces();
941         }
942 }
943
944
945 /*!
946  * Reads spaces and comments until the first non-space, non-comment token.
947  * New paragraphs (double newlines or \\par) are handled like simple spaces
948  * if \p eatParagraph is true.
949  * Spaces are skipped, but comments are written to \p os.
950  */
951 void eat_whitespace(Parser & p, ostream & os, Context & context,
952                     bool eatParagraph)
953 {
954         while (p.good()) {
955                 Token const & t = p.get_token();
956                 if (t.cat() == catComment)
957                         parse_comment(p, os, t, context);
958                 else if ((! eatParagraph && p.isParagraph()) ||
959                          (t.cat() != catSpace && t.cat() != catNewline)) {
960                         p.putback();
961                         return;
962                 }
963         }
964 }
965
966
967 /*!
968  * Set a font attribute, parse text and reset the font attribute.
969  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
970  * \param currentvalue Current value of the attribute. Is set to the new
971  * value during parsing.
972  * \param newvalue New value of the attribute
973  */
974 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
975                            Context & context, string const & attribute,
976                            string & currentvalue, string const & newvalue)
977 {
978         context.check_layout(os);
979         string const oldvalue = currentvalue;
980         currentvalue = newvalue;
981         os << '\n' << attribute << ' ' << newvalue << "\n";
982         parse_text_snippet(p, os, flags, outer, context);
983         context.check_layout(os);
984         os << '\n' << attribute << ' ' << oldvalue << "\n";
985         currentvalue = oldvalue;
986 }
987
988
989 /// get the arguments of a natbib or jurabib citation command
990 void get_cite_arguments(Parser & p, bool natbibOrder,
991         string & before, string & after)
992 {
993         // We need to distinguish "" and "[]", so we can't use p.getOpt().
994
995         // text before the citation
996         before.clear();
997         // text after the citation
998         after = p.getFullOpt();
999
1000         if (!after.empty()) {
1001                 before = p.getFullOpt();
1002                 if (natbibOrder && !before.empty())
1003                         swap(before, after);
1004         }
1005 }
1006
1007
1008 /// Convert filenames with TeX macros and/or quotes to something LyX
1009 /// can understand
1010 string const normalize_filename(string const & name)
1011 {
1012         Parser p(trim(name, "\""));
1013         ostringstream os;
1014         while (p.good()) {
1015                 Token const & t = p.get_token();
1016                 if (t.cat() != catEscape)
1017                         os << t.asInput();
1018                 else if (t.cs() == "lyxdot") {
1019                         // This is used by LyX for simple dots in relative
1020                         // names
1021                         os << '.';
1022                         p.skip_spaces();
1023                 } else if (t.cs() == "space") {
1024                         os << ' ';
1025                         p.skip_spaces();
1026                 } else
1027                         os << t.asInput();
1028         }
1029         return os.str();
1030 }
1031
1032
1033 /// Convert \p name from TeX convention (relative to master file) to LyX
1034 /// convention (relative to .lyx file) if it is relative
1035 void fix_relative_filename(string & name)
1036 {
1037         FileName fname(name);
1038         if (fname.isAbsolute())
1039                 return;
1040
1041         // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1042         // utf8)
1043         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1044                                    from_utf8(getParentFilePath())));
1045 }
1046
1047
1048 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1049 void parse_noweb(Parser & p, ostream & os, Context & context)
1050 {
1051         // assemble the rest of the keyword
1052         string name("<<");
1053         bool scrap = false;
1054         while (p.good()) {
1055                 Token const & t = p.get_token();
1056                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1057                         name += ">>";
1058                         p.get_token();
1059                         scrap = (p.good() && p.next_token().asInput() == "=");
1060                         if (scrap)
1061                                 name += p.get_token().asInput();
1062                         break;
1063                 }
1064                 name += t.asInput();
1065         }
1066
1067         if (!scrap || !context.new_layout_allowed ||
1068             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1069                 cerr << "Warning: Could not interpret '" << name
1070                      << "'. Ignoring it." << endl;
1071                 return;
1072         }
1073
1074         // We use new_paragraph instead of check_end_layout because the stuff
1075         // following the noweb chunk needs to start with a \begin_layout.
1076         // This may create a new paragraph even if there was none in the
1077         // noweb file, but the alternative is an invalid LyX file. Since
1078         // noweb code chunks are implemented with a layout style in LyX they
1079         // always must be in an own paragraph.
1080         context.new_paragraph(os);
1081         Context newcontext(true, context.textclass,
1082                 &context.textclass[from_ascii("Scrap")]);
1083         newcontext.check_layout(os);
1084         os << name;
1085         while (p.good()) {
1086                 Token const & t = p.get_token();
1087                 // We abuse the parser a bit, because this is no TeX syntax
1088                 // at all.
1089                 if (t.cat() == catEscape)
1090                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1091                 else
1092                         os << subst(t.asInput(), "\n", "\n\\newline\n");
1093                 // The scrap chunk is ended by an @ at the beginning of a line.
1094                 // After the @ the line may contain a comment and/or
1095                 // whitespace, but nothing else.
1096                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1097                     (p.next_token().cat() == catSpace ||
1098                      p.next_token().cat() == catNewline ||
1099                      p.next_token().cat() == catComment)) {
1100                         while (p.good() && p.next_token().cat() == catSpace)
1101                                 os << p.get_token().asInput();
1102                         if (p.next_token().cat() == catComment)
1103                                 // The comment includes a final '\n'
1104                                 os << p.get_token().asInput();
1105                         else {
1106                                 if (p.next_token().cat() == catNewline)
1107                                         p.get_token();
1108                                 os << '\n';
1109                         }
1110                         break;
1111                 }
1112         }
1113         newcontext.check_end_layout(os);
1114 }
1115
1116 } // anonymous namespace
1117
1118
1119 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1120                 Context & context)
1121 {
1122         Layout const * newlayout = 0;
1123         // store the current selectlanguage to be used after \foreignlanguage
1124         string selectlang;
1125         // Store the latest bibliographystyle (needed for bibtex inset)
1126         string bibliographystyle;
1127         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1128         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1129         while (p.good()) {
1130                 Token const & t = p.get_token();
1131
1132 #ifdef FILEDEBUG
1133                 cerr << "t: " << t << " flags: " << flags << "\n";
1134 #endif
1135
1136                 if (flags & FLAG_ITEM) {
1137                         if (t.cat() == catSpace)
1138                                 continue;
1139
1140                         flags &= ~FLAG_ITEM;
1141                         if (t.cat() == catBegin) {
1142                                 // skip the brace and collect everything to the next matching
1143                                 // closing brace
1144                                 flags |= FLAG_BRACE_LAST;
1145                                 continue;
1146                         }
1147
1148                         // handle only this single token, leave the loop if done
1149                         flags |= FLAG_LEAVE;
1150                 }
1151
1152                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1153                         return;
1154
1155                 //
1156                 // cat codes
1157                 //
1158                 if (t.cat() == catMath) {
1159                         // we are inside some text mode thingy, so opening new math is allowed
1160                         context.check_layout(os);
1161                         begin_inset(os, "Formula ");
1162                         Token const & n = p.get_token();
1163                         if (n.cat() == catMath && outer) {
1164                                 // TeX's $$...$$ syntax for displayed math
1165                                 os << "\\[";
1166                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1167                                 os << "\\]";
1168                                 p.get_token(); // skip the second '$' token
1169                         } else {
1170                                 // simple $...$  stuff
1171                                 p.putback();
1172                                 os << '$';
1173                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1174                                 os << '$';
1175                         }
1176                         end_inset(os);
1177                 }
1178
1179                 else if (t.cat() == catSuper || t.cat() == catSub)
1180                         cerr << "catcode " << t << " illegal in text mode\n";
1181
1182                 // Basic support for english quotes. This should be
1183                 // extended to other quotes, but is not so easy (a
1184                 // left english quote is the same as a right german
1185                 // quote...)
1186                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1187                         context.check_layout(os);
1188                         begin_inset(os, "Quotes ");
1189                         os << "eld";
1190                         end_inset(os);
1191                         p.get_token();
1192                         skip_braces(p);
1193                 }
1194                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1195                         context.check_layout(os);
1196                         begin_inset(os, "Quotes ");
1197                         os << "erd";
1198                         end_inset(os);
1199                         p.get_token();
1200                         skip_braces(p);
1201                 }
1202
1203                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1204                         context.check_layout(os);
1205                         begin_inset(os, "Quotes ");
1206                         os << "ald";
1207                         end_inset(os);
1208                         p.get_token();
1209                         skip_braces(p);
1210                 }
1211
1212                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1213                         context.check_layout(os);
1214                         begin_inset(os, "Quotes ");
1215                         os << "ard";
1216                         end_inset(os);
1217                         p.get_token();
1218                         skip_braces(p);
1219                 }
1220
1221                 else if (t.asInput() == "<"
1222                          && p.next_token().asInput() == "<" && noweb_mode) {
1223                         p.get_token();
1224                         parse_noweb(p, os, context);
1225                 }
1226
1227                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1228                         check_space(p, os, context);
1229
1230                 else if (t.character() == '[' && noweb_mode &&
1231                          p.next_token().character() == '[') {
1232                         // These can contain underscores
1233                         p.putback();
1234                         string const s = p.getFullOpt() + ']';
1235                         if (p.next_token().character() == ']')
1236                                 p.get_token();
1237                         else
1238                                 cerr << "Warning: Inserting missing ']' in '"
1239                                      << s << "'." << endl;
1240                         handle_ert(os, s, context);
1241                 }
1242
1243                 else if (t.cat() == catLetter ||
1244                                t.cat() == catOther ||
1245                                t.cat() == catAlign ||
1246                                t.cat() == catParameter) {
1247                         // This translates "&" to "\\&" which may be wrong...
1248                         context.check_layout(os);
1249                         os << t.character();
1250                 }
1251
1252                 else if (p.isParagraph()) {
1253                         if (context.new_layout_allowed)
1254                                 context.new_paragraph(os);
1255                         else
1256                                 handle_ert(os, "\\par ", context);
1257                         eat_whitespace(p, os, context, true);
1258                 }
1259
1260                 else if (t.cat() == catActive) {
1261                         context.check_layout(os);
1262                         if (t.character() == '~') {
1263                                 if (context.layout->free_spacing)
1264                                         os << ' ';
1265                                 else
1266                                         os << "\\InsetSpace ~\n";
1267                         } else
1268                                 os << t.character();
1269                 }
1270
1271                 else if (t.cat() == catBegin &&
1272                          p.next_token().cat() == catEnd) {
1273                         // {}
1274                         Token const prev = p.prev_token();
1275                         p.get_token();
1276                         if (p.next_token().character() == '`' ||
1277                             (prev.character() == '-' &&
1278                              p.next_token().character() == '-'))
1279                                 ; // ignore it in {}`` or -{}-
1280                         else
1281                                 handle_ert(os, "{}", context);
1282
1283                 }
1284
1285                 else if (t.cat() == catBegin) {
1286                         context.check_layout(os);
1287                         // special handling of font attribute changes
1288                         Token const prev = p.prev_token();
1289                         Token const next = p.next_token();
1290                         TeXFont const oldFont = context.font;
1291                         if (next.character() == '[' ||
1292                             next.character() == ']' ||
1293                             next.character() == '*') {
1294                                 p.get_token();
1295                                 if (p.next_token().cat() == catEnd) {
1296                                         os << next.character();
1297                                         p.get_token();
1298                                 } else {
1299                                         p.putback();
1300                                         handle_ert(os, "{", context);
1301                                         parse_text_snippet(p, os,
1302                                                         FLAG_BRACE_LAST,
1303                                                         outer, context);
1304                                         handle_ert(os, "}", context);
1305                                 }
1306                         } else if (! context.new_layout_allowed) {
1307                                 handle_ert(os, "{", context);
1308                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1309                                                    outer, context);
1310                                 handle_ert(os, "}", context);
1311                         } else if (is_known(next.cs(), known_sizes)) {
1312                                 // next will change the size, so we must
1313                                 // reset it here
1314                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1315                                                    outer, context);
1316                                 if (!context.atParagraphStart())
1317                                         os << "\n\\size "
1318                                            << context.font.size << "\n";
1319                         } else if (is_known(next.cs(), known_font_families)) {
1320                                 // next will change the font family, so we
1321                                 // must reset it here
1322                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1323                                                    outer, context);
1324                                 if (!context.atParagraphStart())
1325                                         os << "\n\\family "
1326                                            << context.font.family << "\n";
1327                         } else if (is_known(next.cs(), known_font_series)) {
1328                                 // next will change the font series, so we
1329                                 // must reset it here
1330                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1331                                                    outer, context);
1332                                 if (!context.atParagraphStart())
1333                                         os << "\n\\series "
1334                                            << context.font.series << "\n";
1335                         } else if (is_known(next.cs(), known_font_shapes)) {
1336                                 // next will change the font shape, so we
1337                                 // must reset it here
1338                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1339                                                    outer, context);
1340                                 if (!context.atParagraphStart())
1341                                         os << "\n\\shape "
1342                                            << context.font.shape << "\n";
1343                         } else if (is_known(next.cs(), known_old_font_families) ||
1344                                    is_known(next.cs(), known_old_font_series) ||
1345                                    is_known(next.cs(), known_old_font_shapes)) {
1346                                 // next will change the font family, series
1347                                 // and shape, so we must reset it here
1348                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1349                                                    outer, context);
1350                                 if (!context.atParagraphStart())
1351                                         os <<  "\n\\family "
1352                                            << context.font.family
1353                                            << "\n\\series "
1354                                            << context.font.series
1355                                            << "\n\\shape "
1356                                            << context.font.shape << "\n";
1357                         } else {
1358                                 handle_ert(os, "{", context);
1359                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1360                                                    outer, context);
1361                                 handle_ert(os, "}", context);
1362                         }
1363                 }
1364
1365                 else if (t.cat() == catEnd) {
1366                         if (flags & FLAG_BRACE_LAST) {
1367                                 return;
1368                         }
1369                         cerr << "stray '}' in text\n";
1370                         handle_ert(os, "}", context);
1371                 }
1372
1373                 else if (t.cat() == catComment)
1374                         parse_comment(p, os, t, context);
1375
1376                 //
1377                 // control sequences
1378                 //
1379
1380                 else if (t.cs() == "(") {
1381                         context.check_layout(os);
1382                         begin_inset(os, "Formula");
1383                         os << " \\(";
1384                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1385                         os << "\\)";
1386                         end_inset(os);
1387                 }
1388
1389                 else if (t.cs() == "[") {
1390                         context.check_layout(os);
1391                         begin_inset(os, "Formula");
1392                         os << " \\[";
1393                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1394                         os << "\\]";
1395                         end_inset(os);
1396                 }
1397
1398                 else if (t.cs() == "begin")
1399                         parse_environment(p, os, outer, context);
1400
1401                 else if (t.cs() == "end") {
1402                         if (flags & FLAG_END) {
1403                                 // eat environment name
1404                                 string const name = p.getArg('{', '}');
1405                                 if (name != active_environment())
1406                                         cerr << "\\end{" + name + "} does not match \\begin{"
1407                                                 + active_environment() + "}\n";
1408                                 return;
1409                         }
1410                         p.error("found 'end' unexpectedly");
1411                 }
1412
1413                 else if (t.cs() == "item") {
1414                         p.skip_spaces();
1415                         string s;
1416                         bool optarg = false;
1417                         if (p.next_token().character() == '[') {
1418                                 p.get_token(); // eat '['
1419                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1420                                                        outer, context);
1421                                 optarg = true;
1422                         }
1423                         context.set_item();
1424                         context.check_layout(os);
1425                         if (context.has_item) {
1426                                 // An item in an unknown list-like environment
1427                                 // FIXME: Do this in check_layout()!
1428                                 context.has_item = false;
1429                                 if (optarg)
1430                                         handle_ert(os, "\\item", context);
1431                                 else
1432                                         handle_ert(os, "\\item ", context);
1433                         }
1434                         if (optarg) {
1435                                 if (context.layout->labeltype != LABEL_MANUAL) {
1436                                         // lyx does not support \item[\mybullet]
1437                                         // in itemize environments
1438                                         handle_ert(os, "[", context);
1439                                         os << s;
1440                                         handle_ert(os, "]", context);
1441                                 } else if (!s.empty()) {
1442                                         // The space is needed to separate the
1443                                         // item from the rest of the sentence.
1444                                         os << s << ' ';
1445                                         eat_whitespace(p, os, context, false);
1446                                 }
1447                         }
1448                 }
1449
1450                 else if (t.cs() == "bibitem") {
1451                         context.set_item();
1452                         context.check_layout(os);
1453                         os << "\\bibitem ";
1454                         os << p.getOpt();
1455                         os << '{' << p.verbatim_item() << '}' << "\n";
1456                 } 
1457                 
1458                 else if(t.cs() == "global") {
1459                         // skip global which can appear in front of e.g. "def"
1460                 }
1461                 
1462                 else if (t.cs() == "def") {
1463                         context.check_layout(os);
1464                         eat_whitespace(p, os, context, false);
1465                         string name = p.get_token().cs();
1466                         eat_whitespace(p, os, context, false);
1467
1468                         // parameter text
1469                         bool simple = true;
1470                         string paramtext;
1471                         int arity = 0;
1472                         while (p.next_token().cat() != catBegin) {
1473                                 if (p.next_token().cat() == catParameter) {
1474                                         // # found
1475                                         p.get_token();
1476                                         paramtext += "#";
1477
1478                                         // followed by number?
1479                                         if (p.next_token().cat() == catOther) {
1480                                                 char c = p.getChar();
1481                                                 paramtext += c;
1482                                                 // number = current arity + 1?
1483                                                 if (c == arity + '0' + 1)
1484                                                         ++arity;
1485                                                 else
1486                                                         simple = false;
1487                                         } else
1488                                                 paramtext += p.get_token().asString();
1489                                 } else {
1490                                         paramtext += p.get_token().asString();
1491                                         simple = false;
1492                                 }
1493                         }
1494
1495                         // only output simple (i.e. compatible) macro as FormulaMacros
1496                         string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1497                         if (simple) {
1498                                 context.check_layout(os);
1499                                 begin_inset(os, "FormulaMacro");
1500                                 os << "\n" << ert;
1501                                 end_inset(os);
1502                         } else
1503                                 handle_ert(os, ert, context);
1504                 }
1505
1506                 else if (t.cs() == "noindent") {
1507                         p.skip_spaces();
1508                         context.add_extra_stuff("\\noindent\n");
1509                 }
1510
1511                 else if (t.cs() == "appendix") {
1512                         context.add_extra_stuff("\\start_of_appendix\n");
1513                         // We need to start a new paragraph. Otherwise the
1514                         // appendix in 'bla\appendix\chapter{' would start
1515                         // too late.
1516                         context.new_paragraph(os);
1517                         // We need to make sure that the paragraph is
1518                         // generated even if it is empty. Otherwise the
1519                         // appendix in '\par\appendix\par\chapter{' would
1520                         // start too late.
1521                         context.check_layout(os);
1522                         // FIXME: This is a hack to prevent paragraph
1523                         // deletion if it is empty. Handle this better!
1524                         handle_comment(os,
1525                                 "%dummy comment inserted by tex2lyx to "
1526                                 "ensure that this paragraph is not empty",
1527                                 context);
1528                         // Both measures above may generate an additional
1529                         // empty paragraph, but that does not hurt, because
1530                         // whitespace does not matter here.
1531                         eat_whitespace(p, os, context, true);
1532                 }
1533
1534                 // Must attempt to parse "Section*" before "Section".
1535                 else if ((p.next_token().asInput() == "*") &&
1536                          context.new_layout_allowed &&
1537                          // The single '=' is meant here.
1538                          (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1539                           newlayout->isCommand()) {
1540                         p.get_token();
1541                         output_command_layout(os, p, outer, context, newlayout);
1542                         p.skip_spaces();
1543                 }
1544
1545                 // The single '=' is meant here.
1546                 else if (context.new_layout_allowed &&
1547                          (newlayout = findLayout(context.textclass, t.cs())) &&
1548                          newlayout->isCommand()) {
1549                         output_command_layout(os, p, outer, context, newlayout);
1550                         p.skip_spaces();
1551                 }
1552
1553                 // Special handling for \caption
1554                 // FIXME: remove this when InsetCaption is supported.
1555                 else if (context.new_layout_allowed &&
1556                          t.cs() == captionlayout()->latexname()) {
1557                         output_command_layout(os, p, outer, context, 
1558                                               captionlayout());
1559                         p.skip_spaces();
1560                 }
1561
1562                 else if (t.cs() == "includegraphics") {
1563                         bool const clip = p.next_token().asInput() == "*";
1564                         if (clip)
1565                                 p.get_token();
1566                         map<string, string> opts = split_map(p.getArg('[', ']'));
1567                         if (clip)
1568                                 opts["clip"] = string();
1569                         string name = normalize_filename(p.verbatim_item());
1570
1571                         string const path = getMasterFilePath();
1572                         // We want to preserve relative / absolute filenames,
1573                         // therefore path is only used for testing
1574                         // FIXME UNICODE encoding of name and path may be
1575                         // wrong (makeAbsPath expects utf8)
1576                         if (!makeAbsPath(name, path).exists()) {
1577                                 // The file extension is probably missing.
1578                                 // Now try to find it out.
1579                                 string const dvips_name =
1580                                         find_file(name, path,
1581                                                   known_dvips_graphics_formats);
1582                                 string const pdftex_name =
1583                                         find_file(name, path,
1584                                                   known_pdftex_graphics_formats);
1585                                 if (!dvips_name.empty()) {
1586                                         if (!pdftex_name.empty()) {
1587                                                 cerr << "This file contains the "
1588                                                         "latex snippet\n"
1589                                                         "\"\\includegraphics{"
1590                                                      << name << "}\".\n"
1591                                                         "However, files\n\""
1592                                                      << dvips_name << "\" and\n\""
1593                                                      << pdftex_name << "\"\n"
1594                                                         "both exist, so I had to make a "
1595                                                         "choice and took the first one.\n"
1596                                                         "Please move the unwanted one "
1597                                                         "someplace else and try again\n"
1598                                                         "if my choice was wrong."
1599                                                      << endl;
1600                                         }
1601                                         name = dvips_name;
1602                                 } else if (!pdftex_name.empty())
1603                                         name = pdftex_name;
1604                         }
1605
1606                         // FIXME UNICODE encoding of name and path may be
1607                         // wrong (makeAbsPath expects utf8)
1608                         if (makeAbsPath(name, path).exists())
1609                                 fix_relative_filename(name);
1610                         else
1611                                 cerr << "Warning: Could not find graphics file '"
1612                                      << name << "'." << endl;
1613
1614                         context.check_layout(os);
1615                         begin_inset(os, "Graphics ");
1616                         os << "\n\tfilename " << name << '\n';
1617                         if (opts.find("width") != opts.end())
1618                                 os << "\twidth "
1619                                    << translate_len(opts["width"]) << '\n';
1620                         if (opts.find("height") != opts.end())
1621                                 os << "\theight "
1622                                    << translate_len(opts["height"]) << '\n';
1623                         if (opts.find("scale") != opts.end()) {
1624                                 istringstream iss(opts["scale"]);
1625                                 double val;
1626                                 iss >> val;
1627                                 val = val*100;
1628                                 os << "\tscale " << val << '\n';
1629                         }
1630                         if (opts.find("angle") != opts.end())
1631                                 os << "\trotateAngle "
1632                                    << opts["angle"] << '\n';
1633                         if (opts.find("origin") != opts.end()) {
1634                                 ostringstream ss;
1635                                 string const opt = opts["origin"];
1636                                 if (opt.find('l') != string::npos) ss << "left";
1637                                 if (opt.find('r') != string::npos) ss << "right";
1638                                 if (opt.find('c') != string::npos) ss << "center";
1639                                 if (opt.find('t') != string::npos) ss << "Top";
1640                                 if (opt.find('b') != string::npos) ss << "Bottom";
1641                                 if (opt.find('B') != string::npos) ss << "Baseline";
1642                                 if (!ss.str().empty())
1643                                         os << "\trotateOrigin " << ss.str() << '\n';
1644                                 else
1645                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1646                         }
1647                         if (opts.find("keepaspectratio") != opts.end())
1648                                 os << "\tkeepAspectRatio\n";
1649                         if (opts.find("clip") != opts.end())
1650                                 os << "\tclip\n";
1651                         if (opts.find("draft") != opts.end())
1652                                 os << "\tdraft\n";
1653                         if (opts.find("bb") != opts.end())
1654                                 os << "\tBoundingBox "
1655                                    << opts["bb"] << '\n';
1656                         int numberOfbbOptions = 0;
1657                         if (opts.find("bbllx") != opts.end())
1658                                 numberOfbbOptions++;
1659                         if (opts.find("bblly") != opts.end())
1660                                 numberOfbbOptions++;
1661                         if (opts.find("bburx") != opts.end())
1662                                 numberOfbbOptions++;
1663                         if (opts.find("bbury") != opts.end())
1664                                 numberOfbbOptions++;
1665                         if (numberOfbbOptions == 4)
1666                                 os << "\tBoundingBox "
1667                                    << opts["bbllx"] << " " << opts["bblly"] << " "
1668                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
1669                         else if (numberOfbbOptions > 0)
1670                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1671                         numberOfbbOptions = 0;
1672                         if (opts.find("natwidth") != opts.end())
1673                                 numberOfbbOptions++;
1674                         if (opts.find("natheight") != opts.end())
1675                                 numberOfbbOptions++;
1676                         if (numberOfbbOptions == 2)
1677                                 os << "\tBoundingBox 0bp 0bp "
1678                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
1679                         else if (numberOfbbOptions > 0)
1680                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1681                         ostringstream special;
1682                         if (opts.find("hiresbb") != opts.end())
1683                                 special << "hiresbb,";
1684                         if (opts.find("trim") != opts.end())
1685                                 special << "trim,";
1686                         if (opts.find("viewport") != opts.end())
1687                                 special << "viewport=" << opts["viewport"] << ',';
1688                         if (opts.find("totalheight") != opts.end())
1689                                 special << "totalheight=" << opts["totalheight"] << ',';
1690                         if (opts.find("type") != opts.end())
1691                                 special << "type=" << opts["type"] << ',';
1692                         if (opts.find("ext") != opts.end())
1693                                 special << "ext=" << opts["ext"] << ',';
1694                         if (opts.find("read") != opts.end())
1695                                 special << "read=" << opts["read"] << ',';
1696                         if (opts.find("command") != opts.end())
1697                                 special << "command=" << opts["command"] << ',';
1698                         string s_special = special.str();
1699                         if (!s_special.empty()) {
1700                                 // We had special arguments. Remove the trailing ','.
1701                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1702                         }
1703                         // TODO: Handle the unknown settings better.
1704                         // Warn about invalid options.
1705                         // Check whether some option was given twice.
1706                         end_inset(os);
1707                 }
1708
1709                 else if (t.cs() == "footnote" ||
1710                          (t.cs() == "thanks" && context.layout->intitle)) {
1711                         p.skip_spaces();
1712                         context.check_layout(os);
1713                         begin_inset(os, "Foot\n");
1714                         os << "status collapsed\n\n";
1715                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1716                         end_inset(os);
1717                 }
1718
1719                 else if (t.cs() == "marginpar") {
1720                         p.skip_spaces();
1721                         context.check_layout(os);
1722                         begin_inset(os, "Marginal\n");
1723                         os << "status collapsed\n\n";
1724                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1725                         end_inset(os);
1726                 }
1727
1728                 else if (t.cs() == "ensuremath") {
1729                         p.skip_spaces();
1730                         context.check_layout(os);
1731                         string const s = p.verbatim_item();
1732                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1733                                 os << s;
1734                         else
1735                                 handle_ert(os, "\\ensuremath{" + s + "}",
1736                                            context);
1737                 }
1738
1739                 else if (t.cs() == "hfill") {
1740                         context.check_layout(os);
1741                         os << "\n\\hfill\n";
1742                         skip_braces(p);
1743                         p.skip_spaces();
1744                 }
1745
1746                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1747                         // FIXME: Somehow prevent title layouts if
1748                         // "maketitle" was not found
1749                         p.skip_spaces();
1750                         skip_braces(p); // swallow this
1751                 }
1752
1753                 else if (t.cs() == "tableofcontents") {
1754                         p.skip_spaces();
1755                         context.check_layout(os);
1756                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1757                         end_inset(os);
1758                         skip_braces(p); // swallow this
1759                 }
1760
1761                 else if (t.cs() == "listoffigures") {
1762                         p.skip_spaces();
1763                         context.check_layout(os);
1764                         begin_inset(os, "FloatList figure\n");
1765                         end_inset(os);
1766                         skip_braces(p); // swallow this
1767                 }
1768
1769                 else if (t.cs() == "listoftables") {
1770                         p.skip_spaces();
1771                         context.check_layout(os);
1772                         begin_inset(os, "FloatList table\n");
1773                         end_inset(os);
1774                         skip_braces(p); // swallow this
1775                 }
1776
1777                 else if (t.cs() == "listof") {
1778                         p.skip_spaces(true);
1779                         string const name = p.get_token().asString();
1780                         if (context.textclass.floats().typeExist(name)) {
1781                                 context.check_layout(os);
1782                                 begin_inset(os, "FloatList ");
1783                                 os << name << "\n";
1784                                 end_inset(os);
1785                                 p.get_token(); // swallow second arg
1786                         } else
1787                                 handle_ert(os, "\\listof{" + name + "}", context);
1788                 }
1789
1790                 else if (t.cs() == "textrm")
1791                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1792                                               context, "\\family",
1793                                               context.font.family, "roman");
1794
1795                 else if (t.cs() == "textsf")
1796                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1797                                               context, "\\family",
1798                                               context.font.family, "sans");
1799
1800                 else if (t.cs() == "texttt")
1801                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1802                                               context, "\\family",
1803                                               context.font.family, "typewriter");
1804
1805                 else if (t.cs() == "textmd")
1806                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1807                                               context, "\\series",
1808                                               context.font.series, "medium");
1809
1810                 else if (t.cs() == "textbf")
1811                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1812                                               context, "\\series",
1813                                               context.font.series, "bold");
1814
1815                 else if (t.cs() == "textup")
1816                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1817                                               context, "\\shape",
1818                                               context.font.shape, "up");
1819
1820                 else if (t.cs() == "textit")
1821                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1822                                               context, "\\shape",
1823                                               context.font.shape, "italic");
1824
1825                 else if (t.cs() == "textsl")
1826                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1827                                               context, "\\shape",
1828                                               context.font.shape, "slanted");
1829
1830                 else if (t.cs() == "textsc")
1831                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1832                                               context, "\\shape",
1833                                               context.font.shape, "smallcaps");
1834
1835                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1836                         context.check_layout(os);
1837                         TeXFont oldFont = context.font;
1838                         context.font.init();
1839                         context.font.size = oldFont.size;
1840                         os << "\n\\family " << context.font.family << "\n";
1841                         os << "\n\\series " << context.font.series << "\n";
1842                         os << "\n\\shape " << context.font.shape << "\n";
1843                         if (t.cs() == "textnormal") {
1844                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1845                                 output_font_change(os, context.font, oldFont);
1846                                 context.font = oldFont;
1847                         } else
1848                                 eat_whitespace(p, os, context, false);
1849                 }
1850
1851                 else if (t.cs() == "textcolor") {
1852                         // scheme is \textcolor{color name}{text}
1853                         string const color = p.verbatim_item();
1854                         // we only support the predefined colors of the color package
1855                         if (color == "black" || color == "blue" || color == "cyan"
1856                                 || color == "green" || color == "magenta" || color == "red"
1857                                 || color == "white" || color == "yellow") {
1858                                         context.check_layout(os);
1859                                         os << "\n\\color " << color << "\n";
1860                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1861                                         context.check_layout(os);
1862                                         os << "\n\\color inherit\n";
1863                         } else
1864                                 // for custom defined colors
1865                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
1866                 }
1867
1868                 else if (t.cs() == "underbar") {
1869                         // Do NOT handle \underline.
1870                         // \underbar cuts through y, g, q, p etc.,
1871                         // \underline does not.
1872                         context.check_layout(os);
1873                         os << "\n\\bar under\n";
1874                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1875                         context.check_layout(os);
1876                         os << "\n\\bar default\n";
1877                 }
1878
1879                 else if (t.cs() == "emph" || t.cs() == "noun") {
1880                         context.check_layout(os);
1881                         os << "\n\\" << t.cs() << " on\n";
1882                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1883                         context.check_layout(os);
1884                         os << "\n\\" << t.cs() << " default\n";
1885                 }
1886
1887                 else if (use_natbib &&
1888                          is_known(t.cs(), known_natbib_commands) &&
1889                          ((t.cs() != "citefullauthor" &&
1890                            t.cs() != "citeyear" &&
1891                            t.cs() != "citeyearpar") ||
1892                           p.next_token().asInput() != "*")) {
1893                         context.check_layout(os);
1894                         // tex                       lyx
1895                         // \citet[before][after]{a}  \citet[after][before]{a}
1896                         // \citet[before][]{a}       \citet[][before]{a}
1897                         // \citet[after]{a}          \citet[after]{a}
1898                         // \citet{a}                 \citet{a}
1899                         string command = '\\' + t.cs();
1900                         if (p.next_token().asInput() == "*") {
1901                                 command += '*';
1902                                 p.get_token();
1903                         }
1904                         if (command == "\\citefullauthor")
1905                                 // alternative name for "\\citeauthor*"
1906                                 command = "\\citeauthor*";
1907
1908                         // text before the citation
1909                         string before;
1910                         // text after the citation
1911                         string after;
1912                         get_cite_arguments(p, true, before, after);
1913
1914                         if (command == "\\cite") {
1915                                 // \cite without optional argument means
1916                                 // \citet, \cite with at least one optional
1917                                 // argument means \citep.
1918                                 if (before.empty() && after.empty())
1919                                         command = "\\citet";
1920                                 else
1921                                         command = "\\citep";
1922                         }
1923                         if (before.empty() && after == "[]")
1924                                 // avoid \citet[]{a}
1925                                 after.erase();
1926                         else if (before == "[]" && after == "[]") {
1927                                 // avoid \citet[][]{a}
1928                                 before.erase();
1929                                 after.erase();
1930                         }
1931                         begin_inset(os, "LatexCommand ");
1932                         os << command << after << before
1933                            << '{' << p.verbatim_item() << "}\n";
1934                         end_inset(os);
1935                 }
1936
1937                 else if (use_jurabib &&
1938                          is_known(t.cs(), known_jurabib_commands)) {
1939                         context.check_layout(os);
1940                         string const command = '\\' + t.cs();
1941                         char argumentOrder = '\0';
1942                         vector<string> const & options = used_packages["jurabib"];
1943                         if (find(options.begin(), options.end(),
1944                                       "natbiborder") != options.end())
1945                                 argumentOrder = 'n';
1946                         else if (find(options.begin(), options.end(),
1947                                            "jurabiborder") != options.end())
1948                                 argumentOrder = 'j';
1949
1950                         // text before the citation
1951                         string before;
1952                         // text after the citation
1953                         string after;
1954                         get_cite_arguments(p, argumentOrder != 'j', before, after);
1955
1956                         string const citation = p.verbatim_item();
1957                         if (!before.empty() && argumentOrder == '\0') {
1958                                 cerr << "Warning: Assuming argument order "
1959                                         "of jurabib version 0.6 for\n'"
1960                                      << command << before << after << '{'
1961                                      << citation << "}'.\n"
1962                                         "Add 'jurabiborder' to the jurabib "
1963                                         "package options if you used an\n"
1964                                         "earlier jurabib version." << endl;
1965                         }
1966                         begin_inset(os, "LatexCommand ");
1967                         os << command << after << before
1968                            << '{' << citation << "}\n";
1969                         end_inset(os);
1970                 }
1971
1972                 else if (is_known(t.cs(), known_latex_commands)) {
1973                         // This needs to be after the check for natbib and
1974                         // jurabib commands, because "cite" has different
1975                         // arguments with natbib and jurabib.
1976                         context.check_layout(os);
1977                         begin_inset(os, "LatexCommand ");
1978                         os << '\\' << t.cs();
1979                         // lyx cannot handle newlines in a latex command
1980                         // FIXME: Move the substitution into parser::getOpt()?
1981                         os << subst(p.getOpt(), "\n", " ");
1982                         os << subst(p.getOpt(), "\n", " ");
1983                         os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1984                         end_inset(os);
1985                 }
1986
1987                 else if (is_known(t.cs(), known_quotes)) {
1988                         char const * const * where = is_known(t.cs(), known_quotes);
1989                         context.check_layout(os);
1990                         begin_inset(os, "Quotes ");
1991                         os << known_coded_quotes[where - known_quotes];
1992                         end_inset(os);
1993                         // LyX adds {} after the quote, so we have to eat
1994                         // spaces here if there are any before a possible
1995                         // {} pair.
1996                         eat_whitespace(p, os, context, false);
1997                         skip_braces(p);
1998                 }
1999
2000                 else if (is_known(t.cs(), known_sizes) &&
2001                          context.new_layout_allowed) {
2002                         char const * const * where = is_known(t.cs(), known_sizes);
2003                         context.check_layout(os);
2004                         TeXFont const oldFont = context.font;
2005                         context.font.size = known_coded_sizes[where - known_sizes];
2006                         output_font_change(os, oldFont, context.font);
2007                         eat_whitespace(p, os, context, false);
2008                 }
2009
2010                 else if (is_known(t.cs(), known_font_families) &&
2011                          context.new_layout_allowed) {
2012                         char const * const * where =
2013                                 is_known(t.cs(), known_font_families);
2014                         context.check_layout(os);
2015                         TeXFont const oldFont = context.font;
2016                         context.font.family =
2017                                 known_coded_font_families[where - known_font_families];
2018                         output_font_change(os, oldFont, context.font);
2019                         eat_whitespace(p, os, context, false);
2020                 }
2021
2022                 else if (is_known(t.cs(), known_font_series) &&
2023                          context.new_layout_allowed) {
2024                         char const * const * where =
2025                                 is_known(t.cs(), known_font_series);
2026                         context.check_layout(os);
2027                         TeXFont const oldFont = context.font;
2028                         context.font.series =
2029                                 known_coded_font_series[where - known_font_series];
2030                         output_font_change(os, oldFont, context.font);
2031                         eat_whitespace(p, os, context, false);
2032                 }
2033
2034                 else if (is_known(t.cs(), known_font_shapes) &&
2035                          context.new_layout_allowed) {
2036                         char const * const * where =
2037                                 is_known(t.cs(), known_font_shapes);
2038                         context.check_layout(os);
2039                         TeXFont const oldFont = context.font;
2040                         context.font.shape =
2041                                 known_coded_font_shapes[where - known_font_shapes];
2042                         output_font_change(os, oldFont, context.font);
2043                         eat_whitespace(p, os, context, false);
2044                 }
2045                 else if (is_known(t.cs(), known_old_font_families) &&
2046                          context.new_layout_allowed) {
2047                         char const * const * where =
2048                                 is_known(t.cs(), known_old_font_families);
2049                         context.check_layout(os);
2050                         TeXFont const oldFont = context.font;
2051                         context.font.init();
2052                         context.font.size = oldFont.size;
2053                         context.font.family =
2054                                 known_coded_font_families[where - known_old_font_families];
2055                         output_font_change(os, oldFont, context.font);
2056                         eat_whitespace(p, os, context, false);
2057                 }
2058
2059                 else if (is_known(t.cs(), known_old_font_series) &&
2060                          context.new_layout_allowed) {
2061                         char const * const * where =
2062                                 is_known(t.cs(), known_old_font_series);
2063                         context.check_layout(os);
2064                         TeXFont const oldFont = context.font;
2065                         context.font.init();
2066                         context.font.size = oldFont.size;
2067                         context.font.series =
2068                                 known_coded_font_series[where - known_old_font_series];
2069                         output_font_change(os, oldFont, context.font);
2070                         eat_whitespace(p, os, context, false);
2071                 }
2072
2073                 else if (is_known(t.cs(), known_old_font_shapes) &&
2074                          context.new_layout_allowed) {
2075                         char const * const * where =
2076                                 is_known(t.cs(), known_old_font_shapes);
2077                         context.check_layout(os);
2078                         TeXFont const oldFont = context.font;
2079                         context.font.init();
2080                         context.font.size = oldFont.size;
2081                         context.font.shape =
2082                                 known_coded_font_shapes[where - known_old_font_shapes];
2083                         output_font_change(os, oldFont, context.font);
2084                         eat_whitespace(p, os, context, false);
2085                 }
2086
2087                 else if (t.cs() == "selectlanguage") {
2088                         context.check_layout(os);
2089                         // save the language for the case that a \foreignlanguage is used 
2090                         selectlang = subst(p.verbatim_item(), "\n", " ");
2091                         os << "\\lang " << selectlang << "\n";
2092                         
2093                 }
2094
2095                 else if (t.cs() == "foreignlanguage") {
2096                         context.check_layout(os);
2097                         os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2098                         os << subst(p.verbatim_item(), "\n", " ");
2099                         // set back to last selectlanguage
2100                         os << "\n\\lang " << selectlang << "\n";
2101                 }
2102
2103                 else if (t.cs() == "inputencoding")
2104                         // write nothing because this is done by LyX using the "\lang"
2105                         // information given by selectlanguage and foreignlanguage
2106                         subst(p.verbatim_item(), "\n", " ");
2107                 
2108                 else if (t.cs() == "LyX" || t.cs() == "TeX"
2109                          || t.cs() == "LaTeX") {
2110                         context.check_layout(os);
2111                         os << t.cs();
2112                         skip_braces(p); // eat {}
2113                 }
2114
2115                 else if (t.cs() == "LaTeXe") {
2116                         context.check_layout(os);
2117                         os << "LaTeX2e";
2118                         skip_braces(p); // eat {}
2119                 }
2120
2121                 else if (t.cs() == "ldots") {
2122                         context.check_layout(os);
2123                         skip_braces(p);
2124                         os << "\\SpecialChar \\ldots{}\n";
2125                 }
2126
2127                 else if (t.cs() == "lyxarrow") {
2128                         context.check_layout(os);
2129                         os << "\\SpecialChar \\menuseparator\n";
2130                         skip_braces(p);
2131                 }
2132
2133                 else if (t.cs() == "textcompwordmark") {
2134                         context.check_layout(os);
2135                         os << "\\SpecialChar \\textcompwordmark{}\n";
2136                         skip_braces(p);
2137                 }
2138
2139                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2140                         context.check_layout(os);
2141                         os << "\\SpecialChar \\@.\n";
2142                         p.get_token();
2143                 }
2144
2145                 else if (t.cs() == "-") {
2146                         context.check_layout(os);
2147                         os << "\\SpecialChar \\-\n";
2148                 }
2149
2150                 else if (t.cs() == "textasciitilde") {
2151                         context.check_layout(os);
2152                         os << '~';
2153                         skip_braces(p);
2154                 }
2155
2156                 else if (t.cs() == "textasciicircum") {
2157                         context.check_layout(os);
2158                         os << '^';
2159                         skip_braces(p);
2160                 }
2161
2162                 else if (t.cs() == "textbackslash") {
2163                         context.check_layout(os);
2164                         os << "\n\\backslash\n";
2165                         skip_braces(p);
2166                 }
2167
2168                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2169                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2170                             || t.cs() == "%") {
2171                         context.check_layout(os);
2172                         os << t.cs();
2173                 }
2174
2175                 else if (t.cs() == "char") {
2176                         context.check_layout(os);
2177                         if (p.next_token().character() == '`') {
2178                                 p.get_token();
2179                                 if (p.next_token().cs() == "\"") {
2180                                         p.get_token();
2181                                         os << '"';
2182                                         skip_braces(p);
2183                                 } else {
2184                                         handle_ert(os, "\\char`", context);
2185                                 }
2186                         } else {
2187                                 handle_ert(os, "\\char", context);
2188                         }
2189                 }
2190
2191                 else if (t.cs() == "verb") {
2192                         context.check_layout(os);
2193                         char const delimiter = p.next_token().character();
2194                         string const arg = p.getArg(delimiter, delimiter);
2195                         ostringstream oss;
2196                         oss << "\\verb" << delimiter << arg << delimiter;
2197                         handle_ert(os, oss.str(), context);
2198                 }
2199
2200                 else if (t.cs() == "\"") {
2201                         context.check_layout(os);
2202                         string const name = p.verbatim_item();
2203                              if (name == "a") os << '\xe4';
2204                         else if (name == "o") os << '\xf6';
2205                         else if (name == "u") os << '\xfc';
2206                         else if (name == "A") os << '\xc4';
2207                         else if (name == "O") os << '\xd6';
2208                         else if (name == "U") os << '\xdc';
2209                         else handle_ert(os, "\"{" + name + "}", context);
2210                 }
2211
2212                 // Problem: \= creates a tabstop inside the tabbing environment
2213                 // and else an accent. In the latter case we really would want
2214                 // \={o} instead of \= o.
2215                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2216                         handle_ert(os, t.asInput(), context);
2217
2218                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2219                          || t.cs() == "'" || t.cs() == "`"
2220                          || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2221                         // we need the trim as the LyX parser chokes on such spaces
2222                         // The argument of InsetLatexAccent is parsed as a
2223                         // subset of LaTeX, so don't parse anything here,
2224                         // but use the raw argument.
2225                         // Otherwise we would convert \~{\i} wrongly.
2226                         // This will of course not translate \~{\ss} to \~{ß},
2227                         // but that does at least compile and does only look
2228                         // strange on screen.
2229                         context.check_layout(os);
2230                         os << "\\i \\" << t.cs() << "{"
2231                            << trim(p.verbatim_item(), " ")
2232                            << "}\n";
2233                 }
2234
2235                 else if (t.cs() == "ss") {
2236                         context.check_layout(os);
2237                         os << "\xdf";
2238                         skip_braces(p); // eat {}
2239                 }
2240
2241                 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2242                          t.cs() == "L") {
2243                         context.check_layout(os);
2244                         os << "\\i \\" << t.cs() << "{}\n";
2245                         skip_braces(p); // eat {}
2246                 }
2247
2248                 else if (t.cs() == "\\") {
2249                         context.check_layout(os);
2250                         string const next = p.next_token().asInput();
2251                         if (next == "[")
2252                                 handle_ert(os, "\\\\" + p.getOpt(), context);
2253                         else if (next == "*") {
2254                                 p.get_token();
2255                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
2256                         }
2257                         else {
2258                                 os << "\n\\newline\n";
2259                         }
2260                 }
2261
2262                 else if (t.cs() == "newline" ||
2263                         t.cs() == "linebreak") {
2264                         context.check_layout(os);
2265                         os << "\n\\" << t.cs() << "\n";
2266                         skip_braces(p); // eat {}
2267                 }
2268
2269                 else if (t.cs() == "href") {
2270                         context.check_layout(os);
2271                         begin_inset(os, "CommandInset ");
2272                         os << t.cs() << "\n";
2273                         os << "LatexCommand " << t.cs() << "\n";
2274                         bool erase = false;
2275                         size_t pos;
2276                         // the first argument is "type:target", "type:" is optional
2277                         // the second argument the name
2278                         string href_target = subst(p.verbatim_item(), "\n", " ");
2279                         string href_name = subst(p.verbatim_item(), "\n", " ");
2280                         string href_type;
2281                         // serach for the ":" to divide type from target
2282                         if ((pos = href_target.find(":", 0)) != string::npos){
2283                                 href_type = href_target;
2284                                 href_type.erase(pos + 1, href_type.length());
2285                                 href_target.erase(0, pos + 1);
2286                             erase = true;                                                                                       
2287                         }
2288                         os << "name " << '"' << href_name << '"' << "\n";
2289                         os << "target " << '"' << href_target << '"' << "\n";
2290                         if(erase)
2291                                 os << "type " << '"' << href_type << '"' << "\n";
2292                         end_inset(os);
2293                 }
2294
2295                 else if (t.cs() == "input" || t.cs() == "include"
2296                          || t.cs() == "verbatiminput") {
2297                         string name = '\\' + t.cs();
2298                         if (t.cs() == "verbatiminput"
2299                             && p.next_token().asInput() == "*")
2300                                 name += p.get_token().asInput();
2301                         context.check_layout(os);
2302                         begin_inset(os, "Include ");
2303                         string filename(normalize_filename(p.getArg('{', '}')));
2304                         string const path = getMasterFilePath();
2305                         // We want to preserve relative / absolute filenames,
2306                         // therefore path is only used for testing
2307                         // FIXME UNICODE encoding of filename and path may be
2308                         // wrong (makeAbsPath expects utf8)
2309                         if ((t.cs() == "include" || t.cs() == "input") &&
2310                             !makeAbsPath(filename, path).exists()) {
2311                                 // The file extension is probably missing.
2312                                 // Now try to find it out.
2313                                 string const tex_name =
2314                                         find_file(filename, path,
2315                                                   known_tex_extensions);
2316                                 if (!tex_name.empty())
2317                                         filename = tex_name;
2318                         }
2319                         // FIXME UNICODE encoding of filename and path may be
2320                         // wrong (makeAbsPath expects utf8)
2321                         if (makeAbsPath(filename, path).exists()) {
2322                                 string const abstexname =
2323                                         makeAbsPath(filename, path).absFilename();
2324                                 string const abslyxname =
2325                                         changeExtension(abstexname, ".lyx");
2326                                 fix_relative_filename(filename);
2327                                 string const lyxname =
2328                                         changeExtension(filename, ".lyx");
2329                                 if (t.cs() != "verbatiminput" &&
2330                                     tex2lyx(abstexname, FileName(abslyxname))) {
2331                                         os << name << '{' << lyxname << "}\n";
2332                                 } else {
2333                                         os << name << '{' << filename << "}\n";
2334                                 }
2335                         } else {
2336                                 cerr << "Warning: Could not find included file '"
2337                                      << filename << "'." << endl;
2338                                 os << name << '{' << filename << "}\n";
2339                         }
2340                         os << "preview false\n";
2341                         end_inset(os);
2342                 }
2343
2344                 else if (t.cs() == "bibliographystyle") {
2345                         // store new bibliographystyle
2346                         bibliographystyle = p.verbatim_item();
2347                         // output new bibliographystyle.
2348                         // This is only necessary if used in some other macro than \bibliography.
2349                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2350                 }
2351
2352                 else if (t.cs() == "bibliography") {
2353                         context.check_layout(os);
2354                         begin_inset(os, "LatexCommand ");
2355                         os << "\\bibtex";
2356                         // Do we have a bibliographystyle set?
2357                         if (!bibliographystyle.empty()) {
2358                                 os << '[' << bibliographystyle << ']';
2359                         }
2360                         os << '{' << p.verbatim_item() << "}\n";
2361                         end_inset(os);
2362                 }
2363
2364                 else if (t.cs() == "parbox")
2365                         parse_box(p, os, FLAG_ITEM, outer, context, true);
2366                 
2367                 //\makebox() is part of the picture environment and different from \makebox{}
2368                 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
2369                 else if (t.cs() == "makebox") {
2370                         string arg = t.asInput();
2371                         if (p.next_token().character() == '(')
2372                                 //the syntax is: \makebox(x,y)[position]{content}
2373                                 arg += p.getFullParentheseArg();
2374                         else
2375                                 //the syntax is: \makebox[width][position]{content}
2376                                 arg += p.getFullOpt();
2377                         handle_ert(os, arg + p.getFullOpt(), context);
2378                 }
2379
2380                 else if (t.cs() == "smallskip" ||
2381                          t.cs() == "medskip" ||
2382                          t.cs() == "bigskip" ||
2383                          t.cs() == "vfill") {
2384                         context.check_layout(os);
2385                         begin_inset(os, "VSpace ");
2386                         os << t.cs();
2387                         end_inset(os);
2388                         skip_braces(p);
2389                 }
2390
2391                 else if (is_known(t.cs(), known_spaces)) {
2392                         char const * const * where = is_known(t.cs(), known_spaces);
2393                         context.check_layout(os);
2394                         begin_inset(os, "InsetSpace ");
2395                         os << '\\' << known_coded_spaces[where - known_spaces]
2396                            << '\n';
2397                         // LaTeX swallows whitespace after all spaces except
2398                         // "\\,". We have to do that here, too, because LyX
2399                         // adds "{}" which would make the spaces significant.
2400                         if (t.cs() !=  ",")
2401                                 eat_whitespace(p, os, context, false);
2402                         // LyX adds "{}" after all spaces except "\\ " and
2403                         // "\\,", so we have to remove "{}".
2404                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
2405                         // remove the braces after "\\,", too.
2406                         if (t.cs() != " ")
2407                                 skip_braces(p);
2408                 }
2409
2410                 else if (t.cs() == "newpage" ||
2411                         t.cs() == "pagebreak" ||
2412                         t.cs() == "clearpage" ||
2413                         t.cs() == "cleardoublepage") {
2414                         context.check_layout(os);
2415                         os << "\n\\" << t.cs() << "\n";
2416                         skip_braces(p); // eat {}
2417                 }
2418
2419                 else if (t.cs() == "newcommand" ||
2420                          t.cs() == "providecommand" ||
2421                          t.cs() == "renewcommand" ||
2422                          t.cs() == "newlyxcommand") {
2423                         // these could be handled by parse_command(), but
2424                         // we need to call add_known_command() here.
2425                         string name = t.asInput();
2426                         if (p.next_token().asInput() == "*") {
2427                                 // Starred form. Eat '*'
2428                                 p.get_token();
2429                                 name += '*';
2430                         }
2431                         string const command = p.verbatim_item();
2432                         string const opt1 = p.getOpt();
2433                         string optionals;
2434                         unsigned optionalsNum = 0;
2435                         while (true) {
2436                                 string const opt = p.getFullOpt();
2437                                 if (opt.empty())
2438                                         break;
2439                                 optionalsNum++;
2440                                 optionals += opt;
2441                         }
2442                         add_known_command(command, opt1, optionalsNum);
2443                         string const ert = name + '{' + command + '}' + opt1
2444                                 + optionals + '{' + p.verbatim_item() + '}';
2445
2446                         context.check_layout(os);
2447                         begin_inset(os, "FormulaMacro");
2448                         os << "\n" << ert;
2449                         end_inset(os);
2450                 }
2451                 
2452                 else if (t.cs() == "newcommandx" ||
2453                          t.cs() == "renewcommandx") {
2454                         // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
2455
2456                         // get command name
2457                         string command;
2458                         if (p.next_token().cat() == catBegin)
2459                                 command = p.verbatim_item();
2460                         else 
2461                                 command = "\\" + p.get_token().cs();
2462                         
2463                         // get arity, we do not check that it fits to the given
2464                         // optional parameters here.
2465                         string const opt1 = p.getOpt();
2466                         
2467                         // get options and default values for optional parameters
2468                         std::vector<string> optionalValues;
2469                         int optionalsNum = 0;
2470                         if (p.next_token().character() == '[') {
2471                                 // skip '['
2472                                 p.get_token();
2473                                 
2474                                 // handle 'opt=value' options, separated by ','.
2475                                 eat_whitespace(p, os, context, false);
2476                                 while (p.next_token().character() != ']' && p.good()) {
2477                                         char_type nextc = p.next_token().character();
2478                                         if (nextc >= '1' && nextc <= '9') {
2479                                                 // optional value -> get parameter number
2480                                                 int n = p.getChar() - '0';
2481
2482                                                 // skip '='
2483                                                 if (p.next_token().character() != '=') {
2484                                                         cerr << "'=' expected after numeral option of \\newcommandx" << std::endl;
2485                                                         // try to find ] or ,
2486                                                         while (p.next_token().character() != ','
2487                                                                && p.next_token().character() != ']')
2488                                                                 p.get_token();
2489                                                         continue;
2490                                                 } else
2491                                                         p.get_token();
2492                                                 
2493                                                 // get value
2494                                                 optionalValues.resize(max(size_t(n), optionalValues.size()));
2495                                                 optionalValues[n - 1].clear();
2496                                                 while (p.next_token().character() != ']'
2497                                                        && p.next_token().character() != ',')
2498                                                         optionalValues[n - 1] += p.verbatim_item();
2499                                                 optionalsNum = max(n, optionalsNum);
2500                                         } else if (p.next_token().cat() == catLetter) {
2501                                                 // we in fact ignore every non-optional
2502                                                 // parameters
2503                                                 
2504                                                 // get option name
2505                                                 docstring opt;
2506                                                 while (p.next_token().cat() == catLetter)
2507                                                         opt += p.getChar();
2508                                                 
2509                                                 // value?
2510                                                 eat_whitespace(p, os, context, false);
2511                                                 if (p.next_token().character() == '=') {
2512                                                         p.get_token();
2513                                                         while (p.next_token().character() != ']'
2514                                                                && p.next_token().character() != ',')
2515                                                                 p.verbatim_item();
2516                                                 }
2517                                         } else
2518                                                 return;
2519                                         
2520                                         // skip komma
2521                                         eat_whitespace(p, os, context, false);
2522                                         if (p.next_token().character() == ',') {
2523                                                 p.getChar();
2524                                                 eat_whitespace(p, os, context, false);
2525                                         } else if (p.next_token().character() != ']')
2526                                                 continue;
2527                                 }
2528                                 
2529                                 // skip ']'
2530                                 p.get_token();
2531                         }
2532                         
2533                         // concat the default values to the optionals string
2534                         string optionals;
2535                         for (unsigned i = 0; i < optionalValues.size(); ++i)
2536                                 optionals += "[" + optionalValues[i] + "]";
2537                         
2538                         // register and output command
2539                         add_known_command(command, opt1, optionalsNum);
2540                         string const ert = "\\newcommand{" + command + '}' + opt1
2541                         + optionals + '{' + p.verbatim_item() + '}';
2542                         
2543                         context.check_layout(os);
2544                         begin_inset(os, "FormulaMacro");
2545                         os << "\n" << ert;
2546                         end_inset(os);
2547                 }
2548
2549                 else if (t.cs() == "vspace") {
2550                         bool starred = false;
2551                         if (p.next_token().asInput() == "*") {
2552                                 p.get_token();
2553                                 starred = true;
2554                         }
2555                         string const length = p.verbatim_item();
2556                         string unit;
2557                         string valstring;
2558                         bool valid = splitLatexLength(length, valstring, unit);
2559                         bool known_vspace = false;
2560                         bool known_unit = false;
2561                         double value;
2562                         if (valid) {
2563                                 istringstream iss(valstring);
2564                                 iss >> value;
2565                                 if (value == 1.0) {
2566                                         if (unit == "\\smallskipamount") {
2567                                                 unit = "smallskip";
2568                                                 known_vspace = true;
2569                                         } else if (unit == "\\medskipamount") {
2570                                                 unit = "medskip";
2571                                                 known_vspace = true;
2572                                         } else if (unit == "\\bigskipamount") {
2573                                                 unit = "bigskip";
2574                                                 known_vspace = true;
2575                                         } else if (unit == "\\fill") {
2576                                                 unit = "vfill";
2577                                                 known_vspace = true;
2578                                         }
2579                                 }
2580                                 if (!known_vspace) {
2581                                         switch (unitFromString(unit)) {
2582                                         case Length::SP:
2583                                         case Length::PT:
2584                                         case Length::BP:
2585                                         case Length::DD:
2586                                         case Length::MM:
2587                                         case Length::PC:
2588                                         case Length::CC:
2589                                         case Length::CM:
2590                                         case Length::IN:
2591                                         case Length::EX:
2592                                         case Length::EM:
2593                                         case Length::MU:
2594                                                 known_unit = true;
2595                                                 break;
2596                                         default:
2597                                                 break;
2598                                         }
2599                                 }
2600                         }
2601
2602                         if (known_unit || known_vspace) {
2603                                 // Literal length or known variable
2604                                 context.check_layout(os);
2605                                 begin_inset(os, "VSpace ");
2606                                 if (known_unit)
2607                                         os << value;
2608                                 os << unit;
2609                                 if (starred)
2610                                         os << '*';
2611                                 end_inset(os);
2612                         } else {
2613                                 // LyX can't handle other length variables in Inset VSpace
2614                                 string name = t.asInput();
2615                                 if (starred)
2616                                         name += '*';
2617                                 if (valid) {
2618                                         if (value == 1.0)
2619                                                 handle_ert(os, name + '{' + unit + '}', context);
2620                                         else if (value == -1.0)
2621                                                 handle_ert(os, name + "{-" + unit + '}', context);
2622                                         else
2623                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
2624                                 } else
2625                                         handle_ert(os, name + '{' + length + '}', context);
2626                         }
2627                 }
2628
2629                 else {
2630                         //cerr << "#: " << t << " mode: " << mode << endl;
2631                         // heuristic: read up to next non-nested space
2632                         /*
2633                         string s = t.asInput();
2634                         string z = p.verbatim_item();
2635                         while (p.good() && z != " " && z.size()) {
2636                                 //cerr << "read: " << z << endl;
2637                                 s += z;
2638                                 z = p.verbatim_item();
2639                         }
2640                         cerr << "found ERT: " << s << endl;
2641                         handle_ert(os, s + ' ', context);
2642                         */
2643                         string name = t.asInput();
2644                         if (p.next_token().asInput() == "*") {
2645                                 // Starred commands like \vspace*{}
2646                                 p.get_token();                          // Eat '*'
2647                                 name += '*';
2648                         }
2649                         if (! parse_command(name, p, os, outer, context))
2650                                 handle_ert(os, name, context);
2651                 }
2652
2653                 if (flags & FLAG_LEAVE) {
2654                         flags &= ~FLAG_LEAVE;
2655                         break;
2656                 }
2657         }
2658 }
2659
2660 // }])
2661
2662
2663 } // namespace lyx