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