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