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