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