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