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