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