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