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