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