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