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