]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
Harmonize naming
[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 literate Chunk section. The initial "<<" is already parsed.
1997 bool parse_chunk(Parser & p, ostream & os, Context & context)
1998 {
1999         // check whether a chunk is possible here.
2000         if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2001                 return false;
2002         }
2003
2004         p.pushPosition();
2005
2006         // read the parameters
2007         Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2008         if (!params.first) {
2009                 p.popPosition();
2010                 return false;
2011         }
2012
2013         Parser::Arg const code = p.verbatimStuff("\n@");
2014         if (!code.first) {
2015                 p.popPosition();
2016                 return false;
2017         }
2018         string const post_chunk = p.verbatimStuff("\n").second + '\n';
2019         if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2020                 p.popPosition();
2021                 return false;
2022         }
2023         // The last newline read is important for paragraph handling
2024         p.putback();
2025         p.deparse();
2026
2027         //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2028         // We must have a valid layout before outputting the Chunk inset.
2029         context.check_layout(os);
2030         Context chunkcontext(true, context.textclass);
2031         chunkcontext.layout = &context.textclass.plainLayout();
2032         begin_inset(os, "Flex Chunk");
2033         os << "\nstatus open\n";
2034         if (!params.second.empty()) {
2035                 chunkcontext.check_layout(os);
2036                 Context paramscontext(true, context.textclass);
2037                 paramscontext.layout = &context.textclass.plainLayout();
2038                 begin_inset(os, "Argument 1");
2039                 os << "\nstatus open\n";
2040                 output_ert(os, params.second, paramscontext);
2041                 end_inset(os);
2042         }
2043         output_ert(os, code.second, chunkcontext);
2044         end_inset(os);
2045
2046         p.dropPosition();
2047         return true;
2048 }
2049
2050
2051 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2052 bool is_macro(Parser & p)
2053 {
2054         Token first = p.curr_token();
2055         if (first.cat() != catEscape || !p.good())
2056                 return false;
2057         if (first.cs() == "def")
2058                 return true;
2059         if (first.cs() != "global" && first.cs() != "long")
2060                 return false;
2061         Token second = p.get_token();
2062         int pos = 1;
2063         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2064                second.cat() == catNewline || second.cat() == catComment)) {
2065                 second = p.get_token();
2066                 pos++;
2067         }
2068         bool secondvalid = second.cat() == catEscape;
2069         Token third;
2070         bool thirdvalid = false;
2071         if (p.good() && first.cs() == "global" && secondvalid &&
2072             second.cs() == "long") {
2073                 third = p.get_token();
2074                 pos++;
2075                 while (p.good() && !p.isParagraph() &&
2076                        (third.cat() == catSpace ||
2077                         third.cat() == catNewline ||
2078                         third.cat() == catComment)) {
2079                         third = p.get_token();
2080                         pos++;
2081                 }
2082                 thirdvalid = third.cat() == catEscape;
2083         }
2084         for (int i = 0; i < pos; ++i)
2085                 p.putback();
2086         if (!secondvalid)
2087                 return false;
2088         if (!thirdvalid)
2089                 return (first.cs() == "global" || first.cs() == "long") &&
2090                        second.cs() == "def";
2091         return first.cs() == "global" && second.cs() == "long" &&
2092                third.cs() == "def";
2093 }
2094
2095
2096 /// Parse a macro definition (assumes that is_macro() returned true)
2097 void parse_macro(Parser & p, ostream & os, Context & context)
2098 {
2099         context.check_layout(os);
2100         Token first = p.curr_token();
2101         Token second;
2102         Token third;
2103         string command = first.asInput();
2104         if (first.cs() != "def") {
2105                 p.get_token();
2106                 eat_whitespace(p, os, context, false);
2107                 second = p.curr_token();
2108                 command += second.asInput();
2109                 if (second.cs() != "def") {
2110                         p.get_token();
2111                         eat_whitespace(p, os, context, false);
2112                         third = p.curr_token();
2113                         command += third.asInput();
2114                 }
2115         }
2116         eat_whitespace(p, os, context, false);
2117         string const name = p.get_token().cs();
2118         eat_whitespace(p, os, context, false);
2119
2120         // parameter text
2121         bool simple = true;
2122         string paramtext;
2123         int arity = 0;
2124         while (p.next_token().cat() != catBegin) {
2125                 if (p.next_token().cat() == catParameter) {
2126                         // # found
2127                         p.get_token();
2128                         paramtext += "#";
2129
2130                         // followed by number?
2131                         if (p.next_token().cat() == catOther) {
2132                                 string s = p.get_token().asInput();
2133                                 paramtext += s;
2134                                 // number = current arity + 1?
2135                                 if (s.size() == 1 && s[0] == arity + '0' + 1)
2136                                         ++arity;
2137                                 else
2138                                         simple = false;
2139                         } else
2140                                 paramtext += p.get_token().cs();
2141                 } else {
2142                         paramtext += p.get_token().cs();
2143                         simple = false;
2144                 }
2145         }
2146
2147         // only output simple (i.e. compatible) macro as FormulaMacros
2148         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2149         if (simple) {
2150                 context.check_layout(os);
2151                 begin_inset(os, "FormulaMacro");
2152                 os << "\n\\def" << ert;
2153                 end_inset(os);
2154         } else
2155                 output_ert_inset(os, command + ert, context);
2156 }
2157
2158
2159 void registerExternalTemplatePackages(string const & name)
2160 {
2161         external::TemplateManager const & etm = external::TemplateManager::get();
2162         external::Template const * const et = etm.getTemplateByName(name);
2163         if (!et)
2164                 return;
2165         external::Template::Formats::const_iterator cit = et->formats.end();
2166         if (pdflatex)
2167                 cit = et->formats.find("PDFLaTeX");
2168         if (cit == et->formats.end())
2169                 // If the template has not specified a PDFLaTeX output,
2170                 // we try the LaTeX format.
2171                 cit = et->formats.find("LaTeX");
2172         if (cit == et->formats.end())
2173                 return;
2174         vector<string>::const_iterator qit = cit->second.requirements.begin();
2175         vector<string>::const_iterator qend = cit->second.requirements.end();
2176         for (; qit != qend; ++qit)
2177                 preamble.registerAutomaticallyLoadedPackage(*qit);
2178 }
2179
2180 } // anonymous namespace
2181
2182
2183 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2184                 Context & context)
2185 {
2186         Layout const * newlayout = 0;
2187         InsetLayout const * newinsetlayout = 0;
2188         char const * const * where = 0;
2189         // Store the latest bibliographystyle, addcontentslineContent and
2190         // nocite{*} option (needed for bibtex inset)
2191         string btprint;
2192         string contentslineContent;
2193         string bibliographystyle = "default";
2194         bool const use_natbib = isProvided("natbib");
2195         bool const use_jurabib = isProvided("jurabib");
2196         string last_env;
2197         while (p.good()) {
2198                 Token const & t = p.get_token();
2199
2200         // it is impossible to determine the correct encoding for non-CJK Japanese.
2201         // Therefore write a note at the beginning of the document
2202         if (is_nonCJKJapanese) {
2203                 context.check_layout(os);
2204                 begin_inset(os, "Note Note\n");
2205                 os << "status open\n\\begin_layout Plain Layout\n"
2206                    << "\\series bold\n"
2207                    << "Important information:\n"
2208                    << "\\end_layout\n\n"
2209                    << "\\begin_layout Plain Layout\n"
2210                    << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2211                    << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2212                    << " The iconv encoding " << p.getEncoding() << " was used.\n"
2213                    << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2214                    << " and specify the encoding using the -e command-line switch.\n"
2215                    << " In addition, you might want to double check that the desired output encoding\n"
2216                    << " is correctly selected in Document > Settings > Language.\n"
2217                    << "\\end_layout\n";
2218                 end_inset(os);
2219                 is_nonCJKJapanese = false;
2220         }
2221
2222 #ifdef FILEDEBUG
2223                 debugToken(cerr, t, flags);
2224 #endif
2225
2226                 if (flags & FLAG_ITEM) {
2227                         if (t.cat() == catSpace)
2228                                 continue;
2229
2230                         flags &= ~FLAG_ITEM;
2231                         if (t.cat() == catBegin) {
2232                                 // skip the brace and collect everything to the next matching
2233                                 // closing brace
2234                                 flags |= FLAG_BRACE_LAST;
2235                                 continue;
2236                         }
2237
2238                         // handle only this single token, leave the loop if done
2239                         flags |= FLAG_LEAVE;
2240                 }
2241
2242                 if (t.cat() != catEscape && t.character() == ']' &&
2243                     (flags & FLAG_BRACK_LAST))
2244                         return;
2245                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2246                         return;
2247
2248                 // If there is anything between \end{env} and \begin{env} we
2249                 // don't need to output a separator.
2250                 if (t.cat() != catSpace && t.cat() != catNewline &&
2251                     t.asInput() != "\\begin")
2252                         last_env = "";
2253
2254                 //
2255                 // cat codes
2256                 //
2257                 if (t.cat() == catMath) {
2258                         // we are inside some text mode thingy, so opening new math is allowed
2259                         context.check_layout(os);
2260                         begin_inset(os, "Formula ");
2261                         Token const & n = p.get_token();
2262                         bool const display(n.cat() == catMath && outer);
2263                         if (display) {
2264                                 // TeX's $$...$$ syntax for displayed math
2265                                 os << "\\[";
2266                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2267                                 os << "\\]";
2268                                 p.get_token(); // skip the second '$' token
2269                         } else {
2270                                 // simple $...$  stuff
2271                                 p.putback();
2272                                 os << '$';
2273                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2274                                 os << '$';
2275                         }
2276                         end_inset(os);
2277                         if (display) {
2278                                 // Prevent the conversion of a line break to a
2279                                 // space (bug 7668). This does not change the
2280                                 // output, but looks ugly in LyX.
2281                                 eat_whitespace(p, os, context, false);
2282                         }
2283                 }
2284
2285                 else if (t.cat() == catSuper || t.cat() == catSub)
2286                         cerr << "catcode " << t << " illegal in text mode\n";
2287
2288                 // Basic support for english quotes. This should be
2289                 // extended to other quotes, but is not so easy (a
2290                 // left english quote is the same as a right german
2291                 // quote...)
2292                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2293                         context.check_layout(os);
2294                         begin_inset(os, "Quotes ");
2295                         os << "eld";
2296                         end_inset(os);
2297                         p.get_token();
2298                         skip_braces(p);
2299                 }
2300                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2301                         context.check_layout(os);
2302                         begin_inset(os, "Quotes ");
2303                         os << "erd";
2304                         end_inset(os);
2305                         p.get_token();
2306                         skip_braces(p);
2307                 }
2308
2309                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2310                         context.check_layout(os);
2311                         begin_inset(os, "Quotes ");
2312                         os << "ald";
2313                         end_inset(os);
2314                         p.get_token();
2315                         skip_braces(p);
2316                 }
2317
2318                 else if (t.asInput() == "<"
2319                          && p.next_token().asInput() == "<") {
2320                         bool has_chunk = false;
2321                         if (noweb_mode) {
2322                                 p.pushPosition();
2323                                 p.get_token();
2324                                 has_chunk = parse_chunk(p, os, context);
2325                                 if (!has_chunk)
2326                                         p.popPosition();
2327                         }
2328
2329                         if (!has_chunk) {
2330                                 context.check_layout(os);
2331                                 begin_inset(os, "Quotes ");
2332                                 //FIXME: this is a right danish quote;
2333                                 // why not a left french quote?
2334                                 os << "ard";
2335                                 end_inset(os);
2336                                 p.get_token();
2337                                 skip_braces(p);
2338                         }
2339                 }
2340
2341                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2342                         check_space(p, os, context);
2343
2344                 else if (t.character() == '[' && noweb_mode &&
2345                          p.next_token().character() == '[') {
2346                         // These can contain underscores
2347                         p.putback();
2348                         string const s = p.getFullOpt() + ']';
2349                         if (p.next_token().character() == ']')
2350                                 p.get_token();
2351                         else
2352                                 cerr << "Warning: Inserting missing ']' in '"
2353                                      << s << "'." << endl;
2354                         output_ert_inset(os, s, context);
2355                 }
2356
2357                 else if (t.cat() == catLetter) {
2358                         context.check_layout(os);
2359                         // Workaround for bug 4752.
2360                         // FIXME: This whole code block needs to be removed
2361                         //        when the bug is fixed and tex2lyx produces
2362                         //        the updated file format.
2363                         // The replacement algorithm in LyX is so stupid that
2364                         // it even translates a phrase if it is part of a word.
2365                         bool handled = false;
2366                         for (int const * l = known_phrase_lengths; *l; ++l) {
2367                                 string phrase = t.cs();
2368                                 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2369                                         phrase += p.get_token().cs();
2370                                 if (is_known(phrase, known_coded_phrases)) {
2371                                         output_ert_inset(os, phrase, context);
2372                                         handled = true;
2373                                         break;
2374                                 } else {
2375                                         for (size_t i = 1; i < phrase.length(); ++i)
2376                                                 p.putback();
2377                                 }
2378                         }
2379                         if (!handled)
2380                                 os << t.cs();
2381                 }
2382
2383                 else if (t.cat() == catOther ||
2384                                t.cat() == catAlign ||
2385                                t.cat() == catParameter) {
2386                         // This translates "&" to "\\&" which may be wrong...
2387                         context.check_layout(os);
2388                         os << t.cs();
2389                 }
2390
2391                 else if (p.isParagraph()) {
2392                         if (context.new_layout_allowed)
2393                                 context.new_paragraph(os);
2394                         else
2395                                 output_ert_inset(os, "\\par ", context);
2396                         eat_whitespace(p, os, context, true);
2397                 }
2398
2399                 else if (t.cat() == catActive) {
2400                         context.check_layout(os);
2401                         if (t.character() == '~') {
2402                                 if (context.layout->free_spacing)
2403                                         os << ' ';
2404                                 else {
2405                                         begin_inset(os, "space ~\n");
2406                                         end_inset(os);
2407                                 }
2408                         } else
2409                                 os << t.cs();
2410                 }
2411
2412                 else if (t.cat() == catBegin) {
2413                         Token const next = p.next_token();
2414                         Token const end = p.next_next_token();
2415                         if (next.cat() == catEnd) {
2416                                 // {}
2417                                 Token const prev = p.prev_token();
2418                                 p.get_token();
2419                                 if (p.next_token().character() == '`' ||
2420                                     (prev.character() == '-' &&
2421                                      p.next_token().character() == '-'))
2422                                         ; // ignore it in {}`` or -{}-
2423                                 else
2424                                         output_ert_inset(os, "{}", context);
2425                         } else if (next.cat() == catEscape &&
2426                                    is_known(next.cs(), known_quotes) &&
2427                                    end.cat() == catEnd) {
2428                                 // Something like {\textquoteright} (e.g.
2429                                 // from writer2latex). LyX writes
2430                                 // \textquoteright{}, so we may skip the
2431                                 // braces here for better readability.
2432                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2433                                                    outer, context);
2434                         } else if (p.next_token().asInput() == "\\ascii") {
2435                                 // handle the \ascii characters
2436                                 // (the case without braces is handled later)
2437                                 // the code is "{\ascii\xxx}"
2438                                 p.get_token(); // eat \ascii
2439                                 string name2 = p.get_token().asInput();
2440                                 p.get_token(); // eat the final '}'
2441                                 string const name = "{\\ascii" + name2 + "}";
2442                                 bool termination;
2443                                 docstring rem;
2444                                 set<string> req;
2445                                 // get the character from unicodesymbols
2446                                 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2447                                         Encodings::TEXT_CMD, termination, rem, &req);
2448                                 if (!s.empty()) {
2449                                         context.check_layout(os);
2450                                         os << to_utf8(s);
2451                                         if (!rem.empty())
2452                                                 output_ert_inset(os,
2453                                                         to_utf8(rem), context);
2454                                         for (set<string>::const_iterator it = req.begin();
2455                                              it != req.end(); ++it)
2456                                                 preamble.registerAutomaticallyLoadedPackage(*it);
2457                                 } else
2458                                         // we did not find a non-ert version
2459                                         output_ert_inset(os, name, context);
2460                         } else {
2461                         context.check_layout(os);
2462                         // special handling of font attribute changes
2463                         Token const prev = p.prev_token();
2464                         TeXFont const oldFont = context.font;
2465                         if (next.character() == '[' ||
2466                             next.character() == ']' ||
2467                             next.character() == '*') {
2468                                 p.get_token();
2469                                 if (p.next_token().cat() == catEnd) {
2470                                         os << next.cs();
2471                                         p.get_token();
2472                                 } else {
2473                                         p.putback();
2474                                         output_ert_inset(os, "{", context);
2475                                         parse_text_snippet(p, os,
2476                                                         FLAG_BRACE_LAST,
2477                                                         outer, context);
2478                                         output_ert_inset(os, "}", context);
2479                                 }
2480                         } else if (! context.new_layout_allowed) {
2481                                 output_ert_inset(os, "{", context);
2482                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2483                                                    outer, context);
2484                                 output_ert_inset(os, "}", context);
2485                         } else if (is_known(next.cs(), known_sizes)) {
2486                                 // next will change the size, so we must
2487                                 // reset it here
2488                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2489                                                    outer, context);
2490                                 if (!context.atParagraphStart())
2491                                         os << "\n\\size "
2492                                            << context.font.size << "\n";
2493                         } else if (is_known(next.cs(), known_font_families)) {
2494                                 // next will change the font family, so we
2495                                 // must reset it here
2496                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2497                                                    outer, context);
2498                                 if (!context.atParagraphStart())
2499                                         os << "\n\\family "
2500                                            << context.font.family << "\n";
2501                         } else if (is_known(next.cs(), known_font_series)) {
2502                                 // next will change the font series, so we
2503                                 // must reset it here
2504                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2505                                                    outer, context);
2506                                 if (!context.atParagraphStart())
2507                                         os << "\n\\series "
2508                                            << context.font.series << "\n";
2509                         } else if (is_known(next.cs(), known_font_shapes)) {
2510                                 // next will change the font shape, so we
2511                                 // must reset it here
2512                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2513                                                    outer, context);
2514                                 if (!context.atParagraphStart())
2515                                         os << "\n\\shape "
2516                                            << context.font.shape << "\n";
2517                         } else if (is_known(next.cs(), known_old_font_families) ||
2518                                    is_known(next.cs(), known_old_font_series) ||
2519                                    is_known(next.cs(), known_old_font_shapes)) {
2520                                 // next will change the font family, series
2521                                 // and shape, so we must reset it here
2522                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2523                                                    outer, context);
2524                                 if (!context.atParagraphStart())
2525                                         os <<  "\n\\family "
2526                                            << context.font.family
2527                                            << "\n\\series "
2528                                            << context.font.series
2529                                            << "\n\\shape "
2530                                            << context.font.shape << "\n";
2531                         } else {
2532                                 output_ert_inset(os, "{", context);
2533                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2534                                                    outer, context);
2535                                 output_ert_inset(os, "}", context);
2536                                 }
2537                         }
2538                 }
2539
2540                 else if (t.cat() == catEnd) {
2541                         if (flags & FLAG_BRACE_LAST) {
2542                                 return;
2543                         }
2544                         cerr << "stray '}' in text\n";
2545                         output_ert_inset(os, "}", context);
2546                 }
2547
2548                 else if (t.cat() == catComment)
2549                         parse_comment(p, os, t, context);
2550
2551                 //
2552                 // control sequences
2553                 //
2554
2555                 else if (t.cs() == "(" || t.cs() == "[") {
2556                         bool const simple = t.cs() == "(";
2557                         context.check_layout(os);
2558                         begin_inset(os, "Formula");
2559                         os << " \\" << t.cs();
2560                         parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2561                         os << '\\' << (simple ? ')' : ']');
2562                         end_inset(os);
2563                         if (!simple) {
2564                                 // Prevent the conversion of a line break to a
2565                                 // space (bug 7668). This does not change the
2566                                 // output, but looks ugly in LyX.
2567                                 eat_whitespace(p, os, context, false);
2568                         }
2569                 }
2570
2571                 else if (t.cs() == "begin")
2572                         parse_environment(p, os, outer, last_env,
2573                                           context);
2574
2575                 else if (t.cs() == "end") {
2576                         if (flags & FLAG_END) {
2577                                 // eat environment name
2578                                 string const name = p.getArg('{', '}');
2579                                 if (name != active_environment())
2580                                         cerr << "\\end{" + name + "} does not match \\begin{"
2581                                                 + active_environment() + "}\n";
2582                                 return;
2583                         }
2584                         p.error("found 'end' unexpectedly");
2585                 }
2586
2587                 else if (t.cs() == "item") {
2588                         string s;
2589                         bool const optarg = p.hasOpt();
2590                         if (optarg) {
2591                                 // FIXME: This swallows comments, but we cannot use
2592                                 //        eat_whitespace() since we must not output
2593                                 //        anything before the item.
2594                                 p.skip_spaces(true);
2595                                 s = p.verbatimOption();
2596                         } else
2597                                 p.skip_spaces(false);
2598                         context.set_item();
2599                         context.check_layout(os);
2600                         if (context.has_item) {
2601                                 // An item in an unknown list-like environment
2602                                 // FIXME: Do this in check_layout()!
2603                                 context.has_item = false;
2604                                 if (optarg)
2605                                         output_ert_inset(os, "\\item", context);
2606                                 else
2607                                         output_ert_inset(os, "\\item ", context);
2608                         }
2609                         if (optarg) {
2610                                 if (context.layout->labeltype != LABEL_MANUAL) {
2611                                         // LyX does not support \item[\mybullet]
2612                                         // in itemize environments
2613                                         Parser p2(s + ']');
2614                                         os << parse_text_snippet(p2,
2615                                                 FLAG_BRACK_LAST, outer, context);
2616                                 } else if (!s.empty()) {
2617                                         // LyX adds braces around the argument,
2618                                         // so we need to remove them here.
2619                                         if (s.size() > 2 && s[0] == '{' &&
2620                                             s[s.size()-1] == '}')
2621                                                 s = s.substr(1, s.size()-2);
2622                                         // If the argument contains a space we
2623                                         // must put it into ERT: Otherwise LyX
2624                                         // would misinterpret the space as
2625                                         // item delimiter (bug 7663)
2626                                         if (contains(s, ' ')) {
2627                                                 output_ert_inset(os, s, context);
2628                                         } else {
2629                                                 Parser p2(s + ']');
2630                                                 os << parse_text_snippet(p2,
2631                                                         FLAG_BRACK_LAST,
2632                                                         outer, context);
2633                                         }
2634                                         // The space is needed to separate the
2635                                         // item from the rest of the sentence.
2636                                         os << ' ';
2637                                         eat_whitespace(p, os, context, false);
2638                                 }
2639                         }
2640                 }
2641
2642                 else if (t.cs() == "bibitem") {
2643                         context.set_item();
2644                         context.check_layout(os);
2645                         eat_whitespace(p, os, context, false);
2646                         string label = convert_command_inset_arg(p.verbatimOption());
2647                         string key = convert_command_inset_arg(p.verbatim_item());
2648                         if (contains(label, '\\') || contains(key, '\\')) {
2649                                 // LyX can't handle LaTeX commands in labels or keys
2650                                 output_ert_inset(os, t.asInput() + '[' + label +
2651                                                "]{" + p.verbatim_item() + '}',
2652                                            context);
2653                         } else {
2654                                 begin_command_inset(os, "bibitem", "bibitem");
2655                                 os << "label \"" << label << "\"\n"
2656                                       "key \"" << key << "\"\n";
2657                                 end_inset(os);
2658                         }
2659                 }
2660
2661                 else if (is_macro(p)) {
2662                         // catch the case of \def\inputGnumericTable
2663                         bool macro = true;
2664                         if (t.cs() == "def") {
2665                                 Token second = p.next_token();
2666                                 if (second.cs() == "inputGnumericTable") {
2667                                         p.pushPosition();
2668                                         p.get_token();
2669                                         skip_braces(p);
2670                                         Token third = p.get_token();
2671                                         p.popPosition();
2672                                         if (third.cs() == "input") {
2673                                                 p.get_token();
2674                                                 skip_braces(p);
2675                                                 p.get_token();
2676                                                 string name = normalize_filename(p.verbatim_item());
2677                                                 string const path = getMasterFilePath(true);
2678                                                 // We want to preserve relative / absolute filenames,
2679                                                 // therefore path is only used for testing
2680                                                 // The file extension is in every case ".tex".
2681                                                 // So we need to remove this extension and check for
2682                                                 // the original one.
2683                                                 name = removeExtension(name);
2684                                                 if (!makeAbsPath(name, path).exists()) {
2685                                                         char const * const Gnumeric_formats[] = {"gnumeric",
2686                                                                 "ods", "xls", 0};
2687                                                         string const Gnumeric_name =
2688                                                                 find_file(name, path, Gnumeric_formats);
2689                                                         if (!Gnumeric_name.empty())
2690                                                                 name = Gnumeric_name;
2691                                                 }
2692                                                 FileName const absname = makeAbsPath(name, path);
2693                                                 if (absname.exists()) {
2694                                                         fix_child_filename(name);
2695                                                         copy_file(absname, name);
2696                                                 } else
2697                                                         cerr << "Warning: Could not find file '"
2698                                                              << name << "'." << endl;
2699                                                 context.check_layout(os);
2700                                                 begin_inset(os, "External\n\ttemplate ");
2701                                                 os << "GnumericSpreadsheet\n\tfilename "
2702                                                    << name << "\n";
2703                                                 end_inset(os);
2704                                                 context.check_layout(os);
2705                                                 macro = false;
2706                                                 // register the packages that are automatically loaded
2707                                                 // by the Gnumeric template
2708                                                 registerExternalTemplatePackages("GnumericSpreadsheet");
2709                                         }
2710                                 }
2711                         }
2712                         if (macro)
2713                                 parse_macro(p, os, context);
2714                 }
2715
2716                 else if (t.cs() == "noindent") {
2717                         p.skip_spaces();
2718                         context.add_par_extra_stuff("\\noindent\n");
2719                 }
2720
2721                 else if (t.cs() == "appendix") {
2722                         context.add_par_extra_stuff("\\start_of_appendix\n");
2723                         // We need to start a new paragraph. Otherwise the
2724                         // appendix in 'bla\appendix\chapter{' would start
2725                         // too late.
2726                         context.new_paragraph(os);
2727                         // We need to make sure that the paragraph is
2728                         // generated even if it is empty. Otherwise the
2729                         // appendix in '\par\appendix\par\chapter{' would
2730                         // start too late.
2731                         context.check_layout(os);
2732                         // FIXME: This is a hack to prevent paragraph
2733                         // deletion if it is empty. Handle this better!
2734                         output_ert_inset(os,
2735                                 "%dummy comment inserted by tex2lyx to "
2736                                 "ensure that this paragraph is not empty",
2737                                 context);
2738                         // Both measures above may generate an additional
2739                         // empty paragraph, but that does not hurt, because
2740                         // whitespace does not matter here.
2741                         eat_whitespace(p, os, context, true);
2742                 }
2743
2744                 // Must catch empty dates before findLayout is called below
2745                 else if (t.cs() == "date") {
2746                         eat_whitespace(p, os, context, false);
2747                         p.pushPosition();
2748                         string const date = p.verbatim_item();
2749                         p.popPosition();
2750                         if (date.empty()) {
2751                                 preamble.suppressDate(true);
2752                                 p.verbatim_item();
2753                         } else {
2754                                 preamble.suppressDate(false);
2755                                 if (context.new_layout_allowed &&
2756                                     (newlayout = findLayout(context.textclass,
2757                                                             t.cs(), true))) {
2758                                         // write the layout
2759                                         output_command_layout(os, p, outer,
2760                                                         context, newlayout);
2761                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2762                                         if (!preamble.titleLayoutFound())
2763                                                 preamble.titleLayoutFound(newlayout->intitle);
2764                                         set<string> const & req = newlayout->requires();
2765                                         set<string>::const_iterator it = req.begin();
2766                                         set<string>::const_iterator en = req.end();
2767                                         for (; it != en; ++it)
2768                                                 preamble.registerAutomaticallyLoadedPackage(*it);
2769                                 } else
2770                                         output_ert_inset(os,
2771                                                 "\\date{" + p.verbatim_item() + '}',
2772                                                 context);
2773                         }
2774                 }
2775
2776                 // Starred section headings
2777                 // Must attempt to parse "Section*" before "Section".
2778                 else if ((p.next_token().asInput() == "*") &&
2779                          context.new_layout_allowed &&
2780                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2781                         // write the layout
2782                         p.get_token();
2783                         output_command_layout(os, p, outer, context, newlayout);
2784                         p.skip_spaces();
2785                         if (!preamble.titleLayoutFound())
2786                                 preamble.titleLayoutFound(newlayout->intitle);
2787                         set<string> const & req = newlayout->requires();
2788                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2789                                 preamble.registerAutomaticallyLoadedPackage(*it);
2790                 }
2791
2792                 // Section headings and the like
2793                 else if (context.new_layout_allowed &&
2794                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2795                         // write the layout
2796                         output_command_layout(os, p, outer, context, newlayout);
2797                         p.skip_spaces();
2798                         if (!preamble.titleLayoutFound())
2799                                 preamble.titleLayoutFound(newlayout->intitle);
2800                         set<string> const & req = newlayout->requires();
2801                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2802                                 preamble.registerAutomaticallyLoadedPackage(*it);
2803                 }
2804
2805                 else if (t.cs() == "caption") {
2806                         bool starred = false;
2807                         if (p.next_token().asInput() == "*") {
2808                                 p.get_token();
2809                                 starred = true;
2810                         }
2811                         p.skip_spaces();
2812                         context.check_layout(os);
2813                         p.skip_spaces();
2814                         if (starred)
2815                                 begin_inset(os, "Caption LongTableNoNumber\n");
2816                         else
2817                                 begin_inset(os, "Caption Standard\n");
2818                         Context newcontext(true, context.textclass, 0, 0, context.font);
2819                         newcontext.check_layout(os);
2820                         // FIXME InsetArgument is now properly implemented in InsetLayout
2821                         //       (for captions, but also for others)
2822                         if (p.next_token().cat() != catEscape &&
2823                             p.next_token().character() == '[') {
2824                                 p.get_token(); // eat '['
2825                                 begin_inset(os, "Argument 1\n");
2826                                 os << "status collapsed\n";
2827                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2828                                 end_inset(os);
2829                                 eat_whitespace(p, os, context, false);
2830                         }
2831                         parse_text(p, os, FLAG_ITEM, outer, context);
2832                         context.check_end_layout(os);
2833                         // We don't need really a new paragraph, but
2834                         // we must make sure that the next item gets a \begin_layout.
2835                         context.new_paragraph(os);
2836                         end_inset(os);
2837                         p.skip_spaces();
2838                         newcontext.check_end_layout(os);
2839                 }
2840
2841                 else if (t.cs() == "subfloat") {
2842                         // the syntax is \subfloat[caption]{content}
2843                         // if it is a table of figure depends on the surrounding float
2844                         bool has_caption = false;
2845                         p.skip_spaces();
2846                         // do nothing if there is no outer float
2847                         if (!float_type.empty()) {
2848                                 context.check_layout(os);
2849                                 p.skip_spaces();
2850                                 begin_inset(os, "Float " + float_type + "\n");
2851                                 os << "wide false"
2852                                    << "\nsideways false"
2853                                    << "\nstatus collapsed\n\n";
2854                                 // test for caption
2855                                 string caption;
2856                                 if (p.next_token().cat() != catEscape &&
2857                                                 p.next_token().character() == '[') {
2858                                                         p.get_token(); // eat '['
2859                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2860                                                         has_caption = true;
2861                                 }
2862                                 // the content
2863                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2864                                 // the caption comes always as the last
2865                                 if (has_caption) {
2866                                         // we must make sure that the caption gets a \begin_layout
2867                                         os << "\n\\begin_layout Plain Layout";
2868                                         p.skip_spaces();
2869                                         begin_inset(os, "Caption Standard\n");
2870                                         Context newcontext(true, context.textclass,
2871                                                            0, 0, context.font);
2872                                         newcontext.check_layout(os);
2873                                         os << caption << "\n";
2874                                         newcontext.check_end_layout(os);
2875                                         // We don't need really a new paragraph, but
2876                                         // we must make sure that the next item gets a \begin_layout.
2877                                         //newcontext.new_paragraph(os);
2878                                         end_inset(os);
2879                                         p.skip_spaces();
2880                                 }
2881                                 // We don't need really a new paragraph, but
2882                                 // we must make sure that the next item gets a \begin_layout.
2883                                 if (has_caption)
2884                                         context.new_paragraph(os);
2885                                 end_inset(os);
2886                                 p.skip_spaces();
2887                                 context.check_end_layout(os);
2888                                 // close the layout we opened
2889                                 if (has_caption)
2890                                         os << "\n\\end_layout\n";
2891                         } else {
2892                                 // if the float type is not supported or there is no surrounding float
2893                                 // output it as ERT
2894                                 if (p.hasOpt()) {
2895                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2896                                         output_ert_inset(os, t.asInput() + '[' + opt_arg +
2897                                                "]{" + p.verbatim_item() + '}', context);
2898                                 } else
2899                                         output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2900                         }
2901                 }
2902
2903                 else if (t.cs() == "includegraphics") {
2904                         bool const clip = p.next_token().asInput() == "*";
2905                         if (clip)
2906                                 p.get_token();
2907                         string const arg = p.getArg('[', ']');
2908                         map<string, string> opts;
2909                         vector<string> keys;
2910                         split_map(arg, opts, keys);
2911                         if (clip)
2912                                 opts["clip"] = string();
2913                         string name = normalize_filename(p.verbatim_item());
2914
2915                         string const path = getMasterFilePath(true);
2916                         // We want to preserve relative / absolute filenames,
2917                         // therefore path is only used for testing
2918                         if (!makeAbsPath(name, path).exists()) {
2919                                 // The file extension is probably missing.
2920                                 // Now try to find it out.
2921                                 string const dvips_name =
2922                                         find_file(name, path,
2923                                                   known_dvips_graphics_formats);
2924                                 string const pdftex_name =
2925                                         find_file(name, path,
2926                                                   known_pdftex_graphics_formats);
2927                                 if (!dvips_name.empty()) {
2928                                         if (!pdftex_name.empty()) {
2929                                                 cerr << "This file contains the "
2930                                                         "latex snippet\n"
2931                                                         "\"\\includegraphics{"
2932                                                      << name << "}\".\n"
2933                                                         "However, files\n\""
2934                                                      << dvips_name << "\" and\n\""
2935                                                      << pdftex_name << "\"\n"
2936                                                         "both exist, so I had to make a "
2937                                                         "choice and took the first one.\n"
2938                                                         "Please move the unwanted one "
2939                                                         "someplace else and try again\n"
2940                                                         "if my choice was wrong."
2941                                                      << endl;
2942                                         }
2943                                         name = dvips_name;
2944                                 } else if (!pdftex_name.empty()) {
2945                                         name = pdftex_name;
2946                                         pdflatex = true;
2947                                 }
2948                         }
2949
2950                         FileName const absname = makeAbsPath(name, path);
2951                         if (absname.exists()) {
2952                                 fix_child_filename(name);
2953                                 copy_file(absname, name);
2954                         } else
2955                                 cerr << "Warning: Could not find graphics file '"
2956                                      << name << "'." << endl;
2957
2958                         context.check_layout(os);
2959                         begin_inset(os, "Graphics ");
2960                         os << "\n\tfilename " << name << '\n';
2961                         if (opts.find("width") != opts.end())
2962                                 os << "\twidth "
2963                                    << translate_len(opts["width"]) << '\n';
2964                         if (opts.find("height") != opts.end())
2965                                 os << "\theight "
2966                                    << translate_len(opts["height"]) << '\n';
2967                         if (opts.find("scale") != opts.end()) {
2968                                 istringstream iss(opts["scale"]);
2969                                 double val;
2970                                 iss >> val;
2971                                 val = val*100;
2972                                 os << "\tscale " << val << '\n';
2973                         }
2974                         if (opts.find("angle") != opts.end()) {
2975                                 os << "\trotateAngle "
2976                                    << opts["angle"] << '\n';
2977                                 vector<string>::const_iterator a =
2978                                         find(keys.begin(), keys.end(), "angle");
2979                                 vector<string>::const_iterator s =
2980                                         find(keys.begin(), keys.end(), "width");
2981                                 if (s == keys.end())
2982                                         s = find(keys.begin(), keys.end(), "height");
2983                                 if (s == keys.end())
2984                                         s = find(keys.begin(), keys.end(), "scale");
2985                                 if (s != keys.end() && distance(s, a) > 0)
2986                                         os << "\tscaleBeforeRotation\n";
2987                         }
2988                         if (opts.find("origin") != opts.end()) {
2989                                 ostringstream ss;
2990                                 string const opt = opts["origin"];
2991                                 if (opt.find('l') != string::npos) ss << "left";
2992                                 if (opt.find('r') != string::npos) ss << "right";
2993                                 if (opt.find('c') != string::npos) ss << "center";
2994                                 if (opt.find('t') != string::npos) ss << "Top";
2995                                 if (opt.find('b') != string::npos) ss << "Bottom";
2996                                 if (opt.find('B') != string::npos) ss << "Baseline";
2997                                 if (!ss.str().empty())
2998                                         os << "\trotateOrigin " << ss.str() << '\n';
2999                                 else
3000                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3001                         }
3002                         if (opts.find("keepaspectratio") != opts.end())
3003                                 os << "\tkeepAspectRatio\n";
3004                         if (opts.find("clip") != opts.end())
3005                                 os << "\tclip\n";
3006                         if (opts.find("draft") != opts.end())
3007                                 os << "\tdraft\n";
3008                         if (opts.find("bb") != opts.end())
3009                                 os << "\tBoundingBox "
3010                                    << opts["bb"] << '\n';
3011                         int numberOfbbOptions = 0;
3012                         if (opts.find("bbllx") != opts.end())
3013                                 numberOfbbOptions++;
3014                         if (opts.find("bblly") != opts.end())
3015                                 numberOfbbOptions++;
3016                         if (opts.find("bburx") != opts.end())
3017                                 numberOfbbOptions++;
3018                         if (opts.find("bbury") != opts.end())
3019                                 numberOfbbOptions++;
3020                         if (numberOfbbOptions == 4)
3021                                 os << "\tBoundingBox "
3022                                    << opts["bbllx"] << " " << opts["bblly"] << " "
3023                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
3024                         else if (numberOfbbOptions > 0)
3025                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3026                         numberOfbbOptions = 0;
3027                         if (opts.find("natwidth") != opts.end())
3028                                 numberOfbbOptions++;
3029                         if (opts.find("natheight") != opts.end())
3030                                 numberOfbbOptions++;
3031                         if (numberOfbbOptions == 2)
3032                                 os << "\tBoundingBox 0bp 0bp "
3033                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
3034                         else if (numberOfbbOptions > 0)
3035                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3036                         ostringstream special;
3037                         if (opts.find("hiresbb") != opts.end())
3038                                 special << "hiresbb,";
3039                         if (opts.find("trim") != opts.end())
3040                                 special << "trim,";
3041                         if (opts.find("viewport") != opts.end())
3042                                 special << "viewport=" << opts["viewport"] << ',';
3043                         if (opts.find("totalheight") != opts.end())
3044                                 special << "totalheight=" << opts["totalheight"] << ',';
3045                         if (opts.find("type") != opts.end())
3046                                 special << "type=" << opts["type"] << ',';
3047                         if (opts.find("ext") != opts.end())
3048                                 special << "ext=" << opts["ext"] << ',';
3049                         if (opts.find("read") != opts.end())
3050                                 special << "read=" << opts["read"] << ',';
3051                         if (opts.find("command") != opts.end())
3052                                 special << "command=" << opts["command"] << ',';
3053                         string s_special = special.str();
3054                         if (!s_special.empty()) {
3055                                 // We had special arguments. Remove the trailing ','.
3056                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3057                         }
3058                         // TODO: Handle the unknown settings better.
3059                         // Warn about invalid options.
3060                         // Check whether some option was given twice.
3061                         end_inset(os);
3062                         preamble.registerAutomaticallyLoadedPackage("graphicx");
3063                 }
3064
3065                 else if (t.cs() == "footnote" ||
3066                          (t.cs() == "thanks" && context.layout->intitle)) {
3067                         p.skip_spaces();
3068                         context.check_layout(os);
3069                         begin_inset(os, "Foot\n");
3070                         os << "status collapsed\n\n";
3071                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3072                         end_inset(os);
3073                 }
3074
3075                 else if (t.cs() == "marginpar") {
3076                         p.skip_spaces();
3077                         context.check_layout(os);
3078                         begin_inset(os, "Marginal\n");
3079                         os << "status collapsed\n\n";
3080                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3081                         end_inset(os);
3082                 }
3083
3084                 else if (t.cs() == "lstinline") {
3085                         p.skip_spaces();
3086                         parse_listings(p, os, context, true);
3087                 }
3088
3089                 else if (t.cs() == "ensuremath") {
3090                         p.skip_spaces();
3091                         context.check_layout(os);
3092                         string const s = p.verbatim_item();
3093                         //FIXME: this never triggers in UTF8
3094                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3095                                 os << s;
3096                         else
3097                                 output_ert_inset(os, "\\ensuremath{" + s + "}",
3098                                            context);
3099                 }
3100
3101                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3102                         if (preamble.titleLayoutFound()) {
3103                                 // swallow this
3104                                 skip_spaces_braces(p);
3105                         } else
3106                                 output_ert_inset(os, t.asInput(), context);
3107                 }
3108
3109                 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3110                         context.check_layout(os);
3111                         begin_command_inset(os, "toc", t.cs());
3112                         end_inset(os);
3113                         skip_spaces_braces(p);
3114                         if (t.cs() == "lstlistoflistings")
3115                                 preamble.registerAutomaticallyLoadedPackage("listings");
3116                 }
3117
3118                 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3119                         context.check_layout(os);
3120                         if (t.cs() == "listoffigures")
3121                                 begin_inset(os, "FloatList figure\n");
3122                         else
3123                                 begin_inset(os, "FloatList table\n");
3124                         end_inset(os);
3125                         skip_spaces_braces(p);
3126                 }
3127
3128                 else if (t.cs() == "listof") {
3129                         p.skip_spaces(true);
3130                         string const name = p.get_token().cs();
3131                         if (context.textclass.floats().typeExist(name)) {
3132                                 context.check_layout(os);
3133                                 begin_inset(os, "FloatList ");
3134                                 os << name << "\n";
3135                                 end_inset(os);
3136                                 p.get_token(); // swallow second arg
3137                         } else
3138                                 output_ert_inset(os, "\\listof{" + name + "}", context);
3139                 }
3140
3141                 else if ((where = is_known(t.cs(), known_text_font_families)))
3142                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3143                                 context, "\\family", context.font.family,
3144                                 known_coded_font_families[where - known_text_font_families]);
3145
3146                 else if ((where = is_known(t.cs(), known_text_font_series)))
3147                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3148                                 context, "\\series", context.font.series,
3149                                 known_coded_font_series[where - known_text_font_series]);
3150
3151                 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3152                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3153                                 context, "\\shape", context.font.shape,
3154                                 known_coded_font_shapes[where - known_text_font_shapes]);
3155
3156                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3157                         context.check_layout(os);
3158                         TeXFont oldFont = context.font;
3159                         context.font.init();
3160                         context.font.size = oldFont.size;
3161                         os << "\n\\family " << context.font.family << "\n";
3162                         os << "\n\\series " << context.font.series << "\n";
3163                         os << "\n\\shape " << context.font.shape << "\n";
3164                         if (t.cs() == "textnormal") {
3165                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3166                                 output_font_change(os, context.font, oldFont);
3167                                 context.font = oldFont;
3168                         } else
3169                                 eat_whitespace(p, os, context, false);
3170                 }
3171
3172                 else if (t.cs() == "textcolor") {
3173                         // scheme is \textcolor{color name}{text}
3174                         string const color = p.verbatim_item();
3175                         // we only support the predefined colors of the color package
3176                         if (color == "black" || color == "blue" || color == "cyan"
3177                                 || color == "green" || color == "magenta" || color == "red"
3178                                 || color == "white" || color == "yellow") {
3179                                         context.check_layout(os);
3180                                         os << "\n\\color " << color << "\n";
3181                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3182                                         context.check_layout(os);
3183                                         os << "\n\\color inherit\n";
3184                                         preamble.registerAutomaticallyLoadedPackage("color");
3185                         } else
3186                                 // for custom defined colors
3187                                 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3188                 }
3189
3190                 else if (t.cs() == "underbar" || t.cs() == "uline") {
3191                         // \underbar is not 100% correct (LyX outputs \uline
3192                         // of ulem.sty). The difference is that \ulem allows
3193                         // line breaks, and \underbar does not.
3194                         // Do NOT handle \underline.
3195                         // \underbar cuts through y, g, q, p etc.,
3196                         // \underline does not.
3197                         context.check_layout(os);
3198                         os << "\n\\bar under\n";
3199                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3200                         context.check_layout(os);
3201                         os << "\n\\bar default\n";
3202                         preamble.registerAutomaticallyLoadedPackage("ulem");
3203                 }
3204
3205                 else if (t.cs() == "sout") {
3206                         context.check_layout(os);
3207                         os << "\n\\strikeout on\n";
3208                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3209                         context.check_layout(os);
3210                         os << "\n\\strikeout default\n";
3211                         preamble.registerAutomaticallyLoadedPackage("ulem");
3212                 }
3213
3214                 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3215                          t.cs() == "emph" || t.cs() == "noun") {
3216                         context.check_layout(os);
3217                         os << "\n\\" << t.cs() << " on\n";
3218                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3219                         context.check_layout(os);
3220                         os << "\n\\" << t.cs() << " default\n";
3221                         if (t.cs() == "uuline" || t.cs() == "uwave")
3222                                 preamble.registerAutomaticallyLoadedPackage("ulem");
3223                 }
3224
3225                 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3226                         context.check_layout(os);
3227                         string name = p.getArg('{', '}');
3228                         string localtime = p.getArg('{', '}');
3229                         preamble.registerAuthor(name);
3230                         Author const & author = preamble.getAuthor(name);
3231                         // from_asctime_utc() will fail if LyX decides to output the
3232                         // time in the text language.
3233                         time_t ptime = from_asctime_utc(localtime);
3234                         if (ptime == static_cast<time_t>(-1)) {
3235                                 cerr << "Warning: Could not parse time `" << localtime
3236                                      << "´ for change tracking, using current time instead.\n";
3237                                 ptime = current_time();
3238                         }
3239                         if (t.cs() == "lyxadded")
3240                                 os << "\n\\change_inserted ";
3241                         else
3242                                 os << "\n\\change_deleted ";
3243                         os << author.bufferId() << ' ' << ptime << '\n';
3244                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3245                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
3246                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3247                                           LaTeXPackages::isAvailable("xcolor");
3248                         // No need to test for luatex, since luatex comes in
3249                         // two flavours (dvi and pdf), like latex, and those
3250                         // are detected by pdflatex.
3251                         if (pdflatex || xetex) {
3252                                 if (xcolorulem) {
3253                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3254                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3255                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3256                                 }
3257                         } else {
3258                                 if (dvipost) {
3259                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
3260                                 } else if (xcolorulem) {
3261                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3262                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3263                                 }
3264                         }
3265                 }
3266
3267                 else if (t.cs() == "textipa") {
3268                         context.check_layout(os);
3269                         begin_inset(os, "IPA\n");
3270                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3271                         end_inset(os);
3272                         preamble.registerAutomaticallyLoadedPackage("tipa");
3273                         preamble.registerAutomaticallyLoadedPackage("tipx");
3274                 }
3275
3276                 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3277                         context.check_layout(os);
3278                         begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3279                         os << "status open\n";
3280                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3281                         end_inset(os);
3282                         p.skip_spaces();
3283                 }
3284
3285                 else if (t.cs() == "textvertline") {
3286                         // FIXME: This is not correct, \textvertline is higher than |
3287                         os << "|";
3288                         skip_braces(p);
3289                         continue;
3290                 }
3291
3292                 else if (t.cs() == "tone" ) {
3293                         context.check_layout(os);
3294                         // register the tone package
3295                         preamble.registerAutomaticallyLoadedPackage("tone");
3296                         string content = trimSpaceAndEol(p.verbatim_item());
3297                         string command = t.asInput() + "{" + content + "}";
3298                         // some tones can be detected by unicodesymbols, some need special code
3299                         if (is_known(content, known_tones)) {
3300                                 os << "\\IPAChar " << command << "\n";
3301                                 continue;
3302                         }
3303                         // try to see whether the string is in unicodesymbols
3304                         bool termination;
3305                         docstring rem;
3306                         set<string> req;
3307                         docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3308                                 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3309                                 termination, rem, &req);
3310                         if (!s.empty()) {
3311                                 os << to_utf8(s);
3312                                 if (!rem.empty())
3313                                         output_ert_inset(os, to_utf8(rem), context);
3314                                 for (set<string>::const_iterator it = req.begin();
3315                                      it != req.end(); ++it)
3316                                         preamble.registerAutomaticallyLoadedPackage(*it);
3317                         } else
3318                                 // we did not find a non-ert version
3319                                 output_ert_inset(os, command, context);
3320                 }
3321
3322                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3323                              t.cs() == "vphantom") {
3324                         context.check_layout(os);
3325                         if (t.cs() == "phantom")
3326                                 begin_inset(os, "Phantom Phantom\n");
3327                         if (t.cs() == "hphantom")
3328                                 begin_inset(os, "Phantom HPhantom\n");
3329                         if (t.cs() == "vphantom")
3330                                 begin_inset(os, "Phantom VPhantom\n");
3331                         os << "status open\n";
3332                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3333                                             "Phantom");
3334                         end_inset(os);
3335                 }
3336
3337                 else if (t.cs() == "href") {
3338                         context.check_layout(os);
3339                         string target = convert_command_inset_arg(p.verbatim_item());
3340                         string name = convert_command_inset_arg(p.verbatim_item());
3341                         string type;
3342                         size_t i = target.find(':');
3343                         if (i != string::npos) {
3344                                 type = target.substr(0, i + 1);
3345                                 if (type == "mailto:" || type == "file:")
3346                                         target = target.substr(i + 1);
3347                                 // handle the case that name is equal to target, except of "http://"
3348                                 else if (target.substr(i + 3) == name && type == "http:")
3349                                         target = name;
3350                         }
3351                         begin_command_inset(os, "href", "href");
3352                         if (name != target)
3353                                 os << "name \"" << name << "\"\n";
3354                         os << "target \"" << target << "\"\n";
3355                         if (type == "mailto:" || type == "file:")
3356                                 os << "type \"" << type << "\"\n";
3357                         end_inset(os);
3358                         skip_spaces_braces(p);
3359                 }
3360
3361                 else if (t.cs() == "lyxline") {
3362                         // swallow size argument (it is not used anyway)
3363                         p.getArg('{', '}');
3364                         if (!context.atParagraphStart()) {
3365                                 // so our line is in the middle of a paragraph
3366                                 // we need to add a new line, lest this line
3367                                 // follow the other content on that line and
3368                                 // run off the side of the page
3369                                 // FIXME: This may create an empty paragraph,
3370                                 //        but without that it would not be
3371                                 //        possible to set noindent below.
3372                                 //        Fortunately LaTeX does not care
3373                                 //        about the empty paragraph.
3374                                 context.new_paragraph(os);
3375                         }
3376                         if (preamble.indentParagraphs()) {
3377                                 // we need to unindent, lest the line be too long
3378                                 context.add_par_extra_stuff("\\noindent\n");
3379                         }
3380                         context.check_layout(os);
3381                         begin_command_inset(os, "line", "rule");
3382                         os << "offset \"0.5ex\"\n"
3383                               "width \"100line%\"\n"
3384                               "height \"1pt\"\n";
3385                         end_inset(os);
3386                 }
3387
3388                 else if (t.cs() == "rule") {
3389                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3390                         string const width = p.getArg('{', '}');
3391                         string const thickness = p.getArg('{', '}');
3392                         context.check_layout(os);
3393                         begin_command_inset(os, "line", "rule");
3394                         if (!offset.empty())
3395                                 os << "offset \"" << translate_len(offset) << "\"\n";
3396                         os << "width \"" << translate_len(width) << "\"\n"
3397                                   "height \"" << translate_len(thickness) << "\"\n";
3398                         end_inset(os);
3399                 }
3400
3401                 else if (is_known(t.cs(), known_phrases) ||
3402                          (t.cs() == "protect" &&
3403                           p.next_token().cat() == catEscape &&
3404                           is_known(p.next_token().cs(), known_phrases))) {
3405                         // LyX sometimes puts a \protect in front, so we have to ignore it
3406                         // FIXME: This needs to be changed when bug 4752 is fixed.
3407                         where = is_known(
3408                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3409                                 known_phrases);
3410                         context.check_layout(os);
3411                         os << known_coded_phrases[where - known_phrases];
3412                         skip_spaces_braces(p);
3413                 }
3414
3415                 // handle refstyle first to catch \eqref which can also occur
3416                 // without refstyle. Only recognize these commands if
3417                 // refstyle.sty was found in the preamble (otherwise \eqref
3418                 // and user defined ref commands could be misdetected).
3419                 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3420                          preamble.refstyle()) {
3421                         context.check_layout(os);
3422                         begin_command_inset(os, "ref", "formatted");
3423                         os << "reference \"";
3424                         os << known_refstyle_prefixes[where - known_refstyle_commands]
3425                            << ":";
3426                         os << convert_command_inset_arg(p.verbatim_item())
3427                            << "\"\n";
3428                         end_inset(os);
3429                         preamble.registerAutomaticallyLoadedPackage("refstyle");
3430                 }
3431
3432                 // if refstyle is used, we must not convert \prettyref to a
3433                 // formatted reference, since that would result in a refstyle command.
3434                 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3435                          (t.cs() != "prettyref" || !preamble.refstyle())) {
3436                         string const opt = p.getOpt();
3437                         if (opt.empty()) {
3438                                 context.check_layout(os);
3439                                 begin_command_inset(os, "ref",
3440                                         known_coded_ref_commands[where - known_ref_commands]);
3441                                 os << "reference \""
3442                                    << convert_command_inset_arg(p.verbatim_item())
3443                                    << "\"\n";
3444                                 end_inset(os);
3445                                 if (t.cs() == "vref" || t.cs() == "vpageref")
3446                                         preamble.registerAutomaticallyLoadedPackage("varioref");
3447                                 else if (t.cs() == "prettyref")
3448                                         preamble.registerAutomaticallyLoadedPackage("prettyref");
3449                         } else {
3450                                 // LyX does not yet support optional arguments of ref commands
3451                                 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3452                                        p.verbatim_item() + '}', context);
3453                         }
3454                 }
3455
3456                 else if (use_natbib &&
3457                          is_known(t.cs(), known_natbib_commands) &&
3458                          ((t.cs() != "citefullauthor" &&
3459                            t.cs() != "citeyear" &&
3460                            t.cs() != "citeyearpar") ||
3461                           p.next_token().asInput() != "*")) {
3462                         context.check_layout(os);
3463                         string command = t.cs();
3464                         if (p.next_token().asInput() == "*") {
3465                                 command += '*';
3466                                 p.get_token();
3467                         }
3468                         if (command == "citefullauthor")
3469                                 // alternative name for "\\citeauthor*"
3470                                 command = "citeauthor*";
3471
3472                         // text before the citation
3473                         string before;
3474                         // text after the citation
3475                         string after;
3476                         get_cite_arguments(p, true, before, after);
3477
3478                         if (command == "cite") {
3479                                 // \cite without optional argument means
3480                                 // \citet, \cite with at least one optional
3481                                 // argument means \citep.
3482                                 if (before.empty() && after.empty())
3483                                         command = "citet";
3484                                 else
3485                                         command = "citep";
3486                         }
3487                         if (before.empty() && after == "[]")
3488                                 // avoid \citet[]{a}
3489                                 after.erase();
3490                         else if (before == "[]" && after == "[]") {
3491                                 // avoid \citet[][]{a}
3492                                 before.erase();
3493                                 after.erase();
3494                         }
3495                         // remove the brackets around after and before
3496                         if (!after.empty()) {
3497                                 after.erase(0, 1);
3498                                 after.erase(after.length() - 1, 1);
3499                                 after = convert_command_inset_arg(after);
3500                         }
3501                         if (!before.empty()) {
3502                                 before.erase(0, 1);
3503                                 before.erase(before.length() - 1, 1);
3504                                 before = convert_command_inset_arg(before);
3505                         }
3506                         begin_command_inset(os, "citation", command);
3507                         os << "after " << '"' << after << '"' << "\n";
3508                         os << "before " << '"' << before << '"' << "\n";
3509                         os << "key \""
3510                            << convert_command_inset_arg(p.verbatim_item())
3511                            << "\"\n";
3512                         end_inset(os);
3513                         // Need to set the cite engine if natbib is loaded by
3514                         // the document class directly
3515                         if (preamble.citeEngine() == "basic")
3516                                 preamble.citeEngine("natbib");
3517                 }
3518
3519                 else if (use_jurabib &&
3520                          is_known(t.cs(), known_jurabib_commands) &&
3521                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3522                         context.check_layout(os);
3523                         string command = t.cs();
3524                         if (p.next_token().asInput() == "*") {
3525                                 command += '*';
3526                                 p.get_token();
3527                         }
3528                         char argumentOrder = '\0';
3529                         vector<string> const options =
3530                                 preamble.getPackageOptions("jurabib");
3531                         if (find(options.begin(), options.end(),
3532                                       "natbiborder") != options.end())
3533                                 argumentOrder = 'n';
3534                         else if (find(options.begin(), options.end(),
3535                                            "jurabiborder") != options.end())
3536                                 argumentOrder = 'j';
3537
3538                         // text before the citation
3539                         string before;
3540                         // text after the citation
3541                         string after;
3542                         get_cite_arguments(p, argumentOrder != 'j', before, after);
3543
3544                         string const citation = p.verbatim_item();
3545                         if (!before.empty() && argumentOrder == '\0') {
3546                                 cerr << "Warning: Assuming argument order "
3547                                         "of jurabib version 0.6 for\n'"
3548                                      << command << before << after << '{'
3549                                      << citation << "}'.\n"
3550                                         "Add 'jurabiborder' to the jurabib "
3551                                         "package options if you used an\n"
3552                                         "earlier jurabib version." << endl;
3553                         }
3554                         if (!after.empty()) {
3555                                 after.erase(0, 1);
3556                                 after.erase(after.length() - 1, 1);
3557                         }
3558                         if (!before.empty()) {
3559                                 before.erase(0, 1);
3560                                 before.erase(before.length() - 1, 1);
3561                         }
3562                         begin_command_inset(os, "citation", command);
3563                         os << "after " << '"' << after << '"' << "\n";
3564                         os << "before " << '"' << before << '"' << "\n";
3565                         os << "key " << '"' << citation << '"' << "\n";
3566                         end_inset(os);
3567                         // Need to set the cite engine if jurabib is loaded by
3568                         // the document class directly
3569                         if (preamble.citeEngine() == "basic")
3570                                 preamble.citeEngine("jurabib");
3571                 }
3572
3573                 else if (t.cs() == "cite"
3574                         || t.cs() == "nocite") {
3575                         context.check_layout(os);
3576                         string after = convert_command_inset_arg(p.getArg('[', ']'));
3577                         string key = convert_command_inset_arg(p.verbatim_item());
3578                         // store the case that it is "\nocite{*}" to use it later for
3579                         // the BibTeX inset
3580                         if (key != "*") {
3581                                 begin_command_inset(os, "citation", t.cs());
3582                                 os << "after " << '"' << after << '"' << "\n";
3583                                 os << "key " << '"' << key << '"' << "\n";
3584                                 end_inset(os);
3585                         } else if (t.cs() == "nocite")
3586                                 btprint = key;
3587                 }
3588
3589                 else if (t.cs() == "index" ||
3590                          (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3591                         context.check_layout(os);
3592                         string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3593                                 p.getArg('[', ']') : "";
3594                         string const kind = arg.empty() ? "idx" : arg;
3595                         begin_inset(os, "Index ");
3596                         os << kind << "\nstatus collapsed\n";
3597                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3598                         end_inset(os);
3599                         if (kind != "idx")
3600                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3601                 }
3602
3603                 else if (t.cs() == "nomenclature") {
3604                         context.check_layout(os);
3605                         begin_command_inset(os, "nomenclature", "nomenclature");
3606                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3607                         if (!prefix.empty())
3608                                 os << "prefix " << '"' << prefix << '"' << "\n";
3609                         os << "symbol " << '"'
3610                            << convert_command_inset_arg(p.verbatim_item());
3611                         os << "\"\ndescription \""
3612                            << convert_command_inset_arg(p.verbatim_item())
3613                            << "\"\n";
3614                         end_inset(os);
3615                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3616                 }
3617
3618                 else if (t.cs() == "label") {
3619                         context.check_layout(os);
3620                         begin_command_inset(os, "label", "label");
3621                         os << "name \""
3622                            << convert_command_inset_arg(p.verbatim_item())
3623                            << "\"\n";
3624                         end_inset(os);
3625                 }
3626
3627                 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3628                         context.check_layout(os);
3629                         string commandname = t.cs();
3630                         bool star = false;
3631                         if (p.next_token().asInput() == "*") {
3632                                 commandname += "*";
3633                                 star = true;
3634                                 p.get_token();
3635                         }
3636                         begin_command_inset(os, "index_print", commandname);
3637                         string const indexname = p.getArg('[', ']');
3638                         if (!star) {
3639                                 if (indexname.empty())
3640                                         os << "type \"idx\"\n";
3641                                 else
3642                                         os << "type \"" << indexname << "\"\n";
3643                         }
3644                         end_inset(os);
3645                         skip_spaces_braces(p);
3646                         preamble.registerAutomaticallyLoadedPackage("makeidx");
3647                         if (preamble.use_indices() == "true")
3648                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3649                 }
3650
3651                 else if (t.cs() == "printnomenclature") {
3652                         string width = "";
3653                         string width_type = "";
3654                         context.check_layout(os);
3655                         begin_command_inset(os, "nomencl_print", "printnomenclature");
3656                         // case of a custom width
3657                         if (p.hasOpt()) {
3658                                 width = p.getArg('[', ']');
3659                                 width = translate_len(width);
3660                                 width_type = "custom";
3661                         }
3662                         // case of no custom width
3663                         // the case of no custom width but the width set
3664                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
3665                         // because the user could have set anything, not only the width
3666                         // of the longest label (which would be width_type = "auto")
3667                         string label = convert_command_inset_arg(p.getArg('{', '}'));
3668                         if (label.empty() && width_type.empty())
3669                                 width_type = "none";
3670                         os << "set_width \"" << width_type << "\"\n";
3671                         if (width_type == "custom")
3672                                 os << "width \"" << width << '\"';
3673                         end_inset(os);
3674                         skip_spaces_braces(p);
3675                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3676                 }
3677
3678                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3679                         context.check_layout(os);
3680                         begin_inset(os, "script ");
3681                         os << t.cs().substr(4) << '\n';
3682                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3683                         end_inset(os);
3684                         if (t.cs() == "textsubscript")
3685                                 preamble.registerAutomaticallyLoadedPackage("subscript");
3686                 }
3687
3688                 else if ((where = is_known(t.cs(), known_quotes))) {
3689                         context.check_layout(os);
3690                         begin_inset(os, "Quotes ");
3691                         os << known_coded_quotes[where - known_quotes];
3692                         end_inset(os);
3693                         // LyX adds {} after the quote, so we have to eat
3694                         // spaces here if there are any before a possible
3695                         // {} pair.
3696                         eat_whitespace(p, os, context, false);
3697                         skip_braces(p);
3698                 }
3699
3700                 else if ((where = is_known(t.cs(), known_sizes)) &&
3701                          context.new_layout_allowed) {
3702                         context.check_layout(os);
3703                         TeXFont const oldFont = context.font;
3704                         context.font.size = known_coded_sizes[where - known_sizes];
3705                         output_font_change(os, oldFont, context.font);
3706                         eat_whitespace(p, os, context, false);
3707                 }
3708
3709                 else if ((where = is_known(t.cs(), known_font_families)) &&
3710                          context.new_layout_allowed) {
3711                         context.check_layout(os);
3712                         TeXFont const oldFont = context.font;
3713                         context.font.family =
3714                                 known_coded_font_families[where - known_font_families];
3715                         output_font_change(os, oldFont, context.font);
3716                         eat_whitespace(p, os, context, false);
3717                 }
3718
3719                 else if ((where = is_known(t.cs(), known_font_series)) &&
3720                          context.new_layout_allowed) {
3721                         context.check_layout(os);
3722                         TeXFont const oldFont = context.font;
3723                         context.font.series =
3724                                 known_coded_font_series[where - known_font_series];
3725                         output_font_change(os, oldFont, context.font);
3726                         eat_whitespace(p, os, context, false);
3727                 }
3728
3729                 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3730                          context.new_layout_allowed) {
3731                         context.check_layout(os);
3732                         TeXFont const oldFont = context.font;
3733                         context.font.shape =
3734                                 known_coded_font_shapes[where - known_font_shapes];
3735                         output_font_change(os, oldFont, context.font);
3736                         eat_whitespace(p, os, context, false);
3737                 }
3738                 else if ((where = is_known(t.cs(), known_old_font_families)) &&
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.family =
3745                                 known_coded_font_families[where - known_old_font_families];
3746                         output_font_change(os, oldFont, context.font);
3747                         eat_whitespace(p, os, context, false);
3748                 }
3749
3750                 else if ((where = is_known(t.cs(), known_old_font_series)) &&
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.series =
3757                                 known_coded_font_series[where - known_old_font_series];
3758                         output_font_change(os, oldFont, context.font);
3759                         eat_whitespace(p, os, context, false);
3760                 }
3761
3762                 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3763                          context.new_layout_allowed) {
3764                         context.check_layout(os);
3765                         TeXFont const oldFont = context.font;
3766                         context.font.init();
3767                         context.font.size = oldFont.size;
3768                         context.font.shape =
3769                                 known_coded_font_shapes[where - known_old_font_shapes];
3770                         output_font_change(os, oldFont, context.font);
3771                         eat_whitespace(p, os, context, false);
3772                 }
3773
3774                 else if (t.cs() == "selectlanguage") {
3775                         context.check_layout(os);
3776                         // save the language for the case that a
3777                         // \foreignlanguage is used
3778                         context.font.language = babel2lyx(p.verbatim_item());
3779                         os << "\n\\lang " << context.font.language << "\n";
3780                 }
3781
3782                 else if (t.cs() == "foreignlanguage") {
3783                         string const lang = babel2lyx(p.verbatim_item());
3784                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3785                                               context, "\\lang",
3786                                               context.font.language, lang);
3787                 }
3788
3789                 else if (prefixIs(t.cs(), "text")
3790                          && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3791                         // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3792                         string lang;
3793                         // We have to output the whole command if it has an option
3794                         // because LyX doesn't support this yet, see bug #8214,
3795                         // only if there is a single option specifying a variant, we can handle it.
3796                         if (p.hasOpt()) {
3797                                 string langopts = p.getOpt();
3798                                 // check if the option contains a variant, if yes, extract it
3799                                 string::size_type pos_var = langopts.find("variant");
3800                                 string::size_type i = langopts.find(',');
3801                                 string::size_type k = langopts.find('=', pos_var);
3802                                 if (pos_var != string::npos && i == string::npos) {
3803                                         string variant;
3804                                         variant = langopts.substr(k + 1, langopts.length() - k - 2);
3805                                         lang = preamble.polyglossia2lyx(variant);
3806                                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3807                                                                   context, "\\lang",
3808                                                                   context.font.language, lang);
3809                                 } else
3810                                         output_ert_inset(os, t.asInput() + langopts, context);
3811                         } else {
3812                                 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3813                                 parse_text_attributes(p, os, FLAG_ITEM, outer,
3814                                                           context, "\\lang",
3815                                                           context.font.language, lang);
3816                         }
3817                 }
3818
3819                 else if (t.cs() == "inputencoding") {
3820                         // nothing to write here
3821                         string const enc = subst(p.verbatim_item(), "\n", " ");
3822                         p.setEncoding(enc, Encoding::inputenc);
3823                 }
3824
3825                 else if ((where = is_known(t.cs(), known_special_chars))) {
3826                         context.check_layout(os);
3827                         os << known_coded_special_chars[where - known_special_chars];
3828                         skip_spaces_braces(p);
3829                 }
3830
3831                 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3832                          (t.cs() == "@" && p.next_token().asInput() == ".")) {
3833                         context.check_layout(os);
3834                         os << "\\SpecialChar \\" << t.cs()
3835                            << p.get_token().asInput() << '\n';
3836                 }
3837
3838                 else if (t.cs() == "textquotedbl") {
3839                         context.check_layout(os);
3840                         os << "\"";
3841                         skip_braces(p);
3842                 }
3843
3844                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3845                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3846                             || t.cs() == "%" || t.cs() == "-") {
3847                         context.check_layout(os);
3848                         if (t.cs() == "-")
3849                                 os << "\\SpecialChar \\-\n";
3850                         else
3851                                 os << t.cs();
3852                 }
3853
3854                 else if (t.cs() == "char") {
3855                         context.check_layout(os);
3856                         if (p.next_token().character() == '`') {
3857                                 p.get_token();
3858                                 if (p.next_token().cs() == "\"") {
3859                                         p.get_token();
3860                                         os << '"';
3861                                         skip_braces(p);
3862                                 } else {
3863                                         output_ert_inset(os, "\\char`", context);
3864                                 }
3865                         } else {
3866                                 output_ert_inset(os, "\\char", context);
3867                         }
3868                 }
3869
3870                 else if (t.cs() == "verb") {
3871                         context.check_layout(os);
3872                         // set catcodes to verbatim early, just in case.
3873                         p.setCatcodes(VERBATIM_CATCODES);
3874                         string delim = p.get_token().asInput();
3875                         Parser::Arg arg = p.verbatimStuff(delim);
3876                         if (arg.first)
3877                                 output_ert_inset(os, "\\verb" + delim 
3878                                                  + arg.second + delim, context);
3879                         else
3880                                 cerr << "invalid \\verb command. Skipping" << endl;
3881                 }
3882
3883                 // Problem: \= creates a tabstop inside the tabbing environment
3884                 // and else an accent. In the latter case we really would want
3885                 // \={o} instead of \= o.
3886                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3887                         output_ert_inset(os, t.asInput(), context);
3888
3889                 else if (t.cs() == "\\") {
3890                         context.check_layout(os);
3891                         if (p.hasOpt())
3892                                 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3893                         else if (p.next_token().asInput() == "*") {
3894                                 p.get_token();
3895                                 // getOpt() eats the following space if there
3896                                 // is no optional argument, but that is OK
3897                                 // here since it has no effect in the output.
3898                                 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3899                         }
3900                         else {
3901                                 begin_inset(os, "Newline newline");
3902                                 end_inset(os);
3903                         }
3904                 }
3905
3906                 else if (t.cs() == "newline" ||
3907                          (t.cs() == "linebreak" && !p.hasOpt())) {
3908                         context.check_layout(os);
3909                         begin_inset(os, "Newline ");
3910                         os << t.cs();
3911                         end_inset(os);
3912                         skip_spaces_braces(p);
3913                 }
3914
3915                 else if (t.cs() == "input" || t.cs() == "include"
3916                          || t.cs() == "verbatiminput") {
3917                         string name = t.cs();
3918                         if (t.cs() == "verbatiminput"
3919                             && p.next_token().asInput() == "*")
3920                                 name += p.get_token().asInput();
3921                         context.check_layout(os);
3922                         string filename(normalize_filename(p.getArg('{', '}')));
3923                         string const path = getMasterFilePath(true);
3924                         // We want to preserve relative / absolute filenames,
3925                         // therefore path is only used for testing
3926                         if ((t.cs() == "include" || t.cs() == "input") &&
3927                             !makeAbsPath(filename, path).exists()) {
3928                                 // The file extension is probably missing.
3929                                 // Now try to find it out.
3930                                 string const tex_name =
3931                                         find_file(filename, path,
3932                                                   known_tex_extensions);
3933                                 if (!tex_name.empty())
3934                                         filename = tex_name;
3935                         }
3936                         bool external = false;
3937                         string outname;
3938                         if (makeAbsPath(filename, path).exists()) {
3939                                 string const abstexname =
3940                                         makeAbsPath(filename, path).absFileName();
3941                                 string const absfigname =
3942                                         changeExtension(abstexname, ".fig");
3943                                 fix_child_filename(filename);
3944                                 string const lyxname = changeExtension(filename,
3945                                         roundtripMode() ? ".lyx.lyx" : ".lyx");
3946                                 string const abslyxname = makeAbsPath(
3947                                         lyxname, getParentFilePath(false)).absFileName();
3948                                 bool xfig = false;
3949                                 if (!skipChildren())
3950                                         external = FileName(absfigname).exists();
3951                                 if (t.cs() == "input" && !skipChildren()) {
3952                                         string const ext = getExtension(abstexname);
3953
3954                                         // Combined PS/LaTeX:
3955                                         // x.eps, x.pstex_t (old xfig)
3956                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3957                                         FileName const absepsname(
3958                                                 changeExtension(abstexname, ".eps"));
3959                                         FileName const abspstexname(
3960                                                 changeExtension(abstexname, ".pstex"));
3961                                         bool const xfigeps =
3962                                                 (absepsname.exists() ||
3963                                                  abspstexname.exists()) &&
3964                                                 ext == "pstex_t";
3965
3966                                         // Combined PDF/LaTeX:
3967                                         // x.pdf, x.pdftex_t (old xfig)
3968                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3969                                         FileName const abspdfname(
3970                                                 changeExtension(abstexname, ".pdf"));
3971                                         bool const xfigpdf =
3972                                                 abspdfname.exists() &&
3973                                                 (ext == "pdftex_t" || ext == "pdf_t");
3974                                         if (xfigpdf)
3975                                                 pdflatex = true;
3976
3977                                         // Combined PS/PDF/LaTeX:
3978                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3979                                         string const absbase2(
3980                                                 removeExtension(abstexname) + "_pspdftex");
3981                                         FileName const abseps2name(
3982                                                 addExtension(absbase2, ".eps"));
3983                                         FileName const abspdf2name(
3984                                                 addExtension(absbase2, ".pdf"));
3985                                         bool const xfigboth =
3986                                                 abspdf2name.exists() &&
3987                                                 abseps2name.exists() && ext == "pspdftex";
3988
3989                                         xfig = xfigpdf || xfigeps || xfigboth;
3990                                         external = external && xfig;
3991                                 }
3992                                 if (external) {
3993                                         outname = changeExtension(filename, ".fig");
3994                                         FileName abssrc(changeExtension(abstexname, ".fig"));
3995                                         copy_file(abssrc, outname);
3996                                 } else if (xfig) {
3997                                         // Don't try to convert, the result
3998                                         // would be full of ERT.
3999                                         outname = filename;
4000                                         FileName abssrc(abstexname);
4001                                         copy_file(abssrc, outname);
4002                                 } else if (t.cs() != "verbatiminput" &&
4003                                            !skipChildren() &&
4004                                     tex2lyx(abstexname, FileName(abslyxname),
4005                                             p.getEncoding())) {
4006                                         outname = lyxname;
4007                                         // no need to call copy_file
4008                                         // tex2lyx creates the file
4009                                 } else {
4010                                         outname = filename;
4011                                         FileName abssrc(abstexname);
4012                                         copy_file(abssrc, outname);
4013                                 }
4014                         } else {
4015                                 cerr << "Warning: Could not find included file '"
4016                                      << filename << "'." << endl;
4017                                 outname = filename;
4018                         }
4019                         if (external) {
4020                                 begin_inset(os, "External\n");
4021                                 os << "\ttemplate XFig\n"
4022                                    << "\tfilename " << outname << '\n';
4023                                 registerExternalTemplatePackages("XFig");
4024                         } else {
4025                                 begin_command_inset(os, "include", name);
4026                                 outname = subst(outname, "\"", "\\\"");
4027                                 os << "preview false\n"
4028                                       "filename \"" << outname << "\"\n";
4029                                 if (t.cs() == "verbatiminput")
4030                                         preamble.registerAutomaticallyLoadedPackage("verbatim");
4031                         }
4032                         end_inset(os);
4033                 }
4034
4035                 else if (t.cs() == "bibliographystyle") {
4036                         // store new bibliographystyle
4037                         bibliographystyle = p.verbatim_item();
4038                         // If any other command than \bibliography, \addcontentsline
4039                         // and \nocite{*} follows, we need to output the style
4040                         // (because it might be used by that command).
4041                         // Otherwise, it will automatically be output by LyX.
4042                         p.pushPosition();
4043                         bool output = true;
4044                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4045                                 if (t2.cat() == catBegin)
4046                                         break;
4047                                 if (t2.cat() != catEscape)
4048                                         continue;
4049                                 if (t2.cs() == "nocite") {
4050                                         if (p.getArg('{', '}') == "*")
4051                                                 continue;
4052                                 } else if (t2.cs() == "bibliography")
4053                                         output = false;
4054                                 else if (t2.cs() == "phantomsection") {
4055                                         output = false;
4056                                         continue;
4057                                 }
4058                                 else if (t2.cs() == "addcontentsline") {
4059                                         // get the 3 arguments of \addcontentsline
4060                                         p.getArg('{', '}');
4061                                         p.getArg('{', '}');
4062                                         contentslineContent = p.getArg('{', '}');
4063                                         // if the last argument is not \refname we must output
4064                                         if (contentslineContent == "\\refname")
4065                                                 output = false;
4066                                 }
4067                                 break;
4068                         }
4069                         p.popPosition();
4070                         if (output) {
4071                                 output_ert_inset(os,
4072                                         "\\bibliographystyle{" + bibliographystyle + '}',
4073                                         context);
4074                         }
4075                 }
4076
4077                 else if (t.cs() == "phantomsection") {
4078                         // we only support this if it occurs between
4079                         // \bibliographystyle and \bibliography
4080                         if (bibliographystyle.empty())
4081                                 output_ert_inset(os, "\\phantomsection", context);
4082                 }
4083
4084                 else if (t.cs() == "addcontentsline") {
4085                         context.check_layout(os);
4086                         // get the 3 arguments of \addcontentsline
4087                         string const one = p.getArg('{', '}');
4088                         string const two = p.getArg('{', '}');
4089                         string const three = p.getArg('{', '}');
4090                         // only if it is a \refname, we support if for the bibtex inset
4091                         if (contentslineContent != "\\refname") {
4092                                 output_ert_inset(os,
4093                                         "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4094                                         context);
4095                         }
4096                 }
4097
4098                 else if (t.cs() == "bibliography") {
4099                         context.check_layout(os);
4100                         string BibOpts;
4101                         begin_command_inset(os, "bibtex", "bibtex");
4102                         if (!btprint.empty()) {
4103                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4104                                 // clear the string because the next BibTeX inset can be without the
4105                                 // \nocite{*} option
4106                                 btprint.clear();
4107                         }
4108                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4109                         // Do we have addcontentsline?
4110                         if (contentslineContent == "\\refname") {
4111                                 BibOpts = "bibtotoc";
4112                                 // clear string because next BibTeX inset can be without addcontentsline
4113                                 contentslineContent.clear();
4114                         }
4115                         // Do we have a bibliographystyle set?
4116                         if (!bibliographystyle.empty()) {
4117                                 if (BibOpts.empty())
4118                                         BibOpts = bibliographystyle;
4119                                 else
4120                                         BibOpts = BibOpts + ',' + bibliographystyle;
4121                                 // clear it because each bibtex entry has its style
4122                                 // and we need an empty string to handle \phantomsection
4123                                 bibliographystyle.clear();
4124                         }
4125                         os << "options " << '"' << BibOpts << '"' << "\n";
4126                         end_inset(os);
4127                 }
4128
4129                 else if (t.cs() == "parbox") {
4130                         // Test whether this is an outer box of a shaded box
4131                         p.pushPosition();
4132                         // swallow arguments
4133                         while (p.hasOpt()) {
4134                                 p.getArg('[', ']');
4135                                 p.skip_spaces(true);
4136                         }
4137                         p.getArg('{', '}');
4138                         p.skip_spaces(true);
4139                         // eat the '{'
4140                         if (p.next_token().cat() == catBegin)
4141                                 p.get_token();
4142                         p.skip_spaces(true);
4143                         Token to = p.get_token();
4144                         bool shaded = false;
4145                         if (to.asInput() == "\\begin") {
4146                                 p.skip_spaces(true);
4147                                 if (p.getArg('{', '}') == "shaded")
4148                                         shaded = true;
4149                         }
4150                         p.popPosition();
4151                         if (shaded) {
4152                                 parse_outer_box(p, os, FLAG_ITEM, outer,
4153                                                 context, "parbox", "shaded");
4154                         } else
4155                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4156                                           "", "", t.cs());
4157                 }
4158
4159                 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4160                              t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4161                          t.cs() == "shadowbox" || t.cs() == "doublebox")
4162                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4163
4164                 else if (t.cs() == "framebox") {
4165                         if (p.next_token().character() == '(') {
4166                                 //the syntax is: \framebox(x,y)[position]{content}
4167                                 string arg = t.asInput();
4168                                 arg += p.getFullParentheseArg();
4169                                 arg += p.getFullOpt();
4170                                 eat_whitespace(p, os, context, false);
4171                                 output_ert_inset(os, arg + '{', context);
4172                                 parse_text(p, os, FLAG_ITEM, outer, context);
4173                                 output_ert_inset(os, "}", context);
4174                         } else {
4175                                 //the syntax is: \framebox[width][position]{content}
4176                                 string special = p.getFullOpt();
4177                                 special += p.getOpt();
4178                                 parse_outer_box(p, os, FLAG_ITEM, outer,
4179                                                     context, t.cs(), special);
4180                         }
4181                 }
4182
4183                 //\makebox() is part of the picture environment and different from \makebox{}
4184                 //\makebox{} will be parsed by parse_box
4185                 else if (t.cs() == "makebox") {
4186                         if (p.next_token().character() == '(') {
4187                                 //the syntax is: \makebox(x,y)[position]{content}
4188                                 string arg = t.asInput();
4189                                 arg += p.getFullParentheseArg();
4190                                 arg += p.getFullOpt();
4191                                 eat_whitespace(p, os, context, false);
4192                                 output_ert_inset(os, arg + '{', context);
4193                                 parse_text(p, os, FLAG_ITEM, outer, context);
4194                                 output_ert_inset(os, "}", context);
4195                         } else
4196                                 //the syntax is: \makebox[width][position]{content}
4197                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4198                                           "", "", t.cs());
4199                 }
4200
4201                 else if (t.cs() == "smallskip" ||
4202                          t.cs() == "medskip" ||
4203                          t.cs() == "bigskip" ||
4204                          t.cs() == "vfill") {
4205                         context.check_layout(os);
4206                         begin_inset(os, "VSpace ");
4207                         os << t.cs();
4208                         end_inset(os);
4209                         skip_spaces_braces(p);
4210                 }
4211
4212                 else if ((where = is_known(t.cs(), known_spaces))) {
4213                         context.check_layout(os);
4214                         begin_inset(os, "space ");
4215                         os << '\\' << known_coded_spaces[where - known_spaces]
4216                            << '\n';
4217                         end_inset(os);
4218                         // LaTeX swallows whitespace after all spaces except
4219                         // "\\,". We have to do that here, too, because LyX
4220                         // adds "{}" which would make the spaces significant.
4221                         if (t.cs() !=  ",")
4222                                 eat_whitespace(p, os, context, false);
4223                         // LyX adds "{}" after all spaces except "\\ " and
4224                         // "\\,", so we have to remove "{}".
4225                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
4226                         // remove the braces after "\\,", too.
4227                         if (t.cs() != " ")
4228                                 skip_braces(p);
4229                 }
4230
4231                 else if (t.cs() == "newpage" ||
4232                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
4233                          t.cs() == "clearpage" ||
4234                          t.cs() == "cleardoublepage") {
4235                         context.check_layout(os);
4236                         begin_inset(os, "Newpage ");
4237                         os << t.cs();
4238                         end_inset(os);
4239                         skip_spaces_braces(p);
4240                 }
4241
4242                 else if (t.cs() == "DeclareRobustCommand" ||
4243                          t.cs() == "DeclareRobustCommandx" ||
4244                          t.cs() == "newcommand" ||
4245                          t.cs() == "newcommandx" ||
4246                          t.cs() == "providecommand" ||
4247                          t.cs() == "providecommandx" ||
4248                          t.cs() == "renewcommand" ||
4249                          t.cs() == "renewcommandx") {
4250                         // DeclareRobustCommand, DeclareRobustCommandx,
4251                         // providecommand and providecommandx could be handled
4252                         // by parse_command(), but we need to call
4253                         // add_known_command() here.
4254                         string name = t.asInput();
4255                         if (p.next_token().asInput() == "*") {
4256                                 // Starred form. Eat '*'
4257                                 p.get_token();
4258                                 name += '*';
4259                         }
4260                         string const command = p.verbatim_item();
4261                         string const opt1 = p.getFullOpt();
4262                         string const opt2 = p.getFullOpt();
4263                         add_known_command(command, opt1, !opt2.empty());
4264                         string const ert = name + '{' + command + '}' +
4265                                            opt1 + opt2 +
4266                                            '{' + p.verbatim_item() + '}';
4267
4268                         if (t.cs() == "DeclareRobustCommand" ||
4269                             t.cs() == "DeclareRobustCommandx" ||
4270                             t.cs() == "providecommand" ||
4271                             t.cs() == "providecommandx" ||
4272                             name[name.length()-1] == '*')
4273                                 output_ert_inset(os, ert, context);
4274                         else {
4275                                 context.check_layout(os);
4276                                 begin_inset(os, "FormulaMacro");
4277                                 os << "\n" << ert;
4278                                 end_inset(os);
4279                         }
4280                 }
4281
4282                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4283                         // let could be handled by parse_command(),
4284                         // but we need to call add_known_command() here.
4285                         string ert = t.asInput();
4286                         string name;
4287                         p.skip_spaces();
4288                         if (p.next_token().cat() == catBegin) {
4289                                 name = p.verbatim_item();
4290                                 ert += '{' + name + '}';
4291                         } else {
4292                                 name = p.verbatim_item();
4293                                 ert += name;
4294                         }
4295                         string command;
4296                         p.skip_spaces();
4297                         if (p.next_token().cat() == catBegin) {
4298                                 command = p.verbatim_item();
4299                                 ert += '{' + command + '}';
4300                         } else {
4301                                 command = p.verbatim_item();
4302                                 ert += command;
4303                         }
4304                         // If command is known, make name known too, to parse
4305                         // its arguments correctly. For this reason we also
4306                         // have commands in syntax.default that are hardcoded.
4307                         CommandMap::iterator it = known_commands.find(command);
4308                         if (it != known_commands.end())
4309                                 known_commands[t.asInput()] = it->second;
4310                         output_ert_inset(os, ert, context);
4311                 }
4312
4313                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4314                         bool starred = false;
4315                         if (p.next_token().asInput() == "*") {
4316                                 p.get_token();
4317                                 starred = true;
4318                         }
4319                         string name = t.asInput();
4320                         string const length = p.verbatim_item();
4321                         string unit;
4322                         string valstring;
4323                         bool valid = splitLatexLength(length, valstring, unit);
4324                         bool known_hspace = false;
4325                         bool known_vspace = false;
4326                         bool known_unit = false;
4327                         double value;
4328                         if (valid) {
4329                                 istringstream iss(valstring);
4330                                 iss >> value;
4331                                 if (value == 1.0) {
4332                                         if (t.cs()[0] == 'h') {
4333                                                 if (unit == "\\fill") {
4334                                                         if (!starred) {
4335                                                                 unit = "";
4336                                                                 name = "\\hfill";
4337                                                         }
4338                                                         known_hspace = true;
4339                                                 }
4340                                         } else {
4341                                                 if (unit == "\\smallskipamount") {
4342                                                         unit = "smallskip";
4343                                                         known_vspace = true;
4344                                                 } else if (unit == "\\medskipamount") {
4345                                                         unit = "medskip";
4346                                                         known_vspace = true;
4347                                                 } else if (unit == "\\bigskipamount") {
4348                                                         unit = "bigskip";
4349                                                         known_vspace = true;
4350                                                 } else if (unit == "\\fill") {
4351                                                         unit = "vfill";
4352                                                         known_vspace = true;
4353                                                 }
4354                                         }
4355                                 }
4356                                 if (!known_hspace && !known_vspace) {
4357                                         switch (unitFromString(unit)) {
4358                                         case Length::SP:
4359                                         case Length::PT:
4360                                         case Length::BP:
4361                                         case Length::DD:
4362                                         case Length::MM:
4363                                         case Length::PC:
4364                                         case Length::CC:
4365                                         case Length::CM:
4366                                         case Length::IN:
4367                                         case Length::EX:
4368                                         case Length::EM:
4369                                         case Length::MU:
4370                                                 known_unit = true;
4371                                                 break;
4372                                         default:
4373                                                 break;
4374                                         }
4375                                 }
4376                         }
4377
4378                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4379                                 // Literal horizontal length or known variable
4380                                 context.check_layout(os);
4381                                 begin_inset(os, "space ");
4382                                 os << name;
4383                                 if (starred)
4384                                         os << '*';
4385                                 os << '{';
4386                                 if (known_hspace)
4387                                         os << unit;
4388                                 os << "}";
4389                                 if (known_unit && !known_hspace)
4390                                         os << "\n\\length "
4391                                            << translate_len(length);
4392                                 end_inset(os);
4393                         } else if (known_unit || known_vspace) {
4394                                 // Literal vertical length or known variable
4395                                 context.check_layout(os);
4396                                 begin_inset(os, "VSpace ");
4397                                 if (known_unit)
4398                                         os << value;
4399                                 os << unit;
4400                                 if (starred)
4401                                         os << '*';
4402                                 end_inset(os);
4403                         } else {
4404                                 // LyX can't handle other length variables in Inset VSpace/space
4405                                 if (starred)
4406                                         name += '*';
4407                                 if (valid) {
4408                                         if (value == 1.0)
4409                                                 output_ert_inset(os, name + '{' + unit + '}', context);
4410                                         else if (value == -1.0)
4411                                                 output_ert_inset(os, name + "{-" + unit + '}', context);
4412                                         else
4413                                                 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4414                                 } else
4415                                         output_ert_inset(os, name + '{' + length + '}', context);
4416                         }
4417                 }
4418
4419                 // The single '=' is meant here.
4420                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4421                         p.skip_spaces();
4422                         context.check_layout(os);
4423                         begin_inset(os, "Flex ");
4424                         os << to_utf8(newinsetlayout->name()) << '\n'
4425                            << "status collapsed\n";
4426                         if (newinsetlayout->isPassThru()) {
4427                                 // set catcodes to verbatim early, just in case.
4428                                 p.setCatcodes(VERBATIM_CATCODES);
4429                                 string delim = p.get_token().asInput();
4430                                 if (delim != "{")
4431                                         cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4432                                 //FIXME: handle error condition
4433                                 string const arg = p.verbatimStuff("}").second;
4434                                 Context newcontext(true, context.textclass);
4435                                 if (newinsetlayout->forcePlainLayout())
4436                                         newcontext.layout = &context.textclass.plainLayout();
4437                                 output_ert(os, arg, newcontext);
4438                         } else
4439                                 
4440                                 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4441                         end_inset(os);
4442                 }
4443
4444                 else if (t.cs() == "includepdf") {
4445                         p.skip_spaces();
4446                         string const arg = p.getArg('[', ']');
4447                         map<string, string> opts;
4448                         vector<string> keys;
4449                         split_map(arg, opts, keys);
4450                         string name = normalize_filename(p.verbatim_item());
4451                         string const path = getMasterFilePath(true);
4452                         // We want to preserve relative / absolute filenames,
4453                         // therefore path is only used for testing
4454                         if (!makeAbsPath(name, path).exists()) {
4455                                 // The file extension is probably missing.
4456                                 // Now try to find it out.
4457                                 char const * const pdfpages_format[] = {"pdf", 0};
4458                                 string const pdftex_name =
4459                                         find_file(name, path, pdfpages_format);
4460                                 if (!pdftex_name.empty()) {
4461                                         name = pdftex_name;
4462                                         pdflatex = true;
4463                                 }
4464                         }
4465                         FileName const absname = makeAbsPath(name, path);
4466                         if (absname.exists())
4467                         {
4468                                 fix_child_filename(name);
4469                                 copy_file(absname, name);
4470                         } else
4471                                 cerr << "Warning: Could not find file '"
4472                                      << name << "'." << endl;
4473                         // write output
4474                         context.check_layout(os);
4475                         begin_inset(os, "External\n\ttemplate ");
4476                         os << "PDFPages\n\tfilename "
4477                            << name << "\n";
4478                         // parse the options
4479                         if (opts.find("pages") != opts.end())
4480                                 os << "\textra LaTeX \"pages="
4481                                    << opts["pages"] << "\"\n";
4482                         if (opts.find("angle") != opts.end())
4483                                 os << "\trotateAngle "
4484                                    << opts["angle"] << '\n';
4485                         if (opts.find("origin") != opts.end()) {
4486                                 ostringstream ss;
4487                                 string const opt = opts["origin"];
4488                                 if (opt == "tl") ss << "topleft";
4489                                 if (opt == "bl") ss << "bottomleft";
4490                                 if (opt == "Bl") ss << "baselineleft";
4491                                 if (opt == "c") ss << "center";
4492                                 if (opt == "tc") ss << "topcenter";
4493                                 if (opt == "bc") ss << "bottomcenter";
4494                                 if (opt == "Bc") ss << "baselinecenter";
4495                                 if (opt == "tr") ss << "topright";
4496                                 if (opt == "br") ss << "bottomright";
4497                                 if (opt == "Br") ss << "baselineright";
4498                                 if (!ss.str().empty())
4499                                         os << "\trotateOrigin " << ss.str() << '\n';
4500                                 else
4501                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4502                         }
4503                         if (opts.find("width") != opts.end())
4504                                 os << "\twidth "
4505                                    << translate_len(opts["width"]) << '\n';
4506                         if (opts.find("height") != opts.end())
4507                                 os << "\theight "
4508                                    << translate_len(opts["height"]) << '\n';
4509                         if (opts.find("keepaspectratio") != opts.end())
4510                                 os << "\tkeepAspectRatio\n";
4511                         end_inset(os);
4512                         context.check_layout(os);
4513                         registerExternalTemplatePackages("PDFPages");
4514                 }
4515
4516                 else if (t.cs() == "loadgame") {
4517                         p.skip_spaces();
4518                         string name = normalize_filename(p.verbatim_item());
4519                         string const path = getMasterFilePath(true);
4520                         // We want to preserve relative / absolute filenames,
4521                         // therefore path is only used for testing
4522                         if (!makeAbsPath(name, path).exists()) {
4523                                 // The file extension is probably missing.
4524                                 // Now try to find it out.
4525                                 char const * const lyxskak_format[] = {"fen", 0};
4526                                 string const lyxskak_name =
4527                                         find_file(name, path, lyxskak_format);
4528                                 if (!lyxskak_name.empty())
4529                                         name = lyxskak_name;
4530                         }
4531                         FileName const absname = makeAbsPath(name, path);
4532                         if (absname.exists())
4533                         {
4534                                 fix_child_filename(name);
4535                                 copy_file(absname, name);
4536                         } else
4537                                 cerr << "Warning: Could not find file '"
4538                                      << name << "'." << endl;
4539                         context.check_layout(os);
4540                         begin_inset(os, "External\n\ttemplate ");
4541                         os << "ChessDiagram\n\tfilename "
4542                            << name << "\n";
4543                         end_inset(os);
4544                         context.check_layout(os);
4545                         // after a \loadgame follows a \showboard
4546                         if (p.get_token().asInput() == "showboard")
4547                                 p.get_token();
4548                         registerExternalTemplatePackages("ChessDiagram");
4549                 }
4550
4551                 else {
4552                         // try to see whether the string is in unicodesymbols
4553                         // Only use text mode commands, since we are in text mode here,
4554                         // and math commands may be invalid (bug 6797)
4555                         string name = t.asInput();
4556                         // handle the dingbats and Cyrillic
4557                         if (name == "\\ding" || name == "\\textcyr")
4558                                 name = name + '{' + p.getArg('{', '}') + '}';
4559                         // handle the ifsym characters
4560                         else if (name == "\\textifsymbol") {
4561                                 string const optif = p.getFullOpt();
4562                                 string const argif = p.getArg('{', '}');
4563                                 name = name + optif + '{' + argif + '}';
4564                         }
4565                         // handle the \ascii characters
4566                         // the case of \ascii within braces, as LyX outputs it, is already
4567                         // handled for t.cat() == catBegin
4568                         else if (name == "\\ascii") {
4569                                 // the code is "\asci\xxx"
4570                                 name = "{" + name + p.get_token().asInput() + "}";
4571                                 skip_braces(p);
4572                         }
4573                         // handle some TIPA special characters
4574                         else if (preamble.isPackageUsed("tipa")) {
4575                                 if (name == "\\textglobfall") {
4576                                         name = "End";
4577                                         skip_braces(p);
4578                                 } else if (name == "\\s") {
4579                                         // fromLaTeXCommand() does not yet
4580                                         // recognize tipa short cuts
4581                                         name = "\\textsyllabic";
4582                                 } else if (name == "\\=" &&
4583                                            p.next_token().asInput() == "*") {
4584                                         // fromLaTeXCommand() does not yet
4585                                         // recognize tipa short cuts
4586                                         p.get_token();
4587                                         name = "\\b";
4588                                 } else if (name == "\\textdoublevertline") {
4589                                         // FIXME: This is not correct,
4590                                         // \textvertline is higher than \textbardbl
4591                                         name = "\\textbardbl";
4592                                         skip_braces(p);
4593                                 } else if (name == "\\!" ) {
4594                                         if (p.next_token().asInput() == "b") {
4595                                                 p.get_token();  // eat 'b'
4596                                                 name = "\\texthtb";
4597                                                 skip_braces(p);
4598                                         } else if (p.next_token().asInput() == "d") {
4599                                                 p.get_token();
4600                                                 name = "\\texthtd";
4601                                                 skip_braces(p);
4602                                         } else if (p.next_token().asInput() == "g") {
4603                                                 p.get_token();
4604                                                 name = "\\texthtg";
4605                                                 skip_braces(p);
4606                                         } else if (p.next_token().asInput() == "G") {
4607                                                 p.get_token();
4608                                                 name = "\\texthtscg";
4609                                                 skip_braces(p);
4610                                         } else if (p.next_token().asInput() == "j") {
4611                                                 p.get_token();
4612                                                 name = "\\texthtbardotlessj";
4613                                                 skip_braces(p);
4614                                         } else if (p.next_token().asInput() == "o") {
4615                                                 p.get_token();
4616                                                 name = "\\textbullseye";
4617                                                 skip_braces(p);
4618                                         }
4619                                 } else if (name == "\\*" ) {
4620                                         if (p.next_token().asInput() == "k") {
4621                                                 p.get_token();
4622                                                 name = "\\textturnk";
4623                                                 skip_braces(p);
4624                                         } else if (p.next_token().asInput() == "r") {
4625                                                 p.get_token();  // eat 'b'
4626                                                 name = "\\textturnr";
4627                                                 skip_braces(p);
4628                                         } else if (p.next_token().asInput() == "t") {
4629                                                 p.get_token();
4630                                                 name = "\\textturnt";
4631                                                 skip_braces(p);
4632                                         } else if (p.next_token().asInput() == "w") {
4633                                                 p.get_token();
4634                                                 name = "\\textturnw";
4635                                                 skip_braces(p);
4636                                         }
4637                                 }
4638                         }
4639                         if ((name.size() == 2 &&
4640                              contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4641                              p.next_token().asInput() != "*") ||
4642                             is_known(name.substr(1), known_tipa_marks)) {
4643                                 // name is a command that corresponds to a
4644                                 // combining character in unicodesymbols.
4645                                 // Append the argument, fromLaTeXCommand()
4646                                 // will either convert it to a single
4647                                 // character or a combining sequence.
4648                                 name += '{' + p.verbatim_item() + '}';
4649                         }
4650                         // now get the character from unicodesymbols
4651                         bool termination;
4652                         docstring rem;
4653                         set<string> req;
4654                         docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4655                                         Encodings::TEXT_CMD, termination, rem, &req);
4656                         if (!s.empty()) {
4657                                 context.check_layout(os);
4658                                 os << to_utf8(s);
4659                                 if (!rem.empty())
4660                                         output_ert_inset(os, to_utf8(rem), context);
4661                                 if (termination)
4662                                         skip_spaces_braces(p);
4663                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4664                                         preamble.registerAutomaticallyLoadedPackage(*it);
4665                         }
4666                         //cerr << "#: " << t << " mode: " << mode << endl;
4667                         // heuristic: read up to next non-nested space
4668                         /*
4669                         string s = t.asInput();
4670                         string z = p.verbatim_item();
4671                         while (p.good() && z != " " && !z.empty()) {
4672                                 //cerr << "read: " << z << endl;
4673                                 s += z;
4674                                 z = p.verbatim_item();
4675                         }
4676                         cerr << "found ERT: " << s << endl;
4677                         output_ert_inset(os, s + ' ', context);
4678                         */
4679                         else {
4680                                 if (t.asInput() == name &&
4681                                     p.next_token().asInput() == "*") {
4682                                         // Starred commands like \vspace*{}
4683                                         p.get_token();  // Eat '*'
4684                                         name += '*';
4685                                 }
4686                                 if (!parse_command(name, p, os, outer, context))
4687                                         output_ert_inset(os, name, context);
4688                         }
4689                 }
4690
4691                 if (flags & FLAG_LEAVE) {
4692                         flags &= ~FLAG_LEAVE;
4693                         break;
4694                 }
4695         }
4696 }
4697
4698
4699 string guessLanguage(Parser & p, string const & lang)
4700 {
4701         typedef std::map<std::string, size_t> LangMap;
4702         // map from language names to number of characters
4703         LangMap used;
4704         used[lang] = 0;
4705         for (char const * const * i = supported_CJK_languages; *i; i++)
4706                 used[string(*i)] = 0;
4707
4708         while (p.good()) {
4709                 Token const t = p.get_token();
4710                 // comments are not counted for any language
4711                 if (t.cat() == catComment)
4712                         continue;
4713                 // commands are not counted as well, but we need to detect
4714                 // \begin{CJK} and switch encoding if needed
4715                 if (t.cat() == catEscape) {
4716                         if (t.cs() == "inputencoding") {
4717                                 string const enc = subst(p.verbatim_item(), "\n", " ");
4718                                 p.setEncoding(enc, Encoding::inputenc);
4719                                 continue;
4720                         }
4721                         if (t.cs() != "begin")
4722                                 continue;
4723                 } else {
4724                         // Non-CJK content is counted for lang.
4725                         // We do not care about the real language here:
4726                         // If we have more non-CJK contents than CJK contents,
4727                         // we simply use the language that was specified as
4728                         // babel main language.
4729                         used[lang] += t.asInput().length();
4730                         continue;
4731                 }
4732                 // Now we are starting an environment
4733                 p.pushPosition();
4734                 string const name = p.getArg('{', '}');
4735                 if (name != "CJK") {
4736                         p.popPosition();
4737                         continue;
4738                 }
4739                 // It is a CJK environment
4740                 p.popPosition();
4741                 /* name = */ p.getArg('{', '}');
4742                 string const encoding = p.getArg('{', '}');
4743                 /* mapping = */ p.getArg('{', '}');
4744                 string const encoding_old = p.getEncoding();
4745                 char const * const * const where =
4746                         is_known(encoding, supported_CJK_encodings);
4747                 if (where)
4748                         p.setEncoding(encoding, Encoding::CJK);
4749                 else
4750                         p.setEncoding("UTF-8");
4751                 string const text = p.ertEnvironment("CJK");
4752                 p.setEncoding(encoding_old);
4753                 p.skip_spaces();
4754                 if (!where) {
4755                         // ignore contents in unknown CJK encoding
4756                         continue;
4757                 }
4758                 // the language of the text
4759                 string const cjk =
4760                         supported_CJK_languages[where - supported_CJK_encodings];
4761                 used[cjk] += text.length();
4762         }
4763         LangMap::const_iterator use = used.begin();
4764         for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4765                 if (it->second > use->second)
4766                         use = it;
4767         }
4768         return use->first;
4769 }
4770
4771 // }])
4772
4773
4774 } // namespace lyx