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