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