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