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