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