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