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