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