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