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