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