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