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