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