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