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