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