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