]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
75c5745c958e2a273c441c696940da4fe02e114e
[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, InsetLayout const * layout)
45 {
46         bool const forcePlainLayout =
47                 layout ? layout->forcePlainLayout() : false;
48         Context newcontext(true, context.textclass);
49         if (forcePlainLayout)
50                 newcontext.layout = &context.textclass.plainLayout();
51         else
52                 newcontext.font = context.font;
53         parse_text(p, os, flags, outer, newcontext);
54         newcontext.check_end_layout(os);
55 }
56
57
58 namespace {
59
60 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
61                 Context const & context, string const & name)
62 {
63         InsetLayout const * layout = 0;
64         DocumentClass::InsetLayouts::const_iterator it =
65                 context.textclass.insetLayouts().find(from_ascii(name));
66         if (it != context.textclass.insetLayouts().end())
67                 layout = &(it->second);
68         parse_text_in_inset(p, os, flags, outer, context, layout);
69 }
70
71 /// parses a paragraph snippet, useful for example for \\emph{...}
72 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
73                 Context & context)
74 {
75         Context newcontext(context);
76         // Don't inherit the paragraph-level extra stuff
77         newcontext.par_extra_stuff.clear();
78         parse_text(p, os, flags, outer, newcontext);
79         // Make sure that we don't create invalid .lyx files
80         context.need_layout = newcontext.need_layout;
81         context.need_end_layout = newcontext.need_end_layout;
82 }
83
84
85 /*!
86  * Thin wrapper around parse_text_snippet() using a string.
87  *
88  * We completely ignore \c context.need_layout and \c context.need_end_layout,
89  * because our return value is not used directly (otherwise the stream version
90  * of parse_text_snippet() could be used). That means that the caller needs
91  * to do layout management manually.
92  * This is intended to parse text that does not create any layout changes.
93  */
94 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
95                   Context & context)
96 {
97         Context newcontext(context);
98         newcontext.need_layout = false;
99         newcontext.need_end_layout = false;
100         newcontext.new_layout_allowed = false;
101         // Avoid warning by Context::~Context()
102         newcontext.par_extra_stuff.clear();
103         ostringstream os;
104         parse_text_snippet(p, os, flags, outer, newcontext);
105         return os.str();
106 }
107
108
109 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
110  "vpageref", "prettyref", "eqref", 0 };
111
112 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
113  "vpageref", "formatted", "eqref", 0 };
114
115 /*!
116  * natbib commands.
117  * The starred forms are also known except for "citefullauthor",
118  * "citeyear" and "citeyearpar".
119  */
120 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
121 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
122 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
123
124 /*!
125  * jurabib commands.
126  * No starred form other than "cite*" known.
127  */
128 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
129 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
130 // jurabib commands not (yet) supported by LyX:
131 // "fullcite",
132 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
133 // "footciteauthor", "footciteyear", "footciteyearpar",
134 "citefield", "citetitle", 0 };
135
136 /// LaTeX names for quotes
137 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
138 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
139 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
140 "guilsinglleft", "frq", "guilsinglright", 0};
141
142 /// the same as known_quotes with .lyx names
143 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
144 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
145 "gld", "grd", "gls", "ers", "fls",
146 "fls", "frs", "frs", 0};
147
148 /// LaTeX names for font sizes
149 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
150 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
151
152 /// the same as known_sizes with .lyx names
153 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
154 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
155
156 /// LaTeX 2.09 names for font families
157 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
158
159 /// LaTeX names for font families
160 char const * const known_font_families[] = { "rmfamily", "sffamily",
161 "ttfamily", 0};
162
163 /// the same as known_old_font_families and known_font_families with .lyx names
164 char const * const known_coded_font_families[] = { "roman", "sans",
165 "typewriter", 0};
166
167 /// LaTeX 2.09 names for font series
168 char const * const known_old_font_series[] = { "bf", 0};
169
170 /// LaTeX names for font series
171 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
172
173 /// the same as known_old_font_series and known_font_series with .lyx names
174 char const * const known_coded_font_series[] = { "bold", "medium", 0};
175
176 /// LaTeX 2.09 names for font shapes
177 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
178
179 /// LaTeX names for font shapes
180 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
181 "upshape", 0};
182
183 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
184 char const * const known_coded_font_shapes[] = { "italic", "slanted",
185 "smallcaps", "up", 0};
186
187 /*!
188  * Graphics file extensions known by the dvips driver of the graphics package.
189  * These extensions are used to complete the filename of an included
190  * graphics file if it does not contain an extension.
191  * The order must be the same that latex uses to find a file, because we
192  * will use the first extension that matches.
193  * This is only an approximation for the common cases. If we would want to
194  * do it right in all cases, we would need to know which graphics driver is
195  * used and know the extensions of every driver of the graphics package.
196  */
197 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
198 "ps.gz", "eps.Z", "ps.Z", 0};
199
200 /*!
201  * Graphics file extensions known by the pdftex driver of the graphics package.
202  * \sa known_dvips_graphics_formats
203  */
204 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
205 "mps", "tif", 0};
206
207 /*!
208  * Known file extensions for TeX files as used by \\include.
209  */
210 char const * const known_tex_extensions[] = {"tex", 0};
211
212 /// spaces known by InsetSpace
213 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
214 "qquad", "enspace", "enskip", "negthinspace", "hfill", "dotfill", "hrulefill",
215 "leftarrowfill", "rightarrowfill", "upbracefill", "downbracefill", 0};
216
217 /// the same as known_spaces with .lyx names
218 char const * const known_coded_spaces[] = { "space{}", "space{}",
219 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
220 "negthinspace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
221 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
222
223 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
224 /// them in ERT. "LaTeXe" must come before "LaTeX"!
225 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
226 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
227 int const known_phrase_lengths[] = {3, 5, 7, 0};
228
229
230 /// splits "x=z, y=b" into a map and an ordered keyword vector
231 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
232 {
233         vector<string> v;
234         split(s, v);
235         res.clear();
236         keys.resize(v.size());
237         for (size_t i = 0; i < v.size(); ++i) {
238                 size_t const pos   = v[i].find('=');
239                 string const index = trimSpaceAndEol(v[i].substr(0, pos));
240                 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
241                 res[index] = value;
242                 keys[i] = index;
243         }
244 }
245
246
247 /*!
248  * Split a LaTeX length into value and unit.
249  * The latter can be a real unit like "pt", or a latex length variable
250  * like "\textwidth". The unit may contain additional stuff like glue
251  * lengths, but we don't care, because such lengths are ERT anyway.
252  * \returns true if \p value and \p unit are valid.
253  */
254 bool splitLatexLength(string const & len, string & value, string & unit)
255 {
256         if (len.empty())
257                 return false;
258         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
259         //'4,5' is a valid LaTeX length number. Change it to '4.5'
260         string const length = subst(len, ',', '.');
261         if (i == string::npos)
262                 return false;
263         if (i == 0) {
264                 if (len[0] == '\\') {
265                         // We had something like \textwidth without a factor
266                         value = "1.0";
267                 } else {
268                         return false;
269                 }
270         } else {
271                 value = trimSpaceAndEol(string(length, 0, i));
272         }
273         if (value == "-")
274                 value = "-1.0";
275         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
276         if (contains(len, '\\'))
277                 unit = trimSpaceAndEol(string(len, i));
278         else
279                 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
280         return true;
281 }
282
283
284 /// A simple function to translate a latex length to something LyX can
285 /// understand. Not perfect, but rather best-effort.
286 bool translate_len(string const & length, string & valstring, string & unit)
287 {
288         if (!splitLatexLength(length, valstring, unit))
289                 return false;
290         // LyX uses percent values
291         double value;
292         istringstream iss(valstring);
293         iss >> value;
294         value *= 100;
295         ostringstream oss;
296         oss << value;
297         string const percentval = oss.str();
298         // a normal length
299         if (unit.empty() || unit[0] != '\\')
300                 return true;
301         string::size_type const i = unit.find(' ');
302         string const endlen = (i == string::npos) ? string() : string(unit, i);
303         if (unit == "\\textwidth") {
304                 valstring = percentval;
305                 unit = "text%" + endlen;
306         } else if (unit == "\\columnwidth") {
307                 valstring = percentval;
308                 unit = "col%" + endlen;
309         } else if (unit == "\\paperwidth") {
310                 valstring = percentval;
311                 unit = "page%" + endlen;
312         } else if (unit == "\\linewidth") {
313                 valstring = percentval;
314                 unit = "line%" + endlen;
315         } else if (unit == "\\paperheight") {
316                 valstring = percentval;
317                 unit = "pheight%" + endlen;
318         } else if (unit == "\\textheight") {
319                 valstring = percentval;
320                 unit = "theight%" + endlen;
321         }
322         return true;
323 }
324
325 }
326
327
328 string translate_len(string const & length)
329 {
330         string unit;
331         string value;
332         if (translate_len(length, value, unit))
333                 return value + unit;
334         // If the input is invalid, return what we have.
335         return length;
336 }
337
338
339 namespace {
340
341 /*!
342  * Translates a LaTeX length into \p value, \p unit and
343  * \p special parts suitable for a box inset.
344  * The difference from translate_len() is that a box inset knows about
345  * some special "units" that are stored in \p special.
346  */
347 void translate_box_len(string const & length, string & value, string & unit, string & special)
348 {
349         if (translate_len(length, value, unit)) {
350                 if (unit == "\\height" || unit == "\\depth" ||
351                     unit == "\\totalheight" || unit == "\\width") {
352                         special = unit.substr(1);
353                         // The unit is not used, but LyX requires a dummy setting
354                         unit = "in";
355                 } else
356                         special = "none";
357         } else {
358                 value.clear();
359                 unit = length;
360                 special = "none";
361         }
362 }
363
364
365 /*!
366  * Find a file with basename \p name in path \p path and an extension
367  * in \p extensions.
368  */
369 string find_file(string const & name, string const & path,
370                  char const * const * extensions)
371 {
372         for (char const * const * what = extensions; *what; ++what) {
373                 string const trial = addExtension(name, *what);
374                 if (makeAbsPath(trial, path).exists())
375                         return trial;
376         }
377         return string();
378 }
379
380
381 void begin_inset(ostream & os, string const & name)
382 {
383         os << "\n\\begin_inset " << name;
384 }
385
386
387 void begin_command_inset(ostream & os, string const & name,
388                          string const & latexname)
389 {
390         begin_inset(os, "CommandInset ");
391         os << name << "\nLatexCommand " << latexname << '\n';
392 }
393
394
395 void end_inset(ostream & os)
396 {
397         os << "\n\\end_inset\n\n";
398 }
399
400
401 bool skip_braces(Parser & p)
402 {
403         if (p.next_token().cat() != catBegin)
404                 return false;
405         p.get_token();
406         if (p.next_token().cat() == catEnd) {
407                 p.get_token();
408                 return true;
409         }
410         p.putback();
411         return false;
412 }
413
414
415 /// replace LaTeX commands in \p s from the unicodesymbols file with their
416 /// unicode points
417 docstring convert_unicodesymbols(docstring s)
418 {
419         odocstringstream os;
420         for (size_t i = 0; i < s.size();) {
421                 if (s[i] != '\\') {
422                         os.put(s[i++]);
423                         continue;
424                 }
425                 s = s.substr(i);
426                 docstring rem;
427                 docstring parsed = encodings.fromLaTeXCommand(s, rem,
428                                 Encodings::TEXT_CMD);
429                 os << parsed;
430                 s = rem;
431                 if (s.empty() || s[0] != '\\')
432                         i = 0;
433                 else
434                         i = 1;
435         }
436         return os.str();
437 }
438
439
440 /// try to convert \p s to a valid InsetCommand argument
441 string convert_command_inset_arg(string s)
442 {
443         if (isAscii(s))
444                 // since we don't know the input encoding we can't use from_utf8
445                 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
446         // LyX cannot handle newlines in a latex command
447         return subst(s, "\n", " ");
448 }
449
450
451 void handle_backslash(ostream & os, string const & s)
452 {
453         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
454                 if (*it == '\\')
455                         os << "\n\\backslash\n";
456                 else
457                         os << *it;
458         }
459 }
460
461
462 void handle_ert(ostream & os, string const & s, Context & context)
463 {
464         // We must have a valid layout before outputting the ERT inset.
465         context.check_layout(os);
466         Context newcontext(true, context.textclass);
467         begin_inset(os, "ERT");
468         os << "\nstatus collapsed\n";
469         newcontext.check_layout(os);
470         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
471                 if (*it == '\\')
472                         os << "\n\\backslash\n";
473                 else if (*it == '\n') {
474                         newcontext.new_paragraph(os);
475                         newcontext.check_layout(os);
476                 } else
477                         os << *it;
478         }
479         newcontext.check_end_layout(os);
480         end_inset(os);
481 }
482
483
484 void handle_comment(ostream & os, string const & s, Context & context)
485 {
486         // TODO: Handle this better
487         Context newcontext(true, context.textclass);
488         begin_inset(os, "ERT");
489         os << "\nstatus collapsed\n";
490         newcontext.check_layout(os);
491         handle_backslash(os, s);
492         // make sure that our comment is the last thing on the line
493         newcontext.new_paragraph(os);
494         newcontext.check_layout(os);
495         newcontext.check_end_layout(os);
496         end_inset(os);
497 }
498
499
500 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
501 {
502         Layout const * layout = findLayoutWithoutModule(textclass, name, command);
503         if (layout)
504                 return layout;
505         if (checkModule(name, command))
506                 return findLayoutWithoutModule(textclass, name, command);
507         return layout;
508 }
509
510
511 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
512 {
513         InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
514         if (insetlayout)
515                 return insetlayout;
516         if (checkModule(name, command))
517                 return findInsetLayoutWithoutModule(textclass, name, command);
518         return insetlayout;
519 }
520
521
522 void eat_whitespace(Parser &, ostream &, Context &, bool);
523
524
525 /*!
526  * Skips whitespace and braces.
527  * This should be called after a command has been parsed that is not put into
528  * ERT, and where LyX adds "{}" if needed.
529  */
530 void skip_spaces_braces(Parser & p, bool keepws = false)
531 {
532         /* The following four examples produce the same typeset output and
533            should be handled by this function:
534            - abc \j{} xyz
535            - abc \j {} xyz
536            - abc \j 
537              {} xyz
538            - abc \j %comment
539              {} xyz
540          */
541         // Unfortunately we need to skip comments, too.
542         // We can't use eat_whitespace since writing them after the {}
543         // results in different output in some cases.
544         bool const skipped_spaces = p.skip_spaces(true);
545         bool const skipped_braces = skip_braces(p);
546         if (keepws && skipped_spaces && !skipped_braces)
547                 // put back the space (it is better handled by check_space)
548                 p.unskip_spaces(true);
549 }
550
551
552 void output_command_layout(ostream & os, Parser & p, bool outer,
553                            Context & parent_context,
554                            Layout const * newlayout)
555 {
556         TeXFont const oldFont = parent_context.font;
557         // save the current font size
558         string const size = oldFont.size;
559         // reset the font size to default, because the font size switches
560         // don't affect section headings and the like
561         parent_context.font.size = Context::normalfont.size;
562         // we only need to write the font change if we have an open layout
563         if (!parent_context.atParagraphStart())
564                 output_font_change(os, oldFont, parent_context.font);
565         parent_context.check_end_layout(os);
566         Context context(true, parent_context.textclass, newlayout,
567                         parent_context.layout, parent_context.font);
568         if (parent_context.deeper_paragraph) {
569                 // We are beginning a nested environment after a
570                 // deeper paragraph inside the outer list environment.
571                 // Therefore we don't need to output a "begin deeper".
572                 context.need_end_deeper = true;
573         }
574         context.check_deeper(os);
575         context.check_layout(os);
576         unsigned int optargs = 0;
577         while (optargs < context.layout->optargs) {
578                 eat_whitespace(p, os, context, false);
579                 if (p.next_token().cat() == catEscape ||
580                     p.next_token().character() != '[') 
581                         break;
582                 p.get_token(); // eat '['
583                 begin_inset(os, "Argument\n");
584                 os << "status collapsed\n\n";
585                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
586                 end_inset(os);
587                 eat_whitespace(p, os, context, false);
588                 ++optargs;
589         }
590         unsigned int reqargs = 0;
591         while (reqargs < context.layout->reqargs) {
592                 eat_whitespace(p, os, context, false);
593                 if (p.next_token().cat() != catBegin)
594                         break;
595                 p.get_token(); // eat '{'
596                 begin_inset(os, "Argument\n");
597                 os << "status collapsed\n\n";
598                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
599                 end_inset(os);
600                 eat_whitespace(p, os, context, false);
601                 ++reqargs;
602         }
603         parse_text(p, os, FLAG_ITEM, outer, context);
604         context.check_end_layout(os);
605         if (parent_context.deeper_paragraph) {
606                 // We must suppress the "end deeper" because we
607                 // suppressed the "begin deeper" above.
608                 context.need_end_deeper = false;
609         }
610         context.check_end_deeper(os);
611         // We don't need really a new paragraph, but
612         // we must make sure that the next item gets a \begin_layout.
613         parent_context.new_paragraph(os);
614         // Set the font size to the original value. No need to output it here
615         // (Context::begin_layout() will do that if needed)
616         parent_context.font.size = size;
617 }
618
619
620 /*!
621  * Output a space if necessary.
622  * This function gets called for every whitespace token.
623  *
624  * We have three cases here:
625  * 1. A space must be suppressed. Example: The lyxcode case below
626  * 2. A space may be suppressed. Example: Spaces before "\par"
627  * 3. A space must not be suppressed. Example: A space between two words
628  *
629  * We currently handle only 1. and 3 and from 2. only the case of
630  * spaces before newlines as a side effect.
631  *
632  * 2. could be used to suppress as many spaces as possible. This has two effects:
633  * - Reimporting LyX generated LaTeX files changes almost no whitespace
634  * - Superflous whitespace from non LyX generated LaTeX files is removed.
635  * The drawback is that the logic inside the function becomes
636  * complicated, and that is the reason why it is not implemented.
637  */
638 void check_space(Parser & p, ostream & os, Context & context)
639 {
640         Token const next = p.next_token();
641         Token const curr = p.curr_token();
642         // A space before a single newline and vice versa must be ignored
643         // LyX emits a newline before \end{lyxcode}.
644         // This newline must be ignored,
645         // otherwise LyX will add an additional protected space.
646         if (next.cat() == catSpace ||
647             next.cat() == catNewline ||
648             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
649                 return;
650         }
651         context.check_layout(os);
652         os << ' ';
653 }
654
655
656 /*!
657  * Parse all arguments of \p command
658  */
659 void parse_arguments(string const & command,
660                      vector<ArgumentType> const & template_arguments,
661                      Parser & p, ostream & os, bool outer, Context & context)
662 {
663         string ert = command;
664         size_t no_arguments = template_arguments.size();
665         for (size_t i = 0; i < no_arguments; ++i) {
666                 switch (template_arguments[i]) {
667                 case required:
668                         // This argument contains regular LaTeX
669                         handle_ert(os, ert + '{', context);
670                         eat_whitespace(p, os, context, false);
671                         parse_text(p, os, FLAG_ITEM, outer, context);
672                         ert = "}";
673                         break;
674                 case item:
675                         // This argument consists only of a single item.
676                         // The presence of '{' or not must be preserved.
677                         p.skip_spaces();
678                         if (p.next_token().cat() == catBegin)
679                                 ert += '{' + p.verbatim_item() + '}';
680                         else
681                                 ert += p.verbatim_item();
682                         break;
683                 case verbatim:
684                         // This argument may contain special characters
685                         ert += '{' + p.verbatim_item() + '}';
686                         break;
687                 case optional:
688                         // true because we must not eat whitespace
689                         // if an optional arg follows we must not strip the
690                         // brackets from this one
691                         if (i < no_arguments - 1 &&
692                             template_arguments[i+1] == optional)
693                                 ert += p.getFullOpt(true);
694                         else
695                                 ert += p.getOpt(true);
696                         break;
697                 }
698         }
699         handle_ert(os, ert, context);
700 }
701
702
703 /*!
704  * Check whether \p command is a known command. If yes,
705  * handle the command with all arguments.
706  * \return true if the command was parsed, false otherwise.
707  */
708 bool parse_command(string const & command, Parser & p, ostream & os,
709                    bool outer, Context & context)
710 {
711         if (known_commands.find(command) != known_commands.end()) {
712                 parse_arguments(command, known_commands[command], p, os,
713                                 outer, context);
714                 return true;
715         }
716         return false;
717 }
718
719
720 /// Parses a minipage or parbox
721 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
722                unsigned inner_flags, bool outer, Context & parent_context,
723                string const & outer_type, string const & special,
724                string const & inner_type)
725 {
726         string position;
727         string inner_pos;
728         string hor_pos = "c";
729         // We need to set the height to the LaTeX default of 1\\totalheight
730         // for the case when no height argument is given
731         string height_value = "1";
732         string height_unit = "in";
733         string height_special = "totalheight";
734         string latex_height;
735         if (!inner_type.empty() && p.hasOpt()) {
736                 position = p.getArg('[', ']');
737                 if (position != "t" && position != "c" && position != "b") {
738                         cerr << "invalid position " << position << " for "
739                              << inner_type << endl;
740                         position = "c";
741                 }
742                 if (p.hasOpt()) {
743                         latex_height = p.getArg('[', ']');
744                         translate_box_len(latex_height, height_value, height_unit, height_special);
745
746                         if (p.hasOpt()) {
747                                 inner_pos = p.getArg('[', ']');
748                                 if (inner_pos != "c" && inner_pos != "t" &&
749                                     inner_pos != "b" && inner_pos != "s") {
750                                         cerr << "invalid inner_pos "
751                                              << inner_pos << " for "
752                                              << inner_type << endl;
753                                         inner_pos = position;
754                                 }
755                         }
756                 }
757         }
758         string width_value;
759         string width_unit;
760         string latex_width;
761         if (inner_type.empty()) {
762                 if (special.empty())
763                         latex_width = "\\columnwidth";
764                 else {
765                         Parser p2(special);
766                         latex_width = p2.getArg('[', ']');
767                         string const opt = p2.getArg('[', ']');
768                         if (!opt.empty()) {
769                                 hor_pos = opt;
770                                 if (hor_pos != "l" && hor_pos != "c" &&
771                                     hor_pos != "r") {
772                                         cerr << "invalid hor_pos " << hor_pos
773                                              << " for " << outer_type << endl;
774                                         hor_pos = "c";
775                                 }
776                         }
777                 }
778         } else
779                 latex_width = p.verbatim_item();
780         translate_len(latex_width, width_value, width_unit);
781         // LyX can't handle length variables
782         bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
783         if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
784                 // Look whether there is some content after the end of the
785                 // inner box, but before the end of the outer box.
786                 // If yes, we need to output ERT.
787                 p.pushPosition();
788                 if (inner_flags & FLAG_END)
789                         p.verbatimEnvironment(inner_type);
790                 else
791                         p.verbatim_item();
792                 p.skip_spaces(true);
793                 if ((outer_type == "framed" && p.next_token().asInput() != "\\end") ||
794                     (outer_type != "framed" && p.next_token().cat() != catEnd)) {
795                         // something is between the end of the inner box and
796                         // the end of the outer box, so we need to use ERT.
797                         use_ert = true;
798                 }
799                 p.popPosition();
800         }
801         if (use_ert) {
802                 ostringstream ss;
803                 if (!outer_type.empty()) {
804                         if (outer_flags & FLAG_END)
805                                 ss << "\\begin{" << outer_type << '}';
806                         else {
807                                 ss << '\\' << outer_type << '{';
808                                 if (!special.empty())
809                                         ss << special;
810                         }
811                 }
812                 if (!inner_type.empty()) {
813                         if (inner_flags & FLAG_END)
814                                 ss << "\\begin{" << inner_type << '}';
815                         else
816                                 ss << '\\' << inner_type;
817                         if (!position.empty())
818                                 ss << '[' << position << ']';
819                         if (!latex_height.empty())
820                                 ss << '[' << latex_height << ']';
821                         if (!inner_pos.empty())
822                                 ss << '[' << inner_pos << ']';
823                         ss << '{' << latex_width << '}';
824                         if (!(inner_flags & FLAG_END))
825                                 ss << '{';
826                 }
827                 handle_ert(os, ss.str(), parent_context);
828                 if (!inner_type.empty()) {
829                         parse_text(p, os, inner_flags, outer, parent_context);
830                         if (inner_flags & FLAG_END)
831                                 handle_ert(os, "\\end{" + inner_type + '}',
832                                            parent_context);
833                         else
834                                 handle_ert(os, "}", parent_context);
835                 }
836                 if (!outer_type.empty()) {
837                         parse_text(p, os, outer_flags, outer, parent_context);
838                         if (outer_flags & FLAG_END)
839                                 handle_ert(os, "\\end{" + outer_type + '}',
840                                            parent_context);
841                         else
842                                 handle_ert(os, "}", parent_context);
843                 }
844         } else {
845                 // LyX does not like empty positions, so we have
846                 // to set them to the LaTeX default values here.
847                 if (position.empty())
848                         position = "c";
849                 if (inner_pos.empty())
850                         inner_pos = position;
851                 parent_context.check_layout(os);
852                 begin_inset(os, "Box ");
853                 if (outer_type == "framed")
854                         os << "Framed\n";
855                 else if (outer_type == "framebox")
856                         os << "Boxed\n";
857                 else if (outer_type == "shadowbox")
858                         os << "Shadowbox\n";
859                 else if (outer_type == "shaded")
860                         os << "Shaded\n";
861                 else if (outer_type == "doublebox")
862                         os << "Doublebox\n";
863                 else if (outer_type.empty())
864                         os << "Frameless\n";
865                 else
866                         os << outer_type << '\n';
867                 os << "position \"" << position << "\"\n";
868                 os << "hor_pos \"" << hor_pos << "\"\n";
869                 os << "has_inner_box " << !inner_type.empty() << "\n";
870                 os << "inner_pos \"" << inner_pos << "\"\n";
871                 os << "use_parbox " << (inner_type == "parbox") << '\n';
872                 os << "use_makebox 0\n";
873                 os << "width \"" << width_value << width_unit << "\"\n";
874                 os << "special \"none\"\n";
875                 os << "height \"" << height_value << height_unit << "\"\n";
876                 os << "height_special \"" << height_special << "\"\n";
877                 os << "status open\n\n";
878                 Context context(true, parent_context.textclass);
879                 context.font = parent_context.font;
880
881                 // If we have no inner box the contens will be read with the outer box
882                 if (!inner_type.empty())
883                         parse_text(p, os, inner_flags, outer, context);
884
885                 // Ensure that the end of the outer box is parsed correctly:
886                 // The opening brace has been eaten by parse_outer_box()
887                 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
888                         outer_flags &= ~FLAG_ITEM;
889                         outer_flags |= FLAG_BRACE_LAST;
890                 }
891
892                 // Find end of outer box, output contents if inner_type is
893                 // empty and output possible comments
894                 if (!outer_type.empty()) {
895                         // This does not output anything but comments if
896                         // inner_type is not empty (see use_ert)
897                         parse_text(p, os, outer_flags, outer, context);
898                 }
899
900                 context.check_end_layout(os);
901                 end_inset(os);
902 #ifdef PRESERVE_LAYOUT
903                 // LyX puts a % after the end of the minipage
904                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
905                         // new paragraph
906                         //handle_comment(os, "%dummy", parent_context);
907                         p.get_token();
908                         p.skip_spaces();
909                         parent_context.new_paragraph(os);
910                 }
911                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
912                         //handle_comment(os, "%dummy", parent_context);
913                         p.get_token();
914                         p.skip_spaces();
915                         // We add a protected space if something real follows
916                         if (p.good() && p.next_token().cat() != catComment) {
917                                 begin_inset(os, "space ~\n");
918                                 end_inset(os);
919                         }
920                 }
921 #endif
922         }
923 }
924
925
926 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
927                      Context & parent_context, string const & outer_type,
928                      string const & special)
929 {
930         eat_whitespace(p, os, parent_context, false);
931         if (flags & FLAG_ITEM) {
932                 // Eat '{'
933                 if (p.next_token().cat() == catBegin)
934                         p.get_token();
935                 else
936                         cerr << "Warning: Ignoring missing '{' after \\"
937                              << outer_type << '.' << endl;
938                 eat_whitespace(p, os, parent_context, false);
939         }
940         string inner;
941         unsigned int inner_flags = 0;
942         if (outer_type == "shaded") {
943                 // These boxes never have an inner box
944                 ;
945         } else if (p.next_token().asInput() == "\\parbox") {
946                 inner = p.get_token().cs();
947                 inner_flags = FLAG_ITEM;
948         } else if (p.next_token().asInput() == "\\begin") {
949                 // Is this a minipage?
950                 p.pushPosition();
951                 p.get_token();
952                 inner = p.getArg('{', '}');
953                 p.popPosition();
954                 if (inner == "minipage") {
955                         p.get_token();
956                         p.getArg('{', '}');
957                         eat_whitespace(p, os, parent_context, false);
958                         inner_flags = FLAG_END;
959                 } else
960                         inner = "";
961         }
962         if (inner_flags == FLAG_END) {
963                 active_environments.push_back(inner);
964                 parse_box(p, os, flags, FLAG_END, outer, parent_context,
965                           outer_type, special, inner);
966                 active_environments.pop_back();
967         } else {
968                 parse_box(p, os, flags, inner_flags, outer, parent_context,
969                           outer_type, special, inner);
970         }
971 }
972
973
974 void parse_listings(Parser & p, ostream & os, Context & parent_context)
975 {
976         parent_context.check_layout(os);
977         begin_inset(os, "listings\n");
978         os << "inline false\n"
979            << "status collapsed\n";
980         Context context(true, parent_context.textclass);
981         context.layout = &parent_context.textclass.plainLayout();
982         context.check_layout(os);
983         string const s = p.verbatimEnvironment("lstlisting");
984         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
985                 if (*it == '\\')
986                         os << "\n\\backslash\n";
987                 else if (*it == '\n') {
988                         // avoid adding an empty paragraph at the end
989                         if (it + 1 != et) {
990                                 context.new_paragraph(os);
991                                 context.check_layout(os);
992                         }
993                 } else
994                         os << *it;
995         }
996         context.check_end_layout(os);
997         end_inset(os);
998 }
999
1000
1001 /// parse an unknown environment
1002 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1003                                unsigned flags, bool outer,
1004                                Context & parent_context)
1005 {
1006         if (name == "tabbing")
1007                 // We need to remember that we have to handle '\=' specially
1008                 flags |= FLAG_TABBING;
1009
1010         // We need to translate font changes and paragraphs inside the
1011         // environment to ERT if we have a non standard font.
1012         // Otherwise things like
1013         // \large\begin{foo}\huge bar\end{foo}
1014         // will not work.
1015         bool const specialfont =
1016                 (parent_context.font != parent_context.normalfont);
1017         bool const new_layout_allowed = parent_context.new_layout_allowed;
1018         if (specialfont)
1019                 parent_context.new_layout_allowed = false;
1020         handle_ert(os, "\\begin{" + name + "}", parent_context);
1021         parse_text_snippet(p, os, flags, outer, parent_context);
1022         handle_ert(os, "\\end{" + name + "}", parent_context);
1023         if (specialfont)
1024                 parent_context.new_layout_allowed = new_layout_allowed;
1025 }
1026
1027
1028 void parse_environment(Parser & p, ostream & os, bool outer,
1029                        string & last_env, Context & parent_context)
1030 {
1031         Layout const * newlayout;
1032         InsetLayout const * newinsetlayout = 0;
1033         string const name = p.getArg('{', '}');
1034         const bool is_starred = suffixIs(name, '*');
1035         string const unstarred_name = rtrim(name, "*");
1036         active_environments.push_back(name);
1037
1038         if (is_math_env(name)) {
1039                 parent_context.check_layout(os);
1040                 begin_inset(os, "Formula ");
1041                 os << "\\begin{" << name << "}";
1042                 parse_math(p, os, FLAG_END, MATH_MODE);
1043                 os << "\\end{" << name << "}";
1044                 end_inset(os);
1045         }
1046
1047         else if (name == "tabular" || name == "longtable") {
1048                 eat_whitespace(p, os, parent_context, false);
1049                 parent_context.check_layout(os);
1050                 begin_inset(os, "Tabular ");
1051                 handle_tabular(p, os, name == "longtable", parent_context);
1052                 end_inset(os);
1053                 p.skip_spaces();
1054         }
1055
1056         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1057                 eat_whitespace(p, os, parent_context, false);
1058                 parent_context.check_layout(os);
1059                 begin_inset(os, "Float " + unstarred_name + "\n");
1060                 if (p.hasOpt())
1061                         os << "placement " << p.getArg('[', ']') << '\n';
1062                 os << "wide " << convert<string>(is_starred)
1063                    << "\nsideways false"
1064                    << "\nstatus open\n\n";
1065                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1066                 end_inset(os);
1067                 // We don't need really a new paragraph, but
1068                 // we must make sure that the next item gets a \begin_layout.
1069                 parent_context.new_paragraph(os);
1070                 p.skip_spaces();
1071         }
1072
1073         else if (name == "minipage") {
1074                 eat_whitespace(p, os, parent_context, false);
1075                 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1076                 p.skip_spaces();
1077         }
1078
1079         else if (name == "comment") {
1080                 eat_whitespace(p, os, parent_context, false);
1081                 parent_context.check_layout(os);
1082                 begin_inset(os, "Note Comment\n");
1083                 os << "status open\n";
1084                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1085                 end_inset(os);
1086                 p.skip_spaces();
1087                 skip_braces(p); // eat {} that might by set by LyX behind comments
1088         }
1089
1090         else if (name == "lyxgreyedout") {
1091                 eat_whitespace(p, os, parent_context, false);
1092                 parent_context.check_layout(os);
1093                 begin_inset(os, "Note Greyedout\n");
1094                 os << "status open\n";
1095                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1096                 end_inset(os);
1097                 p.skip_spaces();
1098         }
1099
1100         else if (name == "framed" || name == "shaded") {
1101                 eat_whitespace(p, os, parent_context, false);
1102                 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1103                 p.skip_spaces();
1104         }
1105
1106         else if (name == "lstlisting") {
1107                 eat_whitespace(p, os, parent_context, false);
1108                 // FIXME handle listings with parameters
1109                 if (p.hasOpt())
1110                         parse_unknown_environment(p, name, os, FLAG_END,
1111                                                   outer, parent_context);
1112                 else
1113                         parse_listings(p, os, parent_context);
1114                 p.skip_spaces();
1115         }
1116
1117         else if (!parent_context.new_layout_allowed)
1118                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1119                                           parent_context);
1120
1121         // Alignment and spacing settings
1122         // FIXME (bug xxxx): These settings can span multiple paragraphs and
1123         //                                       therefore are totally broken!
1124         // Note that \centering, raggedright, and raggedleft cannot be handled, as
1125         // they are commands not environments. They are furthermore switches that
1126         // can be ended by another switches, but also by commands like \footnote or
1127         // \parbox. So the only safe way is to leave them untouched.
1128         else if (name == "center" || name == "centering" ||
1129                  name == "flushleft" || name == "flushright" ||
1130                  name == "singlespace" || name == "onehalfspace" ||
1131                  name == "doublespace" || name == "spacing") {
1132                 eat_whitespace(p, os, parent_context, false);
1133                 // We must begin a new paragraph if not already done
1134                 if (! parent_context.atParagraphStart()) {
1135                         parent_context.check_end_layout(os);
1136                         parent_context.new_paragraph(os);
1137                 }
1138                 if (name == "flushleft")
1139                         parent_context.add_extra_stuff("\\align left\n");
1140                 else if (name == "flushright")
1141                         parent_context.add_extra_stuff("\\align right\n");
1142                 else if (name == "center" || name == "centering")
1143                         parent_context.add_extra_stuff("\\align center\n");
1144                 else if (name == "singlespace")
1145                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1146                 else if (name == "onehalfspace")
1147                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1148                 else if (name == "doublespace")
1149                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1150                 else if (name == "spacing")
1151                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1152                 parse_text(p, os, FLAG_END, outer, parent_context);
1153                 // Just in case the environment is empty
1154                 parent_context.extra_stuff.erase();
1155                 // We must begin a new paragraph to reset the alignment
1156                 parent_context.new_paragraph(os);
1157                 p.skip_spaces();
1158         }
1159
1160         // The single '=' is meant here.
1161         else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1162                 eat_whitespace(p, os, parent_context, false);
1163                 Context context(true, parent_context.textclass, newlayout,
1164                                 parent_context.layout, parent_context.font);
1165                 if (parent_context.deeper_paragraph) {
1166                         // We are beginning a nested environment after a
1167                         // deeper paragraph inside the outer list environment.
1168                         // Therefore we don't need to output a "begin deeper".
1169                         context.need_end_deeper = true;
1170                 }
1171                 parent_context.check_end_layout(os);
1172                 if (last_env == name) {
1173                         // we need to output a separator since LyX would export
1174                         // the two environments as one otherwise (bug 5716)
1175                         docstring const sep = from_ascii("--Separator--");
1176                         TeX2LyXDocClass const & textclass(parent_context.textclass);
1177                         if (textclass.hasLayout(sep)) {
1178                                 Context newcontext(parent_context);
1179                                 newcontext.layout = &(textclass[sep]);
1180                                 newcontext.check_layout(os);
1181                                 newcontext.check_end_layout(os);
1182                         } else {
1183                                 parent_context.check_layout(os);
1184                                 begin_inset(os, "Note Note\n");
1185                                 os << "status closed\n";
1186                                 Context newcontext(true, textclass,
1187                                                 &(textclass.defaultLayout()));
1188                                 newcontext.check_layout(os);
1189                                 newcontext.check_end_layout(os);
1190                                 end_inset(os);
1191                                 parent_context.check_end_layout(os);
1192                         }
1193                 }
1194                 switch (context.layout->latextype) {
1195                 case  LATEX_LIST_ENVIRONMENT:
1196                         context.add_par_extra_stuff("\\labelwidthstring "
1197                                                     + p.verbatim_item() + '\n');
1198                         p.skip_spaces();
1199                         break;
1200                 case  LATEX_BIB_ENVIRONMENT:
1201                         p.verbatim_item(); // swallow next arg
1202                         p.skip_spaces();
1203                         break;
1204                 default:
1205                         break;
1206                 }
1207                 context.check_deeper(os);
1208                 // handle known optional and required arguments
1209                 // layouts require all optional arguments before the required ones
1210                 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1211                 // It is impossible to place anything after the environment name,
1212                 // but before the first \\item.
1213                 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1214                         bool need_layout = true;
1215                         unsigned int optargs = 0;
1216                         while (optargs < context.layout->optargs) {
1217                                 eat_whitespace(p, os, context, false);
1218                                 if (p.next_token().cat() == catEscape ||
1219                                     p.next_token().character() != '[') 
1220                                         break;
1221                                 p.get_token(); // eat '['
1222                                 if (need_layout) {
1223                                         context.check_layout(os);
1224                                         need_layout = false;
1225                                 }
1226                                 begin_inset(os, "Argument\n");
1227                                 os << "status collapsed\n\n";
1228                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1229                                 end_inset(os);
1230                                 eat_whitespace(p, os, context, false);
1231                                 ++optargs;
1232                         }
1233                         unsigned int reqargs = 0;
1234                         while (reqargs < context.layout->reqargs) {
1235                                 eat_whitespace(p, os, context, false);
1236                                 if (p.next_token().cat() != catBegin)
1237                                         break;
1238                                 p.get_token(); // eat '{'
1239                                 if (need_layout) {
1240                                         context.check_layout(os);
1241                                         need_layout = false;
1242                                 }
1243                                 begin_inset(os, "Argument\n");
1244                                 os << "status collapsed\n\n";
1245                                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1246                                 end_inset(os);
1247                                 eat_whitespace(p, os, context, false);
1248                                 ++reqargs;
1249                         }
1250                 }
1251                 parse_text(p, os, FLAG_END, outer, context);
1252                 context.check_end_layout(os);
1253                 if (parent_context.deeper_paragraph) {
1254                         // We must suppress the "end deeper" because we
1255                         // suppressed the "begin deeper" above.
1256                         context.need_end_deeper = false;
1257                 }
1258                 context.check_end_deeper(os);
1259                 parent_context.new_paragraph(os);
1260                 p.skip_spaces();
1261         }
1262
1263         // The single '=' is meant here.
1264         else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1265                 eat_whitespace(p, os, parent_context, false);
1266                 parent_context.check_layout(os);
1267                 begin_inset(os, "Flex ");
1268                 os << to_utf8(newinsetlayout->name()) << '\n'
1269                    << "status collapsed\n";
1270                 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1271                 end_inset(os);
1272         }
1273
1274         else if (name == "appendix") {
1275                 // This is no good latex style, but it works and is used in some documents...
1276                 eat_whitespace(p, os, parent_context, false);
1277                 parent_context.check_end_layout(os);
1278                 Context context(true, parent_context.textclass, parent_context.layout,
1279                                 parent_context.layout, parent_context.font);
1280                 context.check_layout(os);
1281                 os << "\\start_of_appendix\n";
1282                 parse_text(p, os, FLAG_END, outer, context);
1283                 context.check_end_layout(os);
1284                 p.skip_spaces();
1285         }
1286
1287         else if (known_environments.find(name) != known_environments.end()) {
1288                 vector<ArgumentType> arguments = known_environments[name];
1289                 // The last "argument" denotes wether we may translate the
1290                 // environment contents to LyX
1291                 // The default required if no argument is given makes us
1292                 // compatible with the reLyXre environment.
1293                 ArgumentType contents = arguments.empty() ?
1294                         required :
1295                         arguments.back();
1296                 if (!arguments.empty())
1297                         arguments.pop_back();
1298                 // See comment in parse_unknown_environment()
1299                 bool const specialfont =
1300                         (parent_context.font != parent_context.normalfont);
1301                 bool const new_layout_allowed =
1302                         parent_context.new_layout_allowed;
1303                 if (specialfont)
1304                         parent_context.new_layout_allowed = false;
1305                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1306                                 outer, parent_context);
1307                 if (contents == verbatim)
1308                         handle_ert(os, p.verbatimEnvironment(name),
1309                                    parent_context);
1310                 else
1311                         parse_text_snippet(p, os, FLAG_END, outer,
1312                                            parent_context);
1313                 handle_ert(os, "\\end{" + name + "}", parent_context);
1314                 if (specialfont)
1315                         parent_context.new_layout_allowed = new_layout_allowed;
1316         }
1317
1318         else
1319                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1320                                           parent_context);
1321
1322         last_env = name;
1323         active_environments.pop_back();
1324 }
1325
1326
1327 /// parses a comment and outputs it to \p os.
1328 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1329 {
1330         LASSERT(t.cat() == catComment, return);
1331         if (!t.cs().empty()) {
1332                 context.check_layout(os);
1333                 handle_comment(os, '%' + t.cs(), context);
1334                 if (p.next_token().cat() == catNewline) {
1335                         // A newline after a comment line starts a new
1336                         // paragraph
1337                         if (context.new_layout_allowed) {
1338                                 if(!context.atParagraphStart())
1339                                         // Only start a new paragraph if not already
1340                                         // done (we might get called recursively)
1341                                         context.new_paragraph(os);
1342                         } else
1343                                 handle_ert(os, "\n", context);
1344                         eat_whitespace(p, os, context, true);
1345                 }
1346         } else {
1347                 // "%\n" combination
1348                 p.skip_spaces();
1349         }
1350 }
1351
1352
1353 /*!
1354  * Reads spaces and comments until the first non-space, non-comment token.
1355  * New paragraphs (double newlines or \\par) are handled like simple spaces
1356  * if \p eatParagraph is true.
1357  * Spaces are skipped, but comments are written to \p os.
1358  */
1359 void eat_whitespace(Parser & p, ostream & os, Context & context,
1360                     bool eatParagraph)
1361 {
1362         while (p.good()) {
1363                 Token const & t = p.get_token();
1364                 if (t.cat() == catComment)
1365                         parse_comment(p, os, t, context);
1366                 else if ((! eatParagraph && p.isParagraph()) ||
1367                          (t.cat() != catSpace && t.cat() != catNewline)) {
1368                         p.putback();
1369                         return;
1370                 }
1371         }
1372 }
1373
1374
1375 /*!
1376  * Set a font attribute, parse text and reset the font attribute.
1377  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1378  * \param currentvalue Current value of the attribute. Is set to the new
1379  * value during parsing.
1380  * \param newvalue New value of the attribute
1381  */
1382 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1383                            Context & context, string const & attribute,
1384                            string & currentvalue, string const & newvalue)
1385 {
1386         context.check_layout(os);
1387         string const oldvalue = currentvalue;
1388         currentvalue = newvalue;
1389         os << '\n' << attribute << ' ' << newvalue << "\n";
1390         parse_text_snippet(p, os, flags, outer, context);
1391         context.check_layout(os);
1392         os << '\n' << attribute << ' ' << oldvalue << "\n";
1393         currentvalue = oldvalue;
1394 }
1395
1396
1397 /// get the arguments of a natbib or jurabib citation command
1398 void get_cite_arguments(Parser & p, bool natbibOrder,
1399         string & before, string & after)
1400 {
1401         // We need to distinguish "" and "[]", so we can't use p.getOpt().
1402
1403         // text before the citation
1404         before.clear();
1405         // text after the citation
1406         after = p.getFullOpt();
1407
1408         if (!after.empty()) {
1409                 before = p.getFullOpt();
1410                 if (natbibOrder && !before.empty())
1411                         swap(before, after);
1412         }
1413 }
1414
1415
1416 /// Convert filenames with TeX macros and/or quotes to something LyX
1417 /// can understand
1418 string const normalize_filename(string const & name)
1419 {
1420         Parser p(trim(name, "\""));
1421         ostringstream os;
1422         while (p.good()) {
1423                 Token const & t = p.get_token();
1424                 if (t.cat() != catEscape)
1425                         os << t.asInput();
1426                 else if (t.cs() == "lyxdot") {
1427                         // This is used by LyX for simple dots in relative
1428                         // names
1429                         os << '.';
1430                         p.skip_spaces();
1431                 } else if (t.cs() == "space") {
1432                         os << ' ';
1433                         p.skip_spaces();
1434                 } else
1435                         os << t.asInput();
1436         }
1437         return os.str();
1438 }
1439
1440
1441 /// Convert \p name from TeX convention (relative to master file) to LyX
1442 /// convention (relative to .lyx file) if it is relative
1443 void fix_relative_filename(string & name)
1444 {
1445         if (FileName::isAbsolute(name))
1446                 return;
1447
1448         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1449                                    from_utf8(getParentFilePath())));
1450 }
1451
1452
1453 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1454 void parse_noweb(Parser & p, ostream & os, Context & context)
1455 {
1456         // assemble the rest of the keyword
1457         string name("<<");
1458         bool scrap = false;
1459         while (p.good()) {
1460                 Token const & t = p.get_token();
1461                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1462                         name += ">>";
1463                         p.get_token();
1464                         scrap = (p.good() && p.next_token().asInput() == "=");
1465                         if (scrap)
1466                                 name += p.get_token().asInput();
1467                         break;
1468                 }
1469                 name += t.asInput();
1470         }
1471
1472         if (!scrap || !context.new_layout_allowed ||
1473             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1474                 cerr << "Warning: Could not interpret '" << name
1475                      << "'. Ignoring it." << endl;
1476                 return;
1477         }
1478
1479         // We use new_paragraph instead of check_end_layout because the stuff
1480         // following the noweb chunk needs to start with a \begin_layout.
1481         // This may create a new paragraph even if there was none in the
1482         // noweb file, but the alternative is an invalid LyX file. Since
1483         // noweb code chunks are implemented with a layout style in LyX they
1484         // always must be in an own paragraph.
1485         context.new_paragraph(os);
1486         Context newcontext(true, context.textclass,
1487                 &context.textclass[from_ascii("Scrap")]);
1488         newcontext.check_layout(os);
1489         os << name;
1490         while (p.good()) {
1491                 Token const & t = p.get_token();
1492                 // We abuse the parser a bit, because this is no TeX syntax
1493                 // at all.
1494                 if (t.cat() == catEscape)
1495                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1496                 else {
1497                         ostringstream oss;
1498                         begin_inset(oss, "Newline newline");
1499                         end_inset(oss);
1500                         os << subst(t.asInput(), "\n", oss.str());
1501                 }
1502                 // The scrap chunk is ended by an @ at the beginning of a line.
1503                 // After the @ the line may contain a comment and/or
1504                 // whitespace, but nothing else.
1505                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1506                     (p.next_token().cat() == catSpace ||
1507                      p.next_token().cat() == catNewline ||
1508                      p.next_token().cat() == catComment)) {
1509                         while (p.good() && p.next_token().cat() == catSpace)
1510                                 os << p.get_token().asInput();
1511                         if (p.next_token().cat() == catComment)
1512                                 // The comment includes a final '\n'
1513                                 os << p.get_token().asInput();
1514                         else {
1515                                 if (p.next_token().cat() == catNewline)
1516                                         p.get_token();
1517                                 os << '\n';
1518                         }
1519                         break;
1520                 }
1521         }
1522         newcontext.check_end_layout(os);
1523 }
1524
1525
1526 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1527 bool is_macro(Parser & p)
1528 {
1529         Token first = p.curr_token();
1530         if (first.cat() != catEscape || !p.good())
1531                 return false;
1532         if (first.cs() == "def")
1533                 return true;
1534         if (first.cs() != "global" && first.cs() != "long")
1535                 return false;
1536         Token second = p.get_token();
1537         int pos = 1;
1538         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1539                second.cat() == catNewline || second.cat() == catComment)) {
1540                 second = p.get_token();
1541                 pos++;
1542         }
1543         bool secondvalid = second.cat() == catEscape;
1544         Token third;
1545         bool thirdvalid = false;
1546         if (p.good() && first.cs() == "global" && secondvalid &&
1547             second.cs() == "long") {
1548                 third = p.get_token();
1549                 pos++;
1550                 while (p.good() && !p.isParagraph() &&
1551                        (third.cat() == catSpace ||
1552                         third.cat() == catNewline ||
1553                         third.cat() == catComment)) {
1554                         third = p.get_token();
1555                         pos++;
1556                 }
1557                 thirdvalid = third.cat() == catEscape;
1558         }
1559         for (int i = 0; i < pos; ++i)
1560                 p.putback();
1561         if (!secondvalid)
1562                 return false;
1563         if (!thirdvalid)
1564                 return (first.cs() == "global" || first.cs() == "long") &&
1565                        second.cs() == "def";
1566         return first.cs() == "global" && second.cs() == "long" &&
1567                third.cs() == "def";
1568 }
1569
1570
1571 /// Parse a macro definition (assumes that is_macro() returned true)
1572 void parse_macro(Parser & p, ostream & os, Context & context)
1573 {
1574         context.check_layout(os);
1575         Token first = p.curr_token();
1576         Token second;
1577         Token third;
1578         string command = first.asInput();
1579         if (first.cs() != "def") {
1580                 p.get_token();
1581                 eat_whitespace(p, os, context, false);
1582                 second = p.curr_token();
1583                 command += second.asInput();
1584                 if (second.cs() != "def") {
1585                         p.get_token();
1586                         eat_whitespace(p, os, context, false);
1587                         third = p.curr_token();
1588                         command += third.asInput();
1589                 }
1590         }
1591         eat_whitespace(p, os, context, false);
1592         string const name = p.get_token().cs();
1593         eat_whitespace(p, os, context, false);
1594
1595         // parameter text
1596         bool simple = true;
1597         string paramtext;
1598         int arity = 0;
1599         while (p.next_token().cat() != catBegin) {
1600                 if (p.next_token().cat() == catParameter) {
1601                         // # found
1602                         p.get_token();
1603                         paramtext += "#";
1604
1605                         // followed by number?
1606                         if (p.next_token().cat() == catOther) {
1607                                 char c = p.getChar();
1608                                 paramtext += c;
1609                                 // number = current arity + 1?
1610                                 if (c == arity + '0' + 1)
1611                                         ++arity;
1612                                 else
1613                                         simple = false;
1614                         } else
1615                                 paramtext += p.get_token().cs();
1616                 } else {
1617                         paramtext += p.get_token().cs();
1618                         simple = false;
1619                 }
1620         }
1621
1622         // only output simple (i.e. compatible) macro as FormulaMacros
1623         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1624         if (simple) {
1625                 context.check_layout(os);
1626                 begin_inset(os, "FormulaMacro");
1627                 os << "\n\\def" << ert;
1628                 end_inset(os);
1629         } else
1630                 handle_ert(os, command + ert, context);
1631 }
1632
1633 } // anonymous namespace
1634
1635
1636 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1637                 Context & context)
1638 {
1639         Layout const * newlayout = 0;
1640         InsetLayout const * newinsetlayout = 0;
1641         // Store the latest bibliographystyle and nocite{*} option
1642         // (needed for bibtex inset)
1643         string btprint;
1644         string bibliographystyle;
1645         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1646         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1647         string last_env;
1648         while (p.good()) {
1649                 Token const & t = p.get_token();
1650
1651 #ifdef FILEDEBUG
1652                 debugToken(cerr, t, flags);
1653 #endif
1654
1655                 if (flags & FLAG_ITEM) {
1656                         if (t.cat() == catSpace)
1657                                 continue;
1658
1659                         flags &= ~FLAG_ITEM;
1660                         if (t.cat() == catBegin) {
1661                                 // skip the brace and collect everything to the next matching
1662                                 // closing brace
1663                                 flags |= FLAG_BRACE_LAST;
1664                                 continue;
1665                         }
1666
1667                         // handle only this single token, leave the loop if done
1668                         flags |= FLAG_LEAVE;
1669                 }
1670
1671                 if (t.cat() != catEscape && t.character() == ']' &&
1672                     (flags & FLAG_BRACK_LAST))
1673                         return;
1674                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1675                         return;
1676
1677                 // If there is anything between \end{env} and \begin{env} we
1678                 // don't need to output a separator.
1679                 if (t.cat() != catSpace && t.cat() != catNewline &&
1680                     t.asInput() != "\\begin")
1681                         last_env = "";
1682
1683                 //
1684                 // cat codes
1685                 //
1686                 if (t.cat() == catMath) {
1687                         // we are inside some text mode thingy, so opening new math is allowed
1688                         context.check_layout(os);
1689                         begin_inset(os, "Formula ");
1690                         Token const & n = p.get_token();
1691                         if (n.cat() == catMath && outer) {
1692                                 // TeX's $$...$$ syntax for displayed math
1693                                 os << "\\[";
1694                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1695                                 os << "\\]";
1696                                 p.get_token(); // skip the second '$' token
1697                         } else {
1698                                 // simple $...$  stuff
1699                                 p.putback();
1700                                 os << '$';
1701                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1702                                 os << '$';
1703                         }
1704                         end_inset(os);
1705                 }
1706
1707                 else if (t.cat() == catSuper || t.cat() == catSub)
1708                         cerr << "catcode " << t << " illegal in text mode\n";
1709
1710                 // Basic support for english quotes. This should be
1711                 // extended to other quotes, but is not so easy (a
1712                 // left english quote is the same as a right german
1713                 // quote...)
1714                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1715                         context.check_layout(os);
1716                         begin_inset(os, "Quotes ");
1717                         os << "eld";
1718                         end_inset(os);
1719                         p.get_token();
1720                         skip_braces(p);
1721                 }
1722                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1723                         context.check_layout(os);
1724                         begin_inset(os, "Quotes ");
1725                         os << "erd";
1726                         end_inset(os);
1727                         p.get_token();
1728                         skip_braces(p);
1729                 }
1730
1731                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1732                         context.check_layout(os);
1733                         begin_inset(os, "Quotes ");
1734                         os << "ald";
1735                         end_inset(os);
1736                         p.get_token();
1737                         skip_braces(p);
1738                 }
1739
1740                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1741                         context.check_layout(os);
1742                         begin_inset(os, "Quotes ");
1743                         os << "ard";
1744                         end_inset(os);
1745                         p.get_token();
1746                         skip_braces(p);
1747                 }
1748
1749                 else if (t.asInput() == "<"
1750                          && p.next_token().asInput() == "<" && noweb_mode) {
1751                         p.get_token();
1752                         parse_noweb(p, os, context);
1753                 }
1754
1755                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1756                         check_space(p, os, context);
1757
1758                 else if (t.character() == '[' && noweb_mode &&
1759                          p.next_token().character() == '[') {
1760                         // These can contain underscores
1761                         p.putback();
1762                         string const s = p.getFullOpt() + ']';
1763                         if (p.next_token().character() == ']')
1764                                 p.get_token();
1765                         else
1766                                 cerr << "Warning: Inserting missing ']' in '"
1767                                      << s << "'." << endl;
1768                         handle_ert(os, s, context);
1769                 }
1770
1771                 else if (t.cat() == catLetter) {
1772                         context.check_layout(os);
1773                         // Workaround for bug 4752.
1774                         // FIXME: This whole code block needs to be removed
1775                         //        when the bug is fixed and tex2lyx produces
1776                         //        the updated file format.
1777                         // The replacement algorithm in LyX is so stupid that
1778                         // it even translates a phrase if it is part of a word.
1779                         bool handled = false;
1780                         for (int const * l = known_phrase_lengths; *l; ++l) {
1781                                 string phrase = t.cs();
1782                                 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1783                                         phrase += p.get_token().cs();
1784                                 if (is_known(phrase, known_coded_phrases)) {
1785                                         handle_ert(os, phrase, context);
1786                                         handled = true;
1787                                         break;
1788                                 } else {
1789                                         for (size_t i = 1; i < phrase.length(); ++i)
1790                                                 p.putback();
1791                                 }
1792                         }
1793                         if (!handled)
1794                                 os << t.cs();
1795                 }
1796
1797                 else if (t.cat() == catOther ||
1798                                t.cat() == catAlign ||
1799                                t.cat() == catParameter) {
1800                         // This translates "&" to "\\&" which may be wrong...
1801                         context.check_layout(os);
1802                         os << t.cs();
1803                 }
1804
1805                 else if (p.isParagraph()) {
1806                         if (context.new_layout_allowed)
1807                                 context.new_paragraph(os);
1808                         else
1809                                 handle_ert(os, "\\par ", context);
1810                         eat_whitespace(p, os, context, true);
1811                 }
1812
1813                 else if (t.cat() == catActive) {
1814                         context.check_layout(os);
1815                         if (t.character() == '~') {
1816                                 if (context.layout->free_spacing)
1817                                         os << ' ';
1818                                 else {
1819                                         begin_inset(os, "space ~\n");
1820                                         end_inset(os);
1821                                 }
1822                         } else
1823                                 os << t.cs();
1824                 }
1825
1826                 else if (t.cat() == catBegin &&
1827                          p.next_token().cat() == catEnd) {
1828                         // {}
1829                         Token const prev = p.prev_token();
1830                         p.get_token();
1831                         if (p.next_token().character() == '`' ||
1832                             (prev.character() == '-' &&
1833                              p.next_token().character() == '-'))
1834                                 ; // ignore it in {}`` or -{}-
1835                         else
1836                                 handle_ert(os, "{}", context);
1837
1838                 }
1839
1840                 else if (t.cat() == catBegin) {
1841                         context.check_layout(os);
1842                         // special handling of font attribute changes
1843                         Token const prev = p.prev_token();
1844                         Token const next = p.next_token();
1845                         TeXFont const oldFont = context.font;
1846                         if (next.character() == '[' ||
1847                             next.character() == ']' ||
1848                             next.character() == '*') {
1849                                 p.get_token();
1850                                 if (p.next_token().cat() == catEnd) {
1851                                         os << next.cs();
1852                                         p.get_token();
1853                                 } else {
1854                                         p.putback();
1855                                         handle_ert(os, "{", context);
1856                                         parse_text_snippet(p, os,
1857                                                         FLAG_BRACE_LAST,
1858                                                         outer, context);
1859                                         handle_ert(os, "}", context);
1860                                 }
1861                         } else if (! context.new_layout_allowed) {
1862                                 handle_ert(os, "{", context);
1863                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1864                                                    outer, context);
1865                                 handle_ert(os, "}", context);
1866                         } else if (is_known(next.cs(), known_sizes)) {
1867                                 // next will change the size, so we must
1868                                 // reset it here
1869                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1870                                                    outer, context);
1871                                 if (!context.atParagraphStart())
1872                                         os << "\n\\size "
1873                                            << context.font.size << "\n";
1874                         } else if (is_known(next.cs(), known_font_families)) {
1875                                 // next will change the font family, so we
1876                                 // must reset it here
1877                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1878                                                    outer, context);
1879                                 if (!context.atParagraphStart())
1880                                         os << "\n\\family "
1881                                            << context.font.family << "\n";
1882                         } else if (is_known(next.cs(), known_font_series)) {
1883                                 // next will change the font series, so we
1884                                 // must reset it here
1885                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1886                                                    outer, context);
1887                                 if (!context.atParagraphStart())
1888                                         os << "\n\\series "
1889                                            << context.font.series << "\n";
1890                         } else if (is_known(next.cs(), known_font_shapes)) {
1891                                 // next will change the font shape, so we
1892                                 // must reset it here
1893                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1894                                                    outer, context);
1895                                 if (!context.atParagraphStart())
1896                                         os << "\n\\shape "
1897                                            << context.font.shape << "\n";
1898                         } else if (is_known(next.cs(), known_old_font_families) ||
1899                                    is_known(next.cs(), known_old_font_series) ||
1900                                    is_known(next.cs(), known_old_font_shapes)) {
1901                                 // next will change the font family, series
1902                                 // and shape, so we must reset it here
1903                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1904                                                    outer, context);
1905                                 if (!context.atParagraphStart())
1906                                         os <<  "\n\\family "
1907                                            << context.font.family
1908                                            << "\n\\series "
1909                                            << context.font.series
1910                                            << "\n\\shape "
1911                                            << context.font.shape << "\n";
1912                         } else {
1913                                 handle_ert(os, "{", context);
1914                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1915                                                    outer, context);
1916                                 handle_ert(os, "}", context);
1917                         }
1918                 }
1919
1920                 else if (t.cat() == catEnd) {
1921                         if (flags & FLAG_BRACE_LAST) {
1922                                 return;
1923                         }
1924                         cerr << "stray '}' in text\n";
1925                         handle_ert(os, "}", context);
1926                 }
1927
1928                 else if (t.cat() == catComment)
1929                         parse_comment(p, os, t, context);
1930
1931                 //
1932                 // control sequences
1933                 //
1934
1935                 else if (t.cs() == "(") {
1936                         context.check_layout(os);
1937                         begin_inset(os, "Formula");
1938                         os << " \\(";
1939                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1940                         os << "\\)";
1941                         end_inset(os);
1942                 }
1943
1944                 else if (t.cs() == "[") {
1945                         context.check_layout(os);
1946                         begin_inset(os, "Formula");
1947                         os << " \\[";
1948                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1949                         os << "\\]";
1950                         end_inset(os);
1951                 }
1952
1953                 else if (t.cs() == "begin")
1954                         parse_environment(p, os, outer, last_env, context);
1955
1956                 else if (t.cs() == "end") {
1957                         if (flags & FLAG_END) {
1958                                 // eat environment name
1959                                 string const name = p.getArg('{', '}');
1960                                 if (name != active_environment())
1961                                         cerr << "\\end{" + name + "} does not match \\begin{"
1962                                                 + active_environment() + "}\n";
1963                                 return;
1964                         }
1965                         p.error("found 'end' unexpectedly");
1966                 }
1967
1968                 else if (t.cs() == "item") {
1969                         p.skip_spaces();
1970                         string s;
1971                         bool optarg = false;
1972                         if (p.next_token().cat() != catEscape &&
1973                             p.next_token().character() == '[') {
1974                                 p.get_token(); // eat '['
1975                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1976                                                        outer, context);
1977                                 optarg = true;
1978                         }
1979                         context.set_item();
1980                         context.check_layout(os);
1981                         if (context.has_item) {
1982                                 // An item in an unknown list-like environment
1983                                 // FIXME: Do this in check_layout()!
1984                                 context.has_item = false;
1985                                 if (optarg)
1986                                         handle_ert(os, "\\item", context);
1987                                 else
1988                                         handle_ert(os, "\\item ", context);
1989                         }
1990                         if (optarg) {
1991                                 if (context.layout->labeltype != LABEL_MANUAL) {
1992                                         // LyX does not support \item[\mybullet]
1993                                         // in itemize environments
1994                                         handle_ert(os, "[", context);
1995                                         os << s;
1996                                         handle_ert(os, "]", context);
1997                                 } else if (!s.empty()) {
1998                                         // The space is needed to separate the
1999                                         // item from the rest of the sentence.
2000                                         os << s << ' ';
2001                                         eat_whitespace(p, os, context, false);
2002                                 }
2003                         }
2004                 }
2005
2006                 else if (t.cs() == "bibitem") {
2007                         context.set_item();
2008                         context.check_layout(os);
2009                         string label = convert_command_inset_arg(p.getArg('[', ']'));
2010                         string key = convert_command_inset_arg(p.verbatim_item());
2011                         if (contains(label, '\\') || contains(key, '\\')) {
2012                                 // LyX can't handle LaTeX commands in labels or keys
2013                                 handle_ert(os, t.asInput() + '[' + label +
2014                                                "]{" + p.verbatim_item() + '}',
2015                                            context);
2016                         } else {
2017                                 begin_command_inset(os, "bibitem", "bibitem");
2018                                 os << "label \"" << label << "\"\n"
2019                                       "key \"" << key << "\"\n";
2020                                 end_inset(os);
2021                         }
2022                 }
2023
2024                 else if (is_macro(p))
2025                         parse_macro(p, os, context);
2026
2027                 else if (t.cs() == "noindent") {
2028                         p.skip_spaces();
2029                         context.add_par_extra_stuff("\\noindent\n");
2030                 }
2031
2032                 else if (t.cs() == "appendix") {
2033                         context.add_par_extra_stuff("\\start_of_appendix\n");
2034                         // We need to start a new paragraph. Otherwise the
2035                         // appendix in 'bla\appendix\chapter{' would start
2036                         // too late.
2037                         context.new_paragraph(os);
2038                         // We need to make sure that the paragraph is
2039                         // generated even if it is empty. Otherwise the
2040                         // appendix in '\par\appendix\par\chapter{' would
2041                         // start too late.
2042                         context.check_layout(os);
2043                         // FIXME: This is a hack to prevent paragraph
2044                         // deletion if it is empty. Handle this better!
2045                         handle_comment(os,
2046                                 "%dummy comment inserted by tex2lyx to "
2047                                 "ensure that this paragraph is not empty",
2048                                 context);
2049                         // Both measures above may generate an additional
2050                         // empty paragraph, but that does not hurt, because
2051                         // whitespace does not matter here.
2052                         eat_whitespace(p, os, context, true);
2053                 }
2054
2055                 // Starred section headings
2056                 // Must attempt to parse "Section*" before "Section".
2057                 else if ((p.next_token().asInput() == "*") &&
2058                          context.new_layout_allowed &&
2059                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2060                         // write the layout
2061                         p.get_token();
2062                         output_command_layout(os, p, outer, context, newlayout);
2063                         p.skip_spaces();
2064                 }
2065
2066                 // Section headings and the like
2067                 else if (context.new_layout_allowed &&
2068                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2069                         // write the layout
2070                         output_command_layout(os, p, outer, context, newlayout);
2071                         p.skip_spaces();
2072                 }
2073
2074                 else if (t.cs() == "caption") {
2075                         p.skip_spaces();
2076                         context.check_layout(os);
2077                         p.skip_spaces();
2078                         begin_inset(os, "Caption\n\n");
2079                         Context newcontext(true, context.textclass);
2080                         newcontext.font = context.font;
2081                         newcontext.check_layout(os);
2082                         if (p.next_token().cat() != catEscape &&
2083                             p.next_token().character() == '[') {
2084                                 p.get_token(); // eat '['
2085                                 begin_inset(os, "Argument\n");
2086                                 os << "status collapsed\n";
2087                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2088                                 end_inset(os);
2089                                 eat_whitespace(p, os, context, false);
2090                         }
2091                         parse_text(p, os, FLAG_ITEM, outer, context);
2092                         context.check_end_layout(os);
2093                         // We don't need really a new paragraph, but
2094                         // we must make sure that the next item gets a \begin_layout.
2095                         context.new_paragraph(os);
2096                         end_inset(os);
2097                         p.skip_spaces();
2098                         newcontext.check_end_layout(os);
2099                 }
2100
2101                 else if (t.cs() == "includegraphics") {
2102                         bool const clip = p.next_token().asInput() == "*";
2103                         if (clip)
2104                                 p.get_token();
2105                         string const arg = p.getArg('[', ']');
2106                         map<string, string> opts;
2107                         vector<string> keys;
2108                         split_map(arg, opts, keys);
2109                         if (clip)
2110                                 opts["clip"] = string();
2111                         string name = normalize_filename(p.verbatim_item());
2112
2113                         string const path = getMasterFilePath();
2114                         // We want to preserve relative / absolute filenames,
2115                         // therefore path is only used for testing
2116                         if (!makeAbsPath(name, path).exists()) {
2117                                 // The file extension is probably missing.
2118                                 // Now try to find it out.
2119                                 string const dvips_name =
2120                                         find_file(name, path,
2121                                                   known_dvips_graphics_formats);
2122                                 string const pdftex_name =
2123                                         find_file(name, path,
2124                                                   known_pdftex_graphics_formats);
2125                                 if (!dvips_name.empty()) {
2126                                         if (!pdftex_name.empty()) {
2127                                                 cerr << "This file contains the "
2128                                                         "latex snippet\n"
2129                                                         "\"\\includegraphics{"
2130                                                      << name << "}\".\n"
2131                                                         "However, files\n\""
2132                                                      << dvips_name << "\" and\n\""
2133                                                      << pdftex_name << "\"\n"
2134                                                         "both exist, so I had to make a "
2135                                                         "choice and took the first one.\n"
2136                                                         "Please move the unwanted one "
2137                                                         "someplace else and try again\n"
2138                                                         "if my choice was wrong."
2139                                                      << endl;
2140                                         }
2141                                         name = dvips_name;
2142                                 } else if (!pdftex_name.empty()) {
2143                                         name = pdftex_name;
2144                                         pdflatex = true;
2145                                 }
2146                         }
2147
2148                         if (makeAbsPath(name, path).exists())
2149                                 fix_relative_filename(name);
2150                         else
2151                                 cerr << "Warning: Could not find graphics file '"
2152                                      << name << "'." << endl;
2153
2154                         context.check_layout(os);
2155                         begin_inset(os, "Graphics ");
2156                         os << "\n\tfilename " << name << '\n';
2157                         if (opts.find("width") != opts.end())
2158                                 os << "\twidth "
2159                                    << translate_len(opts["width"]) << '\n';
2160                         if (opts.find("height") != opts.end())
2161                                 os << "\theight "
2162                                    << translate_len(opts["height"]) << '\n';
2163                         if (opts.find("scale") != opts.end()) {
2164                                 istringstream iss(opts["scale"]);
2165                                 double val;
2166                                 iss >> val;
2167                                 val = val*100;
2168                                 os << "\tscale " << val << '\n';
2169                         }
2170                         if (opts.find("angle") != opts.end()) {
2171                                 os << "\trotateAngle "
2172                                    << opts["angle"] << '\n';
2173                                 vector<string>::const_iterator a =
2174                                         find(keys.begin(), keys.end(), "angle");
2175                                 vector<string>::const_iterator s =
2176                                         find(keys.begin(), keys.end(), "width");
2177                                 if (s == keys.end())
2178                                         s = find(keys.begin(), keys.end(), "height");
2179                                 if (s == keys.end())
2180                                         s = find(keys.begin(), keys.end(), "scale");
2181                                 if (s != keys.end() && distance(s, a) > 0)
2182                                         os << "\tscaleBeforeRotation\n";
2183                         }
2184                         if (opts.find("origin") != opts.end()) {
2185                                 ostringstream ss;
2186                                 string const opt = opts["origin"];
2187                                 if (opt.find('l') != string::npos) ss << "left";
2188                                 if (opt.find('r') != string::npos) ss << "right";
2189                                 if (opt.find('c') != string::npos) ss << "center";
2190                                 if (opt.find('t') != string::npos) ss << "Top";
2191                                 if (opt.find('b') != string::npos) ss << "Bottom";
2192                                 if (opt.find('B') != string::npos) ss << "Baseline";
2193                                 if (!ss.str().empty())
2194                                         os << "\trotateOrigin " << ss.str() << '\n';
2195                                 else
2196                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2197                         }
2198                         if (opts.find("keepaspectratio") != opts.end())
2199                                 os << "\tkeepAspectRatio\n";
2200                         if (opts.find("clip") != opts.end())
2201                                 os << "\tclip\n";
2202                         if (opts.find("draft") != opts.end())
2203                                 os << "\tdraft\n";
2204                         if (opts.find("bb") != opts.end())
2205                                 os << "\tBoundingBox "
2206                                    << opts["bb"] << '\n';
2207                         int numberOfbbOptions = 0;
2208                         if (opts.find("bbllx") != opts.end())
2209                                 numberOfbbOptions++;
2210                         if (opts.find("bblly") != opts.end())
2211                                 numberOfbbOptions++;
2212                         if (opts.find("bburx") != opts.end())
2213                                 numberOfbbOptions++;
2214                         if (opts.find("bbury") != opts.end())
2215                                 numberOfbbOptions++;
2216                         if (numberOfbbOptions == 4)
2217                                 os << "\tBoundingBox "
2218                                    << opts["bbllx"] << " " << opts["bblly"] << " "
2219                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
2220                         else if (numberOfbbOptions > 0)
2221                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2222                         numberOfbbOptions = 0;
2223                         if (opts.find("natwidth") != opts.end())
2224                                 numberOfbbOptions++;
2225                         if (opts.find("natheight") != opts.end())
2226                                 numberOfbbOptions++;
2227                         if (numberOfbbOptions == 2)
2228                                 os << "\tBoundingBox 0bp 0bp "
2229                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
2230                         else if (numberOfbbOptions > 0)
2231                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2232                         ostringstream special;
2233                         if (opts.find("hiresbb") != opts.end())
2234                                 special << "hiresbb,";
2235                         if (opts.find("trim") != opts.end())
2236                                 special << "trim,";
2237                         if (opts.find("viewport") != opts.end())
2238                                 special << "viewport=" << opts["viewport"] << ',';
2239                         if (opts.find("totalheight") != opts.end())
2240                                 special << "totalheight=" << opts["totalheight"] << ',';
2241                         if (opts.find("type") != opts.end())
2242                                 special << "type=" << opts["type"] << ',';
2243                         if (opts.find("ext") != opts.end())
2244                                 special << "ext=" << opts["ext"] << ',';
2245                         if (opts.find("read") != opts.end())
2246                                 special << "read=" << opts["read"] << ',';
2247                         if (opts.find("command") != opts.end())
2248                                 special << "command=" << opts["command"] << ',';
2249                         string s_special = special.str();
2250                         if (!s_special.empty()) {
2251                                 // We had special arguments. Remove the trailing ','.
2252                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2253                         }
2254                         // TODO: Handle the unknown settings better.
2255                         // Warn about invalid options.
2256                         // Check whether some option was given twice.
2257                         end_inset(os);
2258                 }
2259
2260                 else if (t.cs() == "footnote" ||
2261                          (t.cs() == "thanks" && context.layout->intitle)) {
2262                         p.skip_spaces();
2263                         context.check_layout(os);
2264                         begin_inset(os, "Foot\n");
2265                         os << "status collapsed\n\n";
2266                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2267                         end_inset(os);
2268                 }
2269
2270                 else if (t.cs() == "marginpar") {
2271                         p.skip_spaces();
2272                         context.check_layout(os);
2273                         begin_inset(os, "Marginal\n");
2274                         os << "status collapsed\n\n";
2275                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2276                         end_inset(os);
2277                 }
2278
2279                 else if (t.cs() == "ensuremath") {
2280                         p.skip_spaces();
2281                         context.check_layout(os);
2282                         string const s = p.verbatim_item();
2283                         //FIXME: this never triggers in UTF8
2284                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2285                                 os << s;
2286                         else
2287                                 handle_ert(os, "\\ensuremath{" + s + "}",
2288                                            context);
2289                 }
2290
2291                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2292                         // FIXME: Somehow prevent title layouts if
2293                         // "maketitle" was not found
2294                         // swallow this
2295                         skip_spaces_braces(p);
2296                 }
2297
2298                 else if (t.cs() == "tableofcontents") {
2299                         context.check_layout(os);
2300                         begin_command_inset(os, "toc", "tableofcontents");
2301                         end_inset(os);
2302                         skip_spaces_braces(p);
2303                 }
2304
2305                 else if (t.cs() == "listoffigures") {
2306                         context.check_layout(os);
2307                         begin_inset(os, "FloatList figure\n");
2308                         end_inset(os);
2309                         skip_spaces_braces(p);
2310                 }
2311
2312                 else if (t.cs() == "listoftables") {
2313                         context.check_layout(os);
2314                         begin_inset(os, "FloatList table\n");
2315                         end_inset(os);
2316                         skip_spaces_braces(p);
2317                 }
2318
2319                 else if (t.cs() == "listof") {
2320                         p.skip_spaces(true);
2321                         string const name = p.get_token().cs();
2322                         if (context.textclass.floats().typeExist(name)) {
2323                                 context.check_layout(os);
2324                                 begin_inset(os, "FloatList ");
2325                                 os << name << "\n";
2326                                 end_inset(os);
2327                                 p.get_token(); // swallow second arg
2328                         } else
2329                                 handle_ert(os, "\\listof{" + name + "}", context);
2330                 }
2331
2332                 else if (t.cs() == "textrm")
2333                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2334                                               context, "\\family",
2335                                               context.font.family, "roman");
2336
2337                 else if (t.cs() == "textsf")
2338                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2339                                               context, "\\family",
2340                                               context.font.family, "sans");
2341
2342                 else if (t.cs() == "texttt")
2343                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2344                                               context, "\\family",
2345                                               context.font.family, "typewriter");
2346
2347                 else if (t.cs() == "textmd")
2348                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2349                                               context, "\\series",
2350                                               context.font.series, "medium");
2351
2352                 else if (t.cs() == "textbf")
2353                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2354                                               context, "\\series",
2355                                               context.font.series, "bold");
2356
2357                 else if (t.cs() == "textup")
2358                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2359                                               context, "\\shape",
2360                                               context.font.shape, "up");
2361
2362                 else if (t.cs() == "textit")
2363                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2364                                               context, "\\shape",
2365                                               context.font.shape, "italic");
2366
2367                 else if (t.cs() == "textsl")
2368                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2369                                               context, "\\shape",
2370                                               context.font.shape, "slanted");
2371
2372                 else if (t.cs() == "textsc")
2373                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2374                                               context, "\\shape",
2375                                               context.font.shape, "smallcaps");
2376
2377                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2378                         context.check_layout(os);
2379                         TeXFont oldFont = context.font;
2380                         context.font.init();
2381                         context.font.size = oldFont.size;
2382                         os << "\n\\family " << context.font.family << "\n";
2383                         os << "\n\\series " << context.font.series << "\n";
2384                         os << "\n\\shape " << context.font.shape << "\n";
2385                         if (t.cs() == "textnormal") {
2386                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2387                                 output_font_change(os, context.font, oldFont);
2388                                 context.font = oldFont;
2389                         } else
2390                                 eat_whitespace(p, os, context, false);
2391                 }
2392
2393                 else if (t.cs() == "textcolor") {
2394                         // scheme is \textcolor{color name}{text}
2395                         string const color = p.verbatim_item();
2396                         // we only support the predefined colors of the color package
2397                         if (color == "black" || color == "blue" || color == "cyan"
2398                                 || color == "green" || color == "magenta" || color == "red"
2399                                 || color == "white" || color == "yellow") {
2400                                         context.check_layout(os);
2401                                         os << "\n\\color " << color << "\n";
2402                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2403                                         context.check_layout(os);
2404                                         os << "\n\\color inherit\n";
2405                         } else
2406                                 // for custom defined colors
2407                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
2408                 }
2409
2410                 else if (t.cs() == "underbar" || t.cs() == "uline") {
2411                         // \underbar is not 100% correct (LyX outputs \uline
2412                         // of ulem.sty). The difference is that \ulem allows
2413                         // line breaks, and \underbar does not.
2414                         // Do NOT handle \underline.
2415                         // \underbar cuts through y, g, q, p etc.,
2416                         // \underline does not.
2417                         context.check_layout(os);
2418                         os << "\n\\bar under\n";
2419                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2420                         context.check_layout(os);
2421                         os << "\n\\bar default\n";
2422                 }
2423
2424                 else if (t.cs() == "emph" || t.cs() == "noun") {
2425                         context.check_layout(os);
2426                         os << "\n\\" << t.cs() << " on\n";
2427                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2428                         context.check_layout(os);
2429                         os << "\n\\" << t.cs() << " default\n";
2430                 }
2431
2432                 else if (t.cs() == "lyxline") {
2433                         // swallow size argument (it is not used anyway)
2434                         p.getArg('{', '}');
2435                         if (!context.atParagraphStart()) {
2436                                 // so our line is in the middle of a paragraph
2437                                 // we need to add a new line, lest this line
2438                                 // follow the other content on that line and
2439                                 // run off the side of the page
2440                                 // FIXME: This may create an empty paragraph,
2441                                 //        but without that it would not be
2442                                 //        possible to set noindent below.
2443                                 //        Fortunately LaTeX does not care
2444                                 //        about the empty paragraph.
2445                                 context.new_paragraph(os);
2446                         }
2447                         if (h_paragraph_separation == "indent") {
2448                                 // we need to unindent, lest the line be too long
2449                                 context.add_par_extra_stuff("\\noindent\n");
2450                         }
2451                         context.check_layout(os);
2452                         begin_command_inset(os, "line", "rule");
2453                         os << "offset \"0.5ex\"\n"
2454                               "width \"100line%\"\n"
2455                               "height \"1pt\"\n";
2456                         end_inset(os);
2457                 }
2458
2459                 else if (is_known(t.cs(), known_phrases) ||
2460                          (t.cs() == "protect" &&
2461                           p.next_token().cat() == catEscape &&
2462                           is_known(p.next_token().cs(), known_phrases))) {
2463                         // LyX sometimes puts a \protect in front, so we have to ignore it
2464                         // FIXME: This needs to be changed when bug 4752 is fixed.
2465                         char const * const * where = is_known(
2466                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2467                                 known_phrases);
2468                         context.check_layout(os);
2469                         os << known_coded_phrases[where - known_phrases];
2470                         skip_spaces_braces(p);
2471                 }
2472
2473                 else if (is_known(t.cs(), known_ref_commands)) {
2474                         string const opt = p.getOpt();
2475                         if (opt.empty()) {
2476                                 context.check_layout(os);
2477                                 char const * const * where = is_known(t.cs(),
2478                                         known_ref_commands);
2479                                 begin_command_inset(os, "ref",
2480                                         known_coded_ref_commands[where - known_ref_commands]);
2481                                 os << "reference \""
2482                                    << convert_command_inset_arg(p.verbatim_item())
2483                                    << "\"\n";
2484                                 end_inset(os);
2485                         } else {
2486                                 // LyX does not support optional arguments of ref commands
2487                                 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2488                                                p.verbatim_item() + "}", context);
2489                         }
2490                 }
2491
2492                 else if (use_natbib &&
2493                          is_known(t.cs(), known_natbib_commands) &&
2494                          ((t.cs() != "citefullauthor" &&
2495                            t.cs() != "citeyear" &&
2496                            t.cs() != "citeyearpar") ||
2497                           p.next_token().asInput() != "*")) {
2498                         context.check_layout(os);
2499                         string command = t.cs();
2500                         if (p.next_token().asInput() == "*") {
2501                                 command += '*';
2502                                 p.get_token();
2503                         }
2504                         if (command == "citefullauthor")
2505                                 // alternative name for "\\citeauthor*"
2506                                 command = "citeauthor*";
2507
2508                         // text before the citation
2509                         string before;
2510                         // text after the citation
2511                         string after;
2512                         get_cite_arguments(p, true, before, after);
2513
2514                         if (command == "cite") {
2515                                 // \cite without optional argument means
2516                                 // \citet, \cite with at least one optional
2517                                 // argument means \citep.
2518                                 if (before.empty() && after.empty())
2519                                         command = "citet";
2520                                 else
2521                                         command = "citep";
2522                         }
2523                         if (before.empty() && after == "[]")
2524                                 // avoid \citet[]{a}
2525                                 after.erase();
2526                         else if (before == "[]" && after == "[]") {
2527                                 // avoid \citet[][]{a}
2528                                 before.erase();
2529                                 after.erase();
2530                         }
2531                         // remove the brackets around after and before
2532                         if (!after.empty()) {
2533                                 after.erase(0, 1);
2534                                 after.erase(after.length() - 1, 1);
2535                                 after = convert_command_inset_arg(after);
2536                         }
2537                         if (!before.empty()) {
2538                                 before.erase(0, 1);
2539                                 before.erase(before.length() - 1, 1);
2540                                 before = convert_command_inset_arg(before);
2541                         }
2542                         begin_command_inset(os, "citation", command);
2543                         os << "after " << '"' << after << '"' << "\n";
2544                         os << "before " << '"' << before << '"' << "\n";
2545                         os << "key \""
2546                            << convert_command_inset_arg(p.verbatim_item())
2547                            << "\"\n";
2548                         end_inset(os);
2549                 }
2550
2551                 else if (use_jurabib &&
2552                          is_known(t.cs(), known_jurabib_commands) &&
2553                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2554                         context.check_layout(os);
2555                         string command = t.cs();
2556                         if (p.next_token().asInput() == "*") {
2557                                 command += '*';
2558                                 p.get_token();
2559                         }
2560                         char argumentOrder = '\0';
2561                         vector<string> const & options = used_packages["jurabib"];
2562                         if (find(options.begin(), options.end(),
2563                                       "natbiborder") != options.end())
2564                                 argumentOrder = 'n';
2565                         else if (find(options.begin(), options.end(),
2566                                            "jurabiborder") != options.end())
2567                                 argumentOrder = 'j';
2568
2569                         // text before the citation
2570                         string before;
2571                         // text after the citation
2572                         string after;
2573                         get_cite_arguments(p, argumentOrder != 'j', before, after);
2574
2575                         string const citation = p.verbatim_item();
2576                         if (!before.empty() && argumentOrder == '\0') {
2577                                 cerr << "Warning: Assuming argument order "
2578                                         "of jurabib version 0.6 for\n'"
2579                                      << command << before << after << '{'
2580                                      << citation << "}'.\n"
2581                                         "Add 'jurabiborder' to the jurabib "
2582                                         "package options if you used an\n"
2583                                         "earlier jurabib version." << endl;
2584                         }
2585                         if (!after.empty()) {
2586                                 after.erase(0, 1);
2587                                 after.erase(after.length() - 1, 1);
2588                         }
2589                         if (!before.empty()) {
2590                                 before.erase(0, 1);
2591                                 before.erase(before.length() - 1, 1);
2592                         }
2593                         begin_command_inset(os, "citation", command);
2594                         os << "after " << '"' << after << '"' << "\n";
2595                         os << "before " << '"' << before << '"' << "\n";
2596                         os << "key " << '"' << citation << '"' << "\n";
2597                         end_inset(os);
2598                 }
2599
2600                 else if (t.cs() == "cite"
2601                         || t.cs() == "nocite") {
2602                         context.check_layout(os);
2603                         string after = convert_command_inset_arg(p.getArg('[', ']'));
2604                         string key = convert_command_inset_arg(p.verbatim_item());
2605                         // store the case that it is "\nocite{*}" to use it later for
2606                         // the BibTeX inset
2607                         if (key != "*") {
2608                                 begin_command_inset(os, "citation", t.cs());
2609                                 os << "after " << '"' << after << '"' << "\n";
2610                                 os << "key " << '"' << key << '"' << "\n";
2611                                 end_inset(os);
2612                         } else if (t.cs() == "nocite")
2613                                 btprint = key;
2614                 }
2615
2616                 else if (t.cs() == "index") {
2617                         context.check_layout(os);
2618                         begin_inset(os, "Index idx\n");
2619                         os << "status collapsed\n";
2620                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2621                         end_inset(os);
2622                 }
2623
2624                 else if (t.cs() == "nomenclature") {
2625                         context.check_layout(os);
2626                         begin_command_inset(os, "nomenclature", "nomenclature");
2627                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2628                         if (!prefix.empty())
2629                                 os << "prefix " << '"' << prefix << '"' << "\n";
2630                         os << "symbol " << '"'
2631                            << convert_command_inset_arg(p.verbatim_item());
2632                         os << "\"\ndescription \""
2633                            << convert_command_inset_arg(p.verbatim_item())
2634                            << "\"\n";
2635                         end_inset(os);
2636                 }
2637                 
2638                 else if (t.cs() == "label") {
2639                         context.check_layout(os);
2640                         begin_command_inset(os, "label", "label");
2641                         os << "name \""
2642                            << convert_command_inset_arg(p.verbatim_item())
2643                            << "\"\n";
2644                         end_inset(os);
2645                 }
2646
2647                 else if (t.cs() == "printindex") {
2648                         context.check_layout(os);
2649                         begin_command_inset(os, "index_print", "printindex");
2650                         os << "type \"idx\"\n";
2651                         end_inset(os);
2652                         skip_spaces_braces(p);
2653                 }
2654
2655                 else if (t.cs() == "printnomenclature") {
2656                         context.check_layout(os);
2657                         begin_command_inset(os, "nomencl_print", "printnomenclature");
2658                         end_inset(os);
2659                         skip_spaces_braces(p);
2660                 }
2661
2662                 else if (LYX_FORMAT >= 408 &&
2663                          (t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2664                         context.check_layout(os);
2665                         begin_inset(os, "script ");
2666                         os << t.cs().substr(4) << '\n';
2667                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2668                         end_inset(os);
2669                 }
2670
2671                 else if (is_known(t.cs(), known_quotes)) {
2672                         char const * const * where = is_known(t.cs(), known_quotes);
2673                         context.check_layout(os);
2674                         begin_inset(os, "Quotes ");
2675                         os << known_coded_quotes[where - known_quotes];
2676                         end_inset(os);
2677                         // LyX adds {} after the quote, so we have to eat
2678                         // spaces here if there are any before a possible
2679                         // {} pair.
2680                         eat_whitespace(p, os, context, false);
2681                         skip_braces(p);
2682                 }
2683
2684                 else if (is_known(t.cs(), known_sizes) &&
2685                          context.new_layout_allowed) {
2686                         char const * const * where = is_known(t.cs(), known_sizes);
2687                         context.check_layout(os);
2688                         TeXFont const oldFont = context.font;
2689                         context.font.size = known_coded_sizes[where - known_sizes];
2690                         output_font_change(os, oldFont, context.font);
2691                         eat_whitespace(p, os, context, false);
2692                 }
2693
2694                 else if (is_known(t.cs(), known_font_families) &&
2695                          context.new_layout_allowed) {
2696                         char const * const * where =
2697                                 is_known(t.cs(), known_font_families);
2698                         context.check_layout(os);
2699                         TeXFont const oldFont = context.font;
2700                         context.font.family =
2701                                 known_coded_font_families[where - known_font_families];
2702                         output_font_change(os, oldFont, context.font);
2703                         eat_whitespace(p, os, context, false);
2704                 }
2705
2706                 else if (is_known(t.cs(), known_font_series) &&
2707                          context.new_layout_allowed) {
2708                         char const * const * where =
2709                                 is_known(t.cs(), known_font_series);
2710                         context.check_layout(os);
2711                         TeXFont const oldFont = context.font;
2712                         context.font.series =
2713                                 known_coded_font_series[where - known_font_series];
2714                         output_font_change(os, oldFont, context.font);
2715                         eat_whitespace(p, os, context, false);
2716                 }
2717
2718                 else if (is_known(t.cs(), known_font_shapes) &&
2719                          context.new_layout_allowed) {
2720                         char const * const * where =
2721                                 is_known(t.cs(), known_font_shapes);
2722                         context.check_layout(os);
2723                         TeXFont const oldFont = context.font;
2724                         context.font.shape =
2725                                 known_coded_font_shapes[where - known_font_shapes];
2726                         output_font_change(os, oldFont, context.font);
2727                         eat_whitespace(p, os, context, false);
2728                 }
2729                 else if (is_known(t.cs(), known_old_font_families) &&
2730                          context.new_layout_allowed) {
2731                         char const * const * where =
2732                                 is_known(t.cs(), known_old_font_families);
2733                         context.check_layout(os);
2734                         TeXFont const oldFont = context.font;
2735                         context.font.init();
2736                         context.font.size = oldFont.size;
2737                         context.font.family =
2738                                 known_coded_font_families[where - known_old_font_families];
2739                         output_font_change(os, oldFont, context.font);
2740                         eat_whitespace(p, os, context, false);
2741                 }
2742
2743                 else if (is_known(t.cs(), known_old_font_series) &&
2744                          context.new_layout_allowed) {
2745                         char const * const * where =
2746                                 is_known(t.cs(), known_old_font_series);
2747                         context.check_layout(os);
2748                         TeXFont const oldFont = context.font;
2749                         context.font.init();
2750                         context.font.size = oldFont.size;
2751                         context.font.series =
2752                                 known_coded_font_series[where - known_old_font_series];
2753                         output_font_change(os, oldFont, context.font);
2754                         eat_whitespace(p, os, context, false);
2755                 }
2756
2757                 else if (is_known(t.cs(), known_old_font_shapes) &&
2758                          context.new_layout_allowed) {
2759                         char const * const * where =
2760                                 is_known(t.cs(), known_old_font_shapes);
2761                         context.check_layout(os);
2762                         TeXFont const oldFont = context.font;
2763                         context.font.init();
2764                         context.font.size = oldFont.size;
2765                         context.font.shape =
2766                                 known_coded_font_shapes[where - known_old_font_shapes];
2767                         output_font_change(os, oldFont, context.font);
2768                         eat_whitespace(p, os, context, false);
2769                 }
2770
2771                 else if (t.cs() == "selectlanguage") {
2772                         context.check_layout(os);
2773                         // save the language for the case that a
2774                         // \foreignlanguage is used 
2775
2776                         context.font.language = babel2lyx(p.verbatim_item());
2777                         os << "\n\\lang " << context.font.language << "\n";
2778                 }
2779
2780                 else if (t.cs() == "foreignlanguage") {
2781                         string const lang = babel2lyx(p.verbatim_item());
2782                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2783                                               context, "\\lang",
2784                                               context.font.language, lang);
2785                 }
2786
2787                 else if (t.cs() == "inputencoding") {
2788                         // nothing to write here
2789                         string const enc = subst(p.verbatim_item(), "\n", " ");
2790                         p.setEncoding(enc);
2791                 }
2792
2793                 else if (t.cs() == "ldots") {
2794                         context.check_layout(os);
2795                         os << "\\SpecialChar \\ldots{}\n";
2796                         skip_spaces_braces(p);
2797                 }
2798
2799                 else if (t.cs() == "lyxarrow") {
2800                         context.check_layout(os);
2801                         os << "\\SpecialChar \\menuseparator\n";
2802                         skip_spaces_braces(p);
2803                 }
2804
2805                 else if (t.cs() == "textcompwordmark") {
2806                         context.check_layout(os);
2807                         os << "\\SpecialChar \\textcompwordmark{}\n";
2808                         skip_spaces_braces(p);
2809                 }
2810
2811                 else if (t.cs() == "slash") {
2812                         context.check_layout(os);
2813                         os << "\\SpecialChar \\slash{}\n";
2814                         skip_spaces_braces(p);
2815                 }
2816
2817                 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2818                         context.check_layout(os);
2819                         os << "\\SpecialChar \\nobreakdash-\n";
2820                         p.get_token();
2821                 }
2822
2823                 else if (t.cs() == "textquotedbl") {
2824                         context.check_layout(os);
2825                         os << "\"";
2826                         skip_braces(p);
2827                 }
2828
2829                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2830                         context.check_layout(os);
2831                         os << "\\SpecialChar \\@.\n";
2832                         p.get_token();
2833                 }
2834
2835                 else if (t.cs() == "-") {
2836                         context.check_layout(os);
2837                         os << "\\SpecialChar \\-\n";
2838                 }
2839
2840                 else if (t.cs() == "textasciitilde") {
2841                         context.check_layout(os);
2842                         os << '~';
2843                         skip_spaces_braces(p);
2844                 }
2845
2846                 else if (t.cs() == "textasciicircum") {
2847                         context.check_layout(os);
2848                         os << '^';
2849                         skip_spaces_braces(p);
2850                 }
2851
2852                 else if (t.cs() == "textbackslash") {
2853                         context.check_layout(os);
2854                         os << "\n\\backslash\n";
2855                         skip_spaces_braces(p);
2856                 }
2857
2858                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2859                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2860                             || t.cs() == "%") {
2861                         context.check_layout(os);
2862                         os << t.cs();
2863                 }
2864
2865                 else if (t.cs() == "char") {
2866                         context.check_layout(os);
2867                         if (p.next_token().character() == '`') {
2868                                 p.get_token();
2869                                 if (p.next_token().cs() == "\"") {
2870                                         p.get_token();
2871                                         os << '"';
2872                                         skip_braces(p);
2873                                 } else {
2874                                         handle_ert(os, "\\char`", context);
2875                                 }
2876                         } else {
2877                                 handle_ert(os, "\\char", context);
2878                         }
2879                 }
2880
2881                 else if (t.cs() == "verb") {
2882                         context.check_layout(os);
2883                         char const delimiter = p.next_token().character();
2884                         string const arg = p.getArg(delimiter, delimiter);
2885                         ostringstream oss;
2886                         oss << "\\verb" << delimiter << arg << delimiter;
2887                         handle_ert(os, oss.str(), context);
2888                 }
2889
2890                 // Problem: \= creates a tabstop inside the tabbing environment
2891                 // and else an accent. In the latter case we really would want
2892                 // \={o} instead of \= o.
2893                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2894                         handle_ert(os, t.asInput(), context);
2895
2896                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2897                 else if (t.cs().size() == 1 
2898                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2899                         context.check_layout(os);
2900                         // try to see whether the string is in unicodesymbols
2901                         docstring rem;
2902                         string command = t.asInput() + "{" 
2903                                 + trimSpaceAndEol(p.verbatim_item())
2904                                 + "}";
2905                         docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2906                         if (!s.empty()) {
2907                                 if (!rem.empty())
2908                                         cerr << "When parsing " << command 
2909                                              << ", result is " << to_utf8(s)
2910                                              << "+" << to_utf8(rem) << endl;
2911                                 os << to_utf8(s);
2912                         } else
2913                                 // we did not find a non-ert version
2914                                 handle_ert(os, command, context);
2915                 }
2916
2917                 else if (t.cs() == "\\") {
2918                         context.check_layout(os);
2919                         if (p.hasOpt())
2920                                 handle_ert(os, "\\\\" + p.getOpt(), context);
2921                         else if (p.next_token().asInput() == "*") {
2922                                 p.get_token();
2923                                 // getOpt() eats the following space if there
2924                                 // is no optional argument, but that is OK
2925                                 // here since it has no effect in the output.
2926                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
2927                         }
2928                         else {
2929                                 begin_inset(os, "Newline newline");
2930                                 end_inset(os);
2931                         }
2932                 }
2933
2934                 else if (t.cs() == "newline" ||
2935                          (t.cs() == "linebreak" && !p.hasOpt())) {
2936                         context.check_layout(os);
2937                         begin_inset(os, "Newline ");
2938                         os << t.cs();
2939                         end_inset(os);
2940                         skip_spaces_braces(p);
2941                 }
2942
2943                 else if (t.cs() == "input" || t.cs() == "include"
2944                          || t.cs() == "verbatiminput") {
2945                         string name = t.cs();
2946                         if (t.cs() == "verbatiminput"
2947                             && p.next_token().asInput() == "*")
2948                                 name += p.get_token().asInput();
2949                         context.check_layout(os);
2950                         string filename(normalize_filename(p.getArg('{', '}')));
2951                         string const path = getMasterFilePath();
2952                         // We want to preserve relative / absolute filenames,
2953                         // therefore path is only used for testing
2954                         if ((t.cs() == "include" || t.cs() == "input") &&
2955                             !makeAbsPath(filename, path).exists()) {
2956                                 // The file extension is probably missing.
2957                                 // Now try to find it out.
2958                                 string const tex_name =
2959                                         find_file(filename, path,
2960                                                   known_tex_extensions);
2961                                 if (!tex_name.empty())
2962                                         filename = tex_name;
2963                         }
2964                         bool external = false;
2965                         string outname;
2966                         if (makeAbsPath(filename, path).exists()) {
2967                                 string const abstexname =
2968                                         makeAbsPath(filename, path).absFileName();
2969                                 string const abslyxname =
2970                                         changeExtension(abstexname, ".lyx");
2971                                 string const absfigname =
2972                                         changeExtension(abstexname, ".fig");
2973                                 fix_relative_filename(filename);
2974                                 string const lyxname =
2975                                         changeExtension(filename, ".lyx");
2976                                 bool xfig = false;
2977                                 external = FileName(absfigname).exists();
2978                                 if (t.cs() == "input") {
2979                                         string const ext = getExtension(abstexname);
2980
2981                                         // Combined PS/LaTeX:
2982                                         // x.eps, x.pstex_t (old xfig)
2983                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
2984                                         FileName const absepsname(
2985                                                 changeExtension(abstexname, ".eps"));
2986                                         FileName const abspstexname(
2987                                                 changeExtension(abstexname, ".pstex"));
2988                                         bool const xfigeps =
2989                                                 (absepsname.exists() ||
2990                                                  abspstexname.exists()) &&
2991                                                 ext == "pstex_t";
2992
2993                                         // Combined PDF/LaTeX:
2994                                         // x.pdf, x.pdftex_t (old xfig)
2995                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
2996                                         FileName const abspdfname(
2997                                                 changeExtension(abstexname, ".pdf"));
2998                                         bool const xfigpdf =
2999                                                 abspdfname.exists() &&
3000                                                 (ext == "pdftex_t" || ext == "pdf_t");
3001                                         if (xfigpdf)
3002                                                 pdflatex = true;
3003
3004                                         // Combined PS/PDF/LaTeX:
3005                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3006                                         string const absbase2(
3007                                                 removeExtension(abstexname) + "_pspdftex");
3008                                         FileName const abseps2name(
3009                                                 addExtension(absbase2, ".eps"));
3010                                         FileName const abspdf2name(
3011                                                 addExtension(absbase2, ".pdf"));
3012                                         bool const xfigboth =
3013                                                 abspdf2name.exists() &&
3014                                                 abseps2name.exists() && ext == "pspdftex";
3015
3016                                         xfig = xfigpdf || xfigeps || xfigboth;
3017                                         external = external && xfig;
3018                                 }
3019                                 if (external) {
3020                                         outname = changeExtension(filename, ".fig");
3021                                 } else if (xfig) {
3022                                         // Don't try to convert, the result
3023                                         // would be full of ERT.
3024                                         outname = filename;
3025                                 } else if (t.cs() != "verbatiminput" &&
3026                                     tex2lyx(abstexname, FileName(abslyxname),
3027                                             p.getEncoding())) {
3028                                         outname = lyxname;
3029                                 } else {
3030                                         outname = filename;
3031                                 }
3032                         } else {
3033                                 cerr << "Warning: Could not find included file '"
3034                                      << filename << "'." << endl;
3035                                 outname = filename;
3036                         }
3037                         if (external) {
3038                                 begin_inset(os, "External\n");
3039                                 os << "\ttemplate XFig\n"
3040                                    << "\tfilename " << outname << '\n';
3041                         } else {
3042                                 begin_command_inset(os, "include", name);
3043                                 os << "preview false\n"
3044                                       "filename \"" << outname << "\"\n";
3045                         }
3046                         end_inset(os);
3047                 }
3048
3049                 else if (t.cs() == "bibliographystyle") {
3050                         // store new bibliographystyle
3051                         bibliographystyle = p.verbatim_item();
3052                         // If any other command than \bibliography and
3053                         // \nocite{*} follows, we need to output the style
3054                         // (because it might be used by that command).
3055                         // Otherwise, it will automatically be output by LyX.
3056                         p.pushPosition();
3057                         bool output = true;
3058                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3059                                 if (t2.cat() == catBegin)
3060                                         break;
3061                                 if (t2.cat() != catEscape)
3062                                         continue;
3063                                 if (t2.cs() == "nocite") {
3064                                         if (p.getArg('{', '}') == "*")
3065                                                 continue;
3066                                 } else if (t2.cs() == "bibliography")
3067                                         output = false;
3068                                 break;
3069                         }
3070                         p.popPosition();
3071                         if (output) {
3072                                 handle_ert(os,
3073                                         "\\bibliographystyle{" + bibliographystyle + '}',
3074                                         context);
3075                         }
3076                 }
3077
3078                 else if (t.cs() == "bibliography") {
3079                         context.check_layout(os);
3080                         begin_command_inset(os, "bibtex", "bibtex");
3081                         if (!btprint.empty()) {
3082                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3083                                 // clear the string because the next BibTeX inset can be without the
3084                                 // \nocite{*} option
3085                                 btprint.clear();
3086                         }
3087                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3088                         // Do we have a bibliographystyle set?
3089                         if (!bibliographystyle.empty())
3090                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
3091                         end_inset(os);
3092                 }
3093
3094                 else if (t.cs() == "parbox")
3095                         parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3096
3097                 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3098                          t.cs() == "shadowbox" || t.cs() == "doublebox")
3099                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3100
3101                 else if (t.cs() == "framebox") {
3102                         string special = p.getFullOpt();
3103                         special += p.getOpt();
3104                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3105                 }
3106
3107                 //\makebox() is part of the picture environment and different from \makebox{}
3108                 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3109                 else if (t.cs() == "makebox") {
3110                         string arg = t.asInput();
3111                         if (p.next_token().character() == '(')
3112                                 //the syntax is: \makebox(x,y)[position]{content}
3113                                 arg += p.getFullParentheseArg();
3114                         else
3115                                 //the syntax is: \makebox[width][position]{content}
3116                                 arg += p.getFullOpt();
3117                         handle_ert(os, arg + p.getFullOpt(), context);
3118                 }
3119
3120                 else if (t.cs() == "smallskip" ||
3121                          t.cs() == "medskip" ||
3122                          t.cs() == "bigskip" ||
3123                          t.cs() == "vfill") {
3124                         context.check_layout(os);
3125                         begin_inset(os, "VSpace ");
3126                         os << t.cs();
3127                         end_inset(os);
3128                         skip_spaces_braces(p);
3129                 }
3130
3131                 else if (is_known(t.cs(), known_spaces)) {
3132                         char const * const * where = is_known(t.cs(), known_spaces);
3133                         context.check_layout(os);
3134                         begin_inset(os, "space ");
3135                         os << '\\' << known_coded_spaces[where - known_spaces]
3136                            << '\n';
3137                         end_inset(os);
3138                         // LaTeX swallows whitespace after all spaces except
3139                         // "\\,". We have to do that here, too, because LyX
3140                         // adds "{}" which would make the spaces significant.
3141                         if (t.cs() !=  ",")
3142                                 eat_whitespace(p, os, context, false);
3143                         // LyX adds "{}" after all spaces except "\\ " and
3144                         // "\\,", so we have to remove "{}".
3145                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
3146                         // remove the braces after "\\,", too.
3147                         if (t.cs() != " ")
3148                                 skip_braces(p);
3149                 }
3150
3151                 else if (t.cs() == "newpage" ||
3152                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
3153                          t.cs() == "clearpage" ||
3154                          t.cs() == "cleardoublepage") {
3155                         context.check_layout(os);
3156                         begin_inset(os, "Newpage ");
3157                         os << t.cs();
3158                         end_inset(os);
3159                         skip_spaces_braces(p);
3160                 }
3161
3162                 else if (t.cs() == "DeclareRobustCommand" ||
3163                          t.cs() == "DeclareRobustCommandx" ||
3164                          t.cs() == "newcommand" ||
3165                          t.cs() == "newcommandx" ||
3166                          t.cs() == "providecommand" ||
3167                          t.cs() == "providecommandx" ||
3168                          t.cs() == "renewcommand" ||
3169                          t.cs() == "renewcommandx") {
3170                         // DeclareRobustCommand, DeclareRobustCommandx,
3171                         // providecommand and providecommandx could be handled
3172                         // by parse_command(), but we need to call
3173                         // add_known_command() here.
3174                         string name = t.asInput();
3175                         if (p.next_token().asInput() == "*") {
3176                                 // Starred form. Eat '*'
3177                                 p.get_token();
3178                                 name += '*';
3179                         }
3180                         string const command = p.verbatim_item();
3181                         string const opt1 = p.getFullOpt();
3182                         string const opt2 = p.getFullOpt();
3183                         add_known_command(command, opt1, !opt2.empty());
3184                         string const ert = name + '{' + command + '}' +
3185                                            opt1 + opt2 +
3186                                            '{' + p.verbatim_item() + '}';
3187
3188                         if (t.cs() == "DeclareRobustCommand" ||
3189                             t.cs() == "DeclareRobustCommandx" ||
3190                             t.cs() == "providecommand" ||
3191                             t.cs() == "providecommandx" ||
3192                             name[name.length()-1] == '*')
3193                                 handle_ert(os, ert, context);
3194                         else {
3195                                 context.check_layout(os);
3196                                 begin_inset(os, "FormulaMacro");
3197                                 os << "\n" << ert;
3198                                 end_inset(os);
3199                         }
3200                 }
3201
3202                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3203                         // let could be handled by parse_command(),
3204                         // but we need to call add_known_command() here.
3205                         string ert = t.asInput();
3206                         string name;
3207                         p.skip_spaces();
3208                         if (p.next_token().cat() == catBegin) {
3209                                 name = p.verbatim_item();
3210                                 ert += '{' + name + '}';
3211                         } else {
3212                                 name = p.verbatim_item();
3213                                 ert += name;
3214                         }
3215                         string command;
3216                         p.skip_spaces();
3217                         if (p.next_token().cat() == catBegin) {
3218                                 command = p.verbatim_item();
3219                                 ert += '{' + command + '}';
3220                         } else {
3221                                 command = p.verbatim_item();
3222                                 ert += command;
3223                         }
3224                         // If command is known, make name known too, to parse
3225                         // its arguments correctly. For this reason we also
3226                         // have commands in syntax.default that are hardcoded.
3227                         CommandMap::iterator it = known_commands.find(command);
3228                         if (it != known_commands.end())
3229                                 known_commands[t.asInput()] = it->second;
3230                         handle_ert(os, ert, context);
3231                 }
3232
3233                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3234                         bool starred = false;
3235                         if (p.next_token().asInput() == "*") {
3236                                 p.get_token();
3237                                 starred = true;
3238                         }
3239                         string name = t.asInput();
3240                         string const length = p.verbatim_item();
3241                         string unit;
3242                         string valstring;
3243                         bool valid = splitLatexLength(length, valstring, unit);
3244                         bool known_hspace = false;
3245                         bool known_vspace = false;
3246                         bool known_unit = false;
3247                         double value;
3248                         if (valid) {
3249                                 istringstream iss(valstring);
3250                                 iss >> value;
3251                                 if (value == 1.0) {
3252                                         if (t.cs()[0] == 'h') {
3253                                                 if (unit == "\\fill") {
3254                                                         if (!starred) {
3255                                                                 unit = "";
3256                                                                 name = "\\hfill";
3257                                                         }
3258                                                         known_hspace = true;
3259                                                 }
3260                                         } else {
3261                                                 if (unit == "\\smallskipamount") {
3262                                                         unit = "smallskip";
3263                                                         known_vspace = true;
3264                                                 } else if (unit == "\\medskipamount") {
3265                                                         unit = "medskip";
3266                                                         known_vspace = true;
3267                                                 } else if (unit == "\\bigskipamount") {
3268                                                         unit = "bigskip";
3269                                                         known_vspace = true;
3270                                                 } else if (unit == "\\fill") {
3271                                                         unit = "vfill";
3272                                                         known_vspace = true;
3273                                                 }
3274                                         }
3275                                 }
3276                                 if (!known_hspace && !known_vspace) {
3277                                         switch (unitFromString(unit)) {
3278                                         case Length::SP:
3279                                         case Length::PT:
3280                                         case Length::BP:
3281                                         case Length::DD:
3282                                         case Length::MM:
3283                                         case Length::PC:
3284                                         case Length::CC:
3285                                         case Length::CM:
3286                                         case Length::IN:
3287                                         case Length::EX:
3288                                         case Length::EM:
3289                                         case Length::MU:
3290                                                 known_unit = true;
3291                                                 break;
3292                                         default:
3293                                                 break;
3294                                         }
3295                                 }
3296                         }
3297
3298                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3299                                 // Literal horizontal length or known variable
3300                                 context.check_layout(os);
3301                                 begin_inset(os, "space ");
3302                                 os << name;
3303                                 if (starred)
3304                                         os << '*';
3305                                 os << '{';
3306                                 if (known_hspace)
3307                                         os << unit;
3308                                 os << "}";
3309                                 if (known_unit && !known_hspace)
3310                                         os << "\n\\length "
3311                                            << translate_len(length);
3312                                 end_inset(os);
3313                         } else if (known_unit || known_vspace) {
3314                                 // Literal vertical length or known variable
3315                                 context.check_layout(os);
3316                                 begin_inset(os, "VSpace ");
3317                                 if (known_unit)
3318                                         os << value;
3319                                 os << unit;
3320                                 if (starred)
3321                                         os << '*';
3322                                 end_inset(os);
3323                         } else {
3324                                 // LyX can't handle other length variables in Inset VSpace/space
3325                                 if (starred)
3326                                         name += '*';
3327                                 if (valid) {
3328                                         if (value == 1.0)
3329                                                 handle_ert(os, name + '{' + unit + '}', context);
3330                                         else if (value == -1.0)
3331                                                 handle_ert(os, name + "{-" + unit + '}', context);
3332                                         else
3333                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
3334                                 } else
3335                                         handle_ert(os, name + '{' + length + '}', context);
3336                         }
3337                 }
3338
3339                 // The single '=' is meant here.
3340                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3341                         p.skip_spaces();
3342                         context.check_layout(os);
3343                         begin_inset(os, "Flex ");
3344                         os << to_utf8(newinsetlayout->name()) << '\n'
3345                            << "status collapsed\n";
3346                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3347                         end_inset(os);
3348                 }
3349
3350                 else {
3351                         // try to see whether the string is in unicodesymbols
3352                         // Only use text mode commands, since we are in text mode here,
3353                         // and math commands may be invalid (bug 6797)
3354                         docstring rem;
3355                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3356                                                                  rem, Encodings::TEXT_CMD);
3357                         if (!s.empty()) {
3358                                 if (!rem.empty())
3359                                         cerr << "When parsing " << t.cs() 
3360                                              << ", result is " << to_utf8(s)
3361                                              << "+" << to_utf8(rem) << endl;
3362                                 context.check_layout(os);
3363                                 os << to_utf8(s);
3364                                 skip_spaces_braces(p);
3365                         }
3366                         //cerr << "#: " << t << " mode: " << mode << endl;
3367                         // heuristic: read up to next non-nested space
3368                         /*
3369                         string s = t.asInput();
3370                         string z = p.verbatim_item();
3371                         while (p.good() && z != " " && z.size()) {
3372                                 //cerr << "read: " << z << endl;
3373                                 s += z;
3374                                 z = p.verbatim_item();
3375                         }
3376                         cerr << "found ERT: " << s << endl;
3377                         handle_ert(os, s + ' ', context);
3378                         */
3379                         else {
3380                                 string name = t.asInput();
3381                                 if (p.next_token().asInput() == "*") {
3382                                         // Starred commands like \vspace*{}
3383                                         p.get_token();  // Eat '*'
3384                                         name += '*';
3385                                 }
3386                                 if (!parse_command(name, p, os, outer, context))
3387                                         handle_ert(os, name, context);
3388                         }
3389                 }
3390
3391                 if (flags & FLAG_LEAVE) {
3392                         flags &= ~FLAG_LEAVE;
3393                         break;
3394                 }
3395         }
3396 }
3397
3398 // }])
3399
3400
3401 } // namespace lyx