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