]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
Add a preference option to specify the default length unit (cm or in).
[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         }
1088
1089         else if (unstarred_name == "sidewaysfigure"
1090                 || unstarred_name == "sidewaystable") {
1091                 eat_whitespace(p, os, parent_context, false);
1092                 parent_context.check_layout(os);
1093                 if (unstarred_name == "sidewaysfigure")
1094                         begin_inset(os, "Float figure\n");
1095                 else
1096                         begin_inset(os, "Float table\n");
1097                 os << "wide " << convert<string>(is_starred)
1098                    << "\nsideways true"
1099                    << "\nstatus open\n\n";
1100                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1101                 end_inset(os);
1102                 // We don't need really a new paragraph, but
1103                 // we must make sure that the next item gets a \begin_layout.
1104                 parent_context.new_paragraph(os);
1105                 p.skip_spaces();
1106         }
1107
1108         else if (name == "wrapfigure" || name == "wraptable") {
1109                 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1110                 eat_whitespace(p, os, parent_context, false);
1111                 parent_context.check_layout(os);
1112                 // default values
1113                 string lines = "0";
1114                 string overhang = "0col%";
1115                 // parse
1116                 if (p.hasOpt())
1117                         lines = p.getArg('[', ']');
1118                 string const placement = p.getArg('{', '}');
1119                 if (p.hasOpt())
1120                         overhang = p.getArg('[', ']');
1121                 string const width = p.getArg('{', '}');
1122                 // write
1123                 if (name == "wrapfigure")
1124                         begin_inset(os, "Wrap figure\n");
1125                 else
1126                         begin_inset(os, "Wrap table\n");
1127                 os << "lines " << lines
1128                    << "\nplacement " << placement
1129                    << "\noverhang " << lyx::translate_len(overhang)
1130                    << "\nwidth " << lyx::translate_len(width)
1131                    << "\nstatus open\n\n";
1132                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1133                 end_inset(os);
1134                 // We don't need really a new paragraph, but
1135                 // we must make sure that the next item gets a \begin_layout.
1136                 parent_context.new_paragraph(os);
1137                 p.skip_spaces();
1138         }
1139
1140         else if (name == "minipage") {
1141                 eat_whitespace(p, os, parent_context, false);
1142                 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1143                 p.skip_spaces();
1144         }
1145
1146         else if (name == "comment") {
1147                 eat_whitespace(p, os, parent_context, false);
1148                 parent_context.check_layout(os);
1149                 begin_inset(os, "Note Comment\n");
1150                 os << "status open\n";
1151                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1152                 end_inset(os);
1153                 p.skip_spaces();
1154                 skip_braces(p); // eat {} that might by set by LyX behind comments
1155         }
1156
1157         else if (name == "lyxgreyedout") {
1158                 eat_whitespace(p, os, parent_context, false);
1159                 parent_context.check_layout(os);
1160                 begin_inset(os, "Note Greyedout\n");
1161                 os << "status open\n";
1162                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1163                 end_inset(os);
1164                 p.skip_spaces();
1165         }
1166
1167         else if (name == "framed" || name == "shaded") {
1168                 eat_whitespace(p, os, parent_context, false);
1169                 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1170                 p.skip_spaces();
1171         }
1172
1173         else if (name == "lstlisting") {
1174                 eat_whitespace(p, os, parent_context, false);
1175                 // FIXME handle listings with parameters
1176                 if (p.hasOpt())
1177                         parse_unknown_environment(p, name, os, FLAG_END,
1178                                                   outer, parent_context);
1179                 else
1180                         parse_listings(p, os, parent_context);
1181                 p.skip_spaces();
1182         }
1183
1184         else if (!parent_context.new_layout_allowed)
1185                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1186                                           parent_context);
1187
1188         // Alignment and spacing settings
1189         // FIXME (bug xxxx): These settings can span multiple paragraphs and
1190         //                                       therefore are totally broken!
1191         // Note that \centering, raggedright, and raggedleft cannot be handled, as
1192         // they are commands not environments. They are furthermore switches that
1193         // can be ended by another switches, but also by commands like \footnote or
1194         // \parbox. So the only safe way is to leave them untouched.
1195         else if (name == "center" || name == "centering" ||
1196                  name == "flushleft" || name == "flushright" ||
1197                  name == "singlespace" || name == "onehalfspace" ||
1198                  name == "doublespace" || name == "spacing") {
1199                 eat_whitespace(p, os, parent_context, false);
1200                 // We must begin a new paragraph if not already done
1201                 if (! parent_context.atParagraphStart()) {
1202                         parent_context.check_end_layout(os);
1203                         parent_context.new_paragraph(os);
1204                 }
1205                 if (name == "flushleft")
1206                         parent_context.add_extra_stuff("\\align left\n");
1207                 else if (name == "flushright")
1208                         parent_context.add_extra_stuff("\\align right\n");
1209                 else if (name == "center" || name == "centering")
1210                         parent_context.add_extra_stuff("\\align center\n");
1211                 else if (name == "singlespace")
1212                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1213                 else if (name == "onehalfspace")
1214                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1215                 else if (name == "doublespace")
1216                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1217                 else if (name == "spacing")
1218                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1219                 parse_text(p, os, FLAG_END, outer, parent_context);
1220                 // Just in case the environment is empty
1221                 parent_context.extra_stuff.erase();
1222                 // We must begin a new paragraph to reset the alignment
1223                 parent_context.new_paragraph(os);
1224                 p.skip_spaces();
1225         }
1226
1227         // The single '=' is meant here.
1228         else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1229                 eat_whitespace(p, os, parent_context, false);
1230                 Context context(true, parent_context.textclass, newlayout,
1231                                 parent_context.layout, parent_context.font);
1232                 if (parent_context.deeper_paragraph) {
1233                         // We are beginning a nested environment after a
1234                         // deeper paragraph inside the outer list environment.
1235                         // Therefore we don't need to output a "begin deeper".
1236                         context.need_end_deeper = true;
1237                 }
1238                 parent_context.check_end_layout(os);
1239                 if (last_env == name) {
1240                         // we need to output a separator since LyX would export
1241                         // the two environments as one otherwise (bug 5716)
1242                         docstring const sep = from_ascii("--Separator--");
1243                         TeX2LyXDocClass const & textclass(parent_context.textclass);
1244                         if (textclass.hasLayout(sep)) {
1245                                 Context newcontext(parent_context);
1246                                 newcontext.layout = &(textclass[sep]);
1247                                 newcontext.check_layout(os);
1248                                 newcontext.check_end_layout(os);
1249                         } else {
1250                                 parent_context.check_layout(os);
1251                                 begin_inset(os, "Note Note\n");
1252                                 os << "status closed\n";
1253                                 Context newcontext(true, textclass,
1254                                                 &(textclass.defaultLayout()));
1255                                 newcontext.check_layout(os);
1256                                 newcontext.check_end_layout(os);
1257                                 end_inset(os);
1258                                 parent_context.check_end_layout(os);
1259                         }
1260                 }
1261                 switch (context.layout->latextype) {
1262                 case  LATEX_LIST_ENVIRONMENT:
1263                         context.add_par_extra_stuff("\\labelwidthstring "
1264                                                     + p.verbatim_item() + '\n');
1265                         p.skip_spaces();
1266                         break;
1267                 case  LATEX_BIB_ENVIRONMENT:
1268                         p.verbatim_item(); // swallow next arg
1269                         p.skip_spaces();
1270                         break;
1271                 default:
1272                         break;
1273                 }
1274                 context.check_deeper(os);
1275                 // handle known optional and required arguments
1276                 // layouts require all optional arguments before the required ones
1277                 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1278                 // It is impossible to place anything after the environment name,
1279                 // but before the first \\item.
1280                 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1281                         bool need_layout = true;
1282                         unsigned int optargs = 0;
1283                         while (optargs < context.layout->optargs) {
1284                                 eat_whitespace(p, os, context, false);
1285                                 if (p.next_token().cat() == catEscape ||
1286                                     p.next_token().character() != '[') 
1287                                         break;
1288                                 p.get_token(); // eat '['
1289                                 if (need_layout) {
1290                                         context.check_layout(os);
1291                                         need_layout = false;
1292                                 }
1293                                 begin_inset(os, "Argument\n");
1294                                 os << "status collapsed\n\n";
1295                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1296                                 end_inset(os);
1297                                 eat_whitespace(p, os, context, false);
1298                                 ++optargs;
1299                         }
1300                         unsigned int reqargs = 0;
1301                         while (reqargs < context.layout->reqargs) {
1302                                 eat_whitespace(p, os, context, false);
1303                                 if (p.next_token().cat() != catBegin)
1304                                         break;
1305                                 p.get_token(); // eat '{'
1306                                 if (need_layout) {
1307                                         context.check_layout(os);
1308                                         need_layout = false;
1309                                 }
1310                                 begin_inset(os, "Argument\n");
1311                                 os << "status collapsed\n\n";
1312                                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1313                                 end_inset(os);
1314                                 eat_whitespace(p, os, context, false);
1315                                 ++reqargs;
1316                         }
1317                 }
1318                 parse_text(p, os, FLAG_END, outer, context);
1319                 context.check_end_layout(os);
1320                 if (parent_context.deeper_paragraph) {
1321                         // We must suppress the "end deeper" because we
1322                         // suppressed the "begin deeper" above.
1323                         context.need_end_deeper = false;
1324                 }
1325                 context.check_end_deeper(os);
1326                 parent_context.new_paragraph(os);
1327                 p.skip_spaces();
1328         }
1329
1330         // The single '=' is meant here.
1331         else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1332                 eat_whitespace(p, os, parent_context, false);
1333                 parent_context.check_layout(os);
1334                 begin_inset(os, "Flex ");
1335                 os << to_utf8(newinsetlayout->name()) << '\n'
1336                    << "status collapsed\n";
1337                 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1338                 end_inset(os);
1339         }
1340
1341         else if (name == "appendix") {
1342                 // This is no good latex style, but it works and is used in some documents...
1343                 eat_whitespace(p, os, parent_context, false);
1344                 parent_context.check_end_layout(os);
1345                 Context context(true, parent_context.textclass, parent_context.layout,
1346                                 parent_context.layout, parent_context.font);
1347                 context.check_layout(os);
1348                 os << "\\start_of_appendix\n";
1349                 parse_text(p, os, FLAG_END, outer, context);
1350                 context.check_end_layout(os);
1351                 p.skip_spaces();
1352         }
1353
1354         else if (known_environments.find(name) != known_environments.end()) {
1355                 vector<ArgumentType> arguments = known_environments[name];
1356                 // The last "argument" denotes wether we may translate the
1357                 // environment contents to LyX
1358                 // The default required if no argument is given makes us
1359                 // compatible with the reLyXre environment.
1360                 ArgumentType contents = arguments.empty() ?
1361                         required :
1362                         arguments.back();
1363                 if (!arguments.empty())
1364                         arguments.pop_back();
1365                 // See comment in parse_unknown_environment()
1366                 bool const specialfont =
1367                         (parent_context.font != parent_context.normalfont);
1368                 bool const new_layout_allowed =
1369                         parent_context.new_layout_allowed;
1370                 if (specialfont)
1371                         parent_context.new_layout_allowed = false;
1372                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1373                                 outer, parent_context);
1374                 if (contents == verbatim)
1375                         handle_ert(os, p.verbatimEnvironment(name),
1376                                    parent_context);
1377                 else
1378                         parse_text_snippet(p, os, FLAG_END, outer,
1379                                            parent_context);
1380                 handle_ert(os, "\\end{" + name + "}", parent_context);
1381                 if (specialfont)
1382                         parent_context.new_layout_allowed = new_layout_allowed;
1383         }
1384
1385         else
1386                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1387                                           parent_context);
1388
1389         last_env = name;
1390         active_environments.pop_back();
1391 }
1392
1393
1394 /// parses a comment and outputs it to \p os.
1395 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1396 {
1397         LASSERT(t.cat() == catComment, return);
1398         if (!t.cs().empty()) {
1399                 context.check_layout(os);
1400                 handle_comment(os, '%' + t.cs(), context);
1401                 if (p.next_token().cat() == catNewline) {
1402                         // A newline after a comment line starts a new
1403                         // paragraph
1404                         if (context.new_layout_allowed) {
1405                                 if(!context.atParagraphStart())
1406                                         // Only start a new paragraph if not already
1407                                         // done (we might get called recursively)
1408                                         context.new_paragraph(os);
1409                         } else
1410                                 handle_ert(os, "\n", context);
1411                         eat_whitespace(p, os, context, true);
1412                 }
1413         } else {
1414                 // "%\n" combination
1415                 p.skip_spaces();
1416         }
1417 }
1418
1419
1420 /*!
1421  * Reads spaces and comments until the first non-space, non-comment token.
1422  * New paragraphs (double newlines or \\par) are handled like simple spaces
1423  * if \p eatParagraph is true.
1424  * Spaces are skipped, but comments are written to \p os.
1425  */
1426 void eat_whitespace(Parser & p, ostream & os, Context & context,
1427                     bool eatParagraph)
1428 {
1429         while (p.good()) {
1430                 Token const & t = p.get_token();
1431                 if (t.cat() == catComment)
1432                         parse_comment(p, os, t, context);
1433                 else if ((! eatParagraph && p.isParagraph()) ||
1434                          (t.cat() != catSpace && t.cat() != catNewline)) {
1435                         p.putback();
1436                         return;
1437                 }
1438         }
1439 }
1440
1441
1442 /*!
1443  * Set a font attribute, parse text and reset the font attribute.
1444  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1445  * \param currentvalue Current value of the attribute. Is set to the new
1446  * value during parsing.
1447  * \param newvalue New value of the attribute
1448  */
1449 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1450                            Context & context, string const & attribute,
1451                            string & currentvalue, string const & newvalue)
1452 {
1453         context.check_layout(os);
1454         string const oldvalue = currentvalue;
1455         currentvalue = newvalue;
1456         os << '\n' << attribute << ' ' << newvalue << "\n";
1457         parse_text_snippet(p, os, flags, outer, context);
1458         context.check_layout(os);
1459         os << '\n' << attribute << ' ' << oldvalue << "\n";
1460         currentvalue = oldvalue;
1461 }
1462
1463
1464 /// get the arguments of a natbib or jurabib citation command
1465 void get_cite_arguments(Parser & p, bool natbibOrder,
1466         string & before, string & after)
1467 {
1468         // We need to distinguish "" and "[]", so we can't use p.getOpt().
1469
1470         // text before the citation
1471         before.clear();
1472         // text after the citation
1473         after = p.getFullOpt();
1474
1475         if (!after.empty()) {
1476                 before = p.getFullOpt();
1477                 if (natbibOrder && !before.empty())
1478                         swap(before, after);
1479         }
1480 }
1481
1482
1483 /// Convert filenames with TeX macros and/or quotes to something LyX
1484 /// can understand
1485 string const normalize_filename(string const & name)
1486 {
1487         Parser p(trim(name, "\""));
1488         ostringstream os;
1489         while (p.good()) {
1490                 Token const & t = p.get_token();
1491                 if (t.cat() != catEscape)
1492                         os << t.asInput();
1493                 else if (t.cs() == "lyxdot") {
1494                         // This is used by LyX for simple dots in relative
1495                         // names
1496                         os << '.';
1497                         p.skip_spaces();
1498                 } else if (t.cs() == "space") {
1499                         os << ' ';
1500                         p.skip_spaces();
1501                 } else
1502                         os << t.asInput();
1503         }
1504         return os.str();
1505 }
1506
1507
1508 /// Convert \p name from TeX convention (relative to master file) to LyX
1509 /// convention (relative to .lyx file) if it is relative
1510 void fix_relative_filename(string & name)
1511 {
1512         if (FileName::isAbsolute(name))
1513                 return;
1514
1515         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1516                                    from_utf8(getParentFilePath())));
1517 }
1518
1519
1520 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1521 void parse_noweb(Parser & p, ostream & os, Context & context)
1522 {
1523         // assemble the rest of the keyword
1524         string name("<<");
1525         bool scrap = false;
1526         while (p.good()) {
1527                 Token const & t = p.get_token();
1528                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1529                         name += ">>";
1530                         p.get_token();
1531                         scrap = (p.good() && p.next_token().asInput() == "=");
1532                         if (scrap)
1533                                 name += p.get_token().asInput();
1534                         break;
1535                 }
1536                 name += t.asInput();
1537         }
1538
1539         if (!scrap || !context.new_layout_allowed ||
1540             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1541                 cerr << "Warning: Could not interpret '" << name
1542                      << "'. Ignoring it." << endl;
1543                 return;
1544         }
1545
1546         // We use new_paragraph instead of check_end_layout because the stuff
1547         // following the noweb chunk needs to start with a \begin_layout.
1548         // This may create a new paragraph even if there was none in the
1549         // noweb file, but the alternative is an invalid LyX file. Since
1550         // noweb code chunks are implemented with a layout style in LyX they
1551         // always must be in an own paragraph.
1552         context.new_paragraph(os);
1553         Context newcontext(true, context.textclass,
1554                 &context.textclass[from_ascii("Scrap")]);
1555         newcontext.check_layout(os);
1556         os << name;
1557         while (p.good()) {
1558                 Token const & t = p.get_token();
1559                 // We abuse the parser a bit, because this is no TeX syntax
1560                 // at all.
1561                 if (t.cat() == catEscape)
1562                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1563                 else {
1564                         ostringstream oss;
1565                         Context tmp(false, context.textclass,
1566                                     &context.textclass[from_ascii("Scrap")]);
1567                         tmp.need_end_layout = true;
1568                         tmp.check_layout(oss);
1569                         os << subst(t.asInput(), "\n", oss.str());
1570                 }
1571                 // The scrap chunk is ended by an @ at the beginning of a line.
1572                 // After the @ the line may contain a comment and/or
1573                 // whitespace, but nothing else.
1574                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1575                     (p.next_token().cat() == catSpace ||
1576                      p.next_token().cat() == catNewline ||
1577                      p.next_token().cat() == catComment)) {
1578                         while (p.good() && p.next_token().cat() == catSpace)
1579                                 os << p.get_token().asInput();
1580                         if (p.next_token().cat() == catComment)
1581                                 // The comment includes a final '\n'
1582                                 os << p.get_token().asInput();
1583                         else {
1584                                 if (p.next_token().cat() == catNewline)
1585                                         p.get_token();
1586                                 os << '\n';
1587                         }
1588                         break;
1589                 }
1590         }
1591         newcontext.check_end_layout(os);
1592 }
1593
1594
1595 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1596 bool is_macro(Parser & p)
1597 {
1598         Token first = p.curr_token();
1599         if (first.cat() != catEscape || !p.good())
1600                 return false;
1601         if (first.cs() == "def")
1602                 return true;
1603         if (first.cs() != "global" && first.cs() != "long")
1604                 return false;
1605         Token second = p.get_token();
1606         int pos = 1;
1607         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1608                second.cat() == catNewline || second.cat() == catComment)) {
1609                 second = p.get_token();
1610                 pos++;
1611         }
1612         bool secondvalid = second.cat() == catEscape;
1613         Token third;
1614         bool thirdvalid = false;
1615         if (p.good() && first.cs() == "global" && secondvalid &&
1616             second.cs() == "long") {
1617                 third = p.get_token();
1618                 pos++;
1619                 while (p.good() && !p.isParagraph() &&
1620                        (third.cat() == catSpace ||
1621                         third.cat() == catNewline ||
1622                         third.cat() == catComment)) {
1623                         third = p.get_token();
1624                         pos++;
1625                 }
1626                 thirdvalid = third.cat() == catEscape;
1627         }
1628         for (int i = 0; i < pos; ++i)
1629                 p.putback();
1630         if (!secondvalid)
1631                 return false;
1632         if (!thirdvalid)
1633                 return (first.cs() == "global" || first.cs() == "long") &&
1634                        second.cs() == "def";
1635         return first.cs() == "global" && second.cs() == "long" &&
1636                third.cs() == "def";
1637 }
1638
1639
1640 /// Parse a macro definition (assumes that is_macro() returned true)
1641 void parse_macro(Parser & p, ostream & os, Context & context)
1642 {
1643         context.check_layout(os);
1644         Token first = p.curr_token();
1645         Token second;
1646         Token third;
1647         string command = first.asInput();
1648         if (first.cs() != "def") {
1649                 p.get_token();
1650                 eat_whitespace(p, os, context, false);
1651                 second = p.curr_token();
1652                 command += second.asInput();
1653                 if (second.cs() != "def") {
1654                         p.get_token();
1655                         eat_whitespace(p, os, context, false);
1656                         third = p.curr_token();
1657                         command += third.asInput();
1658                 }
1659         }
1660         eat_whitespace(p, os, context, false);
1661         string const name = p.get_token().cs();
1662         eat_whitespace(p, os, context, false);
1663
1664         // parameter text
1665         bool simple = true;
1666         string paramtext;
1667         int arity = 0;
1668         while (p.next_token().cat() != catBegin) {
1669                 if (p.next_token().cat() == catParameter) {
1670                         // # found
1671                         p.get_token();
1672                         paramtext += "#";
1673
1674                         // followed by number?
1675                         if (p.next_token().cat() == catOther) {
1676                                 char c = p.getChar();
1677                                 paramtext += c;
1678                                 // number = current arity + 1?
1679                                 if (c == arity + '0' + 1)
1680                                         ++arity;
1681                                 else
1682                                         simple = false;
1683                         } else
1684                                 paramtext += p.get_token().cs();
1685                 } else {
1686                         paramtext += p.get_token().cs();
1687                         simple = false;
1688                 }
1689         }
1690
1691         // only output simple (i.e. compatible) macro as FormulaMacros
1692         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1693         if (simple) {
1694                 context.check_layout(os);
1695                 begin_inset(os, "FormulaMacro");
1696                 os << "\n\\def" << ert;
1697                 end_inset(os);
1698         } else
1699                 handle_ert(os, command + ert, context);
1700 }
1701
1702 } // anonymous namespace
1703
1704
1705 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1706                 Context & context)
1707 {
1708         Layout const * newlayout = 0;
1709         InsetLayout const * newinsetlayout = 0;
1710         // Store the latest bibliographystyle and nocite{*} option
1711         // (needed for bibtex inset)
1712         string btprint;
1713         string bibliographystyle;
1714         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1715         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1716         string last_env;
1717         while (p.good()) {
1718                 Token const & t = p.get_token();
1719
1720 #ifdef FILEDEBUG
1721                 debugToken(cerr, t, flags);
1722 #endif
1723
1724                 if (flags & FLAG_ITEM) {
1725                         if (t.cat() == catSpace)
1726                                 continue;
1727
1728                         flags &= ~FLAG_ITEM;
1729                         if (t.cat() == catBegin) {
1730                                 // skip the brace and collect everything to the next matching
1731                                 // closing brace
1732                                 flags |= FLAG_BRACE_LAST;
1733                                 continue;
1734                         }
1735
1736                         // handle only this single token, leave the loop if done
1737                         flags |= FLAG_LEAVE;
1738                 }
1739
1740                 if (t.cat() != catEscape && t.character() == ']' &&
1741                     (flags & FLAG_BRACK_LAST))
1742                         return;
1743                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1744                         return;
1745
1746                 // If there is anything between \end{env} and \begin{env} we
1747                 // don't need to output a separator.
1748                 if (t.cat() != catSpace && t.cat() != catNewline &&
1749                     t.asInput() != "\\begin")
1750                         last_env = "";
1751
1752                 //
1753                 // cat codes
1754                 //
1755                 if (t.cat() == catMath) {
1756                         // we are inside some text mode thingy, so opening new math is allowed
1757                         context.check_layout(os);
1758                         begin_inset(os, "Formula ");
1759                         Token const & n = p.get_token();
1760                         if (n.cat() == catMath && outer) {
1761                                 // TeX's $$...$$ syntax for displayed math
1762                                 os << "\\[";
1763                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1764                                 os << "\\]";
1765                                 p.get_token(); // skip the second '$' token
1766                         } else {
1767                                 // simple $...$  stuff
1768                                 p.putback();
1769                                 os << '$';
1770                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1771                                 os << '$';
1772                         }
1773                         end_inset(os);
1774                 }
1775
1776                 else if (t.cat() == catSuper || t.cat() == catSub)
1777                         cerr << "catcode " << t << " illegal in text mode\n";
1778
1779                 // Basic support for english quotes. This should be
1780                 // extended to other quotes, but is not so easy (a
1781                 // left english quote is the same as a right german
1782                 // quote...)
1783                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1784                         context.check_layout(os);
1785                         begin_inset(os, "Quotes ");
1786                         os << "eld";
1787                         end_inset(os);
1788                         p.get_token();
1789                         skip_braces(p);
1790                 }
1791                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1792                         context.check_layout(os);
1793                         begin_inset(os, "Quotes ");
1794                         os << "erd";
1795                         end_inset(os);
1796                         p.get_token();
1797                         skip_braces(p);
1798                 }
1799
1800                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1801                         context.check_layout(os);
1802                         begin_inset(os, "Quotes ");
1803                         os << "ald";
1804                         end_inset(os);
1805                         p.get_token();
1806                         skip_braces(p);
1807                 }
1808
1809                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1810                         context.check_layout(os);
1811                         begin_inset(os, "Quotes ");
1812                         os << "ard";
1813                         end_inset(os);
1814                         p.get_token();
1815                         skip_braces(p);
1816                 }
1817
1818                 else if (t.asInput() == "<"
1819                          && p.next_token().asInput() == "<" && noweb_mode) {
1820                         p.get_token();
1821                         parse_noweb(p, os, context);
1822                 }
1823
1824                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1825                         check_space(p, os, context);
1826
1827                 else if (t.character() == '[' && noweb_mode &&
1828                          p.next_token().character() == '[') {
1829                         // These can contain underscores
1830                         p.putback();
1831                         string const s = p.getFullOpt() + ']';
1832                         if (p.next_token().character() == ']')
1833                                 p.get_token();
1834                         else
1835                                 cerr << "Warning: Inserting missing ']' in '"
1836                                      << s << "'." << endl;
1837                         handle_ert(os, s, context);
1838                 }
1839
1840                 else if (t.cat() == catLetter) {
1841                         context.check_layout(os);
1842                         // Workaround for bug 4752.
1843                         // FIXME: This whole code block needs to be removed
1844                         //        when the bug is fixed and tex2lyx produces
1845                         //        the updated file format.
1846                         // The replacement algorithm in LyX is so stupid that
1847                         // it even translates a phrase if it is part of a word.
1848                         bool handled = false;
1849                         for (int const * l = known_phrase_lengths; *l; ++l) {
1850                                 string phrase = t.cs();
1851                                 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1852                                         phrase += p.get_token().cs();
1853                                 if (is_known(phrase, known_coded_phrases)) {
1854                                         handle_ert(os, phrase, context);
1855                                         handled = true;
1856                                         break;
1857                                 } else {
1858                                         for (size_t i = 1; i < phrase.length(); ++i)
1859                                                 p.putback();
1860                                 }
1861                         }
1862                         if (!handled)
1863                                 os << t.cs();
1864                 }
1865
1866                 else if (t.cat() == catOther ||
1867                                t.cat() == catAlign ||
1868                                t.cat() == catParameter) {
1869                         // This translates "&" to "\\&" which may be wrong...
1870                         context.check_layout(os);
1871                         os << t.cs();
1872                 }
1873
1874                 else if (p.isParagraph()) {
1875                         if (context.new_layout_allowed)
1876                                 context.new_paragraph(os);
1877                         else
1878                                 handle_ert(os, "\\par ", context);
1879                         eat_whitespace(p, os, context, true);
1880                 }
1881
1882                 else if (t.cat() == catActive) {
1883                         context.check_layout(os);
1884                         if (t.character() == '~') {
1885                                 if (context.layout->free_spacing)
1886                                         os << ' ';
1887                                 else {
1888                                         begin_inset(os, "space ~\n");
1889                                         end_inset(os);
1890                                 }
1891                         } else
1892                                 os << t.cs();
1893                 }
1894
1895                 else if (t.cat() == catBegin &&
1896                          p.next_token().cat() == catEnd) {
1897                         // {}
1898                         Token const prev = p.prev_token();
1899                         p.get_token();
1900                         if (p.next_token().character() == '`' ||
1901                             (prev.character() == '-' &&
1902                              p.next_token().character() == '-'))
1903                                 ; // ignore it in {}`` or -{}-
1904                         else
1905                                 handle_ert(os, "{}", context);
1906
1907                 }
1908
1909                 else if (t.cat() == catBegin) {
1910                         context.check_layout(os);
1911                         // special handling of font attribute changes
1912                         Token const prev = p.prev_token();
1913                         Token const next = p.next_token();
1914                         TeXFont const oldFont = context.font;
1915                         if (next.character() == '[' ||
1916                             next.character() == ']' ||
1917                             next.character() == '*') {
1918                                 p.get_token();
1919                                 if (p.next_token().cat() == catEnd) {
1920                                         os << next.cs();
1921                                         p.get_token();
1922                                 } else {
1923                                         p.putback();
1924                                         handle_ert(os, "{", context);
1925                                         parse_text_snippet(p, os,
1926                                                         FLAG_BRACE_LAST,
1927                                                         outer, context);
1928                                         handle_ert(os, "}", context);
1929                                 }
1930                         } else if (! context.new_layout_allowed) {
1931                                 handle_ert(os, "{", context);
1932                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1933                                                    outer, context);
1934                                 handle_ert(os, "}", context);
1935                         } else if (is_known(next.cs(), known_sizes)) {
1936                                 // next will change the size, so we must
1937                                 // reset it here
1938                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1939                                                    outer, context);
1940                                 if (!context.atParagraphStart())
1941                                         os << "\n\\size "
1942                                            << context.font.size << "\n";
1943                         } else if (is_known(next.cs(), known_font_families)) {
1944                                 // next will change the font family, so we
1945                                 // must reset it here
1946                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1947                                                    outer, context);
1948                                 if (!context.atParagraphStart())
1949                                         os << "\n\\family "
1950                                            << context.font.family << "\n";
1951                         } else if (is_known(next.cs(), known_font_series)) {
1952                                 // next will change the font series, so we
1953                                 // must reset it here
1954                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1955                                                    outer, context);
1956                                 if (!context.atParagraphStart())
1957                                         os << "\n\\series "
1958                                            << context.font.series << "\n";
1959                         } else if (is_known(next.cs(), known_font_shapes)) {
1960                                 // next will change the font shape, so we
1961                                 // must reset it here
1962                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1963                                                    outer, context);
1964                                 if (!context.atParagraphStart())
1965                                         os << "\n\\shape "
1966                                            << context.font.shape << "\n";
1967                         } else if (is_known(next.cs(), known_old_font_families) ||
1968                                    is_known(next.cs(), known_old_font_series) ||
1969                                    is_known(next.cs(), known_old_font_shapes)) {
1970                                 // next will change the font family, series
1971                                 // and shape, so we must reset it here
1972                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1973                                                    outer, context);
1974                                 if (!context.atParagraphStart())
1975                                         os <<  "\n\\family "
1976                                            << context.font.family
1977                                            << "\n\\series "
1978                                            << context.font.series
1979                                            << "\n\\shape "
1980                                            << context.font.shape << "\n";
1981                         } else {
1982                                 handle_ert(os, "{", context);
1983                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1984                                                    outer, context);
1985                                 handle_ert(os, "}", context);
1986                         }
1987                 }
1988
1989                 else if (t.cat() == catEnd) {
1990                         if (flags & FLAG_BRACE_LAST) {
1991                                 return;
1992                         }
1993                         cerr << "stray '}' in text\n";
1994                         handle_ert(os, "}", context);
1995                 }
1996
1997                 else if (t.cat() == catComment)
1998                         parse_comment(p, os, t, context);
1999
2000                 //
2001                 // control sequences
2002                 //
2003
2004                 else if (t.cs() == "(") {
2005                         context.check_layout(os);
2006                         begin_inset(os, "Formula");
2007                         os << " \\(";
2008                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2009                         os << "\\)";
2010                         end_inset(os);
2011                 }
2012
2013                 else if (t.cs() == "[") {
2014                         context.check_layout(os);
2015                         begin_inset(os, "Formula");
2016                         os << " \\[";
2017                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2018                         os << "\\]";
2019                         end_inset(os);
2020                 }
2021
2022                 else if (t.cs() == "begin")
2023                         parse_environment(p, os, outer, last_env, context);
2024
2025                 else if (t.cs() == "end") {
2026                         if (flags & FLAG_END) {
2027                                 // eat environment name
2028                                 string const name = p.getArg('{', '}');
2029                                 if (name != active_environment())
2030                                         cerr << "\\end{" + name + "} does not match \\begin{"
2031                                                 + active_environment() + "}\n";
2032                                 return;
2033                         }
2034                         p.error("found 'end' unexpectedly");
2035                 }
2036
2037                 else if (t.cs() == "item") {
2038                         p.skip_spaces();
2039                         string s;
2040                         bool optarg = false;
2041                         if (p.next_token().cat() != catEscape &&
2042                             p.next_token().character() == '[') {
2043                                 p.get_token(); // eat '['
2044                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2045                                                        outer, context);
2046                                 optarg = true;
2047                         }
2048                         context.set_item();
2049                         context.check_layout(os);
2050                         if (context.has_item) {
2051                                 // An item in an unknown list-like environment
2052                                 // FIXME: Do this in check_layout()!
2053                                 context.has_item = false;
2054                                 if (optarg)
2055                                         handle_ert(os, "\\item", context);
2056                                 else
2057                                         handle_ert(os, "\\item ", context);
2058                         }
2059                         if (optarg) {
2060                                 if (context.layout->labeltype != LABEL_MANUAL) {
2061                                         // LyX does not support \item[\mybullet]
2062                                         // in itemize environments
2063                                         handle_ert(os, "[", context);
2064                                         os << s;
2065                                         handle_ert(os, "]", context);
2066                                 } else if (!s.empty()) {
2067                                         // The space is needed to separate the
2068                                         // item from the rest of the sentence.
2069                                         os << s << ' ';
2070                                         eat_whitespace(p, os, context, false);
2071                                 }
2072                         }
2073                 }
2074
2075                 else if (t.cs() == "bibitem") {
2076                         context.set_item();
2077                         context.check_layout(os);
2078                         string label = convert_command_inset_arg(p.getArg('[', ']'));
2079                         string key = convert_command_inset_arg(p.verbatim_item());
2080                         if (contains(label, '\\') || contains(key, '\\')) {
2081                                 // LyX can't handle LaTeX commands in labels or keys
2082                                 handle_ert(os, t.asInput() + '[' + label +
2083                                                "]{" + p.verbatim_item() + '}',
2084                                            context);
2085                         } else {
2086                                 begin_command_inset(os, "bibitem", "bibitem");
2087                                 os << "label \"" << label << "\"\n"
2088                                       "key \"" << key << "\"\n";
2089                                 end_inset(os);
2090                         }
2091                 }
2092
2093                 else if (is_macro(p))
2094                         parse_macro(p, os, context);
2095
2096                 else if (t.cs() == "noindent") {
2097                         p.skip_spaces();
2098                         context.add_par_extra_stuff("\\noindent\n");
2099                 }
2100
2101                 else if (t.cs() == "appendix") {
2102                         context.add_par_extra_stuff("\\start_of_appendix\n");
2103                         // We need to start a new paragraph. Otherwise the
2104                         // appendix in 'bla\appendix\chapter{' would start
2105                         // too late.
2106                         context.new_paragraph(os);
2107                         // We need to make sure that the paragraph is
2108                         // generated even if it is empty. Otherwise the
2109                         // appendix in '\par\appendix\par\chapter{' would
2110                         // start too late.
2111                         context.check_layout(os);
2112                         // FIXME: This is a hack to prevent paragraph
2113                         // deletion if it is empty. Handle this better!
2114                         handle_comment(os,
2115                                 "%dummy comment inserted by tex2lyx to "
2116                                 "ensure that this paragraph is not empty",
2117                                 context);
2118                         // Both measures above may generate an additional
2119                         // empty paragraph, but that does not hurt, because
2120                         // whitespace does not matter here.
2121                         eat_whitespace(p, os, context, true);
2122                 }
2123
2124                 // Starred section headings
2125                 // Must attempt to parse "Section*" before "Section".
2126                 else if ((p.next_token().asInput() == "*") &&
2127                          context.new_layout_allowed &&
2128                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2129                         // write the layout
2130                         p.get_token();
2131                         output_command_layout(os, p, outer, context, newlayout);
2132                         p.skip_spaces();
2133                 }
2134
2135                 // Section headings and the like
2136                 else if (context.new_layout_allowed &&
2137                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2138                         // write the layout
2139                         output_command_layout(os, p, outer, context, newlayout);
2140                         p.skip_spaces();
2141                 }
2142
2143                 else if (t.cs() == "caption") {
2144                         p.skip_spaces();
2145                         context.check_layout(os);
2146                         p.skip_spaces();
2147                         begin_inset(os, "Caption\n");
2148                         Context newcontext(true, context.textclass);
2149                         newcontext.font = context.font;
2150                         newcontext.check_layout(os);
2151                         if (p.next_token().cat() != catEscape &&
2152                             p.next_token().character() == '[') {
2153                                 p.get_token(); // eat '['
2154                                 begin_inset(os, "Argument\n");
2155                                 os << "status collapsed\n";
2156                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2157                                 end_inset(os);
2158                                 eat_whitespace(p, os, context, false);
2159                         }
2160                         parse_text(p, os, FLAG_ITEM, outer, context);
2161                         context.check_end_layout(os);
2162                         // We don't need really a new paragraph, but
2163                         // we must make sure that the next item gets a \begin_layout.
2164                         context.new_paragraph(os);
2165                         end_inset(os);
2166                         p.skip_spaces();
2167                         newcontext.check_end_layout(os);
2168                 }
2169
2170                 else if (t.cs() == "subfloat") {
2171                         // the syntax is \subfloat[caption]{content}
2172                         // if it is a table of figure depends on the surrounding float
2173                         bool has_caption = false;
2174                         p.skip_spaces();
2175                         // do nothing if there is no outer float
2176                         if (!float_type.empty()) {
2177                                 context.check_layout(os);
2178                                 p.skip_spaces();
2179                                 begin_inset(os, "Float " + float_type + "\n");
2180                                 os << "wide false"
2181                                    << "\nsideways false"
2182                                    << "\nstatus collapsed\n\n";
2183                                 // test for caption
2184                                 string caption;
2185                                 if (p.next_token().cat() != catEscape &&
2186                                                 p.next_token().character() == '[') {
2187                                                         p.get_token(); // eat '['
2188                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2189                                                         has_caption = true;
2190                                 }
2191                                 // the content
2192                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2193                                 // the caption comes always as the last
2194                                 if (has_caption) {
2195                                         // we must make sure that the caption gets a \begin_layout
2196                                         os << "\n\\begin_layout Plain Layout";
2197                                         p.skip_spaces();
2198                                         begin_inset(os, "Caption\n");
2199                                         Context newcontext(true, context.textclass);
2200                                         newcontext.font = context.font;
2201                                         newcontext.check_layout(os);
2202                                         os << caption << "\n";
2203                                         newcontext.check_end_layout(os);
2204                                         // We don't need really a new paragraph, but
2205                                         // we must make sure that the next item gets a \begin_layout.
2206                                         //newcontext.new_paragraph(os);
2207                                         end_inset(os);
2208                                         p.skip_spaces();
2209                                 }
2210                                 // We don't need really a new paragraph, but
2211                                 // we must make sure that the next item gets a \begin_layout.
2212                                 if (has_caption)
2213                                         context.new_paragraph(os);
2214                                 end_inset(os);
2215                                 p.skip_spaces();
2216                                 context.check_end_layout(os);
2217                                 // close the layout we opened
2218                                 if (has_caption)
2219                                         os << "\n\\end_layout\n";
2220                         } else {
2221                                 // if the float type is not supported or there is no surrounding float
2222                                 // output it as ERT
2223                                 if (p.hasOpt()) {
2224                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2225                                         handle_ert(os, t.asInput() + '[' + opt_arg +
2226                                                "]{" + p.verbatim_item() + '}', context);
2227                                 } else
2228                                         handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2229                         }
2230                 }
2231
2232                 else if (t.cs() == "includegraphics") {
2233                         bool const clip = p.next_token().asInput() == "*";
2234                         if (clip)
2235                                 p.get_token();
2236                         string const arg = p.getArg('[', ']');
2237                         map<string, string> opts;
2238                         vector<string> keys;
2239                         split_map(arg, opts, keys);
2240                         if (clip)
2241                                 opts["clip"] = string();
2242                         string name = normalize_filename(p.verbatim_item());
2243
2244                         string const path = getMasterFilePath();
2245                         // We want to preserve relative / absolute filenames,
2246                         // therefore path is only used for testing
2247                         if (!makeAbsPath(name, path).exists()) {
2248                                 // The file extension is probably missing.
2249                                 // Now try to find it out.
2250                                 string const dvips_name =
2251                                         find_file(name, path,
2252                                                   known_dvips_graphics_formats);
2253                                 string const pdftex_name =
2254                                         find_file(name, path,
2255                                                   known_pdftex_graphics_formats);
2256                                 if (!dvips_name.empty()) {
2257                                         if (!pdftex_name.empty()) {
2258                                                 cerr << "This file contains the "
2259                                                         "latex snippet\n"
2260                                                         "\"\\includegraphics{"
2261                                                      << name << "}\".\n"
2262                                                         "However, files\n\""
2263                                                      << dvips_name << "\" and\n\""
2264                                                      << pdftex_name << "\"\n"
2265                                                         "both exist, so I had to make a "
2266                                                         "choice and took the first one.\n"
2267                                                         "Please move the unwanted one "
2268                                                         "someplace else and try again\n"
2269                                                         "if my choice was wrong."
2270                                                      << endl;
2271                                         }
2272                                         name = dvips_name;
2273                                 } else if (!pdftex_name.empty()) {
2274                                         name = pdftex_name;
2275                                         pdflatex = true;
2276                                 }
2277                         }
2278
2279                         if (makeAbsPath(name, path).exists())
2280                                 fix_relative_filename(name);
2281                         else
2282                                 cerr << "Warning: Could not find graphics file '"
2283                                      << name << "'." << endl;
2284
2285                         context.check_layout(os);
2286                         begin_inset(os, "Graphics ");
2287                         os << "\n\tfilename " << name << '\n';
2288                         if (opts.find("width") != opts.end())
2289                                 os << "\twidth "
2290                                    << translate_len(opts["width"]) << '\n';
2291                         if (opts.find("height") != opts.end())
2292                                 os << "\theight "
2293                                    << translate_len(opts["height"]) << '\n';
2294                         if (opts.find("scale") != opts.end()) {
2295                                 istringstream iss(opts["scale"]);
2296                                 double val;
2297                                 iss >> val;
2298                                 val = val*100;
2299                                 os << "\tscale " << val << '\n';
2300                         }
2301                         if (opts.find("angle") != opts.end()) {
2302                                 os << "\trotateAngle "
2303                                    << opts["angle"] << '\n';
2304                                 vector<string>::const_iterator a =
2305                                         find(keys.begin(), keys.end(), "angle");
2306                                 vector<string>::const_iterator s =
2307                                         find(keys.begin(), keys.end(), "width");
2308                                 if (s == keys.end())
2309                                         s = find(keys.begin(), keys.end(), "height");
2310                                 if (s == keys.end())
2311                                         s = find(keys.begin(), keys.end(), "scale");
2312                                 if (s != keys.end() && distance(s, a) > 0)
2313                                         os << "\tscaleBeforeRotation\n";
2314                         }
2315                         if (opts.find("origin") != opts.end()) {
2316                                 ostringstream ss;
2317                                 string const opt = opts["origin"];
2318                                 if (opt.find('l') != string::npos) ss << "left";
2319                                 if (opt.find('r') != string::npos) ss << "right";
2320                                 if (opt.find('c') != string::npos) ss << "center";
2321                                 if (opt.find('t') != string::npos) ss << "Top";
2322                                 if (opt.find('b') != string::npos) ss << "Bottom";
2323                                 if (opt.find('B') != string::npos) ss << "Baseline";
2324                                 if (!ss.str().empty())
2325                                         os << "\trotateOrigin " << ss.str() << '\n';
2326                                 else
2327                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2328                         }
2329                         if (opts.find("keepaspectratio") != opts.end())
2330                                 os << "\tkeepAspectRatio\n";
2331                         if (opts.find("clip") != opts.end())
2332                                 os << "\tclip\n";
2333                         if (opts.find("draft") != opts.end())
2334                                 os << "\tdraft\n";
2335                         if (opts.find("bb") != opts.end())
2336                                 os << "\tBoundingBox "
2337                                    << opts["bb"] << '\n';
2338                         int numberOfbbOptions = 0;
2339                         if (opts.find("bbllx") != opts.end())
2340                                 numberOfbbOptions++;
2341                         if (opts.find("bblly") != opts.end())
2342                                 numberOfbbOptions++;
2343                         if (opts.find("bburx") != opts.end())
2344                                 numberOfbbOptions++;
2345                         if (opts.find("bbury") != opts.end())
2346                                 numberOfbbOptions++;
2347                         if (numberOfbbOptions == 4)
2348                                 os << "\tBoundingBox "
2349                                    << opts["bbllx"] << " " << opts["bblly"] << " "
2350                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
2351                         else if (numberOfbbOptions > 0)
2352                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2353                         numberOfbbOptions = 0;
2354                         if (opts.find("natwidth") != opts.end())
2355                                 numberOfbbOptions++;
2356                         if (opts.find("natheight") != opts.end())
2357                                 numberOfbbOptions++;
2358                         if (numberOfbbOptions == 2)
2359                                 os << "\tBoundingBox 0bp 0bp "
2360                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
2361                         else if (numberOfbbOptions > 0)
2362                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2363                         ostringstream special;
2364                         if (opts.find("hiresbb") != opts.end())
2365                                 special << "hiresbb,";
2366                         if (opts.find("trim") != opts.end())
2367                                 special << "trim,";
2368                         if (opts.find("viewport") != opts.end())
2369                                 special << "viewport=" << opts["viewport"] << ',';
2370                         if (opts.find("totalheight") != opts.end())
2371                                 special << "totalheight=" << opts["totalheight"] << ',';
2372                         if (opts.find("type") != opts.end())
2373                                 special << "type=" << opts["type"] << ',';
2374                         if (opts.find("ext") != opts.end())
2375                                 special << "ext=" << opts["ext"] << ',';
2376                         if (opts.find("read") != opts.end())
2377                                 special << "read=" << opts["read"] << ',';
2378                         if (opts.find("command") != opts.end())
2379                                 special << "command=" << opts["command"] << ',';
2380                         string s_special = special.str();
2381                         if (!s_special.empty()) {
2382                                 // We had special arguments. Remove the trailing ','.
2383                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2384                         }
2385                         // TODO: Handle the unknown settings better.
2386                         // Warn about invalid options.
2387                         // Check whether some option was given twice.
2388                         end_inset(os);
2389                 }
2390
2391                 else if (t.cs() == "footnote" ||
2392                          (t.cs() == "thanks" && context.layout->intitle)) {
2393                         p.skip_spaces();
2394                         context.check_layout(os);
2395                         begin_inset(os, "Foot\n");
2396                         os << "status collapsed\n\n";
2397                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2398                         end_inset(os);
2399                 }
2400
2401                 else if (t.cs() == "marginpar") {
2402                         p.skip_spaces();
2403                         context.check_layout(os);
2404                         begin_inset(os, "Marginal\n");
2405                         os << "status collapsed\n\n";
2406                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2407                         end_inset(os);
2408                 }
2409
2410                 else if (t.cs() == "ensuremath") {
2411                         p.skip_spaces();
2412                         context.check_layout(os);
2413                         string const s = p.verbatim_item();
2414                         //FIXME: this never triggers in UTF8
2415                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2416                                 os << s;
2417                         else
2418                                 handle_ert(os, "\\ensuremath{" + s + "}",
2419                                            context);
2420                 }
2421
2422                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2423                         // FIXME: Somehow prevent title layouts if
2424                         // "maketitle" was not found
2425                         // swallow this
2426                         skip_spaces_braces(p);
2427                 }
2428
2429                 else if (t.cs() == "tableofcontents") {
2430                         context.check_layout(os);
2431                         begin_command_inset(os, "toc", "tableofcontents");
2432                         end_inset(os);
2433                         skip_spaces_braces(p);
2434                 }
2435
2436                 else if (t.cs() == "listoffigures") {
2437                         context.check_layout(os);
2438                         begin_inset(os, "FloatList figure\n");
2439                         end_inset(os);
2440                         skip_spaces_braces(p);
2441                 }
2442
2443                 else if (t.cs() == "listoftables") {
2444                         context.check_layout(os);
2445                         begin_inset(os, "FloatList table\n");
2446                         end_inset(os);
2447                         skip_spaces_braces(p);
2448                 }
2449
2450                 else if (t.cs() == "listof") {
2451                         p.skip_spaces(true);
2452                         string const name = p.get_token().cs();
2453                         if (context.textclass.floats().typeExist(name)) {
2454                                 context.check_layout(os);
2455                                 begin_inset(os, "FloatList ");
2456                                 os << name << "\n";
2457                                 end_inset(os);
2458                                 p.get_token(); // swallow second arg
2459                         } else
2460                                 handle_ert(os, "\\listof{" + name + "}", context);
2461                 }
2462
2463                 else if (t.cs() == "textrm")
2464                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2465                                               context, "\\family",
2466                                               context.font.family, "roman");
2467
2468                 else if (t.cs() == "textsf")
2469                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2470                                               context, "\\family",
2471                                               context.font.family, "sans");
2472
2473                 else if (t.cs() == "texttt")
2474                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2475                                               context, "\\family",
2476                                               context.font.family, "typewriter");
2477
2478                 else if (t.cs() == "textmd")
2479                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2480                                               context, "\\series",
2481                                               context.font.series, "medium");
2482
2483                 else if (t.cs() == "textbf")
2484                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2485                                               context, "\\series",
2486                                               context.font.series, "bold");
2487
2488                 else if (t.cs() == "textup")
2489                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2490                                               context, "\\shape",
2491                                               context.font.shape, "up");
2492
2493                 else if (t.cs() == "textit")
2494                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2495                                               context, "\\shape",
2496                                               context.font.shape, "italic");
2497
2498                 else if (t.cs() == "textsl")
2499                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2500                                               context, "\\shape",
2501                                               context.font.shape, "slanted");
2502
2503                 else if (t.cs() == "textsc")
2504                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2505                                               context, "\\shape",
2506                                               context.font.shape, "smallcaps");
2507
2508                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2509                         context.check_layout(os);
2510                         TeXFont oldFont = context.font;
2511                         context.font.init();
2512                         context.font.size = oldFont.size;
2513                         os << "\n\\family " << context.font.family << "\n";
2514                         os << "\n\\series " << context.font.series << "\n";
2515                         os << "\n\\shape " << context.font.shape << "\n";
2516                         if (t.cs() == "textnormal") {
2517                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2518                                 output_font_change(os, context.font, oldFont);
2519                                 context.font = oldFont;
2520                         } else
2521                                 eat_whitespace(p, os, context, false);
2522                 }
2523
2524                 else if (t.cs() == "textcolor") {
2525                         // scheme is \textcolor{color name}{text}
2526                         string const color = p.verbatim_item();
2527                         // we only support the predefined colors of the color package
2528                         if (color == "black" || color == "blue" || color == "cyan"
2529                                 || color == "green" || color == "magenta" || color == "red"
2530                                 || color == "white" || color == "yellow") {
2531                                         context.check_layout(os);
2532                                         os << "\n\\color " << color << "\n";
2533                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2534                                         context.check_layout(os);
2535                                         os << "\n\\color inherit\n";
2536                         } else
2537                                 // for custom defined colors
2538                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
2539                 }
2540
2541                 else if (t.cs() == "underbar" || t.cs() == "uline") {
2542                         // \underbar is not 100% correct (LyX outputs \uline
2543                         // of ulem.sty). The difference is that \ulem allows
2544                         // line breaks, and \underbar does not.
2545                         // Do NOT handle \underline.
2546                         // \underbar cuts through y, g, q, p etc.,
2547                         // \underline does not.
2548                         context.check_layout(os);
2549                         os << "\n\\bar under\n";
2550                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2551                         context.check_layout(os);
2552                         os << "\n\\bar default\n";
2553                 }
2554
2555                 else if (t.cs() == "sout") {
2556                         context.check_layout(os);
2557                         os << "\n\\strikeout on\n";
2558                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2559                         context.check_layout(os);
2560                         os << "\n\\strikeout default\n";
2561                 }
2562
2563                 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2564                          t.cs() == "emph" || t.cs() == "noun") {
2565                         context.check_layout(os);
2566                         os << "\n\\" << t.cs() << " on\n";
2567                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2568                         context.check_layout(os);
2569                         os << "\n\\" << t.cs() << " default\n";
2570                 }
2571
2572                 // FIXME, the inset layout should be plain, not standard, see bug #7846
2573                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2574                              t.cs() == "vphantom") {
2575                         context.check_layout(os);
2576                         if (t.cs() == "phantom")
2577                                 begin_inset(os, "Phantom Phantom\n");
2578                         if (t.cs() == "hphantom")
2579                                 begin_inset(os, "Phantom HPhantom\n");
2580                         if (t.cs() == "vphantom")
2581                                 begin_inset(os, "Phantom VPhantom\n");
2582                         os << "status open\n";
2583                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2584                         end_inset(os);
2585                 }
2586
2587                 else if (t.cs() == "href") {
2588                         context.check_layout(os);
2589                         string target = p.getArg('{', '}');
2590                         string name = p.getArg('{', '}');
2591                         string type;
2592                         size_t i = target.find(':');
2593                         if (i != string::npos) {
2594                                 type = target.substr(0, i + 1);
2595                                 if (type == "mailto:" || type == "file:")
2596                                         target = target.substr(i + 1);
2597                                 // handle the case that name is equal to target, except of "http://"
2598                                 else if (target.substr(i + 3) == name && type == "http:")
2599                                         target = name;
2600                         }
2601                         begin_command_inset(os, "href", "href");
2602                         if (name != target)
2603                                 os << "name \"" << name << "\"\n";
2604                         os << "target \"" << target << "\"\n";
2605                         if (type == "mailto:" || type == "file:")
2606                                 os << "type \"" << type << "\"\n";
2607                         end_inset(os);
2608                         skip_spaces_braces(p);
2609                 }
2610                 
2611                 else if (t.cs() == "lyxline") {
2612                         // swallow size argument (it is not used anyway)
2613                         p.getArg('{', '}');
2614                         if (!context.atParagraphStart()) {
2615                                 // so our line is in the middle of a paragraph
2616                                 // we need to add a new line, lest this line
2617                                 // follow the other content on that line and
2618                                 // run off the side of the page
2619                                 // FIXME: This may create an empty paragraph,
2620                                 //        but without that it would not be
2621                                 //        possible to set noindent below.
2622                                 //        Fortunately LaTeX does not care
2623                                 //        about the empty paragraph.
2624                                 context.new_paragraph(os);
2625                         }
2626                         if (h_paragraph_separation == "indent") {
2627                                 // we need to unindent, lest the line be too long
2628                                 context.add_par_extra_stuff("\\noindent\n");
2629                         }
2630                         context.check_layout(os);
2631                         begin_command_inset(os, "line", "rule");
2632                         os << "offset \"0.5ex\"\n"
2633                               "width \"100line%\"\n"
2634                               "height \"1pt\"\n";
2635                         end_inset(os);
2636                 }
2637
2638                 else if (t.cs() == "rule") {
2639                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2640                         string const width = p.getArg('{', '}');
2641                         string const thickness = p.getArg('{', '}');
2642                         context.check_layout(os);
2643                         begin_command_inset(os, "line", "rule");
2644                         if (!offset.empty())
2645                                 os << "offset \"" << translate_len(offset) << "\"\n";
2646                         os << "width \"" << translate_len(width) << "\"\n"
2647                                   "height \"" << translate_len(thickness) << "\"\n";
2648                         end_inset(os);
2649                 }
2650
2651                 else if (is_known(t.cs(), known_phrases) ||
2652                          (t.cs() == "protect" &&
2653                           p.next_token().cat() == catEscape &&
2654                           is_known(p.next_token().cs(), known_phrases))) {
2655                         // LyX sometimes puts a \protect in front, so we have to ignore it
2656                         // FIXME: This needs to be changed when bug 4752 is fixed.
2657                         char const * const * where = is_known(
2658                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2659                                 known_phrases);
2660                         context.check_layout(os);
2661                         os << known_coded_phrases[where - known_phrases];
2662                         skip_spaces_braces(p);
2663                 }
2664
2665                 else if (is_known(t.cs(), known_ref_commands)) {
2666                         string const opt = p.getOpt();
2667                         if (opt.empty()) {
2668                                 context.check_layout(os);
2669                                 char const * const * where = is_known(t.cs(),
2670                                         known_ref_commands);
2671                                 begin_command_inset(os, "ref",
2672                                         known_coded_ref_commands[where - known_ref_commands]);
2673                                 os << "reference \""
2674                                    << convert_command_inset_arg(p.verbatim_item())
2675                                    << "\"\n";
2676                                 end_inset(os);
2677                         } else {
2678                                 // LyX does not support optional arguments of ref commands
2679                                 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2680                                                p.verbatim_item() + "}", context);
2681                         }
2682                 }
2683
2684                 else if (use_natbib &&
2685                          is_known(t.cs(), known_natbib_commands) &&
2686                          ((t.cs() != "citefullauthor" &&
2687                            t.cs() != "citeyear" &&
2688                            t.cs() != "citeyearpar") ||
2689                           p.next_token().asInput() != "*")) {
2690                         context.check_layout(os);
2691                         string command = t.cs();
2692                         if (p.next_token().asInput() == "*") {
2693                                 command += '*';
2694                                 p.get_token();
2695                         }
2696                         if (command == "citefullauthor")
2697                                 // alternative name for "\\citeauthor*"
2698                                 command = "citeauthor*";
2699
2700                         // text before the citation
2701                         string before;
2702                         // text after the citation
2703                         string after;
2704                         get_cite_arguments(p, true, before, after);
2705
2706                         if (command == "cite") {
2707                                 // \cite without optional argument means
2708                                 // \citet, \cite with at least one optional
2709                                 // argument means \citep.
2710                                 if (before.empty() && after.empty())
2711                                         command = "citet";
2712                                 else
2713                                         command = "citep";
2714                         }
2715                         if (before.empty() && after == "[]")
2716                                 // avoid \citet[]{a}
2717                                 after.erase();
2718                         else if (before == "[]" && after == "[]") {
2719                                 // avoid \citet[][]{a}
2720                                 before.erase();
2721                                 after.erase();
2722                         }
2723                         // remove the brackets around after and before
2724                         if (!after.empty()) {
2725                                 after.erase(0, 1);
2726                                 after.erase(after.length() - 1, 1);
2727                                 after = convert_command_inset_arg(after);
2728                         }
2729                         if (!before.empty()) {
2730                                 before.erase(0, 1);
2731                                 before.erase(before.length() - 1, 1);
2732                                 before = convert_command_inset_arg(before);
2733                         }
2734                         begin_command_inset(os, "citation", command);
2735                         os << "after " << '"' << after << '"' << "\n";
2736                         os << "before " << '"' << before << '"' << "\n";
2737                         os << "key \""
2738                            << convert_command_inset_arg(p.verbatim_item())
2739                            << "\"\n";
2740                         end_inset(os);
2741                 }
2742
2743                 else if (use_jurabib &&
2744                          is_known(t.cs(), known_jurabib_commands) &&
2745                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2746                         context.check_layout(os);
2747                         string command = t.cs();
2748                         if (p.next_token().asInput() == "*") {
2749                                 command += '*';
2750                                 p.get_token();
2751                         }
2752                         char argumentOrder = '\0';
2753                         vector<string> const & options = used_packages["jurabib"];
2754                         if (find(options.begin(), options.end(),
2755                                       "natbiborder") != options.end())
2756                                 argumentOrder = 'n';
2757                         else if (find(options.begin(), options.end(),
2758                                            "jurabiborder") != options.end())
2759                                 argumentOrder = 'j';
2760
2761                         // text before the citation
2762                         string before;
2763                         // text after the citation
2764                         string after;
2765                         get_cite_arguments(p, argumentOrder != 'j', before, after);
2766
2767                         string const citation = p.verbatim_item();
2768                         if (!before.empty() && argumentOrder == '\0') {
2769                                 cerr << "Warning: Assuming argument order "
2770                                         "of jurabib version 0.6 for\n'"
2771                                      << command << before << after << '{'
2772                                      << citation << "}'.\n"
2773                                         "Add 'jurabiborder' to the jurabib "
2774                                         "package options if you used an\n"
2775                                         "earlier jurabib version." << endl;
2776                         }
2777                         if (!after.empty()) {
2778                                 after.erase(0, 1);
2779                                 after.erase(after.length() - 1, 1);
2780                         }
2781                         if (!before.empty()) {
2782                                 before.erase(0, 1);
2783                                 before.erase(before.length() - 1, 1);
2784                         }
2785                         begin_command_inset(os, "citation", command);
2786                         os << "after " << '"' << after << '"' << "\n";
2787                         os << "before " << '"' << before << '"' << "\n";
2788                         os << "key " << '"' << citation << '"' << "\n";
2789                         end_inset(os);
2790                 }
2791
2792                 else if (t.cs() == "cite"
2793                         || t.cs() == "nocite") {
2794                         context.check_layout(os);
2795                         string after = convert_command_inset_arg(p.getArg('[', ']'));
2796                         string key = convert_command_inset_arg(p.verbatim_item());
2797                         // store the case that it is "\nocite{*}" to use it later for
2798                         // the BibTeX inset
2799                         if (key != "*") {
2800                                 begin_command_inset(os, "citation", t.cs());
2801                                 os << "after " << '"' << after << '"' << "\n";
2802                                 os << "key " << '"' << key << '"' << "\n";
2803                                 end_inset(os);
2804                         } else if (t.cs() == "nocite")
2805                                 btprint = key;
2806                 }
2807
2808                 else if (t.cs() == "index") {
2809                         context.check_layout(os);
2810                         begin_inset(os, "Index idx\n");
2811                         os << "status collapsed\n";
2812                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2813                         end_inset(os);
2814                 }
2815
2816                 else if (t.cs() == "nomenclature") {
2817                         context.check_layout(os);
2818                         begin_command_inset(os, "nomenclature", "nomenclature");
2819                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2820                         if (!prefix.empty())
2821                                 os << "prefix " << '"' << prefix << '"' << "\n";
2822                         os << "symbol " << '"'
2823                            << convert_command_inset_arg(p.verbatim_item());
2824                         os << "\"\ndescription \""
2825                            << convert_command_inset_arg(p.verbatim_item())
2826                            << "\"\n";
2827                         end_inset(os);
2828                 }
2829                 
2830                 else if (t.cs() == "label") {
2831                         context.check_layout(os);
2832                         begin_command_inset(os, "label", "label");
2833                         os << "name \""
2834                            << convert_command_inset_arg(p.verbatim_item())
2835                            << "\"\n";
2836                         end_inset(os);
2837                 }
2838
2839                 else if (t.cs() == "printindex") {
2840                         context.check_layout(os);
2841                         begin_command_inset(os, "index_print", "printindex");
2842                         os << "type \"idx\"\n";
2843                         end_inset(os);
2844                         skip_spaces_braces(p);
2845                 }
2846
2847                 else if (t.cs() == "printnomenclature") {
2848                         string width = "";
2849                         string width_type = "";
2850                         context.check_layout(os);
2851                         begin_command_inset(os, "nomencl_print", "printnomenclature");
2852                         // case of a custom width
2853                         if (p.hasOpt()) {
2854                                 width = p.getArg('[', ']');
2855                                 width = translate_len(width);
2856                                 width_type = "custom";
2857                         }
2858                         // case of no custom width
2859                         // the case of no custom width but the width set
2860                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
2861                         // because the user could have set anything, not only the width
2862                         // of the longest label (which would be width_type = "auto")
2863                         string label = convert_command_inset_arg(p.getArg('{', '}'));
2864                         if (label.empty() && width_type.empty())
2865                                 width_type = "none";
2866                         os << "set_width \"" << width_type << "\"\n";
2867                         if (width_type == "custom")
2868                                 os << "width \"" << width << '\"';
2869                         end_inset(os);
2870                         skip_spaces_braces(p);
2871                 }
2872
2873                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2874                         context.check_layout(os);
2875                         begin_inset(os, "script ");
2876                         os << t.cs().substr(4) << '\n';
2877                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2878                         end_inset(os);
2879                 }
2880
2881                 else if (is_known(t.cs(), known_quotes)) {
2882                         char const * const * where = is_known(t.cs(), known_quotes);
2883                         context.check_layout(os);
2884                         begin_inset(os, "Quotes ");
2885                         os << known_coded_quotes[where - known_quotes];
2886                         end_inset(os);
2887                         // LyX adds {} after the quote, so we have to eat
2888                         // spaces here if there are any before a possible
2889                         // {} pair.
2890                         eat_whitespace(p, os, context, false);
2891                         skip_braces(p);
2892                 }
2893
2894                 else if (is_known(t.cs(), known_sizes) &&
2895                          context.new_layout_allowed) {
2896                         char const * const * where = is_known(t.cs(), known_sizes);
2897                         context.check_layout(os);
2898                         TeXFont const oldFont = context.font;
2899                         context.font.size = known_coded_sizes[where - known_sizes];
2900                         output_font_change(os, oldFont, context.font);
2901                         eat_whitespace(p, os, context, false);
2902                 }
2903
2904                 else if (is_known(t.cs(), known_font_families) &&
2905                          context.new_layout_allowed) {
2906                         char const * const * where =
2907                                 is_known(t.cs(), known_font_families);
2908                         context.check_layout(os);
2909                         TeXFont const oldFont = context.font;
2910                         context.font.family =
2911                                 known_coded_font_families[where - known_font_families];
2912                         output_font_change(os, oldFont, context.font);
2913                         eat_whitespace(p, os, context, false);
2914                 }
2915
2916                 else if (is_known(t.cs(), known_font_series) &&
2917                          context.new_layout_allowed) {
2918                         char const * const * where =
2919                                 is_known(t.cs(), known_font_series);
2920                         context.check_layout(os);
2921                         TeXFont const oldFont = context.font;
2922                         context.font.series =
2923                                 known_coded_font_series[where - known_font_series];
2924                         output_font_change(os, oldFont, context.font);
2925                         eat_whitespace(p, os, context, false);
2926                 }
2927
2928                 else if (is_known(t.cs(), known_font_shapes) &&
2929                          context.new_layout_allowed) {
2930                         char const * const * where =
2931                                 is_known(t.cs(), known_font_shapes);
2932                         context.check_layout(os);
2933                         TeXFont const oldFont = context.font;
2934                         context.font.shape =
2935                                 known_coded_font_shapes[where - known_font_shapes];
2936                         output_font_change(os, oldFont, context.font);
2937                         eat_whitespace(p, os, context, false);
2938                 }
2939                 else if (is_known(t.cs(), known_old_font_families) &&
2940                          context.new_layout_allowed) {
2941                         char const * const * where =
2942                                 is_known(t.cs(), known_old_font_families);
2943                         context.check_layout(os);
2944                         TeXFont const oldFont = context.font;
2945                         context.font.init();
2946                         context.font.size = oldFont.size;
2947                         context.font.family =
2948                                 known_coded_font_families[where - known_old_font_families];
2949                         output_font_change(os, oldFont, context.font);
2950                         eat_whitespace(p, os, context, false);
2951                 }
2952
2953                 else if (is_known(t.cs(), known_old_font_series) &&
2954                          context.new_layout_allowed) {
2955                         char const * const * where =
2956                                 is_known(t.cs(), known_old_font_series);
2957                         context.check_layout(os);
2958                         TeXFont const oldFont = context.font;
2959                         context.font.init();
2960                         context.font.size = oldFont.size;
2961                         context.font.series =
2962                                 known_coded_font_series[where - known_old_font_series];
2963                         output_font_change(os, oldFont, context.font);
2964                         eat_whitespace(p, os, context, false);
2965                 }
2966
2967                 else if (is_known(t.cs(), known_old_font_shapes) &&
2968                          context.new_layout_allowed) {
2969                         char const * const * where =
2970                                 is_known(t.cs(), known_old_font_shapes);
2971                         context.check_layout(os);
2972                         TeXFont const oldFont = context.font;
2973                         context.font.init();
2974                         context.font.size = oldFont.size;
2975                         context.font.shape =
2976                                 known_coded_font_shapes[where - known_old_font_shapes];
2977                         output_font_change(os, oldFont, context.font);
2978                         eat_whitespace(p, os, context, false);
2979                 }
2980
2981                 else if (t.cs() == "selectlanguage") {
2982                         context.check_layout(os);
2983                         // save the language for the case that a
2984                         // \foreignlanguage is used 
2985
2986                         context.font.language = babel2lyx(p.verbatim_item());
2987                         os << "\n\\lang " << context.font.language << "\n";
2988                 }
2989
2990                 else if (t.cs() == "foreignlanguage") {
2991                         string const lang = babel2lyx(p.verbatim_item());
2992                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2993                                               context, "\\lang",
2994                                               context.font.language, lang);
2995                 }
2996
2997                 else if (t.cs() == "inputencoding") {
2998                         // nothing to write here
2999                         string const enc = subst(p.verbatim_item(), "\n", " ");
3000                         p.setEncoding(enc);
3001                 }
3002
3003                 else if (t.cs() == "ldots") {
3004                         context.check_layout(os);
3005                         os << "\\SpecialChar \\ldots{}\n";
3006                         skip_spaces_braces(p);
3007                 }
3008
3009                 else if (t.cs() == "lyxarrow") {
3010                         context.check_layout(os);
3011                         os << "\\SpecialChar \\menuseparator\n";
3012                         skip_spaces_braces(p);
3013                 }
3014
3015                 else if (t.cs() == "textcompwordmark") {
3016                         context.check_layout(os);
3017                         os << "\\SpecialChar \\textcompwordmark{}\n";
3018                         skip_spaces_braces(p);
3019                 }
3020
3021                 else if (t.cs() == "slash") {
3022                         context.check_layout(os);
3023                         os << "\\SpecialChar \\slash{}\n";
3024                         skip_spaces_braces(p);
3025                 }
3026
3027                 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3028                         context.check_layout(os);
3029                         os << "\\SpecialChar \\nobreakdash-\n";
3030                         p.get_token();
3031                 }
3032
3033                 else if (t.cs() == "textquotedbl") {
3034                         context.check_layout(os);
3035                         os << "\"";
3036                         skip_braces(p);
3037                 }
3038
3039                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3040                         context.check_layout(os);
3041                         os << "\\SpecialChar \\@.\n";
3042                         p.get_token();
3043                 }
3044
3045                 else if (t.cs() == "-") {
3046                         context.check_layout(os);
3047                         os << "\\SpecialChar \\-\n";
3048                 }
3049
3050                 else if (t.cs() == "textasciitilde") {
3051                         context.check_layout(os);
3052                         os << '~';
3053                         skip_spaces_braces(p);
3054                 }
3055
3056                 else if (t.cs() == "textasciicircum") {
3057                         context.check_layout(os);
3058                         os << '^';
3059                         skip_spaces_braces(p);
3060                 }
3061
3062                 else if (t.cs() == "textbackslash") {
3063                         context.check_layout(os);
3064                         os << "\n\\backslash\n";
3065                         skip_spaces_braces(p);
3066                 }
3067
3068                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3069                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3070                             || t.cs() == "%") {
3071                         context.check_layout(os);
3072                         os << t.cs();
3073                 }
3074
3075                 else if (t.cs() == "char") {
3076                         context.check_layout(os);
3077                         if (p.next_token().character() == '`') {
3078                                 p.get_token();
3079                                 if (p.next_token().cs() == "\"") {
3080                                         p.get_token();
3081                                         os << '"';
3082                                         skip_braces(p);
3083                                 } else {
3084                                         handle_ert(os, "\\char`", context);
3085                                 }
3086                         } else {
3087                                 handle_ert(os, "\\char", context);
3088                         }
3089                 }
3090
3091                 else if (t.cs() == "verb") {
3092                         context.check_layout(os);
3093                         char const delimiter = p.next_token().character();
3094                         string const arg = p.getArg(delimiter, delimiter);
3095                         ostringstream oss;
3096                         oss << "\\verb" << delimiter << arg << delimiter;
3097                         handle_ert(os, oss.str(), context);
3098                 }
3099
3100                 // Problem: \= creates a tabstop inside the tabbing environment
3101                 // and else an accent. In the latter case we really would want
3102                 // \={o} instead of \= o.
3103                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3104                         handle_ert(os, t.asInput(), context);
3105
3106                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3107                 else if (t.cs().size() == 1 
3108                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3109                         context.check_layout(os);
3110                         // try to see whether the string is in unicodesymbols
3111                         docstring rem;
3112                         string command = t.asInput() + "{" 
3113                                 + trimSpaceAndEol(p.verbatim_item())
3114                                 + "}";
3115                         docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3116                         if (!s.empty()) {
3117                                 if (!rem.empty())
3118                                         cerr << "When parsing " << command 
3119                                              << ", result is " << to_utf8(s)
3120                                              << "+" << to_utf8(rem) << endl;
3121                                 os << to_utf8(s);
3122                         } else
3123                                 // we did not find a non-ert version
3124                                 handle_ert(os, command, context);
3125                 }
3126
3127                 else if (t.cs() == "\\") {
3128                         context.check_layout(os);
3129                         if (p.hasOpt())
3130                                 handle_ert(os, "\\\\" + p.getOpt(), context);
3131                         else if (p.next_token().asInput() == "*") {
3132                                 p.get_token();
3133                                 // getOpt() eats the following space if there
3134                                 // is no optional argument, but that is OK
3135                                 // here since it has no effect in the output.
3136                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
3137                         }
3138                         else {
3139                                 begin_inset(os, "Newline newline");
3140                                 end_inset(os);
3141                         }
3142                 }
3143
3144                 else if (t.cs() == "newline" ||
3145                          (t.cs() == "linebreak" && !p.hasOpt())) {
3146                         context.check_layout(os);
3147                         begin_inset(os, "Newline ");
3148                         os << t.cs();
3149                         end_inset(os);
3150                         skip_spaces_braces(p);
3151                 }
3152
3153                 else if (t.cs() == "input" || t.cs() == "include"
3154                          || t.cs() == "verbatiminput") {
3155                         string name = t.cs();
3156                         if (t.cs() == "verbatiminput"
3157                             && p.next_token().asInput() == "*")
3158                                 name += p.get_token().asInput();
3159                         context.check_layout(os);
3160                         string filename(normalize_filename(p.getArg('{', '}')));
3161                         string const path = getMasterFilePath();
3162                         // We want to preserve relative / absolute filenames,
3163                         // therefore path is only used for testing
3164                         if ((t.cs() == "include" || t.cs() == "input") &&
3165                             !makeAbsPath(filename, path).exists()) {
3166                                 // The file extension is probably missing.
3167                                 // Now try to find it out.
3168                                 string const tex_name =
3169                                         find_file(filename, path,
3170                                                   known_tex_extensions);
3171                                 if (!tex_name.empty())
3172                                         filename = tex_name;
3173                         }
3174                         bool external = false;
3175                         string outname;
3176                         if (makeAbsPath(filename, path).exists()) {
3177                                 string const abstexname =
3178                                         makeAbsPath(filename, path).absFileName();
3179                                 string const abslyxname =
3180                                         changeExtension(abstexname, ".lyx");
3181                                 string const absfigname =
3182                                         changeExtension(abstexname, ".fig");
3183                                 fix_relative_filename(filename);
3184                                 string const lyxname =
3185                                         changeExtension(filename, ".lyx");
3186                                 bool xfig = false;
3187                                 external = FileName(absfigname).exists();
3188                                 if (t.cs() == "input") {
3189                                         string const ext = getExtension(abstexname);
3190
3191                                         // Combined PS/LaTeX:
3192                                         // x.eps, x.pstex_t (old xfig)
3193                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3194                                         FileName const absepsname(
3195                                                 changeExtension(abstexname, ".eps"));
3196                                         FileName const abspstexname(
3197                                                 changeExtension(abstexname, ".pstex"));
3198                                         bool const xfigeps =
3199                                                 (absepsname.exists() ||
3200                                                  abspstexname.exists()) &&
3201                                                 ext == "pstex_t";
3202
3203                                         // Combined PDF/LaTeX:
3204                                         // x.pdf, x.pdftex_t (old xfig)
3205                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3206                                         FileName const abspdfname(
3207                                                 changeExtension(abstexname, ".pdf"));
3208                                         bool const xfigpdf =
3209                                                 abspdfname.exists() &&
3210                                                 (ext == "pdftex_t" || ext == "pdf_t");
3211                                         if (xfigpdf)
3212                                                 pdflatex = true;
3213
3214                                         // Combined PS/PDF/LaTeX:
3215                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3216                                         string const absbase2(
3217                                                 removeExtension(abstexname) + "_pspdftex");
3218                                         FileName const abseps2name(
3219                                                 addExtension(absbase2, ".eps"));
3220                                         FileName const abspdf2name(
3221                                                 addExtension(absbase2, ".pdf"));
3222                                         bool const xfigboth =
3223                                                 abspdf2name.exists() &&
3224                                                 abseps2name.exists() && ext == "pspdftex";
3225
3226                                         xfig = xfigpdf || xfigeps || xfigboth;
3227                                         external = external && xfig;
3228                                 }
3229                                 if (external) {
3230                                         outname = changeExtension(filename, ".fig");
3231                                 } else if (xfig) {
3232                                         // Don't try to convert, the result
3233                                         // would be full of ERT.
3234                                         outname = filename;
3235                                 } else if (t.cs() != "verbatiminput" &&
3236                                     tex2lyx(abstexname, FileName(abslyxname),
3237                                             p.getEncoding())) {
3238                                         outname = lyxname;
3239                                 } else {
3240                                         outname = filename;
3241                                 }
3242                         } else {
3243                                 cerr << "Warning: Could not find included file '"
3244                                      << filename << "'." << endl;
3245                                 outname = filename;
3246                         }
3247                         if (external) {
3248                                 begin_inset(os, "External\n");
3249                                 os << "\ttemplate XFig\n"
3250                                    << "\tfilename " << outname << '\n';
3251                         } else {
3252                                 begin_command_inset(os, "include", name);
3253                                 os << "preview false\n"
3254                                       "filename \"" << outname << "\"\n";
3255                         }
3256                         end_inset(os);
3257                 }
3258
3259                 else if (t.cs() == "bibliographystyle") {
3260                         // store new bibliographystyle
3261                         bibliographystyle = p.verbatim_item();
3262                         // If any other command than \bibliography and
3263                         // \nocite{*} follows, we need to output the style
3264                         // (because it might be used by that command).
3265                         // Otherwise, it will automatically be output by LyX.
3266                         p.pushPosition();
3267                         bool output = true;
3268                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3269                                 if (t2.cat() == catBegin)
3270                                         break;
3271                                 if (t2.cat() != catEscape)
3272                                         continue;
3273                                 if (t2.cs() == "nocite") {
3274                                         if (p.getArg('{', '}') == "*")
3275                                                 continue;
3276                                 } else if (t2.cs() == "bibliography")
3277                                         output = false;
3278                                 break;
3279                         }
3280                         p.popPosition();
3281                         if (output) {
3282                                 handle_ert(os,
3283                                         "\\bibliographystyle{" + bibliographystyle + '}',
3284                                         context);
3285                         }
3286                 }
3287
3288                 else if (t.cs() == "bibliography") {
3289                         context.check_layout(os);
3290                         begin_command_inset(os, "bibtex", "bibtex");
3291                         if (!btprint.empty()) {
3292                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3293                                 // clear the string because the next BibTeX inset can be without the
3294                                 // \nocite{*} option
3295                                 btprint.clear();
3296                         }
3297                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3298                         // Do we have a bibliographystyle set?
3299                         if (!bibliographystyle.empty())
3300                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
3301                         end_inset(os);
3302                 }
3303
3304                 else if (t.cs() == "parbox")
3305                         parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3306
3307                 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3308                          t.cs() == "shadowbox" || t.cs() == "doublebox")
3309                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3310
3311                 else if (t.cs() == "framebox") {
3312                         string special = p.getFullOpt();
3313                         special += p.getOpt();
3314                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3315                 }
3316
3317                 //\makebox() is part of the picture environment and different from \makebox{}
3318                 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3319                 else if (t.cs() == "makebox") {
3320                         string arg = t.asInput();
3321                         if (p.next_token().character() == '(')
3322                                 //the syntax is: \makebox(x,y)[position]{content}
3323                                 arg += p.getFullParentheseArg();
3324                         else
3325                                 //the syntax is: \makebox[width][position]{content}
3326                                 arg += p.getFullOpt();
3327                         handle_ert(os, arg + p.getFullOpt(), context);
3328                 }
3329
3330                 else if (t.cs() == "smallskip" ||
3331                          t.cs() == "medskip" ||
3332                          t.cs() == "bigskip" ||
3333                          t.cs() == "vfill") {
3334                         context.check_layout(os);
3335                         begin_inset(os, "VSpace ");
3336                         os << t.cs();
3337                         end_inset(os);
3338                         skip_spaces_braces(p);
3339                 }
3340
3341                 else if (is_known(t.cs(), known_spaces)) {
3342                         char const * const * where = is_known(t.cs(), known_spaces);
3343                         context.check_layout(os);
3344                         begin_inset(os, "space ");
3345                         os << '\\' << known_coded_spaces[where - known_spaces]
3346                            << '\n';
3347                         end_inset(os);
3348                         // LaTeX swallows whitespace after all spaces except
3349                         // "\\,". We have to do that here, too, because LyX
3350                         // adds "{}" which would make the spaces significant.
3351                         if (t.cs() !=  ",")
3352                                 eat_whitespace(p, os, context, false);
3353                         // LyX adds "{}" after all spaces except "\\ " and
3354                         // "\\,", so we have to remove "{}".
3355                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
3356                         // remove the braces after "\\,", too.
3357                         if (t.cs() != " ")
3358                                 skip_braces(p);
3359                 }
3360
3361                 else if (t.cs() == "newpage" ||
3362                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
3363                          t.cs() == "clearpage" ||
3364                          t.cs() == "cleardoublepage") {
3365                         context.check_layout(os);
3366                         begin_inset(os, "Newpage ");
3367                         os << t.cs();
3368                         end_inset(os);
3369                         skip_spaces_braces(p);
3370                 }
3371
3372                 else if (t.cs() == "DeclareRobustCommand" ||
3373                          t.cs() == "DeclareRobustCommandx" ||
3374                          t.cs() == "newcommand" ||
3375                          t.cs() == "newcommandx" ||
3376                          t.cs() == "providecommand" ||
3377                          t.cs() == "providecommandx" ||
3378                          t.cs() == "renewcommand" ||
3379                          t.cs() == "renewcommandx") {
3380                         // DeclareRobustCommand, DeclareRobustCommandx,
3381                         // providecommand and providecommandx could be handled
3382                         // by parse_command(), but we need to call
3383                         // add_known_command() here.
3384                         string name = t.asInput();
3385                         if (p.next_token().asInput() == "*") {
3386                                 // Starred form. Eat '*'
3387                                 p.get_token();
3388                                 name += '*';
3389                         }
3390                         string const command = p.verbatim_item();
3391                         string const opt1 = p.getFullOpt();
3392                         string const opt2 = p.getFullOpt();
3393                         add_known_command(command, opt1, !opt2.empty());
3394                         string const ert = name + '{' + command + '}' +
3395                                            opt1 + opt2 +
3396                                            '{' + p.verbatim_item() + '}';
3397
3398                         if (t.cs() == "DeclareRobustCommand" ||
3399                             t.cs() == "DeclareRobustCommandx" ||
3400                             t.cs() == "providecommand" ||
3401                             t.cs() == "providecommandx" ||
3402                             name[name.length()-1] == '*')
3403                                 handle_ert(os, ert, context);
3404                         else {
3405                                 context.check_layout(os);
3406                                 begin_inset(os, "FormulaMacro");
3407                                 os << "\n" << ert;
3408                                 end_inset(os);
3409                         }
3410                 }
3411
3412                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3413                         // let could be handled by parse_command(),
3414                         // but we need to call add_known_command() here.
3415                         string ert = t.asInput();
3416                         string name;
3417                         p.skip_spaces();
3418                         if (p.next_token().cat() == catBegin) {
3419                                 name = p.verbatim_item();
3420                                 ert += '{' + name + '}';
3421                         } else {
3422                                 name = p.verbatim_item();
3423                                 ert += name;
3424                         }
3425                         string command;
3426                         p.skip_spaces();
3427                         if (p.next_token().cat() == catBegin) {
3428                                 command = p.verbatim_item();
3429                                 ert += '{' + command + '}';
3430                         } else {
3431                                 command = p.verbatim_item();
3432                                 ert += command;
3433                         }
3434                         // If command is known, make name known too, to parse
3435                         // its arguments correctly. For this reason we also
3436                         // have commands in syntax.default that are hardcoded.
3437                         CommandMap::iterator it = known_commands.find(command);
3438                         if (it != known_commands.end())
3439                                 known_commands[t.asInput()] = it->second;
3440                         handle_ert(os, ert, context);
3441                 }
3442
3443                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3444                         bool starred = false;
3445                         if (p.next_token().asInput() == "*") {
3446                                 p.get_token();
3447                                 starred = true;
3448                         }
3449                         string name = t.asInput();
3450                         string const length = p.verbatim_item();
3451                         string unit;
3452                         string valstring;
3453                         bool valid = splitLatexLength(length, valstring, unit);
3454                         bool known_hspace = false;
3455                         bool known_vspace = false;
3456                         bool known_unit = false;
3457                         double value;
3458                         if (valid) {
3459                                 istringstream iss(valstring);
3460                                 iss >> value;
3461                                 if (value == 1.0) {
3462                                         if (t.cs()[0] == 'h') {
3463                                                 if (unit == "\\fill") {
3464                                                         if (!starred) {
3465                                                                 unit = "";
3466                                                                 name = "\\hfill";
3467                                                         }
3468                                                         known_hspace = true;
3469                                                 }
3470                                         } else {
3471                                                 if (unit == "\\smallskipamount") {
3472                                                         unit = "smallskip";
3473                                                         known_vspace = true;
3474                                                 } else if (unit == "\\medskipamount") {
3475                                                         unit = "medskip";
3476                                                         known_vspace = true;
3477                                                 } else if (unit == "\\bigskipamount") {
3478                                                         unit = "bigskip";
3479                                                         known_vspace = true;
3480                                                 } else if (unit == "\\fill") {
3481                                                         unit = "vfill";
3482                                                         known_vspace = true;
3483                                                 }
3484                                         }
3485                                 }
3486                                 if (!known_hspace && !known_vspace) {
3487                                         switch (unitFromString(unit)) {
3488                                         case Length::SP:
3489                                         case Length::PT:
3490                                         case Length::BP:
3491                                         case Length::DD:
3492                                         case Length::MM:
3493                                         case Length::PC:
3494                                         case Length::CC:
3495                                         case Length::CM:
3496                                         case Length::IN:
3497                                         case Length::EX:
3498                                         case Length::EM:
3499                                         case Length::MU:
3500                                                 known_unit = true;
3501                                                 break;
3502                                         default:
3503                                                 break;
3504                                         }
3505                                 }
3506                         }
3507
3508                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3509                                 // Literal horizontal length or known variable
3510                                 context.check_layout(os);
3511                                 begin_inset(os, "space ");
3512                                 os << name;
3513                                 if (starred)
3514                                         os << '*';
3515                                 os << '{';
3516                                 if (known_hspace)
3517                                         os << unit;
3518                                 os << "}";
3519                                 if (known_unit && !known_hspace)
3520                                         os << "\n\\length "
3521                                            << translate_len(length);
3522                                 end_inset(os);
3523                         } else if (known_unit || known_vspace) {
3524                                 // Literal vertical length or known variable
3525                                 context.check_layout(os);
3526                                 begin_inset(os, "VSpace ");
3527                                 if (known_unit)
3528                                         os << value;
3529                                 os << unit;
3530                                 if (starred)
3531                                         os << '*';
3532                                 end_inset(os);
3533                         } else {
3534                                 // LyX can't handle other length variables in Inset VSpace/space
3535                                 if (starred)
3536                                         name += '*';
3537                                 if (valid) {
3538                                         if (value == 1.0)
3539                                                 handle_ert(os, name + '{' + unit + '}', context);
3540                                         else if (value == -1.0)
3541                                                 handle_ert(os, name + "{-" + unit + '}', context);
3542                                         else
3543                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
3544                                 } else
3545                                         handle_ert(os, name + '{' + length + '}', context);
3546                         }
3547                 }
3548
3549                 // The single '=' is meant here.
3550                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3551                         p.skip_spaces();
3552                         context.check_layout(os);
3553                         begin_inset(os, "Flex ");
3554                         os << to_utf8(newinsetlayout->name()) << '\n'
3555                            << "status collapsed\n";
3556                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3557                         end_inset(os);
3558                 }
3559
3560                 else {
3561                         // try to see whether the string is in unicodesymbols
3562                         // Only use text mode commands, since we are in text mode here,
3563                         // and math commands may be invalid (bug 6797)
3564                         docstring rem;
3565                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3566                                                                  rem, Encodings::TEXT_CMD);
3567                         if (!s.empty()) {
3568                                 if (!rem.empty())
3569                                         cerr << "When parsing " << t.cs() 
3570                                              << ", result is " << to_utf8(s)
3571                                              << "+" << to_utf8(rem) << endl;
3572                                 context.check_layout(os);
3573                                 os << to_utf8(s);
3574                                 skip_spaces_braces(p);
3575                         }
3576                         //cerr << "#: " << t << " mode: " << mode << endl;
3577                         // heuristic: read up to next non-nested space
3578                         /*
3579                         string s = t.asInput();
3580                         string z = p.verbatim_item();
3581                         while (p.good() && z != " " && z.size()) {
3582                                 //cerr << "read: " << z << endl;
3583                                 s += z;
3584                                 z = p.verbatim_item();
3585                         }
3586                         cerr << "found ERT: " << s << endl;
3587                         handle_ert(os, s + ' ', context);
3588                         */
3589                         else {
3590                                 string name = t.asInput();
3591                                 if (p.next_token().asInput() == "*") {
3592                                         // Starred commands like \vspace*{}
3593                                         p.get_token();  // Eat '*'
3594                                         name += '*';
3595                                 }
3596                                 if (!parse_command(name, p, os, outer, context))
3597                                         handle_ert(os, name, context);
3598                         }
3599                 }
3600
3601                 if (flags & FLAG_LEAVE) {
3602                         flags &= ~FLAG_LEAVE;
3603                         break;
3604                 }
3605         }
3606 }
3607
3608 // }])
3609
3610
3611 } // namespace lyx