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