]> git.lyx.org Git - features.git/blob - src/tex2lyx/text.cpp
Respect the encoding passed to tex2lyx on the command line.
[features.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, Encoding::CJK);
1469                 else {
1470                         // FIXME: This will read garbage, since the data is not encoded in utf8.
1471                         p.setEncoding("UTF-8");
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                    << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2222                    << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2223                    << " The iconv encoding " << p.getEncoding() << " was used.\n"
2224                    << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2225                    << " and specify the encoding using the -e command-line switch.\n"
2226                    << " In addition, you might want to double check that the desired output encoding\n"
2227                    << " is correctly selected in Document > Settings > Language.\n"
2228                    << "\\end_layout\n";
2229                 end_inset(os);
2230                 is_nonCJKJapanese = false;
2231         }
2232
2233 #ifdef FILEDEBUG
2234                 debugToken(cerr, t, flags);
2235 #endif
2236
2237                 if (flags & FLAG_ITEM) {
2238                         if (t.cat() == catSpace)
2239                                 continue;
2240
2241                         flags &= ~FLAG_ITEM;
2242                         if (t.cat() == catBegin) {
2243                                 // skip the brace and collect everything to the next matching
2244                                 // closing brace
2245                                 flags |= FLAG_BRACE_LAST;
2246                                 continue;
2247                         }
2248
2249                         // handle only this single token, leave the loop if done
2250                         flags |= FLAG_LEAVE;
2251                 }
2252
2253                 if (t.cat() != catEscape && t.character() == ']' &&
2254                     (flags & FLAG_BRACK_LAST))
2255                         return;
2256                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2257                         return;
2258
2259                 // If there is anything between \end{env} and \begin{env} we
2260                 // don't need to output a separator.
2261                 if (t.cat() != catSpace && t.cat() != catNewline &&
2262                     t.asInput() != "\\begin")
2263                         last_env = "";
2264
2265                 //
2266                 // cat codes
2267                 //
2268                 if (t.cat() == catMath) {
2269                         // we are inside some text mode thingy, so opening new math is allowed
2270                         context.check_layout(os);
2271                         begin_inset(os, "Formula ");
2272                         Token const & n = p.get_token();
2273                         bool const display(n.cat() == catMath && outer);
2274                         if (display) {
2275                                 // TeX's $$...$$ syntax for displayed math
2276                                 os << "\\[";
2277                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2278                                 os << "\\]";
2279                                 p.get_token(); // skip the second '$' token
2280                         } else {
2281                                 // simple $...$  stuff
2282                                 p.putback();
2283                                 os << '$';
2284                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2285                                 os << '$';
2286                         }
2287                         end_inset(os);
2288                         if (display) {
2289                                 // Prevent the conversion of a line break to a
2290                                 // space (bug 7668). This does not change the
2291                                 // output, but looks ugly in LyX.
2292                                 eat_whitespace(p, os, context, false);
2293                         }
2294                 }
2295
2296                 else if (t.cat() == catSuper || t.cat() == catSub)
2297                         cerr << "catcode " << t << " illegal in text mode\n";
2298
2299                 // Basic support for english quotes. This should be
2300                 // extended to other quotes, but is not so easy (a
2301                 // left english quote is the same as a right german
2302                 // quote...)
2303                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2304                         context.check_layout(os);
2305                         begin_inset(os, "Quotes ");
2306                         os << "eld";
2307                         end_inset(os);
2308                         p.get_token();
2309                         skip_braces(p);
2310                 }
2311                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2312                         context.check_layout(os);
2313                         begin_inset(os, "Quotes ");
2314                         os << "erd";
2315                         end_inset(os);
2316                         p.get_token();
2317                         skip_braces(p);
2318                 }
2319
2320                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2321                         context.check_layout(os);
2322                         begin_inset(os, "Quotes ");
2323                         os << "ald";
2324                         end_inset(os);
2325                         p.get_token();
2326                         skip_braces(p);
2327                 }
2328
2329                 else if (t.asInput() == "<"
2330                          && p.next_token().asInput() == "<" && noweb_mode) {
2331                         p.get_token();
2332                         parse_noweb(p, os, context);
2333                 }
2334
2335                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2336                         context.check_layout(os);
2337                         begin_inset(os, "Quotes ");
2338                         os << "ard";
2339                         end_inset(os);
2340                         p.get_token();
2341                         skip_braces(p);
2342                 }
2343
2344                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2345                         check_space(p, os, context);
2346
2347                 else if (t.character() == '[' && noweb_mode &&
2348                          p.next_token().character() == '[') {
2349                         // These can contain underscores
2350                         p.putback();
2351                         string const s = p.getFullOpt() + ']';
2352                         if (p.next_token().character() == ']')
2353                                 p.get_token();
2354                         else
2355                                 cerr << "Warning: Inserting missing ']' in '"
2356                                      << s << "'." << endl;
2357                         handle_ert(os, s, context);
2358                 }
2359
2360                 else if (t.cat() == catLetter) {
2361                         context.check_layout(os);
2362                         // Workaround for bug 4752.
2363                         // FIXME: This whole code block needs to be removed
2364                         //        when the bug is fixed and tex2lyx produces
2365                         //        the updated file format.
2366                         // The replacement algorithm in LyX is so stupid that
2367                         // it even translates a phrase if it is part of a word.
2368                         bool handled = false;
2369                         for (int const * l = known_phrase_lengths; *l; ++l) {
2370                                 string phrase = t.cs();
2371                                 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2372                                         phrase += p.get_token().cs();
2373                                 if (is_known(phrase, known_coded_phrases)) {
2374                                         handle_ert(os, phrase, context);
2375                                         handled = true;
2376                                         break;
2377                                 } else {
2378                                         for (size_t i = 1; i < phrase.length(); ++i)
2379                                                 p.putback();
2380                                 }
2381                         }
2382                         if (!handled)
2383                                 os << t.cs();
2384                 }
2385
2386                 else if (t.cat() == catOther ||
2387                                t.cat() == catAlign ||
2388                                t.cat() == catParameter) {
2389                         // This translates "&" to "\\&" which may be wrong...
2390                         context.check_layout(os);
2391                         os << t.cs();
2392                 }
2393
2394                 else if (p.isParagraph()) {
2395                         if (context.new_layout_allowed)
2396                                 context.new_paragraph(os);
2397                         else
2398                                 handle_ert(os, "\\par ", context);
2399                         eat_whitespace(p, os, context, true);
2400                 }
2401
2402                 else if (t.cat() == catActive) {
2403                         context.check_layout(os);
2404                         if (t.character() == '~') {
2405                                 if (context.layout->free_spacing)
2406                                         os << ' ';
2407                                 else {
2408                                         begin_inset(os, "space ~\n");
2409                                         end_inset(os);
2410                                 }
2411                         } else
2412                                 os << t.cs();
2413                 }
2414
2415                 else if (t.cat() == catBegin) {
2416                         Token const next = p.next_token();
2417                         Token const end = p.next_next_token();
2418                         if (next.cat() == catEnd) {
2419                         // {}
2420                         Token const prev = p.prev_token();
2421                         p.get_token();
2422                         if (p.next_token().character() == '`' ||
2423                             (prev.character() == '-' &&
2424                              p.next_token().character() == '-'))
2425                                 ; // ignore it in {}`` or -{}-
2426                         else
2427                                 handle_ert(os, "{}", context);
2428                         } else if (next.cat() == catEscape &&
2429                                    is_known(next.cs(), known_quotes) &&
2430                                    end.cat() == catEnd) {
2431                                 // Something like {\textquoteright} (e.g.
2432                                 // from writer2latex). LyX writes
2433                                 // \textquoteright{}, so we may skip the
2434                                 // braces here for better readability.
2435                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2436                                                    outer, context);
2437                         } else {
2438                         context.check_layout(os);
2439                         // special handling of font attribute changes
2440                         Token const prev = p.prev_token();
2441                         TeXFont const oldFont = context.font;
2442                         if (next.character() == '[' ||
2443                             next.character() == ']' ||
2444                             next.character() == '*') {
2445                                 p.get_token();
2446                                 if (p.next_token().cat() == catEnd) {
2447                                         os << next.cs();
2448                                         p.get_token();
2449                                 } else {
2450                                         p.putback();
2451                                         handle_ert(os, "{", context);
2452                                         parse_text_snippet(p, os,
2453                                                         FLAG_BRACE_LAST,
2454                                                         outer, context);
2455                                         handle_ert(os, "}", context);
2456                                 }
2457                         } else if (! context.new_layout_allowed) {
2458                                 handle_ert(os, "{", context);
2459                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2460                                                    outer, context);
2461                                 handle_ert(os, "}", context);
2462                         } else if (is_known(next.cs(), known_sizes)) {
2463                                 // next will change the size, so we must
2464                                 // reset it here
2465                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2466                                                    outer, context);
2467                                 if (!context.atParagraphStart())
2468                                         os << "\n\\size "
2469                                            << context.font.size << "\n";
2470                         } else if (is_known(next.cs(), known_font_families)) {
2471                                 // next will change the font family, so we
2472                                 // must reset it here
2473                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2474                                                    outer, context);
2475                                 if (!context.atParagraphStart())
2476                                         os << "\n\\family "
2477                                            << context.font.family << "\n";
2478                         } else if (is_known(next.cs(), known_font_series)) {
2479                                 // next will change the font series, so we
2480                                 // must reset it here
2481                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2482                                                    outer, context);
2483                                 if (!context.atParagraphStart())
2484                                         os << "\n\\series "
2485                                            << context.font.series << "\n";
2486                         } else if (is_known(next.cs(), known_font_shapes)) {
2487                                 // next will change the font shape, so we
2488                                 // must reset it here
2489                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2490                                                    outer, context);
2491                                 if (!context.atParagraphStart())
2492                                         os << "\n\\shape "
2493                                            << context.font.shape << "\n";
2494                         } else if (is_known(next.cs(), known_old_font_families) ||
2495                                    is_known(next.cs(), known_old_font_series) ||
2496                                    is_known(next.cs(), known_old_font_shapes)) {
2497                                 // next will change the font family, series
2498                                 // and shape, so we must reset it here
2499                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2500                                                    outer, context);
2501                                 if (!context.atParagraphStart())
2502                                         os <<  "\n\\family "
2503                                            << context.font.family
2504                                            << "\n\\series "
2505                                            << context.font.series
2506                                            << "\n\\shape "
2507                                            << context.font.shape << "\n";
2508                         } else {
2509                                 handle_ert(os, "{", context);
2510                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2511                                                    outer, context);
2512                                 handle_ert(os, "}", context);
2513                                 }
2514                         }
2515                 }
2516
2517                 else if (t.cat() == catEnd) {
2518                         if (flags & FLAG_BRACE_LAST) {
2519                                 return;
2520                         }
2521                         cerr << "stray '}' in text\n";
2522                         handle_ert(os, "}", context);
2523                 }
2524
2525                 else if (t.cat() == catComment)
2526                         parse_comment(p, os, t, context);
2527
2528                 //
2529                 // control sequences
2530                 //
2531
2532                 else if (t.cs() == "(") {
2533                         context.check_layout(os);
2534                         begin_inset(os, "Formula");
2535                         os << " \\(";
2536                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2537                         os << "\\)";
2538                         end_inset(os);
2539                 }
2540
2541                 else if (t.cs() == "[") {
2542                         context.check_layout(os);
2543                         begin_inset(os, "Formula");
2544                         os << " \\[";
2545                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2546                         os << "\\]";
2547                         end_inset(os);
2548                         // Prevent the conversion of a line break to a space
2549                         // (bug 7668). This does not change the output, but
2550                         // looks ugly in LyX.
2551                         eat_whitespace(p, os, context, false);
2552                 }
2553
2554                 else if (t.cs() == "begin")
2555                         parse_environment(p, os, outer, last_env,
2556                                           context);
2557
2558                 else if (t.cs() == "end") {
2559                         if (flags & FLAG_END) {
2560                                 // eat environment name
2561                                 string const name = p.getArg('{', '}');
2562                                 if (name != active_environment())
2563                                         cerr << "\\end{" + name + "} does not match \\begin{"
2564                                                 + active_environment() + "}\n";
2565                                 return;
2566                         }
2567                         p.error("found 'end' unexpectedly");
2568                 }
2569
2570                 else if (t.cs() == "item") {
2571                         string s;
2572                         bool const optarg = p.hasOpt();
2573                         if (optarg) {
2574                                 // FIXME: This swallows comments, but we cannot use
2575                                 //        eat_whitespace() since we must not output
2576                                 //        anything before the item.
2577                                 p.skip_spaces(true);
2578                                 s = p.verbatimOption();
2579                         } else
2580                                 p.skip_spaces(false);
2581                         context.set_item();
2582                         context.check_layout(os);
2583                         if (context.has_item) {
2584                                 // An item in an unknown list-like environment
2585                                 // FIXME: Do this in check_layout()!
2586                                 context.has_item = false;
2587                                 if (optarg)
2588                                         handle_ert(os, "\\item", context);
2589                                 else
2590                                         handle_ert(os, "\\item ", context);
2591                         }
2592                         if (optarg) {
2593                                 if (context.layout->labeltype != LABEL_MANUAL) {
2594                                         // LyX does not support \item[\mybullet]
2595                                         // in itemize environments
2596                                         Parser p2(s + ']');
2597                                         os << parse_text_snippet(p2,
2598                                                 FLAG_BRACK_LAST, outer, context);
2599                                 } else if (!s.empty()) {
2600                                         // LyX adds braces around the argument,
2601                                         // so we need to remove them here.
2602                                         if (s.size() > 2 && s[0] == '{' &&
2603                                             s[s.size()-1] == '}')
2604                                                 s = s.substr(1, s.size()-2);
2605                                         // If the argument contains a space we
2606                                         // must put it into ERT: Otherwise LyX
2607                                         // would misinterpret the space as
2608                                         // item delimiter (bug 7663)
2609                                         if (contains(s, ' ')) {
2610                                                 handle_ert(os, s, context);
2611                                         } else {
2612                                                 Parser p2(s + ']');
2613                                                 os << parse_text_snippet(p2,
2614                                                         FLAG_BRACK_LAST,
2615                                                         outer, context);
2616                                         }
2617                                         // The space is needed to separate the
2618                                         // item from the rest of the sentence.
2619                                         os << ' ';
2620                                         eat_whitespace(p, os, context, false);
2621                                 }
2622                         }
2623                 }
2624
2625                 else if (t.cs() == "bibitem") {
2626                         context.set_item();
2627                         context.check_layout(os);
2628                         eat_whitespace(p, os, context, false);
2629                         string label = convert_command_inset_arg(p.verbatimOption());
2630                         string key = convert_command_inset_arg(p.verbatim_item());
2631                         if (contains(label, '\\') || contains(key, '\\')) {
2632                                 // LyX can't handle LaTeX commands in labels or keys
2633                                 handle_ert(os, t.asInput() + '[' + label +
2634                                                "]{" + p.verbatim_item() + '}',
2635                                            context);
2636                         } else {
2637                                 begin_command_inset(os, "bibitem", "bibitem");
2638                                 os << "label \"" << label << "\"\n"
2639                                       "key \"" << key << "\"\n";
2640                                 end_inset(os);
2641                         }
2642                 }
2643
2644                 else if (is_macro(p)) {
2645                         // catch the case of \def\inputGnumericTable
2646                         bool macro = true;
2647                         if (t.cs() == "def") {
2648                                 Token second = p.next_token();
2649                                 if (second.cs() == "inputGnumericTable") {
2650                                         p.pushPosition();
2651                                         p.get_token();
2652                                         skip_braces(p);
2653                                         Token third = p.get_token();
2654                                         p.popPosition();
2655                                         if (third.cs() == "input") {
2656                                                 p.get_token();
2657                                                 skip_braces(p);
2658                                                 p.get_token();
2659                                                 string name = normalize_filename(p.verbatim_item());
2660                                                 string const path = getMasterFilePath(true);
2661                                                 // We want to preserve relative / absolute filenames,
2662                                                 // therefore path is only used for testing
2663                                                 // The file extension is in every case ".tex".
2664                                                 // So we need to remove this extension and check for
2665                                                 // the original one.
2666                                                 name = removeExtension(name);
2667                                                 if (!makeAbsPath(name, path).exists()) {
2668                                                         char const * const Gnumeric_formats[] = {"gnumeric",
2669                                                                 "ods", "xls", 0};
2670                                                         string const Gnumeric_name =
2671                                                                 find_file(name, path, Gnumeric_formats);
2672                                                         if (!Gnumeric_name.empty())
2673                                                                 name = Gnumeric_name;
2674                                                 }
2675                                                 FileName const absname = makeAbsPath(name, path);
2676                                                 if (absname.exists()) {
2677                                                         fix_child_filename(name);
2678                                                         copy_file(absname, name);
2679                                                 } else
2680                                                         cerr << "Warning: Could not find file '"
2681                                                              << name << "'." << endl;
2682                                                 context.check_layout(os);
2683                                                 begin_inset(os, "External\n\ttemplate ");
2684                                                 os << "GnumericSpreadsheet\n\tfilename "
2685                                                    << name << "\n";
2686                                                 end_inset(os);
2687                                                 context.check_layout(os);
2688                                                 macro = false;
2689                                                 // register the packages that are automatically loaded
2690                                                 // by the Gnumeric template
2691                                                 registerExternalTemplatePackages("GnumericSpreadsheet");
2692                                         }
2693                                 }
2694                         }
2695                         if (macro)
2696                                 parse_macro(p, os, context);
2697                 }
2698
2699                 else if (t.cs() == "noindent") {
2700                         p.skip_spaces();
2701                         context.add_par_extra_stuff("\\noindent\n");
2702                 }
2703
2704                 else if (t.cs() == "appendix") {
2705                         context.add_par_extra_stuff("\\start_of_appendix\n");
2706                         // We need to start a new paragraph. Otherwise the
2707                         // appendix in 'bla\appendix\chapter{' would start
2708                         // too late.
2709                         context.new_paragraph(os);
2710                         // We need to make sure that the paragraph is
2711                         // generated even if it is empty. Otherwise the
2712                         // appendix in '\par\appendix\par\chapter{' would
2713                         // start too late.
2714                         context.check_layout(os);
2715                         // FIXME: This is a hack to prevent paragraph
2716                         // deletion if it is empty. Handle this better!
2717                         handle_comment(os,
2718                                 "%dummy comment inserted by tex2lyx to "
2719                                 "ensure that this paragraph is not empty",
2720                                 context);
2721                         // Both measures above may generate an additional
2722                         // empty paragraph, but that does not hurt, because
2723                         // whitespace does not matter here.
2724                         eat_whitespace(p, os, context, true);
2725                 }
2726
2727                 // Must catch empty dates before findLayout is called below
2728                 else if (t.cs() == "date") {
2729                         eat_whitespace(p, os, context, false);
2730                         p.pushPosition();
2731                         string const date = p.verbatim_item();
2732                         p.popPosition();
2733                         if (date.empty()) {
2734                                 preamble.suppressDate(true);
2735                                 p.verbatim_item();
2736                         } else {
2737                                 preamble.suppressDate(false);
2738                                 if (context.new_layout_allowed &&
2739                                     (newlayout = findLayout(context.textclass,
2740                                                             t.cs(), true))) {
2741                                         // write the layout
2742                                         output_command_layout(os, p, outer,
2743                                                         context, newlayout);
2744                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2745                                         if (!preamble.titleLayoutFound())
2746                                                 preamble.titleLayoutFound(newlayout->intitle);
2747                                         set<string> const & req = newlayout->requires();
2748                                         set<string>::const_iterator it = req.begin();
2749                                         set<string>::const_iterator en = req.end();
2750                                         for (; it != en; ++it)
2751                                                 preamble.registerAutomaticallyLoadedPackage(*it);
2752                                 } else
2753                                         handle_ert(os,
2754                                                 "\\date{" + p.verbatim_item() + '}',
2755                                                 context);
2756                         }
2757                 }
2758
2759                 // Starred section headings
2760                 // Must attempt to parse "Section*" before "Section".
2761                 else if ((p.next_token().asInput() == "*") &&
2762                          context.new_layout_allowed &&
2763                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2764                         // write the layout
2765                         p.get_token();
2766                         output_command_layout(os, p, outer, context, newlayout);
2767                         p.skip_spaces();
2768                         if (!preamble.titleLayoutFound())
2769                                 preamble.titleLayoutFound(newlayout->intitle);
2770                         set<string> const & req = newlayout->requires();
2771                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2772                                 preamble.registerAutomaticallyLoadedPackage(*it);
2773                 }
2774
2775                 // Section headings and the like
2776                 else if (context.new_layout_allowed &&
2777                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2778                         // write the layout
2779                         output_command_layout(os, p, outer, context, newlayout);
2780                         p.skip_spaces();
2781                         if (!preamble.titleLayoutFound())
2782                                 preamble.titleLayoutFound(newlayout->intitle);
2783                         set<string> const & req = newlayout->requires();
2784                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2785                                 preamble.registerAutomaticallyLoadedPackage(*it);
2786                 }
2787
2788                 else if (t.cs() == "caption") {
2789                         p.skip_spaces();
2790                         context.check_layout(os);
2791                         p.skip_spaces();
2792                         begin_inset(os, "Caption Standard\n");
2793                         Context newcontext(true, context.textclass, 0, 0, context.font);
2794                         newcontext.check_layout(os);
2795                         // FIXME InsetArgument is now properly implemented in InsetLayout
2796                         //       (for captions, but also for others)
2797                         if (p.next_token().cat() != catEscape &&
2798                             p.next_token().character() == '[') {
2799                                 p.get_token(); // eat '['
2800                                 begin_inset(os, "Argument 1\n");
2801                                 os << "status collapsed\n";
2802                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2803                                 end_inset(os);
2804                                 eat_whitespace(p, os, context, false);
2805                         }
2806                         parse_text(p, os, FLAG_ITEM, outer, context);
2807                         context.check_end_layout(os);
2808                         // We don't need really a new paragraph, but
2809                         // we must make sure that the next item gets a \begin_layout.
2810                         context.new_paragraph(os);
2811                         end_inset(os);
2812                         p.skip_spaces();
2813                         newcontext.check_end_layout(os);
2814                 }
2815
2816                 else if (t.cs() == "subfloat") {
2817                         // the syntax is \subfloat[caption]{content}
2818                         // if it is a table of figure depends on the surrounding float
2819                         bool has_caption = false;
2820                         p.skip_spaces();
2821                         // do nothing if there is no outer float
2822                         if (!float_type.empty()) {
2823                                 context.check_layout(os);
2824                                 p.skip_spaces();
2825                                 begin_inset(os, "Float " + float_type + "\n");
2826                                 os << "wide false"
2827                                    << "\nsideways false"
2828                                    << "\nstatus collapsed\n\n";
2829                                 // test for caption
2830                                 string caption;
2831                                 if (p.next_token().cat() != catEscape &&
2832                                                 p.next_token().character() == '[') {
2833                                                         p.get_token(); // eat '['
2834                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2835                                                         has_caption = true;
2836                                 }
2837                                 // the content
2838                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2839                                 // the caption comes always as the last
2840                                 if (has_caption) {
2841                                         // we must make sure that the caption gets a \begin_layout
2842                                         os << "\n\\begin_layout Plain Layout";
2843                                         p.skip_spaces();
2844                                         begin_inset(os, "Caption Standard\n");
2845                                         Context newcontext(true, context.textclass,
2846                                                            0, 0, context.font);
2847                                         newcontext.check_layout(os);
2848                                         os << caption << "\n";
2849                                         newcontext.check_end_layout(os);
2850                                         // We don't need really a new paragraph, but
2851                                         // we must make sure that the next item gets a \begin_layout.
2852                                         //newcontext.new_paragraph(os);
2853                                         end_inset(os);
2854                                         p.skip_spaces();
2855                                 }
2856                                 // We don't need really a new paragraph, but
2857                                 // we must make sure that the next item gets a \begin_layout.
2858                                 if (has_caption)
2859                                         context.new_paragraph(os);
2860                                 end_inset(os);
2861                                 p.skip_spaces();
2862                                 context.check_end_layout(os);
2863                                 // close the layout we opened
2864                                 if (has_caption)
2865                                         os << "\n\\end_layout\n";
2866                         } else {
2867                                 // if the float type is not supported or there is no surrounding float
2868                                 // output it as ERT
2869                                 if (p.hasOpt()) {
2870                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2871                                         handle_ert(os, t.asInput() + '[' + opt_arg +
2872                                                "]{" + p.verbatim_item() + '}', context);
2873                                 } else
2874                                         handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2875                         }
2876                 }
2877
2878                 else if (t.cs() == "includegraphics") {
2879                         bool const clip = p.next_token().asInput() == "*";
2880                         if (clip)
2881                                 p.get_token();
2882                         string const arg = p.getArg('[', ']');
2883                         map<string, string> opts;
2884                         vector<string> keys;
2885                         split_map(arg, opts, keys);
2886                         if (clip)
2887                                 opts["clip"] = string();
2888                         string name = normalize_filename(p.verbatim_item());
2889
2890                         string const path = getMasterFilePath(true);
2891                         // We want to preserve relative / absolute filenames,
2892                         // therefore path is only used for testing
2893                         if (!makeAbsPath(name, path).exists()) {
2894                                 // The file extension is probably missing.
2895                                 // Now try to find it out.
2896                                 string const dvips_name =
2897                                         find_file(name, path,
2898                                                   known_dvips_graphics_formats);
2899                                 string const pdftex_name =
2900                                         find_file(name, path,
2901                                                   known_pdftex_graphics_formats);
2902                                 if (!dvips_name.empty()) {
2903                                         if (!pdftex_name.empty()) {
2904                                                 cerr << "This file contains the "
2905                                                         "latex snippet\n"
2906                                                         "\"\\includegraphics{"
2907                                                      << name << "}\".\n"
2908                                                         "However, files\n\""
2909                                                      << dvips_name << "\" and\n\""
2910                                                      << pdftex_name << "\"\n"
2911                                                         "both exist, so I had to make a "
2912                                                         "choice and took the first one.\n"
2913                                                         "Please move the unwanted one "
2914                                                         "someplace else and try again\n"
2915                                                         "if my choice was wrong."
2916                                                      << endl;
2917                                         }
2918                                         name = dvips_name;
2919                                 } else if (!pdftex_name.empty()) {
2920                                         name = pdftex_name;
2921                                         pdflatex = true;
2922                                 }
2923                         }
2924
2925                         FileName const absname = makeAbsPath(name, path);
2926                         if (absname.exists()) {
2927                                 fix_child_filename(name);
2928                                 copy_file(absname, name);
2929                         } else
2930                                 cerr << "Warning: Could not find graphics file '"
2931                                      << name << "'." << endl;
2932
2933                         context.check_layout(os);
2934                         begin_inset(os, "Graphics ");
2935                         os << "\n\tfilename " << name << '\n';
2936                         if (opts.find("width") != opts.end())
2937                                 os << "\twidth "
2938                                    << translate_len(opts["width"]) << '\n';
2939                         if (opts.find("height") != opts.end())
2940                                 os << "\theight "
2941                                    << translate_len(opts["height"]) << '\n';
2942                         if (opts.find("scale") != opts.end()) {
2943                                 istringstream iss(opts["scale"]);
2944                                 double val;
2945                                 iss >> val;
2946                                 val = val*100;
2947                                 os << "\tscale " << val << '\n';
2948                         }
2949                         if (opts.find("angle") != opts.end()) {
2950                                 os << "\trotateAngle "
2951                                    << opts["angle"] << '\n';
2952                                 vector<string>::const_iterator a =
2953                                         find(keys.begin(), keys.end(), "angle");
2954                                 vector<string>::const_iterator s =
2955                                         find(keys.begin(), keys.end(), "width");
2956                                 if (s == keys.end())
2957                                         s = find(keys.begin(), keys.end(), "height");
2958                                 if (s == keys.end())
2959                                         s = find(keys.begin(), keys.end(), "scale");
2960                                 if (s != keys.end() && distance(s, a) > 0)
2961                                         os << "\tscaleBeforeRotation\n";
2962                         }
2963                         if (opts.find("origin") != opts.end()) {
2964                                 ostringstream ss;
2965                                 string const opt = opts["origin"];
2966                                 if (opt.find('l') != string::npos) ss << "left";
2967                                 if (opt.find('r') != string::npos) ss << "right";
2968                                 if (opt.find('c') != string::npos) ss << "center";
2969                                 if (opt.find('t') != string::npos) ss << "Top";
2970                                 if (opt.find('b') != string::npos) ss << "Bottom";
2971                                 if (opt.find('B') != string::npos) ss << "Baseline";
2972                                 if (!ss.str().empty())
2973                                         os << "\trotateOrigin " << ss.str() << '\n';
2974                                 else
2975                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2976                         }
2977                         if (opts.find("keepaspectratio") != opts.end())
2978                                 os << "\tkeepAspectRatio\n";
2979                         if (opts.find("clip") != opts.end())
2980                                 os << "\tclip\n";
2981                         if (opts.find("draft") != opts.end())
2982                                 os << "\tdraft\n";
2983                         if (opts.find("bb") != opts.end())
2984                                 os << "\tBoundingBox "
2985                                    << opts["bb"] << '\n';
2986                         int numberOfbbOptions = 0;
2987                         if (opts.find("bbllx") != opts.end())
2988                                 numberOfbbOptions++;
2989                         if (opts.find("bblly") != opts.end())
2990                                 numberOfbbOptions++;
2991                         if (opts.find("bburx") != opts.end())
2992                                 numberOfbbOptions++;
2993                         if (opts.find("bbury") != opts.end())
2994                                 numberOfbbOptions++;
2995                         if (numberOfbbOptions == 4)
2996                                 os << "\tBoundingBox "
2997                                    << opts["bbllx"] << " " << opts["bblly"] << " "
2998                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
2999                         else if (numberOfbbOptions > 0)
3000                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3001                         numberOfbbOptions = 0;
3002                         if (opts.find("natwidth") != opts.end())
3003                                 numberOfbbOptions++;
3004                         if (opts.find("natheight") != opts.end())
3005                                 numberOfbbOptions++;
3006                         if (numberOfbbOptions == 2)
3007                                 os << "\tBoundingBox 0bp 0bp "
3008                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
3009                         else if (numberOfbbOptions > 0)
3010                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3011                         ostringstream special;
3012                         if (opts.find("hiresbb") != opts.end())
3013                                 special << "hiresbb,";
3014                         if (opts.find("trim") != opts.end())
3015                                 special << "trim,";
3016                         if (opts.find("viewport") != opts.end())
3017                                 special << "viewport=" << opts["viewport"] << ',';
3018                         if (opts.find("totalheight") != opts.end())
3019                                 special << "totalheight=" << opts["totalheight"] << ',';
3020                         if (opts.find("type") != opts.end())
3021                                 special << "type=" << opts["type"] << ',';
3022                         if (opts.find("ext") != opts.end())
3023                                 special << "ext=" << opts["ext"] << ',';
3024                         if (opts.find("read") != opts.end())
3025                                 special << "read=" << opts["read"] << ',';
3026                         if (opts.find("command") != opts.end())
3027                                 special << "command=" << opts["command"] << ',';
3028                         string s_special = special.str();
3029                         if (!s_special.empty()) {
3030                                 // We had special arguments. Remove the trailing ','.
3031                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3032                         }
3033                         // TODO: Handle the unknown settings better.
3034                         // Warn about invalid options.
3035                         // Check whether some option was given twice.
3036                         end_inset(os);
3037                         preamble.registerAutomaticallyLoadedPackage("graphicx");
3038                 }
3039
3040                 else if (t.cs() == "footnote" ||
3041                          (t.cs() == "thanks" && context.layout->intitle)) {
3042                         p.skip_spaces();
3043                         context.check_layout(os);
3044                         begin_inset(os, "Foot\n");
3045                         os << "status collapsed\n\n";
3046                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3047                         end_inset(os);
3048                 }
3049
3050                 else if (t.cs() == "marginpar") {
3051                         p.skip_spaces();
3052                         context.check_layout(os);
3053                         begin_inset(os, "Marginal\n");
3054                         os << "status collapsed\n\n";
3055                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3056                         end_inset(os);
3057                 }
3058
3059                 else if (t.cs() == "lstinline") {
3060                         p.skip_spaces();
3061                         parse_listings(p, os, context, true);
3062                 }
3063
3064                 else if (t.cs() == "ensuremath") {
3065                         p.skip_spaces();
3066                         context.check_layout(os);
3067                         string const s = p.verbatim_item();
3068                         //FIXME: this never triggers in UTF8
3069                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3070                                 os << s;
3071                         else
3072                                 handle_ert(os, "\\ensuremath{" + s + "}",
3073                                            context);
3074                 }
3075
3076                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3077                         if (preamble.titleLayoutFound()) {
3078                                 // swallow this
3079                                 skip_spaces_braces(p);
3080                         } else
3081                                 handle_ert(os, t.asInput(), context);
3082                 }
3083
3084                 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3085                         context.check_layout(os);
3086                         begin_command_inset(os, "toc", t.cs());
3087                         end_inset(os);
3088                         skip_spaces_braces(p);
3089                         if (t.cs() == "lstlistoflistings")
3090                                 preamble.registerAutomaticallyLoadedPackage("listings");
3091                 }
3092
3093                 else if (t.cs() == "listoffigures") {
3094                         context.check_layout(os);
3095                         begin_inset(os, "FloatList figure\n");
3096                         end_inset(os);
3097                         skip_spaces_braces(p);
3098                 }
3099
3100                 else if (t.cs() == "listoftables") {
3101                         context.check_layout(os);
3102                         begin_inset(os, "FloatList table\n");
3103                         end_inset(os);
3104                         skip_spaces_braces(p);
3105                 }
3106
3107                 else if (t.cs() == "listof") {
3108                         p.skip_spaces(true);
3109                         string const name = p.get_token().cs();
3110                         if (context.textclass.floats().typeExist(name)) {
3111                                 context.check_layout(os);
3112                                 begin_inset(os, "FloatList ");
3113                                 os << name << "\n";
3114                                 end_inset(os);
3115                                 p.get_token(); // swallow second arg
3116                         } else
3117                                 handle_ert(os, "\\listof{" + name + "}", context);
3118                 }
3119
3120                 else if ((where = is_known(t.cs(), known_text_font_families)))
3121                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3122                                 context, "\\family", context.font.family,
3123                                 known_coded_font_families[where - known_text_font_families]);
3124
3125                 else if ((where = is_known(t.cs(), known_text_font_series)))
3126                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3127                                 context, "\\series", context.font.series,
3128                                 known_coded_font_series[where - known_text_font_series]);
3129
3130                 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3131                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3132                                 context, "\\shape", context.font.shape,
3133                                 known_coded_font_shapes[where - known_text_font_shapes]);
3134
3135                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3136                         context.check_layout(os);
3137                         TeXFont oldFont = context.font;
3138                         context.font.init();
3139                         context.font.size = oldFont.size;
3140                         os << "\n\\family " << context.font.family << "\n";
3141                         os << "\n\\series " << context.font.series << "\n";
3142                         os << "\n\\shape " << context.font.shape << "\n";
3143                         if (t.cs() == "textnormal") {
3144                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3145                                 output_font_change(os, context.font, oldFont);
3146                                 context.font = oldFont;
3147                         } else
3148                                 eat_whitespace(p, os, context, false);
3149                 }
3150
3151                 else if (t.cs() == "textcolor") {
3152                         // scheme is \textcolor{color name}{text}
3153                         string const color = p.verbatim_item();
3154                         // we only support the predefined colors of the color package
3155                         if (color == "black" || color == "blue" || color == "cyan"
3156                                 || color == "green" || color == "magenta" || color == "red"
3157                                 || color == "white" || color == "yellow") {
3158                                         context.check_layout(os);
3159                                         os << "\n\\color " << color << "\n";
3160                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3161                                         context.check_layout(os);
3162                                         os << "\n\\color inherit\n";
3163                                         preamble.registerAutomaticallyLoadedPackage("color");
3164                         } else
3165                                 // for custom defined colors
3166                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
3167                 }
3168
3169                 else if (t.cs() == "underbar" || t.cs() == "uline") {
3170                         // \underbar is not 100% correct (LyX outputs \uline
3171                         // of ulem.sty). The difference is that \ulem allows
3172                         // line breaks, and \underbar does not.
3173                         // Do NOT handle \underline.
3174                         // \underbar cuts through y, g, q, p etc.,
3175                         // \underline does not.
3176                         context.check_layout(os);
3177                         os << "\n\\bar under\n";
3178                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3179                         context.check_layout(os);
3180                         os << "\n\\bar default\n";
3181                         preamble.registerAutomaticallyLoadedPackage("ulem");
3182                 }
3183
3184                 else if (t.cs() == "sout") {
3185                         context.check_layout(os);
3186                         os << "\n\\strikeout on\n";
3187                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3188                         context.check_layout(os);
3189                         os << "\n\\strikeout default\n";
3190                         preamble.registerAutomaticallyLoadedPackage("ulem");
3191                 }
3192
3193                 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3194                          t.cs() == "emph" || t.cs() == "noun") {
3195                         context.check_layout(os);
3196                         os << "\n\\" << t.cs() << " on\n";
3197                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3198                         context.check_layout(os);
3199                         os << "\n\\" << t.cs() << " default\n";
3200                         if (t.cs() == "uuline" || t.cs() == "uwave")
3201                                 preamble.registerAutomaticallyLoadedPackage("ulem");
3202                 }
3203
3204                 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3205                         context.check_layout(os);
3206                         string name = p.getArg('{', '}');
3207                         string localtime = p.getArg('{', '}');
3208                         preamble.registerAuthor(name);
3209                         Author const & author = preamble.getAuthor(name);
3210                         // from_asctime_utc() will fail if LyX decides to output the
3211                         // time in the text language.
3212                         time_t ptime = from_asctime_utc(localtime);
3213                         if (ptime == static_cast<time_t>(-1)) {
3214                                 cerr << "Warning: Could not parse time `" << localtime
3215                                      << "´ for change tracking, using current time instead.\n";
3216                                 ptime = current_time();
3217                         }
3218                         if (t.cs() == "lyxadded")
3219                                 os << "\n\\change_inserted ";
3220                         else
3221                                 os << "\n\\change_deleted ";
3222                         os << author.bufferId() << ' ' << ptime << '\n';
3223                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3224                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
3225                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3226                                           LaTeXPackages::isAvailable("xcolor");
3227                         // No need to test for luatex, since luatex comes in
3228                         // two flavours (dvi and pdf), like latex, and those
3229                         // are detected by pdflatex.
3230                         if (pdflatex || xetex) {
3231                                 if (xcolorulem) {
3232                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3233                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3234                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3235                                 }
3236                         } else {
3237                                 if (dvipost) {
3238                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
3239                                 } else if (xcolorulem) {
3240                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3241                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3242                                 }
3243                         }
3244                 }
3245
3246                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3247                              t.cs() == "vphantom") {
3248                         context.check_layout(os);
3249                         if (t.cs() == "phantom")
3250                                 begin_inset(os, "Phantom Phantom\n");
3251                         if (t.cs() == "hphantom")
3252                                 begin_inset(os, "Phantom HPhantom\n");
3253                         if (t.cs() == "vphantom")
3254                                 begin_inset(os, "Phantom VPhantom\n");
3255                         os << "status open\n";
3256                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3257                                             "Phantom");
3258                         end_inset(os);
3259                 }
3260
3261                 else if (t.cs() == "href") {
3262                         context.check_layout(os);
3263                         string target = convert_command_inset_arg(p.verbatim_item());
3264                         string name = convert_command_inset_arg(p.verbatim_item());
3265                         string type;
3266                         size_t i = target.find(':');
3267                         if (i != string::npos) {
3268                                 type = target.substr(0, i + 1);
3269                                 if (type == "mailto:" || type == "file:")
3270                                         target = target.substr(i + 1);
3271                                 // handle the case that name is equal to target, except of "http://"
3272                                 else if (target.substr(i + 3) == name && type == "http:")
3273                                         target = name;
3274                         }
3275                         begin_command_inset(os, "href", "href");
3276                         if (name != target)
3277                                 os << "name \"" << name << "\"\n";
3278                         os << "target \"" << target << "\"\n";
3279                         if (type == "mailto:" || type == "file:")
3280                                 os << "type \"" << type << "\"\n";
3281                         end_inset(os);
3282                         skip_spaces_braces(p);
3283                 }
3284
3285                 else if (t.cs() == "lyxline") {
3286                         // swallow size argument (it is not used anyway)
3287                         p.getArg('{', '}');
3288                         if (!context.atParagraphStart()) {
3289                                 // so our line is in the middle of a paragraph
3290                                 // we need to add a new line, lest this line
3291                                 // follow the other content on that line and
3292                                 // run off the side of the page
3293                                 // FIXME: This may create an empty paragraph,
3294                                 //        but without that it would not be
3295                                 //        possible to set noindent below.
3296                                 //        Fortunately LaTeX does not care
3297                                 //        about the empty paragraph.
3298                                 context.new_paragraph(os);
3299                         }
3300                         if (preamble.indentParagraphs()) {
3301                                 // we need to unindent, lest the line be too long
3302                                 context.add_par_extra_stuff("\\noindent\n");
3303                         }
3304                         context.check_layout(os);
3305                         begin_command_inset(os, "line", "rule");
3306                         os << "offset \"0.5ex\"\n"
3307                               "width \"100line%\"\n"
3308                               "height \"1pt\"\n";
3309                         end_inset(os);
3310                 }
3311
3312                 else if (t.cs() == "rule") {
3313                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3314                         string const width = p.getArg('{', '}');
3315                         string const thickness = p.getArg('{', '}');
3316                         context.check_layout(os);
3317                         begin_command_inset(os, "line", "rule");
3318                         if (!offset.empty())
3319                                 os << "offset \"" << translate_len(offset) << "\"\n";
3320                         os << "width \"" << translate_len(width) << "\"\n"
3321                                   "height \"" << translate_len(thickness) << "\"\n";
3322                         end_inset(os);
3323                 }
3324
3325                 else if (is_known(t.cs(), known_phrases) ||
3326                          (t.cs() == "protect" &&
3327                           p.next_token().cat() == catEscape &&
3328                           is_known(p.next_token().cs(), known_phrases))) {
3329                         // LyX sometimes puts a \protect in front, so we have to ignore it
3330                         // FIXME: This needs to be changed when bug 4752 is fixed.
3331                         where = is_known(
3332                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3333                                 known_phrases);
3334                         context.check_layout(os);
3335                         os << known_coded_phrases[where - known_phrases];
3336                         skip_spaces_braces(p);
3337                 }
3338
3339                 else if ((where = is_known(t.cs(), known_ref_commands))) {
3340                         string const opt = p.getOpt();
3341                         if (opt.empty()) {
3342                                 context.check_layout(os);
3343                                 begin_command_inset(os, "ref",
3344                                         known_coded_ref_commands[where - known_ref_commands]);
3345                                 os << "reference \""
3346                                    << convert_command_inset_arg(p.verbatim_item())
3347                                    << "\"\n";
3348                                 end_inset(os);
3349                                 if (t.cs() == "vref" || t.cs() == "vpageref")
3350                                         preamble.registerAutomaticallyLoadedPackage("varioref");
3351
3352                         } else {
3353                                 // LyX does not support optional arguments of ref commands
3354                                 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3355                                                p.verbatim_item() + "}", context);
3356                         }
3357                 }
3358
3359                 else if (use_natbib &&
3360                          is_known(t.cs(), known_natbib_commands) &&
3361                          ((t.cs() != "citefullauthor" &&
3362                            t.cs() != "citeyear" &&
3363                            t.cs() != "citeyearpar") ||
3364                           p.next_token().asInput() != "*")) {
3365                         context.check_layout(os);
3366                         string command = t.cs();
3367                         if (p.next_token().asInput() == "*") {
3368                                 command += '*';
3369                                 p.get_token();
3370                         }
3371                         if (command == "citefullauthor")
3372                                 // alternative name for "\\citeauthor*"
3373                                 command = "citeauthor*";
3374
3375                         // text before the citation
3376                         string before;
3377                         // text after the citation
3378                         string after;
3379                         get_cite_arguments(p, true, before, after);
3380
3381                         if (command == "cite") {
3382                                 // \cite without optional argument means
3383                                 // \citet, \cite with at least one optional
3384                                 // argument means \citep.
3385                                 if (before.empty() && after.empty())
3386                                         command = "citet";
3387                                 else
3388                                         command = "citep";
3389                         }
3390                         if (before.empty() && after == "[]")
3391                                 // avoid \citet[]{a}
3392                                 after.erase();
3393                         else if (before == "[]" && after == "[]") {
3394                                 // avoid \citet[][]{a}
3395                                 before.erase();
3396                                 after.erase();
3397                         }
3398                         // remove the brackets around after and before
3399                         if (!after.empty()) {
3400                                 after.erase(0, 1);
3401                                 after.erase(after.length() - 1, 1);
3402                                 after = convert_command_inset_arg(after);
3403                         }
3404                         if (!before.empty()) {
3405                                 before.erase(0, 1);
3406                                 before.erase(before.length() - 1, 1);
3407                                 before = convert_command_inset_arg(before);
3408                         }
3409                         begin_command_inset(os, "citation", command);
3410                         os << "after " << '"' << after << '"' << "\n";
3411                         os << "before " << '"' << before << '"' << "\n";
3412                         os << "key \""
3413                            << convert_command_inset_arg(p.verbatim_item())
3414                            << "\"\n";
3415                         end_inset(os);
3416                         // Need to set the cite engine if natbib is loaded by
3417                         // the document class directly
3418                         if (preamble.citeEngine() == "basic")
3419                                 preamble.citeEngine("natbib");
3420                 }
3421
3422                 else if (use_jurabib &&
3423                          is_known(t.cs(), known_jurabib_commands) &&
3424                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3425                         context.check_layout(os);
3426                         string command = t.cs();
3427                         if (p.next_token().asInput() == "*") {
3428                                 command += '*';
3429                                 p.get_token();
3430                         }
3431                         char argumentOrder = '\0';
3432                         vector<string> const options =
3433                                 preamble.getPackageOptions("jurabib");
3434                         if (find(options.begin(), options.end(),
3435                                       "natbiborder") != options.end())
3436                                 argumentOrder = 'n';
3437                         else if (find(options.begin(), options.end(),
3438                                            "jurabiborder") != options.end())
3439                                 argumentOrder = 'j';
3440
3441                         // text before the citation
3442                         string before;
3443                         // text after the citation
3444                         string after;
3445                         get_cite_arguments(p, argumentOrder != 'j', before, after);
3446
3447                         string const citation = p.verbatim_item();
3448                         if (!before.empty() && argumentOrder == '\0') {
3449                                 cerr << "Warning: Assuming argument order "
3450                                         "of jurabib version 0.6 for\n'"
3451                                      << command << before << after << '{'
3452                                      << citation << "}'.\n"
3453                                         "Add 'jurabiborder' to the jurabib "
3454                                         "package options if you used an\n"
3455                                         "earlier jurabib version." << endl;
3456                         }
3457                         if (!after.empty()) {
3458                                 after.erase(0, 1);
3459                                 after.erase(after.length() - 1, 1);
3460                         }
3461                         if (!before.empty()) {
3462                                 before.erase(0, 1);
3463                                 before.erase(before.length() - 1, 1);
3464                         }
3465                         begin_command_inset(os, "citation", command);
3466                         os << "after " << '"' << after << '"' << "\n";
3467                         os << "before " << '"' << before << '"' << "\n";
3468                         os << "key " << '"' << citation << '"' << "\n";
3469                         end_inset(os);
3470                         // Need to set the cite engine if jurabib is loaded by
3471                         // the document class directly
3472                         if (preamble.citeEngine() == "basic")
3473                                 preamble.citeEngine("jurabib");
3474                 }
3475
3476                 else if (t.cs() == "cite"
3477                         || t.cs() == "nocite") {
3478                         context.check_layout(os);
3479                         string after = convert_command_inset_arg(p.getArg('[', ']'));
3480                         string key = convert_command_inset_arg(p.verbatim_item());
3481                         // store the case that it is "\nocite{*}" to use it later for
3482                         // the BibTeX inset
3483                         if (key != "*") {
3484                                 begin_command_inset(os, "citation", t.cs());
3485                                 os << "after " << '"' << after << '"' << "\n";
3486                                 os << "key " << '"' << key << '"' << "\n";
3487                                 end_inset(os);
3488                         } else if (t.cs() == "nocite")
3489                                 btprint = key;
3490                 }
3491
3492                 else if (t.cs() == "index" ||
3493                          (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3494                         context.check_layout(os);
3495                         string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3496                                 p.getArg('[', ']') : "";
3497                         string const kind = arg.empty() ? "idx" : arg;
3498                         begin_inset(os, "Index ");
3499                         os << kind << "\nstatus collapsed\n";
3500                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3501                         end_inset(os);
3502                         if (kind != "idx")
3503                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3504                 }
3505
3506                 else if (t.cs() == "nomenclature") {
3507                         context.check_layout(os);
3508                         begin_command_inset(os, "nomenclature", "nomenclature");
3509                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3510                         if (!prefix.empty())
3511                                 os << "prefix " << '"' << prefix << '"' << "\n";
3512                         os << "symbol " << '"'
3513                            << convert_command_inset_arg(p.verbatim_item());
3514                         os << "\"\ndescription \""
3515                            << convert_command_inset_arg(p.verbatim_item())
3516                            << "\"\n";
3517                         end_inset(os);
3518                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3519                 }
3520
3521                 else if (t.cs() == "label") {
3522                         context.check_layout(os);
3523                         begin_command_inset(os, "label", "label");
3524                         os << "name \""
3525                            << convert_command_inset_arg(p.verbatim_item())
3526                            << "\"\n";
3527                         end_inset(os);
3528                 }
3529
3530                 else if (t.cs() == "printindex") {
3531                         context.check_layout(os);
3532                         begin_command_inset(os, "index_print", "printindex");
3533                         os << "type \"idx\"\n";
3534                         end_inset(os);
3535                         skip_spaces_braces(p);
3536                         preamble.registerAutomaticallyLoadedPackage("makeidx");
3537                         if (preamble.use_indices() == "true")
3538                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3539                 }
3540
3541                 else if (t.cs() == "printnomenclature") {
3542                         string width = "";
3543                         string width_type = "";
3544                         context.check_layout(os);
3545                         begin_command_inset(os, "nomencl_print", "printnomenclature");
3546                         // case of a custom width
3547                         if (p.hasOpt()) {
3548                                 width = p.getArg('[', ']');
3549                                 width = translate_len(width);
3550                                 width_type = "custom";
3551                         }
3552                         // case of no custom width
3553                         // the case of no custom width but the width set
3554                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
3555                         // because the user could have set anything, not only the width
3556                         // of the longest label (which would be width_type = "auto")
3557                         string label = convert_command_inset_arg(p.getArg('{', '}'));
3558                         if (label.empty() && width_type.empty())
3559                                 width_type = "none";
3560                         os << "set_width \"" << width_type << "\"\n";
3561                         if (width_type == "custom")
3562                                 os << "width \"" << width << '\"';
3563                         end_inset(os);
3564                         skip_spaces_braces(p);
3565                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3566                 }
3567
3568                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3569                         context.check_layout(os);
3570                         begin_inset(os, "script ");
3571                         os << t.cs().substr(4) << '\n';
3572                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3573                         end_inset(os);
3574                         if (t.cs() == "textsubscript")
3575                                 preamble.registerAutomaticallyLoadedPackage("subscript");
3576                 }
3577
3578                 else if ((where = is_known(t.cs(), known_quotes))) {
3579                         context.check_layout(os);
3580                         begin_inset(os, "Quotes ");
3581                         os << known_coded_quotes[where - known_quotes];
3582                         end_inset(os);
3583                         // LyX adds {} after the quote, so we have to eat
3584                         // spaces here if there are any before a possible
3585                         // {} pair.
3586                         eat_whitespace(p, os, context, false);
3587                         skip_braces(p);
3588                 }
3589
3590                 else if ((where = is_known(t.cs(), known_sizes)) &&
3591                          context.new_layout_allowed) {
3592                         context.check_layout(os);
3593                         TeXFont const oldFont = context.font;
3594                         context.font.size = known_coded_sizes[where - known_sizes];
3595                         output_font_change(os, oldFont, context.font);
3596                         eat_whitespace(p, os, context, false);
3597                 }
3598
3599                 else if ((where = is_known(t.cs(), known_font_families)) &&
3600                          context.new_layout_allowed) {
3601                         context.check_layout(os);
3602                         TeXFont const oldFont = context.font;
3603                         context.font.family =
3604                                 known_coded_font_families[where - known_font_families];
3605                         output_font_change(os, oldFont, context.font);
3606                         eat_whitespace(p, os, context, false);
3607                 }
3608
3609                 else if ((where = is_known(t.cs(), known_font_series)) &&
3610                          context.new_layout_allowed) {
3611                         context.check_layout(os);
3612                         TeXFont const oldFont = context.font;
3613                         context.font.series =
3614                                 known_coded_font_series[where - known_font_series];
3615                         output_font_change(os, oldFont, context.font);
3616                         eat_whitespace(p, os, context, false);
3617                 }
3618
3619                 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3620                          context.new_layout_allowed) {
3621                         context.check_layout(os);
3622                         TeXFont const oldFont = context.font;
3623                         context.font.shape =
3624                                 known_coded_font_shapes[where - known_font_shapes];
3625                         output_font_change(os, oldFont, context.font);
3626                         eat_whitespace(p, os, context, false);
3627                 }
3628                 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3629                          context.new_layout_allowed) {
3630                         context.check_layout(os);
3631                         TeXFont const oldFont = context.font;
3632                         context.font.init();
3633                         context.font.size = oldFont.size;
3634                         context.font.family =
3635                                 known_coded_font_families[where - known_old_font_families];
3636                         output_font_change(os, oldFont, context.font);
3637                         eat_whitespace(p, os, context, false);
3638                 }
3639
3640                 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3641                          context.new_layout_allowed) {
3642                         context.check_layout(os);
3643                         TeXFont const oldFont = context.font;
3644                         context.font.init();
3645                         context.font.size = oldFont.size;
3646                         context.font.series =
3647                                 known_coded_font_series[where - known_old_font_series];
3648                         output_font_change(os, oldFont, context.font);
3649                         eat_whitespace(p, os, context, false);
3650                 }
3651
3652                 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3653                          context.new_layout_allowed) {
3654                         context.check_layout(os);
3655                         TeXFont const oldFont = context.font;
3656                         context.font.init();
3657                         context.font.size = oldFont.size;
3658                         context.font.shape =
3659                                 known_coded_font_shapes[where - known_old_font_shapes];
3660                         output_font_change(os, oldFont, context.font);
3661                         eat_whitespace(p, os, context, false);
3662                 }
3663
3664                 else if (t.cs() == "selectlanguage") {
3665                         context.check_layout(os);
3666                         // save the language for the case that a
3667                         // \foreignlanguage is used
3668                         context.font.language = babel2lyx(p.verbatim_item());
3669                         os << "\n\\lang " << context.font.language << "\n";
3670                 }
3671
3672                 else if (t.cs() == "foreignlanguage") {
3673                         string const lang = babel2lyx(p.verbatim_item());
3674                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3675                                               context, "\\lang",
3676                                               context.font.language, lang);
3677                 }
3678
3679                 else if (prefixIs(t.cs(), "text")
3680                          && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3681                         // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3682                         string lang;
3683                         // We have to output the whole command if it has an option
3684                         // because LyX doesn't support this yet, see bug #8214,
3685                         // only if there is a single option specifying a variant, we can handle it.
3686                         if (p.hasOpt()) {
3687                                 string langopts = p.getOpt();
3688                                 // check if the option contains a variant, if yes, extract it
3689                                 string::size_type pos_var = langopts.find("variant");
3690                                 string::size_type i = langopts.find(',');
3691                                 string::size_type k = langopts.find('=', pos_var);
3692                                 if (pos_var != string::npos && i == string::npos) {
3693                                         string variant;
3694                                         variant = langopts.substr(k + 1, langopts.length() - k - 2);
3695                                         lang = preamble.polyglossia2lyx(variant);
3696                                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3697                                                                   context, "\\lang",
3698                                                                   context.font.language, lang);
3699                                 } else
3700                                         handle_ert(os, t.asInput() + langopts, context);
3701                         } else {
3702                                 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3703                                 parse_text_attributes(p, os, FLAG_ITEM, outer,
3704                                                           context, "\\lang",
3705                                                           context.font.language, lang);
3706                         }
3707                 }
3708
3709                 else if (t.cs() == "inputencoding") {
3710                         // nothing to write here
3711                         string const enc = subst(p.verbatim_item(), "\n", " ");
3712                         p.setEncoding(enc, Encoding::inputenc);
3713                 }
3714
3715                 else if ((where = is_known(t.cs(), known_special_chars))) {
3716                         context.check_layout(os);
3717                         os << "\\SpecialChar \\"
3718                            << known_coded_special_chars[where - known_special_chars]
3719                            << '\n';
3720                         skip_spaces_braces(p);
3721                 }
3722
3723                 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3724                         context.check_layout(os);
3725                         os << "\\SpecialChar \\nobreakdash-\n";
3726                         p.get_token();
3727                 }
3728
3729                 else if (t.cs() == "textquotedbl") {
3730                         context.check_layout(os);
3731                         os << "\"";
3732                         skip_braces(p);
3733                 }
3734
3735                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3736                         context.check_layout(os);
3737                         os << "\\SpecialChar \\@.\n";
3738                         p.get_token();
3739                 }
3740
3741                 else if (t.cs() == "-") {
3742                         context.check_layout(os);
3743                         os << "\\SpecialChar \\-\n";
3744                 }
3745
3746                 else if (t.cs() == "textasciitilde") {
3747                         context.check_layout(os);
3748                         os << '~';
3749                         skip_spaces_braces(p);
3750                 }
3751
3752                 else if (t.cs() == "textasciicircum") {
3753                         context.check_layout(os);
3754                         os << '^';
3755                         skip_spaces_braces(p);
3756                 }
3757
3758                 else if (t.cs() == "textbackslash") {
3759                         context.check_layout(os);
3760                         os << "\n\\backslash\n";
3761                         skip_spaces_braces(p);
3762                 }
3763
3764                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3765                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3766                             || t.cs() == "%") {
3767                         context.check_layout(os);
3768                         os << t.cs();
3769                 }
3770
3771                 else if (t.cs() == "char") {
3772                         context.check_layout(os);
3773                         if (p.next_token().character() == '`') {
3774                                 p.get_token();
3775                                 if (p.next_token().cs() == "\"") {
3776                                         p.get_token();
3777                                         os << '"';
3778                                         skip_braces(p);
3779                                 } else {
3780                                         handle_ert(os, "\\char`", context);
3781                                 }
3782                         } else {
3783                                 handle_ert(os, "\\char", context);
3784                         }
3785                 }
3786
3787                 else if (t.cs() == "verb") {
3788                         context.check_layout(os);
3789                         char const delimiter = p.next_token().character();
3790                         // \verb is special: The usual escaping rules do not
3791                         // apply, e.g. "\verb+\+" is valid and denotes a single
3792                         // backslash (bug #4468). Therefore we do not allow
3793                         // escaping in getArg().
3794                         string const arg = p.getArg(delimiter, delimiter, false);
3795                         ostringstream oss;
3796                         oss << "\\verb" << delimiter << arg << delimiter;
3797                         handle_ert(os, oss.str(), context);
3798                 }
3799
3800                 // Problem: \= creates a tabstop inside the tabbing environment
3801                 // and else an accent. In the latter case we really would want
3802                 // \={o} instead of \= o.
3803                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3804                         handle_ert(os, t.asInput(), context);
3805
3806                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3807                 else if (t.cs().size() == 1
3808                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3809                         context.check_layout(os);
3810                         // try to see whether the string is in unicodesymbols
3811                         bool termination;
3812                         docstring rem;
3813                         string command = t.asInput() + "{"
3814                                 + trimSpaceAndEol(p.verbatim_item())
3815                                 + "}";
3816                         set<string> req;
3817                         docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3818                                 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3819                                 termination, rem, &req);
3820                         if (!s.empty()) {
3821                                 if (!rem.empty())
3822                                         cerr << "When parsing " << command
3823                                              << ", result is " << to_utf8(s)
3824                                              << "+" << to_utf8(rem) << endl;
3825                                 os << to_utf8(s);
3826                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3827                                         preamble.registerAutomaticallyLoadedPackage(*it);
3828                         } else
3829                                 // we did not find a non-ert version
3830                                 handle_ert(os, command, context);
3831                 }
3832
3833                 else if (t.cs() == "\\") {
3834                         context.check_layout(os);
3835                         if (p.hasOpt())
3836                                 handle_ert(os, "\\\\" + p.getOpt(), context);
3837                         else if (p.next_token().asInput() == "*") {
3838                                 p.get_token();
3839                                 // getOpt() eats the following space if there
3840                                 // is no optional argument, but that is OK
3841                                 // here since it has no effect in the output.
3842                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
3843                         }
3844                         else {
3845                                 begin_inset(os, "Newline newline");
3846                                 end_inset(os);
3847                         }
3848                 }
3849
3850                 else if (t.cs() == "newline" ||
3851                          (t.cs() == "linebreak" && !p.hasOpt())) {
3852                         context.check_layout(os);
3853                         begin_inset(os, "Newline ");
3854                         os << t.cs();
3855                         end_inset(os);
3856                         skip_spaces_braces(p);
3857                 }
3858
3859                 else if (t.cs() == "input" || t.cs() == "include"
3860                          || t.cs() == "verbatiminput") {
3861                         string name = t.cs();
3862                         if (t.cs() == "verbatiminput"
3863                             && p.next_token().asInput() == "*")
3864                                 name += p.get_token().asInput();
3865                         context.check_layout(os);
3866                         string filename(normalize_filename(p.getArg('{', '}')));
3867                         string const path = getMasterFilePath(true);
3868                         // We want to preserve relative / absolute filenames,
3869                         // therefore path is only used for testing
3870                         if ((t.cs() == "include" || t.cs() == "input") &&
3871                             !makeAbsPath(filename, path).exists()) {
3872                                 // The file extension is probably missing.
3873                                 // Now try to find it out.
3874                                 string const tex_name =
3875                                         find_file(filename, path,
3876                                                   known_tex_extensions);
3877                                 if (!tex_name.empty())
3878                                         filename = tex_name;
3879                         }
3880                         bool external = false;
3881                         string outname;
3882                         if (makeAbsPath(filename, path).exists()) {
3883                                 string const abstexname =
3884                                         makeAbsPath(filename, path).absFileName();
3885                                 string const absfigname =
3886                                         changeExtension(abstexname, ".fig");
3887                                 fix_child_filename(filename);
3888                                 string const lyxname =
3889                                         changeExtension(filename, ".lyx");
3890                                 string const abslyxname = makeAbsPath(
3891                                         lyxname, getParentFilePath(false)).absFileName();
3892                                 bool xfig = false;
3893                                 if (!skipChildren())
3894                                         external = FileName(absfigname).exists();
3895                                 if (t.cs() == "input" && !skipChildren()) {
3896                                         string const ext = getExtension(abstexname);
3897
3898                                         // Combined PS/LaTeX:
3899                                         // x.eps, x.pstex_t (old xfig)
3900                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3901                                         FileName const absepsname(
3902                                                 changeExtension(abstexname, ".eps"));
3903                                         FileName const abspstexname(
3904                                                 changeExtension(abstexname, ".pstex"));
3905                                         bool const xfigeps =
3906                                                 (absepsname.exists() ||
3907                                                  abspstexname.exists()) &&
3908                                                 ext == "pstex_t";
3909
3910                                         // Combined PDF/LaTeX:
3911                                         // x.pdf, x.pdftex_t (old xfig)
3912                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3913                                         FileName const abspdfname(
3914                                                 changeExtension(abstexname, ".pdf"));
3915                                         bool const xfigpdf =
3916                                                 abspdfname.exists() &&
3917                                                 (ext == "pdftex_t" || ext == "pdf_t");
3918                                         if (xfigpdf)
3919                                                 pdflatex = true;
3920
3921                                         // Combined PS/PDF/LaTeX:
3922                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3923                                         string const absbase2(
3924                                                 removeExtension(abstexname) + "_pspdftex");
3925                                         FileName const abseps2name(
3926                                                 addExtension(absbase2, ".eps"));
3927                                         FileName const abspdf2name(
3928                                                 addExtension(absbase2, ".pdf"));
3929                                         bool const xfigboth =
3930                                                 abspdf2name.exists() &&
3931                                                 abseps2name.exists() && ext == "pspdftex";
3932
3933                                         xfig = xfigpdf || xfigeps || xfigboth;
3934                                         external = external && xfig;
3935                                 }
3936                                 if (external) {
3937                                         outname = changeExtension(filename, ".fig");
3938                                         FileName abssrc(changeExtension(abstexname, ".fig"));
3939                                         copy_file(abssrc, outname);
3940                                 } else if (xfig) {
3941                                         // Don't try to convert, the result
3942                                         // would be full of ERT.
3943                                         outname = filename;
3944                                         FileName abssrc(abstexname);
3945                                         copy_file(abssrc, outname);
3946                                 } else if (t.cs() != "verbatiminput" &&
3947                                            !skipChildren() &&
3948                                     tex2lyx(abstexname, FileName(abslyxname),
3949                                             p.getEncoding())) {
3950                                         outname = lyxname;
3951                                         // no need to call copy_file
3952                                         // tex2lyx creates the file
3953                                 } else {
3954                                         outname = filename;
3955                                         FileName abssrc(abstexname);
3956                                         copy_file(abssrc, outname);
3957                                 }
3958                         } else {
3959                                 cerr << "Warning: Could not find included file '"
3960                                      << filename << "'." << endl;
3961                                 outname = filename;
3962                         }
3963                         if (external) {
3964                                 begin_inset(os, "External\n");
3965                                 os << "\ttemplate XFig\n"
3966                                    << "\tfilename " << outname << '\n';
3967                                 registerExternalTemplatePackages("XFig");
3968                         } else {
3969                                 begin_command_inset(os, "include", name);
3970                                 outname = subst(outname, "\"", "\\\"");
3971                                 os << "preview false\n"
3972                                       "filename \"" << outname << "\"\n";
3973                                 if (t.cs() == "verbatiminput")
3974                                         preamble.registerAutomaticallyLoadedPackage("verbatim");
3975                         }
3976                         end_inset(os);
3977                 }
3978
3979                 else if (t.cs() == "bibliographystyle") {
3980                         // store new bibliographystyle
3981                         bibliographystyle = p.verbatim_item();
3982                         // If any other command than \bibliography and
3983                         // \nocite{*} follows, we need to output the style
3984                         // (because it might be used by that command).
3985                         // Otherwise, it will automatically be output by LyX.
3986                         p.pushPosition();
3987                         bool output = true;
3988                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3989                                 if (t2.cat() == catBegin)
3990                                         break;
3991                                 if (t2.cat() != catEscape)
3992                                         continue;
3993                                 if (t2.cs() == "nocite") {
3994                                         if (p.getArg('{', '}') == "*")
3995                                                 continue;
3996                                 } else if (t2.cs() == "bibliography")
3997                                         output = false;
3998                                 break;
3999                         }
4000                         p.popPosition();
4001                         if (output) {
4002                                 handle_ert(os,
4003                                         "\\bibliographystyle{" + bibliographystyle + '}',
4004                                         context);
4005                         }
4006                 }
4007
4008                 else if (t.cs() == "bibliography") {
4009                         context.check_layout(os);
4010                         begin_command_inset(os, "bibtex", "bibtex");
4011                         if (!btprint.empty()) {
4012                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4013                                 // clear the string because the next BibTeX inset can be without the
4014                                 // \nocite{*} option
4015                                 btprint.clear();
4016                         }
4017                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4018                         // Do we have a bibliographystyle set?
4019                         if (!bibliographystyle.empty())
4020                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
4021                         end_inset(os);
4022                 }
4023
4024                 else if (t.cs() == "parbox") {
4025                         // Test whether this is an outer box of a shaded box
4026                         p.pushPosition();
4027                         // swallow arguments
4028                         while (p.hasOpt()) {
4029                                 p.getArg('[', ']');
4030                                 p.skip_spaces(true);
4031                         }
4032                         p.getArg('{', '}');
4033                         p.skip_spaces(true);
4034                         // eat the '{'
4035                         if (p.next_token().cat() == catBegin)
4036                                 p.get_token();
4037                         p.skip_spaces(true);
4038                         Token to = p.get_token();
4039                         bool shaded = false;
4040                         if (to.asInput() == "\\begin") {
4041                                 p.skip_spaces(true);
4042                                 if (p.getArg('{', '}') == "shaded")
4043                                         shaded = true;
4044                         }
4045                         p.popPosition();
4046                         if (shaded) {
4047                                 parse_outer_box(p, os, FLAG_ITEM, outer,
4048                                                 context, "parbox", "shaded");
4049                         } else
4050                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4051                                           "", "", t.cs());
4052                 }
4053
4054                 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4055                          t.cs() == "shadowbox" || t.cs() == "doublebox")
4056                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4057
4058                 else if (t.cs() == "framebox") {
4059                         if (p.next_token().character() == '(') {
4060                                 //the syntax is: \framebox(x,y)[position]{content}
4061                                 string arg = t.asInput();
4062                                 arg += p.getFullParentheseArg();
4063                                 arg += p.getFullOpt();
4064                                 eat_whitespace(p, os, context, false);
4065                                 handle_ert(os, arg + '{', context);
4066                                 parse_text(p, os, FLAG_ITEM, outer, context);
4067                                 handle_ert(os, "}", context);
4068                         } else {
4069                                 string special = p.getFullOpt();
4070                                 special += p.getOpt();
4071                                 // LyX does not yet support \framebox without any option
4072                                 if (!special.empty())
4073                                         parse_outer_box(p, os, FLAG_ITEM, outer,
4074                                                         context, t.cs(), special);
4075                                 else {
4076                                         eat_whitespace(p, os, context, false);
4077                                         handle_ert(os, "\\framebox{", context);
4078                                         parse_text(p, os, FLAG_ITEM, outer, context);
4079                                         handle_ert(os, "}", context);
4080                                 }
4081                         }
4082                 }
4083
4084                 //\makebox() is part of the picture environment and different from \makebox{}
4085                 //\makebox{} will be parsed by parse_box
4086                 else if (t.cs() == "makebox") {
4087                         if (p.next_token().character() == '(') {
4088                                 //the syntax is: \makebox(x,y)[position]{content}
4089                                 string arg = t.asInput();
4090                                 arg += p.getFullParentheseArg();
4091                                 arg += p.getFullOpt();
4092                                 eat_whitespace(p, os, context, false);
4093                                 handle_ert(os, arg + '{', context);
4094                                 parse_text(p, os, FLAG_ITEM, outer, context);
4095                                 handle_ert(os, "}", context);
4096                         } else
4097                                 //the syntax is: \makebox[width][position]{content}
4098                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4099                                           "", "", t.cs());
4100                 }
4101
4102                 else if (t.cs() == "smallskip" ||
4103                          t.cs() == "medskip" ||
4104                          t.cs() == "bigskip" ||
4105                          t.cs() == "vfill") {
4106                         context.check_layout(os);
4107                         begin_inset(os, "VSpace ");
4108                         os << t.cs();
4109                         end_inset(os);
4110                         skip_spaces_braces(p);
4111                 }
4112
4113                 else if ((where = is_known(t.cs(), known_spaces))) {
4114                         context.check_layout(os);
4115                         begin_inset(os, "space ");
4116                         os << '\\' << known_coded_spaces[where - known_spaces]
4117                            << '\n';
4118                         end_inset(os);
4119                         // LaTeX swallows whitespace after all spaces except
4120                         // "\\,". We have to do that here, too, because LyX
4121                         // adds "{}" which would make the spaces significant.
4122                         if (t.cs() !=  ",")
4123                                 eat_whitespace(p, os, context, false);
4124                         // LyX adds "{}" after all spaces except "\\ " and
4125                         // "\\,", so we have to remove "{}".
4126                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
4127                         // remove the braces after "\\,", too.
4128                         if (t.cs() != " ")
4129                                 skip_braces(p);
4130                 }
4131
4132                 else if (t.cs() == "newpage" ||
4133                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
4134                          t.cs() == "clearpage" ||
4135                          t.cs() == "cleardoublepage") {
4136                         context.check_layout(os);
4137                         begin_inset(os, "Newpage ");
4138                         os << t.cs();
4139                         end_inset(os);
4140                         skip_spaces_braces(p);
4141                 }
4142
4143                 else if (t.cs() == "DeclareRobustCommand" ||
4144                          t.cs() == "DeclareRobustCommandx" ||
4145                          t.cs() == "newcommand" ||
4146                          t.cs() == "newcommandx" ||
4147                          t.cs() == "providecommand" ||
4148                          t.cs() == "providecommandx" ||
4149                          t.cs() == "renewcommand" ||
4150                          t.cs() == "renewcommandx") {
4151                         // DeclareRobustCommand, DeclareRobustCommandx,
4152                         // providecommand and providecommandx could be handled
4153                         // by parse_command(), but we need to call
4154                         // add_known_command() here.
4155                         string name = t.asInput();
4156                         if (p.next_token().asInput() == "*") {
4157                                 // Starred form. Eat '*'
4158                                 p.get_token();
4159                                 name += '*';
4160                         }
4161                         string const command = p.verbatim_item();
4162                         string const opt1 = p.getFullOpt();
4163                         string const opt2 = p.getFullOpt();
4164                         add_known_command(command, opt1, !opt2.empty());
4165                         string const ert = name + '{' + command + '}' +
4166                                            opt1 + opt2 +
4167                                            '{' + p.verbatim_item() + '}';
4168
4169                         if (t.cs() == "DeclareRobustCommand" ||
4170                             t.cs() == "DeclareRobustCommandx" ||
4171                             t.cs() == "providecommand" ||
4172                             t.cs() == "providecommandx" ||
4173                             name[name.length()-1] == '*')
4174                                 handle_ert(os, ert, context);
4175                         else {
4176                                 context.check_layout(os);
4177                                 begin_inset(os, "FormulaMacro");
4178                                 os << "\n" << ert;
4179                                 end_inset(os);
4180                         }
4181                 }
4182
4183                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4184                         // let could be handled by parse_command(),
4185                         // but we need to call add_known_command() here.
4186                         string ert = t.asInput();
4187                         string name;
4188                         p.skip_spaces();
4189                         if (p.next_token().cat() == catBegin) {
4190                                 name = p.verbatim_item();
4191                                 ert += '{' + name + '}';
4192                         } else {
4193                                 name = p.verbatim_item();
4194                                 ert += name;
4195                         }
4196                         string command;
4197                         p.skip_spaces();
4198                         if (p.next_token().cat() == catBegin) {
4199                                 command = p.verbatim_item();
4200                                 ert += '{' + command + '}';
4201                         } else {
4202                                 command = p.verbatim_item();
4203                                 ert += command;
4204                         }
4205                         // If command is known, make name known too, to parse
4206                         // its arguments correctly. For this reason we also
4207                         // have commands in syntax.default that are hardcoded.
4208                         CommandMap::iterator it = known_commands.find(command);
4209                         if (it != known_commands.end())
4210                                 known_commands[t.asInput()] = it->second;
4211                         handle_ert(os, ert, context);
4212                 }
4213
4214                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4215                         bool starred = false;
4216                         if (p.next_token().asInput() == "*") {
4217                                 p.get_token();
4218                                 starred = true;
4219                         }
4220                         string name = t.asInput();
4221                         string const length = p.verbatim_item();
4222                         string unit;
4223                         string valstring;
4224                         bool valid = splitLatexLength(length, valstring, unit);
4225                         bool known_hspace = false;
4226                         bool known_vspace = false;
4227                         bool known_unit = false;
4228                         double value;
4229                         if (valid) {
4230                                 istringstream iss(valstring);
4231                                 iss >> value;
4232                                 if (value == 1.0) {
4233                                         if (t.cs()[0] == 'h') {
4234                                                 if (unit == "\\fill") {
4235                                                         if (!starred) {
4236                                                                 unit = "";
4237                                                                 name = "\\hfill";
4238                                                         }
4239                                                         known_hspace = true;
4240                                                 }
4241                                         } else {
4242                                                 if (unit == "\\smallskipamount") {
4243                                                         unit = "smallskip";
4244                                                         known_vspace = true;
4245                                                 } else if (unit == "\\medskipamount") {
4246                                                         unit = "medskip";
4247                                                         known_vspace = true;
4248                                                 } else if (unit == "\\bigskipamount") {
4249                                                         unit = "bigskip";
4250                                                         known_vspace = true;
4251                                                 } else if (unit == "\\fill") {
4252                                                         unit = "vfill";
4253                                                         known_vspace = true;
4254                                                 }
4255                                         }
4256                                 }
4257                                 if (!known_hspace && !known_vspace) {
4258                                         switch (unitFromString(unit)) {
4259                                         case Length::SP:
4260                                         case Length::PT:
4261                                         case Length::BP:
4262                                         case Length::DD:
4263                                         case Length::MM:
4264                                         case Length::PC:
4265                                         case Length::CC:
4266                                         case Length::CM:
4267                                         case Length::IN:
4268                                         case Length::EX:
4269                                         case Length::EM:
4270                                         case Length::MU:
4271                                                 known_unit = true;
4272                                                 break;
4273                                         default:
4274                                                 break;
4275                                         }
4276                                 }
4277                         }
4278
4279                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4280                                 // Literal horizontal length or known variable
4281                                 context.check_layout(os);
4282                                 begin_inset(os, "space ");
4283                                 os << name;
4284                                 if (starred)
4285                                         os << '*';
4286                                 os << '{';
4287                                 if (known_hspace)
4288                                         os << unit;
4289                                 os << "}";
4290                                 if (known_unit && !known_hspace)
4291                                         os << "\n\\length "
4292                                            << translate_len(length);
4293                                 end_inset(os);
4294                         } else if (known_unit || known_vspace) {
4295                                 // Literal vertical length or known variable
4296                                 context.check_layout(os);
4297                                 begin_inset(os, "VSpace ");
4298                                 if (known_unit)
4299                                         os << value;
4300                                 os << unit;
4301                                 if (starred)
4302                                         os << '*';
4303                                 end_inset(os);
4304                         } else {
4305                                 // LyX can't handle other length variables in Inset VSpace/space
4306                                 if (starred)
4307                                         name += '*';
4308                                 if (valid) {
4309                                         if (value == 1.0)
4310                                                 handle_ert(os, name + '{' + unit + '}', context);
4311                                         else if (value == -1.0)
4312                                                 handle_ert(os, name + "{-" + unit + '}', context);
4313                                         else
4314                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
4315                                 } else
4316                                         handle_ert(os, name + '{' + length + '}', context);
4317                         }
4318                 }
4319
4320                 // The single '=' is meant here.
4321                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4322                         p.skip_spaces();
4323                         context.check_layout(os);
4324                         begin_inset(os, "Flex ");
4325                         os << to_utf8(newinsetlayout->name()) << '\n'
4326                            << "status collapsed\n";
4327                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4328                         end_inset(os);
4329                 }
4330
4331                 else if (t.cs() == "includepdf") {
4332                         p.skip_spaces();
4333                         string const arg = p.getArg('[', ']');
4334                         map<string, string> opts;
4335                         vector<string> keys;
4336                         split_map(arg, opts, keys);
4337                         string name = normalize_filename(p.verbatim_item());
4338                         string const path = getMasterFilePath(true);
4339                         // We want to preserve relative / absolute filenames,
4340                         // therefore path is only used for testing
4341                         if (!makeAbsPath(name, path).exists()) {
4342                                 // The file extension is probably missing.
4343                                 // Now try to find it out.
4344                                 char const * const pdfpages_format[] = {"pdf", 0};
4345                                 string const pdftex_name =
4346                                         find_file(name, path, pdfpages_format);
4347                                 if (!pdftex_name.empty()) {
4348                                         name = pdftex_name;
4349                                         pdflatex = true;
4350                                 }
4351                         }
4352                         FileName const absname = makeAbsPath(name, path);
4353                         if (absname.exists())
4354                         {
4355                                 fix_child_filename(name);
4356                                 copy_file(absname, name);
4357                         } else
4358                                 cerr << "Warning: Could not find file '"
4359                                      << name << "'." << endl;
4360                         // write output
4361                         context.check_layout(os);
4362                         begin_inset(os, "External\n\ttemplate ");
4363                         os << "PDFPages\n\tfilename "
4364                            << name << "\n";
4365                         // parse the options
4366                         if (opts.find("pages") != opts.end())
4367                                 os << "\textra LaTeX \"pages="
4368                                    << opts["pages"] << "\"\n";
4369                         if (opts.find("angle") != opts.end())
4370                                 os << "\trotateAngle "
4371                                    << opts["angle"] << '\n';
4372                         if (opts.find("origin") != opts.end()) {
4373                                 ostringstream ss;
4374                                 string const opt = opts["origin"];
4375                                 if (opt == "tl") ss << "topleft";
4376                                 if (opt == "bl") ss << "bottomleft";
4377                                 if (opt == "Bl") ss << "baselineleft";
4378                                 if (opt == "c") ss << "center";
4379                                 if (opt == "tc") ss << "topcenter";
4380                                 if (opt == "bc") ss << "bottomcenter";
4381                                 if (opt == "Bc") ss << "baselinecenter";
4382                                 if (opt == "tr") ss << "topright";
4383                                 if (opt == "br") ss << "bottomright";
4384                                 if (opt == "Br") ss << "baselineright";
4385                                 if (!ss.str().empty())
4386                                         os << "\trotateOrigin " << ss.str() << '\n';
4387                                 else
4388                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4389                         }
4390                         if (opts.find("width") != opts.end())
4391                                 os << "\twidth "
4392                                    << translate_len(opts["width"]) << '\n';
4393                         if (opts.find("height") != opts.end())
4394                                 os << "\theight "
4395                                    << translate_len(opts["height"]) << '\n';
4396                         if (opts.find("keepaspectratio") != opts.end())
4397                                 os << "\tkeepAspectRatio\n";
4398                         end_inset(os);
4399                         context.check_layout(os);
4400                         registerExternalTemplatePackages("PDFPages");
4401                 }
4402
4403                 else if (t.cs() == "loadgame") {
4404                         p.skip_spaces();
4405                         string name = normalize_filename(p.verbatim_item());
4406                         string const path = getMasterFilePath(true);
4407                         // We want to preserve relative / absolute filenames,
4408                         // therefore path is only used for testing
4409                         if (!makeAbsPath(name, path).exists()) {
4410                                 // The file extension is probably missing.
4411                                 // Now try to find it out.
4412                                 char const * const lyxskak_format[] = {"fen", 0};
4413                                 string const lyxskak_name =
4414                                         find_file(name, path, lyxskak_format);
4415                                 if (!lyxskak_name.empty())
4416                                         name = lyxskak_name;
4417                         }
4418                         FileName const absname = makeAbsPath(name, path);
4419                         if (absname.exists())
4420                         {
4421                                 fix_child_filename(name);
4422                                 copy_file(absname, name);
4423                         } else
4424                                 cerr << "Warning: Could not find file '"
4425                                      << name << "'." << endl;
4426                         context.check_layout(os);
4427                         begin_inset(os, "External\n\ttemplate ");
4428                         os << "ChessDiagram\n\tfilename "
4429                            << name << "\n";
4430                         end_inset(os);
4431                         context.check_layout(os);
4432                         // after a \loadgame follows a \showboard
4433                         if (p.get_token().asInput() == "showboard")
4434                                 p.get_token();
4435                         registerExternalTemplatePackages("ChessDiagram");
4436                 }
4437
4438                 else {
4439                         // try to see whether the string is in unicodesymbols
4440                         // Only use text mode commands, since we are in text mode here,
4441                         // and math commands may be invalid (bug 6797)
4442                         bool termination;
4443                         docstring rem;
4444                         set<string> req;
4445                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4446                                         Encodings::TEXT_CMD, termination, rem, &req);
4447                         if (!s.empty()) {
4448                                 if (!rem.empty())
4449                                         cerr << "When parsing " << t.cs()
4450                                              << ", result is " << to_utf8(s)
4451                                              << "+" << to_utf8(rem) << endl;
4452                                 context.check_layout(os);
4453                                 os << to_utf8(s);
4454                                 if (termination)
4455                                         skip_spaces_braces(p);
4456                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4457                                         preamble.registerAutomaticallyLoadedPackage(*it);
4458                         }
4459                         //cerr << "#: " << t << " mode: " << mode << endl;
4460                         // heuristic: read up to next non-nested space
4461                         /*
4462                         string s = t.asInput();
4463                         string z = p.verbatim_item();
4464                         while (p.good() && z != " " && !z.empty()) {
4465                                 //cerr << "read: " << z << endl;
4466                                 s += z;
4467                                 z = p.verbatim_item();
4468                         }
4469                         cerr << "found ERT: " << s << endl;
4470                         handle_ert(os, s + ' ', context);
4471                         */
4472                         else {
4473                                 string name = t.asInput();
4474                                 if (p.next_token().asInput() == "*") {
4475                                         // Starred commands like \vspace*{}
4476                                         p.get_token();  // Eat '*'
4477                                         name += '*';
4478                                 }
4479                                 if (!parse_command(name, p, os, outer, context))
4480                                         handle_ert(os, name, context);
4481                         }
4482                 }
4483
4484                 if (flags & FLAG_LEAVE) {
4485                         flags &= ~FLAG_LEAVE;
4486                         break;
4487                 }
4488         }
4489 }
4490
4491
4492 string guessLanguage(Parser & p, string const & lang)
4493 {
4494         typedef std::map<std::string, size_t> LangMap;
4495         // map from language names to number of characters
4496         LangMap used;
4497         used[lang] = 0;
4498         for (char const * const * i = supported_CJK_languages; *i; i++)
4499                 used[string(*i)] = 0;
4500
4501         while (p.good()) {
4502                 Token const t = p.get_token();
4503                 // comments are not counted for any language
4504                 if (t.cat() == catComment)
4505                         continue;
4506                 // commands are not counted as well, but we need to detect
4507                 // \begin{CJK} and switch encoding if needed
4508                 if (t.cat() == catEscape) {
4509                         if (t.cs() == "inputencoding") {
4510                                 string const enc = subst(p.verbatim_item(), "\n", " ");
4511                                 p.setEncoding(enc, Encoding::inputenc);
4512                                 continue;
4513                         }
4514                         if (t.cs() != "begin")
4515                                 continue;
4516                 } else {
4517                         // Non-CJK content is counted for lang.
4518                         // We do not care about the real language here:
4519                         // If we have more non-CJK contents than CJK contents,
4520                         // we simply use the language that was specified as
4521                         // babel main language.
4522                         used[lang] += t.asInput().length();
4523                         continue;
4524                 }
4525                 // Now we are starting an environment
4526                 p.pushPosition();
4527                 string const name = p.getArg('{', '}');
4528                 if (name != "CJK") {
4529                         p.popPosition();
4530                         continue;
4531                 }
4532                 // It is a CJK environment
4533                 p.popPosition();
4534                 /* name = */ p.getArg('{', '}');
4535                 string const encoding = p.getArg('{', '}');
4536                 /* mapping = */ p.getArg('{', '}');
4537                 string const encoding_old = p.getEncoding();
4538                 char const * const * const where =
4539                         is_known(encoding, supported_CJK_encodings);
4540                 if (where)
4541                         p.setEncoding(encoding, Encoding::CJK);
4542                 else
4543                         p.setEncoding("UTF-8");
4544                 string const text = p.verbatimEnvironment("CJK");
4545                 p.setEncoding(encoding_old);
4546                 p.skip_spaces();
4547                 if (!where) {
4548                         // ignore contents in unknown CJK encoding
4549                         continue;
4550                 }
4551                 // the language of the text
4552                 string const cjk =
4553                         supported_CJK_languages[where - supported_CJK_encodings];
4554                 used[cjk] += text.length();
4555         }
4556         LangMap::const_iterator use = used.begin();
4557         for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4558                 if (it->second > use->second)
4559                         use = it;
4560         }
4561         return use->first;
4562 }
4563
4564 // }])
4565
4566
4567 } // namespace lyx