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