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