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