]> git.lyx.org Git - features.git/blob - src/tex2lyx/text.cpp
721db0ce6bb9212a386ed3e5a03663d1854ac7a7
[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                         Context newcontext(true, context.textclass, 0, 0, context.font);
2835                         newcontext.check_layout(os);
2836                         // FIXME InsetArgument is now properly implemented in InsetLayout
2837                         //       (for captions, but also for others)
2838                         if (p.next_token().cat() != catEscape &&
2839                             p.next_token().character() == '[') {
2840                                 p.get_token(); // eat '['
2841                                 begin_inset(os, "Argument 1\n");
2842                                 os << "status collapsed\n";
2843                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2844                                 end_inset(os);
2845                                 eat_whitespace(p, os, context, false);
2846                         }
2847                         parse_text(p, os, FLAG_ITEM, outer, context);
2848                         context.check_end_layout(os);
2849                         // We don't need really a new paragraph, but
2850                         // we must make sure that the next item gets a \begin_layout.
2851                         context.new_paragraph(os);
2852                         end_inset(os);
2853                         p.skip_spaces();
2854                         newcontext.check_end_layout(os);
2855                 }
2856
2857                 else if (t.cs() == "subfloat") {
2858                         // the syntax is \subfloat[caption]{content}
2859                         // if it is a table of figure depends on the surrounding float
2860                         bool has_caption = false;
2861                         p.skip_spaces();
2862                         // do nothing if there is no outer float
2863                         if (!float_type.empty()) {
2864                                 context.check_layout(os);
2865                                 p.skip_spaces();
2866                                 begin_inset(os, "Float " + float_type + "\n");
2867                                 os << "wide false"
2868                                    << "\nsideways false"
2869                                    << "\nstatus collapsed\n\n";
2870                                 // test for caption
2871                                 string caption;
2872                                 if (p.next_token().cat() != catEscape &&
2873                                                 p.next_token().character() == '[') {
2874                                                         p.get_token(); // eat '['
2875                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2876                                                         has_caption = true;
2877                                 }
2878                                 // the content
2879                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2880                                 // the caption comes always as the last
2881                                 if (has_caption) {
2882                                         // we must make sure that the caption gets a \begin_layout
2883                                         os << "\n\\begin_layout Plain Layout";
2884                                         p.skip_spaces();
2885                                         begin_inset(os, "Caption Standard\n");
2886                                         Context newcontext(true, context.textclass,
2887                                                            0, 0, context.font);
2888                                         newcontext.check_layout(os);
2889                                         os << caption << "\n";
2890                                         newcontext.check_end_layout(os);
2891                                         // We don't need really a new paragraph, but
2892                                         // we must make sure that the next item gets a \begin_layout.
2893                                         //newcontext.new_paragraph(os);
2894                                         end_inset(os);
2895                                         p.skip_spaces();
2896                                 }
2897                                 // We don't need really a new paragraph, but
2898                                 // we must make sure that the next item gets a \begin_layout.
2899                                 if (has_caption)
2900                                         context.new_paragraph(os);
2901                                 end_inset(os);
2902                                 p.skip_spaces();
2903                                 context.check_end_layout(os);
2904                                 // close the layout we opened
2905                                 if (has_caption)
2906                                         os << "\n\\end_layout\n";
2907                         } else {
2908                                 // if the float type is not supported or there is no surrounding float
2909                                 // output it as ERT
2910                                 if (p.hasOpt()) {
2911                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2912                                         output_ert_inset(os, t.asInput() + '[' + opt_arg +
2913                                                "]{" + p.verbatim_item() + '}', context);
2914                                 } else
2915                                         output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2916                         }
2917                 }
2918
2919                 else if (t.cs() == "includegraphics") {
2920                         bool const clip = p.next_token().asInput() == "*";
2921                         if (clip)
2922                                 p.get_token();
2923                         string const arg = p.getArg('[', ']');
2924                         map<string, string> opts;
2925                         vector<string> keys;
2926                         split_map(arg, opts, keys);
2927                         if (clip)
2928                                 opts["clip"] = string();
2929                         string name = normalize_filename(p.verbatim_item());
2930
2931                         string const path = getMasterFilePath(true);
2932                         // We want to preserve relative / absolute filenames,
2933                         // therefore path is only used for testing
2934                         if (!makeAbsPath(name, path).exists()) {
2935                                 // The file extension is probably missing.
2936                                 // Now try to find it out.
2937                                 string const dvips_name =
2938                                         find_file(name, path,
2939                                                   known_dvips_graphics_formats);
2940                                 string const pdftex_name =
2941                                         find_file(name, path,
2942                                                   known_pdftex_graphics_formats);
2943                                 if (!dvips_name.empty()) {
2944                                         if (!pdftex_name.empty()) {
2945                                                 cerr << "This file contains the "
2946                                                         "latex snippet\n"
2947                                                         "\"\\includegraphics{"
2948                                                      << name << "}\".\n"
2949                                                         "However, files\n\""
2950                                                      << dvips_name << "\" and\n\""
2951                                                      << pdftex_name << "\"\n"
2952                                                         "both exist, so I had to make a "
2953                                                         "choice and took the first one.\n"
2954                                                         "Please move the unwanted one "
2955                                                         "someplace else and try again\n"
2956                                                         "if my choice was wrong."
2957                                                      << endl;
2958                                         }
2959                                         name = dvips_name;
2960                                 } else if (!pdftex_name.empty()) {
2961                                         name = pdftex_name;
2962                                         pdflatex = true;
2963                                 }
2964                         }
2965
2966                         FileName const absname = makeAbsPath(name, path);
2967                         if (absname.exists()) {
2968                                 fix_child_filename(name);
2969                                 copy_file(absname, name);
2970                         } else
2971                                 cerr << "Warning: Could not find graphics file '"
2972                                      << name << "'." << endl;
2973
2974                         context.check_layout(os);
2975                         begin_inset(os, "Graphics ");
2976                         os << "\n\tfilename " << name << '\n';
2977                         if (opts.find("width") != opts.end())
2978                                 os << "\twidth "
2979                                    << translate_len(opts["width"]) << '\n';
2980                         if (opts.find("height") != opts.end())
2981                                 os << "\theight "
2982                                    << translate_len(opts["height"]) << '\n';
2983                         if (opts.find("scale") != opts.end()) {
2984                                 istringstream iss(opts["scale"]);
2985                                 double val;
2986                                 iss >> val;
2987                                 val = val*100;
2988                                 os << "\tscale " << val << '\n';
2989                         }
2990                         if (opts.find("angle") != opts.end()) {
2991                                 os << "\trotateAngle "
2992                                    << opts["angle"] << '\n';
2993                                 vector<string>::const_iterator a =
2994                                         find(keys.begin(), keys.end(), "angle");
2995                                 vector<string>::const_iterator s =
2996                                         find(keys.begin(), keys.end(), "width");
2997                                 if (s == keys.end())
2998                                         s = find(keys.begin(), keys.end(), "height");
2999                                 if (s == keys.end())
3000                                         s = find(keys.begin(), keys.end(), "scale");
3001                                 if (s != keys.end() && distance(s, a) > 0)
3002                                         os << "\tscaleBeforeRotation\n";
3003                         }
3004                         if (opts.find("origin") != opts.end()) {
3005                                 ostringstream ss;
3006                                 string const opt = opts["origin"];
3007                                 if (opt.find('l') != string::npos) ss << "left";
3008                                 if (opt.find('r') != string::npos) ss << "right";
3009                                 if (opt.find('c') != string::npos) ss << "center";
3010                                 if (opt.find('t') != string::npos) ss << "Top";
3011                                 if (opt.find('b') != string::npos) ss << "Bottom";
3012                                 if (opt.find('B') != string::npos) ss << "Baseline";
3013                                 if (!ss.str().empty())
3014                                         os << "\trotateOrigin " << ss.str() << '\n';
3015                                 else
3016                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3017                         }
3018                         if (opts.find("keepaspectratio") != opts.end())
3019                                 os << "\tkeepAspectRatio\n";
3020                         if (opts.find("clip") != opts.end())
3021                                 os << "\tclip\n";
3022                         if (opts.find("draft") != opts.end())
3023                                 os << "\tdraft\n";
3024                         if (opts.find("bb") != opts.end())
3025                                 os << "\tBoundingBox "
3026                                    << opts["bb"] << '\n';
3027                         int numberOfbbOptions = 0;
3028                         if (opts.find("bbllx") != opts.end())
3029                                 numberOfbbOptions++;
3030                         if (opts.find("bblly") != opts.end())
3031                                 numberOfbbOptions++;
3032                         if (opts.find("bburx") != opts.end())
3033                                 numberOfbbOptions++;
3034                         if (opts.find("bbury") != opts.end())
3035                                 numberOfbbOptions++;
3036                         if (numberOfbbOptions == 4)
3037                                 os << "\tBoundingBox "
3038                                    << opts["bbllx"] << " " << opts["bblly"] << " "
3039                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
3040                         else if (numberOfbbOptions > 0)
3041                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3042                         numberOfbbOptions = 0;
3043                         if (opts.find("natwidth") != opts.end())
3044                                 numberOfbbOptions++;
3045                         if (opts.find("natheight") != opts.end())
3046                                 numberOfbbOptions++;
3047                         if (numberOfbbOptions == 2)
3048                                 os << "\tBoundingBox 0bp 0bp "
3049                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
3050                         else if (numberOfbbOptions > 0)
3051                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3052                         ostringstream special;
3053                         if (opts.find("hiresbb") != opts.end())
3054                                 special << "hiresbb,";
3055                         if (opts.find("trim") != opts.end())
3056                                 special << "trim,";
3057                         if (opts.find("viewport") != opts.end())
3058                                 special << "viewport=" << opts["viewport"] << ',';
3059                         if (opts.find("totalheight") != opts.end())
3060                                 special << "totalheight=" << opts["totalheight"] << ',';
3061                         if (opts.find("type") != opts.end())
3062                                 special << "type=" << opts["type"] << ',';
3063                         if (opts.find("ext") != opts.end())
3064                                 special << "ext=" << opts["ext"] << ',';
3065                         if (opts.find("read") != opts.end())
3066                                 special << "read=" << opts["read"] << ',';
3067                         if (opts.find("command") != opts.end())
3068                                 special << "command=" << opts["command"] << ',';
3069                         string s_special = special.str();
3070                         if (!s_special.empty()) {
3071                                 // We had special arguments. Remove the trailing ','.
3072                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3073                         }
3074                         // TODO: Handle the unknown settings better.
3075                         // Warn about invalid options.
3076                         // Check whether some option was given twice.
3077                         end_inset(os);
3078                         preamble.registerAutomaticallyLoadedPackage("graphicx");
3079                 }
3080
3081                 else if (t.cs() == "footnote" ||
3082                          (t.cs() == "thanks" && context.layout->intitle)) {
3083                         p.skip_spaces();
3084                         context.check_layout(os);
3085                         begin_inset(os, "Foot\n");
3086                         os << "status collapsed\n\n";
3087                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3088                         end_inset(os);
3089                 }
3090
3091                 else if (t.cs() == "marginpar") {
3092                         p.skip_spaces();
3093                         context.check_layout(os);
3094                         begin_inset(os, "Marginal\n");
3095                         os << "status collapsed\n\n";
3096                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3097                         end_inset(os);
3098                 }
3099
3100                 else if (t.cs() == "lstinline") {
3101                         p.skip_spaces();
3102                         parse_listings(p, os, context, true);
3103                 }
3104
3105                 else if (t.cs() == "ensuremath") {
3106                         p.skip_spaces();
3107                         context.check_layout(os);
3108                         string const s = p.verbatim_item();
3109                         //FIXME: this never triggers in UTF8
3110                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3111                                 os << s;
3112                         else
3113                                 output_ert_inset(os, "\\ensuremath{" + s + "}",
3114                                            context);
3115                 }
3116
3117                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3118                         if (preamble.titleLayoutFound()) {
3119                                 // swallow this
3120                                 skip_spaces_braces(p);
3121                         } else
3122                                 output_ert_inset(os, t.asInput(), context);
3123                 }
3124
3125                 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3126                         context.check_layout(os);
3127                         begin_command_inset(os, "toc", t.cs());
3128                         end_inset(os);
3129                         skip_spaces_braces(p);
3130                         if (t.cs() == "lstlistoflistings")
3131                                 preamble.registerAutomaticallyLoadedPackage("listings");
3132                 }
3133
3134                 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3135                         context.check_layout(os);
3136                         if (t.cs() == "listoffigures")
3137                                 begin_inset(os, "FloatList figure\n");
3138                         else
3139                                 begin_inset(os, "FloatList table\n");
3140                         end_inset(os);
3141                         skip_spaces_braces(p);
3142                 }
3143
3144                 else if (t.cs() == "listof") {
3145                         p.skip_spaces(true);
3146                         string const name = p.get_token().cs();
3147                         if (context.textclass.floats().typeExist(name)) {
3148                                 context.check_layout(os);
3149                                 begin_inset(os, "FloatList ");
3150                                 os << name << "\n";
3151                                 end_inset(os);
3152                                 p.get_token(); // swallow second arg
3153                         } else
3154                                 output_ert_inset(os, "\\listof{" + name + "}", context);
3155                 }
3156
3157                 else if ((where = is_known(t.cs(), known_text_font_families)))
3158                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3159                                 context, "\\family", context.font.family,
3160                                 known_coded_font_families[where - known_text_font_families]);
3161
3162                 else if ((where = is_known(t.cs(), known_text_font_series)))
3163                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3164                                 context, "\\series", context.font.series,
3165                                 known_coded_font_series[where - known_text_font_series]);
3166
3167                 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3168                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3169                                 context, "\\shape", context.font.shape,
3170                                 known_coded_font_shapes[where - known_text_font_shapes]);
3171
3172                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3173                         context.check_layout(os);
3174                         TeXFont oldFont = context.font;
3175                         context.font.init();
3176                         context.font.size = oldFont.size;
3177                         os << "\n\\family " << context.font.family << "\n";
3178                         os << "\n\\series " << context.font.series << "\n";
3179                         os << "\n\\shape " << context.font.shape << "\n";
3180                         if (t.cs() == "textnormal") {
3181                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3182                                 output_font_change(os, context.font, oldFont);
3183                                 context.font = oldFont;
3184                         } else
3185                                 eat_whitespace(p, os, context, false);
3186                 }
3187
3188                 else if (t.cs() == "textcolor") {
3189                         // scheme is \textcolor{color name}{text}
3190                         string const color = p.verbatim_item();
3191                         // we only support the predefined colors of the color package
3192                         if (color == "black" || color == "blue" || color == "cyan"
3193                                 || color == "green" || color == "magenta" || color == "red"
3194                                 || color == "white" || color == "yellow") {
3195                                         context.check_layout(os);
3196                                         os << "\n\\color " << color << "\n";
3197                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3198                                         context.check_layout(os);
3199                                         os << "\n\\color inherit\n";
3200                                         preamble.registerAutomaticallyLoadedPackage("color");
3201                         } else
3202                                 // for custom defined colors
3203                                 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3204                 }
3205
3206                 else if (t.cs() == "underbar" || t.cs() == "uline") {
3207                         // \underbar is not 100% correct (LyX outputs \uline
3208                         // of ulem.sty). The difference is that \ulem allows
3209                         // line breaks, and \underbar does not.
3210                         // Do NOT handle \underline.
3211                         // \underbar cuts through y, g, q, p etc.,
3212                         // \underline does not.
3213                         context.check_layout(os);
3214                         os << "\n\\bar under\n";
3215                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3216                         context.check_layout(os);
3217                         os << "\n\\bar default\n";
3218                         preamble.registerAutomaticallyLoadedPackage("ulem");
3219                 }
3220
3221                 else if (t.cs() == "sout") {
3222                         context.check_layout(os);
3223                         os << "\n\\strikeout on\n";
3224                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3225                         context.check_layout(os);
3226                         os << "\n\\strikeout default\n";
3227                         preamble.registerAutomaticallyLoadedPackage("ulem");
3228                 }
3229
3230                 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3231                          t.cs() == "emph" || t.cs() == "noun") {
3232                         context.check_layout(os);
3233                         os << "\n\\" << t.cs() << " on\n";
3234                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3235                         context.check_layout(os);
3236                         os << "\n\\" << t.cs() << " default\n";
3237                         if (t.cs() == "uuline" || t.cs() == "uwave")
3238                                 preamble.registerAutomaticallyLoadedPackage("ulem");
3239                 }
3240
3241                 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3242                         context.check_layout(os);
3243                         string name = p.getArg('{', '}');
3244                         string localtime = p.getArg('{', '}');
3245                         preamble.registerAuthor(name);
3246                         Author const & author = preamble.getAuthor(name);
3247                         // from_asctime_utc() will fail if LyX decides to output the
3248                         // time in the text language.
3249                         time_t ptime = from_asctime_utc(localtime);
3250                         if (ptime == static_cast<time_t>(-1)) {
3251                                 cerr << "Warning: Could not parse time `" << localtime
3252                                      << "´ for change tracking, using current time instead.\n";
3253                                 ptime = current_time();
3254                         }
3255                         if (t.cs() == "lyxadded")
3256                                 os << "\n\\change_inserted ";
3257                         else
3258                                 os << "\n\\change_deleted ";
3259                         os << author.bufferId() << ' ' << ptime << '\n';
3260                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3261                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
3262                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3263                                           LaTeXPackages::isAvailable("xcolor");
3264                         // No need to test for luatex, since luatex comes in
3265                         // two flavours (dvi and pdf), like latex, and those
3266                         // are detected by pdflatex.
3267                         if (pdflatex || xetex) {
3268                                 if (xcolorulem) {
3269                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3270                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3271                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3272                                 }
3273                         } else {
3274                                 if (dvipost) {
3275                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
3276                                 } else if (xcolorulem) {
3277                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3278                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3279                                 }
3280                         }
3281                 }
3282
3283                 else if (t.cs() == "textipa") {
3284                         context.check_layout(os);
3285                         begin_inset(os, "IPA\n");
3286                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3287                         end_inset(os);
3288                         preamble.registerAutomaticallyLoadedPackage("tipa");
3289                         preamble.registerAutomaticallyLoadedPackage("tipx");
3290                 }
3291
3292                 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3293                         context.check_layout(os);
3294                         begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3295                         os << "status open\n";
3296                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3297                         end_inset(os);
3298                         p.skip_spaces();
3299                 }
3300
3301                 else if (t.cs() == "textvertline") {
3302                         // FIXME: This is not correct, \textvertline is higher than |
3303                         os << "|";
3304                         skip_braces(p);
3305                         continue;
3306                 }
3307
3308                 else if (t.cs() == "tone" ) {
3309                         context.check_layout(os);
3310                         // register the tone package
3311                         preamble.registerAutomaticallyLoadedPackage("tone");
3312                         string content = trimSpaceAndEol(p.verbatim_item());
3313                         string command = t.asInput() + "{" + content + "}";
3314                         // some tones can be detected by unicodesymbols, some need special code
3315                         if (is_known(content, known_tones)) {
3316                                 os << "\\IPAChar " << command << "\n";
3317                                 continue;
3318                         }
3319                         // try to see whether the string is in unicodesymbols
3320                         bool termination;
3321                         docstring rem;
3322                         set<string> req;
3323                         docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3324                                 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3325                                 termination, rem, &req);
3326                         if (!s.empty()) {
3327                                 os << to_utf8(s);
3328                                 if (!rem.empty())
3329                                         output_ert_inset(os, to_utf8(rem), context);
3330                                 for (set<string>::const_iterator it = req.begin();
3331                                      it != req.end(); ++it)
3332                                         preamble.registerAutomaticallyLoadedPackage(*it);
3333                         } else
3334                                 // we did not find a non-ert version
3335                                 output_ert_inset(os, command, context);
3336                 }
3337
3338                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3339                              t.cs() == "vphantom") {
3340                         context.check_layout(os);
3341                         if (t.cs() == "phantom")
3342                                 begin_inset(os, "Phantom Phantom\n");
3343                         if (t.cs() == "hphantom")
3344                                 begin_inset(os, "Phantom HPhantom\n");
3345                         if (t.cs() == "vphantom")
3346                                 begin_inset(os, "Phantom VPhantom\n");
3347                         os << "status open\n";
3348                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3349                                             "Phantom");
3350                         end_inset(os);
3351                 }
3352
3353                 else if (t.cs() == "href") {
3354                         context.check_layout(os);
3355                         string target = convert_command_inset_arg(p.verbatim_item());
3356                         string name = convert_command_inset_arg(p.verbatim_item());
3357                         string type;
3358                         size_t i = target.find(':');
3359                         if (i != string::npos) {
3360                                 type = target.substr(0, i + 1);
3361                                 if (type == "mailto:" || type == "file:")
3362                                         target = target.substr(i + 1);
3363                                 // handle the case that name is equal to target, except of "http://"
3364                                 else if (target.substr(i + 3) == name && type == "http:")
3365                                         target = name;
3366                         }
3367                         begin_command_inset(os, "href", "href");
3368                         if (name != target)
3369                                 os << "name \"" << name << "\"\n";
3370                         os << "target \"" << target << "\"\n";
3371                         if (type == "mailto:" || type == "file:")
3372                                 os << "type \"" << type << "\"\n";
3373                         end_inset(os);
3374                         skip_spaces_braces(p);
3375                 }
3376
3377                 else if (t.cs() == "lyxline") {
3378                         // swallow size argument (it is not used anyway)
3379                         p.getArg('{', '}');
3380                         if (!context.atParagraphStart()) {
3381                                 // so our line is in the middle of a paragraph
3382                                 // we need to add a new line, lest this line
3383                                 // follow the other content on that line and
3384                                 // run off the side of the page
3385                                 // FIXME: This may create an empty paragraph,
3386                                 //        but without that it would not be
3387                                 //        possible to set noindent below.
3388                                 //        Fortunately LaTeX does not care
3389                                 //        about the empty paragraph.
3390                                 context.new_paragraph(os);
3391                         }
3392                         if (preamble.indentParagraphs()) {
3393                                 // we need to unindent, lest the line be too long
3394                                 context.add_par_extra_stuff("\\noindent\n");
3395                         }
3396                         context.check_layout(os);
3397                         begin_command_inset(os, "line", "rule");
3398                         os << "offset \"0.5ex\"\n"
3399                               "width \"100line%\"\n"
3400                               "height \"1pt\"\n";
3401                         end_inset(os);
3402                 }
3403
3404                 else if (t.cs() == "rule") {
3405                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3406                         string const width = p.getArg('{', '}');
3407                         string const thickness = p.getArg('{', '}');
3408                         context.check_layout(os);
3409                         begin_command_inset(os, "line", "rule");
3410                         if (!offset.empty())
3411                                 os << "offset \"" << translate_len(offset) << "\"\n";
3412                         os << "width \"" << translate_len(width) << "\"\n"
3413                                   "height \"" << translate_len(thickness) << "\"\n";
3414                         end_inset(os);
3415                 }
3416
3417                 else if (is_known(t.cs(), known_phrases) ||
3418                          (t.cs() == "protect" &&
3419                           p.next_token().cat() == catEscape &&
3420                           is_known(p.next_token().cs(), known_phrases))) {
3421                         // LyX sometimes puts a \protect in front, so we have to ignore it
3422                         // FIXME: This needs to be changed when bug 4752 is fixed.
3423                         where = is_known(
3424                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3425                                 known_phrases);
3426                         context.check_layout(os);
3427                         os << known_coded_phrases[where - known_phrases];
3428                         skip_spaces_braces(p);
3429                 }
3430
3431                 // handle refstyle first to catch \eqref which can also occur
3432                 // without refstyle. Only recognize these commands if
3433                 // refstyle.sty was found in the preamble (otherwise \eqref
3434                 // and user defined ref commands could be misdetected).
3435                 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3436                          preamble.refstyle()) {
3437                         context.check_layout(os);
3438                         begin_command_inset(os, "ref", "formatted");
3439                         os << "reference \"";
3440                         os << known_refstyle_prefixes[where - known_refstyle_commands]
3441                            << ":";
3442                         os << convert_command_inset_arg(p.verbatim_item())
3443                            << "\"\n";
3444                         end_inset(os);
3445                         preamble.registerAutomaticallyLoadedPackage("refstyle");
3446                 }
3447
3448                 // if refstyle is used, we must not convert \prettyref to a
3449                 // formatted reference, since that would result in a refstyle command.
3450                 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3451                          (t.cs() != "prettyref" || !preamble.refstyle())) {
3452                         string const opt = p.getOpt();
3453                         if (opt.empty()) {
3454                                 context.check_layout(os);
3455                                 begin_command_inset(os, "ref",
3456                                         known_coded_ref_commands[where - known_ref_commands]);
3457                                 os << "reference \""
3458                                    << convert_command_inset_arg(p.verbatim_item())
3459                                    << "\"\n";
3460                                 end_inset(os);
3461                                 if (t.cs() == "vref" || t.cs() == "vpageref")
3462                                         preamble.registerAutomaticallyLoadedPackage("varioref");
3463                                 else if (t.cs() == "prettyref")
3464                                         preamble.registerAutomaticallyLoadedPackage("prettyref");
3465                         } else {
3466                                 // LyX does not yet support optional arguments of ref commands
3467                                 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3468                                        p.verbatim_item() + '}', context);
3469                         }
3470                 }
3471
3472                 else if (use_natbib &&
3473                          is_known(t.cs(), known_natbib_commands) &&
3474                          ((t.cs() != "citefullauthor" &&
3475                            t.cs() != "citeyear" &&
3476                            t.cs() != "citeyearpar") ||
3477                           p.next_token().asInput() != "*")) {
3478                         context.check_layout(os);
3479                         string command = t.cs();
3480                         if (p.next_token().asInput() == "*") {
3481                                 command += '*';
3482                                 p.get_token();
3483                         }
3484                         if (command == "citefullauthor")
3485                                 // alternative name for "\\citeauthor*"
3486                                 command = "citeauthor*";
3487
3488                         // text before the citation
3489                         string before;
3490                         // text after the citation
3491                         string after;
3492                         get_cite_arguments(p, true, before, after);
3493
3494                         if (command == "cite") {
3495                                 // \cite without optional argument means
3496                                 // \citet, \cite with at least one optional
3497                                 // argument means \citep.
3498                                 if (before.empty() && after.empty())
3499                                         command = "citet";
3500                                 else
3501                                         command = "citep";
3502                         }
3503                         if (before.empty() && after == "[]")
3504                                 // avoid \citet[]{a}
3505                                 after.erase();
3506                         else if (before == "[]" && after == "[]") {
3507                                 // avoid \citet[][]{a}
3508                                 before.erase();
3509                                 after.erase();
3510                         }
3511                         // remove the brackets around after and before
3512                         if (!after.empty()) {
3513                                 after.erase(0, 1);
3514                                 after.erase(after.length() - 1, 1);
3515                                 after = convert_command_inset_arg(after);
3516                         }
3517                         if (!before.empty()) {
3518                                 before.erase(0, 1);
3519                                 before.erase(before.length() - 1, 1);
3520                                 before = convert_command_inset_arg(before);
3521                         }
3522                         begin_command_inset(os, "citation", command);
3523                         os << "after " << '"' << after << '"' << "\n";
3524                         os << "before " << '"' << before << '"' << "\n";
3525                         os << "key \""
3526                            << convert_command_inset_arg(p.verbatim_item())
3527                            << "\"\n";
3528                         end_inset(os);
3529                         // Need to set the cite engine if natbib is loaded by
3530                         // the document class directly
3531                         if (preamble.citeEngine() == "basic")
3532                                 preamble.citeEngine("natbib");
3533                 }
3534
3535                 else if (use_jurabib &&
3536                          is_known(t.cs(), known_jurabib_commands) &&
3537                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3538                         context.check_layout(os);
3539                         string command = t.cs();
3540                         if (p.next_token().asInput() == "*") {
3541                                 command += '*';
3542                                 p.get_token();
3543                         }
3544                         char argumentOrder = '\0';
3545                         vector<string> const options =
3546                                 preamble.getPackageOptions("jurabib");
3547                         if (find(options.begin(), options.end(),
3548                                       "natbiborder") != options.end())
3549                                 argumentOrder = 'n';
3550                         else if (find(options.begin(), options.end(),
3551                                            "jurabiborder") != options.end())
3552                                 argumentOrder = 'j';
3553
3554                         // text before the citation
3555                         string before;
3556                         // text after the citation
3557                         string after;
3558                         get_cite_arguments(p, argumentOrder != 'j', before, after);
3559
3560                         string const citation = p.verbatim_item();
3561                         if (!before.empty() && argumentOrder == '\0') {
3562                                 cerr << "Warning: Assuming argument order "
3563                                         "of jurabib version 0.6 for\n'"
3564                                      << command << before << after << '{'
3565                                      << citation << "}'.\n"
3566                                         "Add 'jurabiborder' to the jurabib "
3567                                         "package options if you used an\n"
3568                                         "earlier jurabib version." << endl;
3569                         }
3570                         if (!after.empty()) {
3571                                 after.erase(0, 1);
3572                                 after.erase(after.length() - 1, 1);
3573                         }
3574                         if (!before.empty()) {
3575                                 before.erase(0, 1);
3576                                 before.erase(before.length() - 1, 1);
3577                         }
3578                         begin_command_inset(os, "citation", command);
3579                         os << "after " << '"' << after << '"' << "\n";
3580                         os << "before " << '"' << before << '"' << "\n";
3581                         os << "key " << '"' << citation << '"' << "\n";
3582                         end_inset(os);
3583                         // Need to set the cite engine if jurabib is loaded by
3584                         // the document class directly
3585                         if (preamble.citeEngine() == "basic")
3586                                 preamble.citeEngine("jurabib");
3587                 }
3588
3589                 else if (t.cs() == "cite"
3590                         || t.cs() == "nocite") {
3591                         context.check_layout(os);
3592                         string after = convert_command_inset_arg(p.getArg('[', ']'));
3593                         string key = convert_command_inset_arg(p.verbatim_item());
3594                         // store the case that it is "\nocite{*}" to use it later for
3595                         // the BibTeX inset
3596                         if (key != "*") {
3597                                 begin_command_inset(os, "citation", t.cs());
3598                                 os << "after " << '"' << after << '"' << "\n";
3599                                 os << "key " << '"' << key << '"' << "\n";
3600                                 end_inset(os);
3601                         } else if (t.cs() == "nocite")
3602                                 btprint = key;
3603                 }
3604
3605                 else if (t.cs() == "index" ||
3606                          (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3607                         context.check_layout(os);
3608                         string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3609                                 p.getArg('[', ']') : "";
3610                         string const kind = arg.empty() ? "idx" : arg;
3611                         begin_inset(os, "Index ");
3612                         os << kind << "\nstatus collapsed\n";
3613                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3614                         end_inset(os);
3615                         if (kind != "idx")
3616                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3617                 }
3618
3619                 else if (t.cs() == "nomenclature") {
3620                         context.check_layout(os);
3621                         begin_command_inset(os, "nomenclature", "nomenclature");
3622                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3623                         if (!prefix.empty())
3624                                 os << "prefix " << '"' << prefix << '"' << "\n";
3625                         os << "symbol " << '"'
3626                            << convert_command_inset_arg(p.verbatim_item());
3627                         os << "\"\ndescription \""
3628                            << convert_command_inset_arg(p.verbatim_item())
3629                            << "\"\n";
3630                         end_inset(os);
3631                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3632                 }
3633
3634                 else if (t.cs() == "label") {
3635                         context.check_layout(os);
3636                         begin_command_inset(os, "label", "label");
3637                         os << "name \""
3638                            << convert_command_inset_arg(p.verbatim_item())
3639                            << "\"\n";
3640                         end_inset(os);
3641                 }
3642
3643                 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3644                         context.check_layout(os);
3645                         string commandname = t.cs();
3646                         bool star = false;
3647                         if (p.next_token().asInput() == "*") {
3648                                 commandname += "*";
3649                                 star = true;
3650                                 p.get_token();
3651                         }
3652                         begin_command_inset(os, "index_print", commandname);
3653                         string const indexname = p.getArg('[', ']');
3654                         if (!star) {
3655                                 if (indexname.empty())
3656                                         os << "type \"idx\"\n";
3657                                 else
3658                                         os << "type \"" << indexname << "\"\n";
3659                         }
3660                         end_inset(os);
3661                         skip_spaces_braces(p);
3662                         preamble.registerAutomaticallyLoadedPackage("makeidx");
3663                         if (preamble.use_indices() == "true")
3664                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3665                 }
3666
3667                 else if (t.cs() == "printnomenclature") {
3668                         string width = "";
3669                         string width_type = "";
3670                         context.check_layout(os);
3671                         begin_command_inset(os, "nomencl_print", "printnomenclature");
3672                         // case of a custom width
3673                         if (p.hasOpt()) {
3674                                 width = p.getArg('[', ']');
3675                                 width = translate_len(width);
3676                                 width_type = "custom";
3677                         }
3678                         // case of no custom width
3679                         // the case of no custom width but the width set
3680                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
3681                         // because the user could have set anything, not only the width
3682                         // of the longest label (which would be width_type = "auto")
3683                         string label = convert_command_inset_arg(p.getArg('{', '}'));
3684                         if (label.empty() && width_type.empty())
3685                                 width_type = "none";
3686                         os << "set_width \"" << width_type << "\"\n";
3687                         if (width_type == "custom")
3688                                 os << "width \"" << width << '\"';
3689                         end_inset(os);
3690                         skip_spaces_braces(p);
3691                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3692                 }
3693
3694                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3695                         context.check_layout(os);
3696                         begin_inset(os, "script ");
3697                         os << t.cs().substr(4) << '\n';
3698                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3699                         end_inset(os);
3700                         if (t.cs() == "textsubscript")
3701                                 preamble.registerAutomaticallyLoadedPackage("subscript");
3702                 }
3703
3704                 else if ((where = is_known(t.cs(), known_quotes))) {
3705                         context.check_layout(os);
3706                         begin_inset(os, "Quotes ");
3707                         os << known_coded_quotes[where - known_quotes];
3708                         end_inset(os);
3709                         // LyX adds {} after the quote, so we have to eat
3710                         // spaces here if there are any before a possible
3711                         // {} pair.
3712                         eat_whitespace(p, os, context, false);
3713                         skip_braces(p);
3714                 }
3715
3716                 else if ((where = is_known(t.cs(), known_sizes)) &&
3717                          context.new_layout_allowed) {
3718                         context.check_layout(os);
3719                         TeXFont const oldFont = context.font;
3720                         context.font.size = known_coded_sizes[where - known_sizes];
3721                         output_font_change(os, oldFont, context.font);
3722                         eat_whitespace(p, os, context, false);
3723                 }
3724
3725                 else if ((where = is_known(t.cs(), known_font_families)) &&
3726                          context.new_layout_allowed) {
3727                         context.check_layout(os);
3728                         TeXFont const oldFont = context.font;
3729                         context.font.family =
3730                                 known_coded_font_families[where - known_font_families];
3731                         output_font_change(os, oldFont, context.font);
3732                         eat_whitespace(p, os, context, false);
3733                 }
3734
3735                 else if ((where = is_known(t.cs(), known_font_series)) &&
3736                          context.new_layout_allowed) {
3737                         context.check_layout(os);
3738                         TeXFont const oldFont = context.font;
3739                         context.font.series =
3740                                 known_coded_font_series[where - known_font_series];
3741                         output_font_change(os, oldFont, context.font);
3742                         eat_whitespace(p, os, context, false);
3743                 }
3744
3745                 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3746                          context.new_layout_allowed) {
3747                         context.check_layout(os);
3748                         TeXFont const oldFont = context.font;
3749                         context.font.shape =
3750                                 known_coded_font_shapes[where - known_font_shapes];
3751                         output_font_change(os, oldFont, context.font);
3752                         eat_whitespace(p, os, context, false);
3753                 }
3754                 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3755                          context.new_layout_allowed) {
3756                         context.check_layout(os);
3757                         TeXFont const oldFont = context.font;
3758                         context.font.init();
3759                         context.font.size = oldFont.size;
3760                         context.font.family =
3761                                 known_coded_font_families[where - known_old_font_families];
3762                         output_font_change(os, oldFont, context.font);
3763                         eat_whitespace(p, os, context, false);
3764                 }
3765
3766                 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3767                          context.new_layout_allowed) {
3768                         context.check_layout(os);
3769                         TeXFont const oldFont = context.font;
3770                         context.font.init();
3771                         context.font.size = oldFont.size;
3772                         context.font.series =
3773                                 known_coded_font_series[where - known_old_font_series];
3774                         output_font_change(os, oldFont, context.font);
3775                         eat_whitespace(p, os, context, false);
3776                 }
3777
3778                 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3779                          context.new_layout_allowed) {
3780                         context.check_layout(os);
3781                         TeXFont const oldFont = context.font;
3782                         context.font.init();
3783                         context.font.size = oldFont.size;
3784                         context.font.shape =
3785                                 known_coded_font_shapes[where - known_old_font_shapes];
3786                         output_font_change(os, oldFont, context.font);
3787                         eat_whitespace(p, os, context, false);
3788                 }
3789
3790                 else if (t.cs() == "selectlanguage") {
3791                         context.check_layout(os);
3792                         // save the language for the case that a
3793                         // \foreignlanguage is used
3794                         context.font.language = babel2lyx(p.verbatim_item());
3795                         os << "\n\\lang " << context.font.language << "\n";
3796                 }
3797
3798                 else if (t.cs() == "foreignlanguage") {
3799                         string const lang = babel2lyx(p.verbatim_item());
3800                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3801                                               context, "\\lang",
3802                                               context.font.language, lang);
3803                 }
3804
3805                 else if (prefixIs(t.cs(), "text")
3806                          && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3807                         // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3808                         string lang;
3809                         // We have to output the whole command if it has an option
3810                         // because LyX doesn't support this yet, see bug #8214,
3811                         // only if there is a single option specifying a variant, we can handle it.
3812                         if (p.hasOpt()) {
3813                                 string langopts = p.getOpt();
3814                                 // check if the option contains a variant, if yes, extract it
3815                                 string::size_type pos_var = langopts.find("variant");
3816                                 string::size_type i = langopts.find(',');
3817                                 string::size_type k = langopts.find('=', pos_var);
3818                                 if (pos_var != string::npos && i == string::npos) {
3819                                         string variant;
3820                                         variant = langopts.substr(k + 1, langopts.length() - k - 2);
3821                                         lang = preamble.polyglossia2lyx(variant);
3822                                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3823                                                                   context, "\\lang",
3824                                                                   context.font.language, lang);
3825                                 } else
3826                                         output_ert_inset(os, t.asInput() + langopts, context);
3827                         } else {
3828                                 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3829                                 parse_text_attributes(p, os, FLAG_ITEM, outer,
3830                                                           context, "\\lang",
3831                                                           context.font.language, lang);
3832                         }
3833                 }
3834
3835                 else if (t.cs() == "inputencoding") {
3836                         // nothing to write here
3837                         string const enc = subst(p.verbatim_item(), "\n", " ");
3838                         p.setEncoding(enc, Encoding::inputenc);
3839                 }
3840
3841                 else if ((where = is_known(t.cs(), known_special_chars))) {
3842                         context.check_layout(os);
3843                         os << known_coded_special_chars[where - known_special_chars];
3844                         skip_spaces_braces(p);
3845                 }
3846
3847                 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3848                          (t.cs() == "@" && p.next_token().asInput() == ".")) {
3849                         context.check_layout(os);
3850                         os << "\\SpecialChar \\" << t.cs()
3851                            << p.get_token().asInput() << '\n';
3852                 }
3853
3854                 else if (t.cs() == "textquotedbl") {
3855                         context.check_layout(os);
3856                         os << "\"";
3857                         skip_braces(p);
3858                 }
3859
3860                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3861                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3862                             || t.cs() == "%" || t.cs() == "-") {
3863                         context.check_layout(os);
3864                         if (t.cs() == "-")
3865                                 os << "\\SpecialChar \\-\n";
3866                         else
3867                                 os << t.cs();
3868                 }
3869
3870                 else if (t.cs() == "char") {
3871                         context.check_layout(os);
3872                         if (p.next_token().character() == '`') {
3873                                 p.get_token();
3874                                 if (p.next_token().cs() == "\"") {
3875                                         p.get_token();
3876                                         os << '"';
3877                                         skip_braces(p);
3878                                 } else {
3879                                         output_ert_inset(os, "\\char`", context);
3880                                 }
3881                         } else {
3882                                 output_ert_inset(os, "\\char", context);
3883                         }
3884                 }
3885
3886                 else if (t.cs() == "verb") {
3887                         context.check_layout(os);
3888                         // set catcodes to verbatim early, just in case.
3889                         p.setCatcodes(VERBATIM_CATCODES);
3890                         string delim = p.get_token().asInput();
3891                         Parser::Arg arg = p.verbatimStuff(delim);
3892                         if (arg.first)
3893                                 output_ert_inset(os, "\\verb" + delim
3894                                                  + arg.second + delim, context);
3895                         else
3896                                 cerr << "invalid \\verb command. Skipping" << endl;
3897                 }
3898
3899                 // Problem: \= creates a tabstop inside the tabbing environment
3900                 // and else an accent. In the latter case we really would want
3901                 // \={o} instead of \= o.
3902                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3903                         output_ert_inset(os, t.asInput(), context);
3904
3905                 else if (t.cs() == "\\") {
3906                         context.check_layout(os);
3907                         if (p.hasOpt())
3908                                 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3909                         else if (p.next_token().asInput() == "*") {
3910                                 p.get_token();
3911                                 // getOpt() eats the following space if there
3912                                 // is no optional argument, but that is OK
3913                                 // here since it has no effect in the output.
3914                                 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3915                         }
3916                         else {
3917                                 begin_inset(os, "Newline newline");
3918                                 end_inset(os);
3919                         }
3920                 }
3921
3922                 else if (t.cs() == "newline" ||
3923                          (t.cs() == "linebreak" && !p.hasOpt())) {
3924                         context.check_layout(os);
3925                         begin_inset(os, "Newline ");
3926                         os << t.cs();
3927                         end_inset(os);
3928                         skip_spaces_braces(p);
3929                 }
3930
3931                 else if (t.cs() == "input" || t.cs() == "include"
3932                          || t.cs() == "verbatiminput") {
3933                         string name = t.cs();
3934                         if (t.cs() == "verbatiminput"
3935                             && p.next_token().asInput() == "*")
3936                                 name += p.get_token().asInput();
3937                         context.check_layout(os);
3938                         string filename(normalize_filename(p.getArg('{', '}')));
3939                         string const path = getMasterFilePath(true);
3940                         // We want to preserve relative / absolute filenames,
3941                         // therefore path is only used for testing
3942                         if ((t.cs() == "include" || t.cs() == "input") &&
3943                             !makeAbsPath(filename, path).exists()) {
3944                                 // The file extension is probably missing.
3945                                 // Now try to find it out.
3946                                 string const tex_name =
3947                                         find_file(filename, path,
3948                                                   known_tex_extensions);
3949                                 if (!tex_name.empty())
3950                                         filename = tex_name;
3951                         }
3952                         bool external = false;
3953                         string outname;
3954                         if (makeAbsPath(filename, path).exists()) {
3955                                 string const abstexname =
3956                                         makeAbsPath(filename, path).absFileName();
3957                                 string const absfigname =
3958                                         changeExtension(abstexname, ".fig");
3959                                 fix_child_filename(filename);
3960                                 string const lyxname = changeExtension(filename,
3961                                         roundtripMode() ? ".lyx.lyx" : ".lyx");
3962                                 string const abslyxname = makeAbsPath(
3963                                         lyxname, getParentFilePath(false)).absFileName();
3964                                 bool xfig = false;
3965                                 if (!skipChildren())
3966                                         external = FileName(absfigname).exists();
3967                                 if (t.cs() == "input" && !skipChildren()) {
3968                                         string const ext = getExtension(abstexname);
3969
3970                                         // Combined PS/LaTeX:
3971                                         // x.eps, x.pstex_t (old xfig)
3972                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3973                                         FileName const absepsname(
3974                                                 changeExtension(abstexname, ".eps"));
3975                                         FileName const abspstexname(
3976                                                 changeExtension(abstexname, ".pstex"));
3977                                         bool const xfigeps =
3978                                                 (absepsname.exists() ||
3979                                                  abspstexname.exists()) &&
3980                                                 ext == "pstex_t";
3981
3982                                         // Combined PDF/LaTeX:
3983                                         // x.pdf, x.pdftex_t (old xfig)
3984                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3985                                         FileName const abspdfname(
3986                                                 changeExtension(abstexname, ".pdf"));
3987                                         bool const xfigpdf =
3988                                                 abspdfname.exists() &&
3989                                                 (ext == "pdftex_t" || ext == "pdf_t");
3990                                         if (xfigpdf)
3991                                                 pdflatex = true;
3992
3993                                         // Combined PS/PDF/LaTeX:
3994                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3995                                         string const absbase2(
3996                                                 removeExtension(abstexname) + "_pspdftex");
3997                                         FileName const abseps2name(
3998                                                 addExtension(absbase2, ".eps"));
3999                                         FileName const abspdf2name(
4000                                                 addExtension(absbase2, ".pdf"));
4001                                         bool const xfigboth =
4002                                                 abspdf2name.exists() &&
4003                                                 abseps2name.exists() && ext == "pspdftex";
4004
4005                                         xfig = xfigpdf || xfigeps || xfigboth;
4006                                         external = external && xfig;
4007                                 }
4008                                 if (external) {
4009                                         outname = changeExtension(filename, ".fig");
4010                                         FileName abssrc(changeExtension(abstexname, ".fig"));
4011                                         copy_file(abssrc, outname);
4012                                 } else if (xfig) {
4013                                         // Don't try to convert, the result
4014                                         // would be full of ERT.
4015                                         outname = filename;
4016                                         FileName abssrc(abstexname);
4017                                         copy_file(abssrc, outname);
4018                                 } else if (t.cs() != "verbatiminput" &&
4019                                            !skipChildren() &&
4020                                     tex2lyx(abstexname, FileName(abslyxname),
4021                                             p.getEncoding())) {
4022                                         outname = lyxname;
4023                                         // no need to call copy_file
4024                                         // tex2lyx creates the file
4025                                 } else {
4026                                         outname = filename;
4027                                         FileName abssrc(abstexname);
4028                                         copy_file(abssrc, outname);
4029                                 }
4030                         } else {
4031                                 cerr << "Warning: Could not find included file '"
4032                                      << filename << "'." << endl;
4033                                 outname = filename;
4034                         }
4035                         if (external) {
4036                                 begin_inset(os, "External\n");
4037                                 os << "\ttemplate XFig\n"
4038                                    << "\tfilename " << outname << '\n';
4039                                 registerExternalTemplatePackages("XFig");
4040                         } else {
4041                                 begin_command_inset(os, "include", name);
4042                                 outname = subst(outname, "\"", "\\\"");
4043                                 os << "preview false\n"
4044                                       "filename \"" << outname << "\"\n";
4045                                 if (t.cs() == "verbatiminput")
4046                                         preamble.registerAutomaticallyLoadedPackage("verbatim");
4047                         }
4048                         end_inset(os);
4049                 }
4050
4051                 else if (t.cs() == "bibliographystyle") {
4052                         // store new bibliographystyle
4053                         bibliographystyle = p.verbatim_item();
4054                         // If any other command than \bibliography, \addcontentsline
4055                         // and \nocite{*} follows, we need to output the style
4056                         // (because it might be used by that command).
4057                         // Otherwise, it will automatically be output by LyX.
4058                         p.pushPosition();
4059                         bool output = true;
4060                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4061                                 if (t2.cat() == catBegin)
4062                                         break;
4063                                 if (t2.cat() != catEscape)
4064                                         continue;
4065                                 if (t2.cs() == "nocite") {
4066                                         if (p.getArg('{', '}') == "*")
4067                                                 continue;
4068                                 } else if (t2.cs() == "bibliography")
4069                                         output = false;
4070                                 else if (t2.cs() == "phantomsection") {
4071                                         output = false;
4072                                         continue;
4073                                 }
4074                                 else if (t2.cs() == "addcontentsline") {
4075                                         // get the 3 arguments of \addcontentsline
4076                                         p.getArg('{', '}');
4077                                         p.getArg('{', '}');
4078                                         contentslineContent = p.getArg('{', '}');
4079                                         // if the last argument is not \refname we must output
4080                                         if (contentslineContent == "\\refname")
4081                                                 output = false;
4082                                 }
4083                                 break;
4084                         }
4085                         p.popPosition();
4086                         if (output) {
4087                                 output_ert_inset(os,
4088                                         "\\bibliographystyle{" + bibliographystyle + '}',
4089                                         context);
4090                         }
4091                 }
4092
4093                 else if (t.cs() == "phantomsection") {
4094                         // we only support this if it occurs between
4095                         // \bibliographystyle and \bibliography
4096                         if (bibliographystyle.empty())
4097                                 output_ert_inset(os, "\\phantomsection", context);
4098                 }
4099
4100                 else if (t.cs() == "addcontentsline") {
4101                         context.check_layout(os);
4102                         // get the 3 arguments of \addcontentsline
4103                         string const one = p.getArg('{', '}');
4104                         string const two = p.getArg('{', '}');
4105                         string const three = p.getArg('{', '}');
4106                         // only if it is a \refname, we support if for the bibtex inset
4107                         if (contentslineContent != "\\refname") {
4108                                 output_ert_inset(os,
4109                                         "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4110                                         context);
4111                         }
4112                 }
4113
4114                 else if (t.cs() == "bibliography") {
4115                         context.check_layout(os);
4116                         string BibOpts;
4117                         begin_command_inset(os, "bibtex", "bibtex");
4118                         if (!btprint.empty()) {
4119                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4120                                 // clear the string because the next BibTeX inset can be without the
4121                                 // \nocite{*} option
4122                                 btprint.clear();
4123                         }
4124                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4125                         // Do we have addcontentsline?
4126                         if (contentslineContent == "\\refname") {
4127                                 BibOpts = "bibtotoc";
4128                                 // clear string because next BibTeX inset can be without addcontentsline
4129                                 contentslineContent.clear();
4130                         }
4131                         // Do we have a bibliographystyle set?
4132                         if (!bibliographystyle.empty()) {
4133                                 if (BibOpts.empty())
4134                                         BibOpts = bibliographystyle;
4135                                 else
4136                                         BibOpts = BibOpts + ',' + bibliographystyle;
4137                                 // clear it because each bibtex entry has its style
4138                                 // and we need an empty string to handle \phantomsection
4139                                 bibliographystyle.clear();
4140                         }
4141                         os << "options " << '"' << BibOpts << '"' << "\n";
4142                         end_inset(os);
4143                 }
4144
4145                 else if (t.cs() == "parbox") {
4146                         // Test whether this is an outer box of a shaded box
4147                         p.pushPosition();
4148                         // swallow arguments
4149                         while (p.hasOpt()) {
4150                                 p.getArg('[', ']');
4151                                 p.skip_spaces(true);
4152                         }
4153                         p.getArg('{', '}');
4154                         p.skip_spaces(true);
4155                         // eat the '{'
4156                         if (p.next_token().cat() == catBegin)
4157                                 p.get_token();
4158                         p.skip_spaces(true);
4159                         Token to = p.get_token();
4160                         bool shaded = false;
4161                         if (to.asInput() == "\\begin") {
4162                                 p.skip_spaces(true);
4163                                 if (p.getArg('{', '}') == "shaded")
4164                                         shaded = true;
4165                         }
4166                         p.popPosition();
4167                         if (shaded) {
4168                                 parse_outer_box(p, os, FLAG_ITEM, outer,
4169                                                 context, "parbox", "shaded");
4170                         } else
4171                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4172                                           "", "", t.cs());
4173                 }
4174
4175                 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4176                              t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4177                          t.cs() == "shadowbox" || t.cs() == "doublebox")
4178                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4179
4180                 else if (t.cs() == "framebox") {
4181                         if (p.next_token().character() == '(') {
4182                                 //the syntax is: \framebox(x,y)[position]{content}
4183                                 string arg = t.asInput();
4184                                 arg += p.getFullParentheseArg();
4185                                 arg += p.getFullOpt();
4186                                 eat_whitespace(p, os, context, false);
4187                                 output_ert_inset(os, arg + '{', context);
4188                                 parse_text(p, os, FLAG_ITEM, outer, context);
4189                                 output_ert_inset(os, "}", context);
4190                         } else {
4191                                 //the syntax is: \framebox[width][position]{content}
4192                                 string special = p.getFullOpt();
4193                                 special += p.getOpt();
4194                                 parse_outer_box(p, os, FLAG_ITEM, outer,
4195                                                     context, t.cs(), special);
4196                         }
4197                 }
4198
4199                 //\makebox() is part of the picture environment and different from \makebox{}
4200                 //\makebox{} will be parsed by parse_box
4201                 else if (t.cs() == "makebox") {
4202                         if (p.next_token().character() == '(') {
4203                                 //the syntax is: \makebox(x,y)[position]{content}
4204                                 string arg = t.asInput();
4205                                 arg += p.getFullParentheseArg();
4206                                 arg += p.getFullOpt();
4207                                 eat_whitespace(p, os, context, false);
4208                                 output_ert_inset(os, arg + '{', context);
4209                                 parse_text(p, os, FLAG_ITEM, outer, context);
4210                                 output_ert_inset(os, "}", context);
4211                         } else
4212                                 //the syntax is: \makebox[width][position]{content}
4213                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4214                                           "", "", t.cs());
4215                 }
4216
4217                 else if (t.cs() == "smallskip" ||
4218                          t.cs() == "medskip" ||
4219                          t.cs() == "bigskip" ||
4220                          t.cs() == "vfill") {
4221                         context.check_layout(os);
4222                         begin_inset(os, "VSpace ");
4223                         os << t.cs();
4224                         end_inset(os);
4225                         skip_spaces_braces(p);
4226                 }
4227
4228                 else if ((where = is_known(t.cs(), known_spaces))) {
4229                         context.check_layout(os);
4230                         begin_inset(os, "space ");
4231                         os << '\\' << known_coded_spaces[where - known_spaces]
4232                            << '\n';
4233                         end_inset(os);
4234                         // LaTeX swallows whitespace after all spaces except
4235                         // "\\,". We have to do that here, too, because LyX
4236                         // adds "{}" which would make the spaces significant.
4237                         if (t.cs() !=  ",")
4238                                 eat_whitespace(p, os, context, false);
4239                         // LyX adds "{}" after all spaces except "\\ " and
4240                         // "\\,", so we have to remove "{}".
4241                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
4242                         // remove the braces after "\\,", too.
4243                         if (t.cs() != " ")
4244                                 skip_braces(p);
4245                 }
4246
4247                 else if (t.cs() == "newpage" ||
4248                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
4249                          t.cs() == "clearpage" ||
4250                          t.cs() == "cleardoublepage") {
4251                         context.check_layout(os);
4252                         begin_inset(os, "Newpage ");
4253                         os << t.cs();
4254                         end_inset(os);
4255                         skip_spaces_braces(p);
4256                 }
4257
4258                 else if (t.cs() == "DeclareRobustCommand" ||
4259                          t.cs() == "DeclareRobustCommandx" ||
4260                          t.cs() == "newcommand" ||
4261                          t.cs() == "newcommandx" ||
4262                          t.cs() == "providecommand" ||
4263                          t.cs() == "providecommandx" ||
4264                          t.cs() == "renewcommand" ||
4265                          t.cs() == "renewcommandx") {
4266                         // DeclareRobustCommand, DeclareRobustCommandx,
4267                         // providecommand and providecommandx could be handled
4268                         // by parse_command(), but we need to call
4269                         // add_known_command() here.
4270                         string name = t.asInput();
4271                         if (p.next_token().asInput() == "*") {
4272                                 // Starred form. Eat '*'
4273                                 p.get_token();
4274                                 name += '*';
4275                         }
4276                         string const command = p.verbatim_item();
4277                         string const opt1 = p.getFullOpt();
4278                         string const opt2 = p.getFullOpt();
4279                         add_known_command(command, opt1, !opt2.empty());
4280                         string const ert = name + '{' + command + '}' +
4281                                            opt1 + opt2 +
4282                                            '{' + p.verbatim_item() + '}';
4283
4284                         if (t.cs() == "DeclareRobustCommand" ||
4285                             t.cs() == "DeclareRobustCommandx" ||
4286                             t.cs() == "providecommand" ||
4287                             t.cs() == "providecommandx" ||
4288                             name[name.length()-1] == '*')
4289                                 output_ert_inset(os, ert, context);
4290                         else {
4291                                 context.check_layout(os);
4292                                 begin_inset(os, "FormulaMacro");
4293                                 os << "\n" << ert;
4294                                 end_inset(os);
4295                         }
4296                 }
4297
4298                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4299                         // let could be handled by parse_command(),
4300                         // but we need to call add_known_command() here.
4301                         string ert = t.asInput();
4302                         string name;
4303                         p.skip_spaces();
4304                         if (p.next_token().cat() == catBegin) {
4305                                 name = p.verbatim_item();
4306                                 ert += '{' + name + '}';
4307                         } else {
4308                                 name = p.verbatim_item();
4309                                 ert += name;
4310                         }
4311                         string command;
4312                         p.skip_spaces();
4313                         if (p.next_token().cat() == catBegin) {
4314                                 command = p.verbatim_item();
4315                                 ert += '{' + command + '}';
4316                         } else {
4317                                 command = p.verbatim_item();
4318                                 ert += command;
4319                         }
4320                         // If command is known, make name known too, to parse
4321                         // its arguments correctly. For this reason we also
4322                         // have commands in syntax.default that are hardcoded.
4323                         CommandMap::iterator it = known_commands.find(command);
4324                         if (it != known_commands.end())
4325                                 known_commands[t.asInput()] = it->second;
4326                         output_ert_inset(os, ert, context);
4327                 }
4328
4329                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4330                         if (starred)
4331                                 p.get_token();
4332                         string name = t.asInput();
4333                         string const length = p.verbatim_item();
4334                         string unit;
4335                         string valstring;
4336                         bool valid = splitLatexLength(length, valstring, unit);
4337                         bool known_hspace = false;
4338                         bool known_vspace = false;
4339                         bool known_unit = false;
4340                         double value;
4341                         if (valid) {
4342                                 istringstream iss(valstring);
4343                                 iss >> value;
4344                                 if (value == 1.0) {
4345                                         if (t.cs()[0] == 'h') {
4346                                                 if (unit == "\\fill") {
4347                                                         if (!starred) {
4348                                                                 unit = "";
4349                                                                 name = "\\hfill";
4350                                                         }
4351                                                         known_hspace = true;
4352                                                 }
4353                                         } else {
4354                                                 if (unit == "\\smallskipamount") {
4355                                                         unit = "smallskip";
4356                                                         known_vspace = true;
4357                                                 } else if (unit == "\\medskipamount") {
4358                                                         unit = "medskip";
4359                                                         known_vspace = true;
4360                                                 } else if (unit == "\\bigskipamount") {
4361                                                         unit = "bigskip";
4362                                                         known_vspace = true;
4363                                                 } else if (unit == "\\fill") {
4364                                                         unit = "vfill";
4365                                                         known_vspace = true;
4366                                                 }
4367                                         }
4368                                 }
4369                                 if (!known_hspace && !known_vspace) {
4370                                         switch (unitFromString(unit)) {
4371                                         case Length::SP:
4372                                         case Length::PT:
4373                                         case Length::BP:
4374                                         case Length::DD:
4375                                         case Length::MM:
4376                                         case Length::PC:
4377                                         case Length::CC:
4378                                         case Length::CM:
4379                                         case Length::IN:
4380                                         case Length::EX:
4381                                         case Length::EM:
4382                                         case Length::MU:
4383                                                 known_unit = true;
4384                                                 break;
4385                                         default: {
4386                                                 //unitFromString(unit) fails for relative units like Length::PCW
4387                                                 // therefore handle them separately
4388                                                 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4389                                                         || unit == "\\textwidth" || unit == "\\linewidth"
4390                                                         || unit == "\\textheight" || unit == "\\paperheight")
4391                                                         known_unit = true;
4392                                                 break;
4393                                                          }
4394                                         }
4395                                 }
4396                         }
4397
4398                         // check for glue lengths
4399                         bool is_gluelength = false;
4400                         string gluelength = length;
4401                         string::size_type i = length.find(" minus");
4402                         if (i == string::npos) {
4403                                 i = length.find(" plus");
4404                                 if (i != string::npos)
4405                                         is_gluelength = true;
4406                         } else
4407                                 is_gluelength = true;
4408                         // if yes transform "9xx minus 8yy plus 7zz"
4409                         // to "9xx-8yy+7zz"
4410                         if (is_gluelength) {
4411                                 i = gluelength.find(" minus");
4412                                 if (i != string::npos)
4413                                         gluelength.replace(i, 7, "-");
4414                                 i = gluelength.find(" plus");
4415                                 if (i != string::npos)
4416                                         gluelength.replace(i, 6, "+");
4417                         }
4418
4419                         if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4420                                 // Literal horizontal length or known variable
4421                                 context.check_layout(os);
4422                                 begin_inset(os, "space ");
4423                                 os << name;
4424                                 if (starred)
4425                                         os << '*';
4426                                 os << '{';
4427                                 if (known_hspace)
4428                                         os << unit;
4429                                 os << "}";
4430                                 if (known_unit && !known_hspace)
4431                                         os << "\n\\length " << translate_len(length);
4432                                 if (is_gluelength)
4433                                         os << "\n\\length " << gluelength;
4434                                 end_inset(os);
4435                         } else if (known_unit || known_vspace || is_gluelength) {
4436                                 // Literal vertical length or known variable
4437                                 context.check_layout(os);
4438                                 begin_inset(os, "VSpace ");
4439                                 if (known_vspace)
4440                                         os << unit;
4441                                 if (known_unit && !known_vspace)
4442                                         os << translate_len(length);
4443                                 if (is_gluelength)
4444                                         os << gluelength;
4445                                 if (starred)
4446                                         os << '*';
4447                                 end_inset(os);
4448                         } else {
4449                                 // LyX can't handle other length variables in Inset VSpace/space
4450                                 if (starred)
4451                                         name += '*';
4452                                 if (valid) {
4453                                         if (value == 1.0)
4454                                                 output_ert_inset(os, name + '{' + unit + '}', context);
4455                                         else if (value == -1.0)
4456                                                 output_ert_inset(os, name + "{-" + unit + '}', context);
4457                                         else
4458                                                 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4459                                 } else
4460                                         output_ert_inset(os, name + '{' + length + '}', context);
4461                         }
4462                 }
4463
4464                 // The single '=' is meant here.
4465                 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4466                         if (starred)
4467                                 p.get_token();
4468                         p.skip_spaces();
4469                         context.check_layout(os);
4470                         begin_inset(os, "Flex ");
4471                         os << to_utf8(newinsetlayout->name()) << '\n'
4472                            << "status collapsed\n";
4473                         if (newinsetlayout->isPassThru()) {
4474                                 // set catcodes to verbatim early, just in case.
4475                                 p.setCatcodes(VERBATIM_CATCODES);
4476                                 string delim = p.get_token().asInput();
4477                                 if (delim != "{")
4478                                         cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4479                                 //FIXME: handle error condition
4480                                 string const arg = p.verbatimStuff("}").second;
4481                                 Context newcontext(true, context.textclass);
4482                                 if (newinsetlayout->forcePlainLayout())
4483                                         newcontext.layout = &context.textclass.plainLayout();
4484                                 output_ert(os, arg, newcontext);
4485                         } else
4486                                 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4487                         end_inset(os);
4488                 }
4489
4490                 else if (t.cs() == "includepdf") {
4491                         p.skip_spaces();
4492                         string const arg = p.getArg('[', ']');
4493                         map<string, string> opts;
4494                         vector<string> keys;
4495                         split_map(arg, opts, keys);
4496                         string name = normalize_filename(p.verbatim_item());
4497                         string const path = getMasterFilePath(true);
4498                         // We want to preserve relative / absolute filenames,
4499                         // therefore path is only used for testing
4500                         if (!makeAbsPath(name, path).exists()) {
4501                                 // The file extension is probably missing.
4502                                 // Now try to find it out.
4503                                 char const * const pdfpages_format[] = {"pdf", 0};
4504                                 string const pdftex_name =
4505                                         find_file(name, path, pdfpages_format);
4506                                 if (!pdftex_name.empty()) {
4507                                         name = pdftex_name;
4508                                         pdflatex = true;
4509                                 }
4510                         }
4511                         FileName const absname = makeAbsPath(name, path);
4512                         if (absname.exists())
4513                         {
4514                                 fix_child_filename(name);
4515                                 copy_file(absname, name);
4516                         } else
4517                                 cerr << "Warning: Could not find file '"
4518                                      << name << "'." << endl;
4519                         // write output
4520                         context.check_layout(os);
4521                         begin_inset(os, "External\n\ttemplate ");
4522                         os << "PDFPages\n\tfilename "
4523                            << name << "\n";
4524                         // parse the options
4525                         if (opts.find("pages") != opts.end())
4526                                 os << "\textra LaTeX \"pages="
4527                                    << opts["pages"] << "\"\n";
4528                         if (opts.find("angle") != opts.end())
4529                                 os << "\trotateAngle "
4530                                    << opts["angle"] << '\n';
4531                         if (opts.find("origin") != opts.end()) {
4532                                 ostringstream ss;
4533                                 string const opt = opts["origin"];
4534                                 if (opt == "tl") ss << "topleft";
4535                                 if (opt == "bl") ss << "bottomleft";
4536                                 if (opt == "Bl") ss << "baselineleft";
4537                                 if (opt == "c") ss << "center";
4538                                 if (opt == "tc") ss << "topcenter";
4539                                 if (opt == "bc") ss << "bottomcenter";
4540                                 if (opt == "Bc") ss << "baselinecenter";
4541                                 if (opt == "tr") ss << "topright";
4542                                 if (opt == "br") ss << "bottomright";
4543                                 if (opt == "Br") ss << "baselineright";
4544                                 if (!ss.str().empty())
4545                                         os << "\trotateOrigin " << ss.str() << '\n';
4546                                 else
4547                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4548                         }
4549                         if (opts.find("width") != opts.end())
4550                                 os << "\twidth "
4551                                    << translate_len(opts["width"]) << '\n';
4552                         if (opts.find("height") != opts.end())
4553                                 os << "\theight "
4554                                    << translate_len(opts["height"]) << '\n';
4555                         if (opts.find("keepaspectratio") != opts.end())
4556                                 os << "\tkeepAspectRatio\n";
4557                         end_inset(os);
4558                         context.check_layout(os);
4559                         registerExternalTemplatePackages("PDFPages");
4560                 }
4561
4562                 else if (t.cs() == "loadgame") {
4563                         p.skip_spaces();
4564                         string name = normalize_filename(p.verbatim_item());
4565                         string const path = getMasterFilePath(true);
4566                         // We want to preserve relative / absolute filenames,
4567                         // therefore path is only used for testing
4568                         if (!makeAbsPath(name, path).exists()) {
4569                                 // The file extension is probably missing.
4570                                 // Now try to find it out.
4571                                 char const * const lyxskak_format[] = {"fen", 0};
4572                                 string const lyxskak_name =
4573                                         find_file(name, path, lyxskak_format);
4574                                 if (!lyxskak_name.empty())
4575                                         name = lyxskak_name;
4576                         }
4577                         FileName const absname = makeAbsPath(name, path);
4578                         if (absname.exists())
4579                         {
4580                                 fix_child_filename(name);
4581                                 copy_file(absname, name);
4582                         } else
4583                                 cerr << "Warning: Could not find file '"
4584                                      << name << "'." << endl;
4585                         context.check_layout(os);
4586                         begin_inset(os, "External\n\ttemplate ");
4587                         os << "ChessDiagram\n\tfilename "
4588                            << name << "\n";
4589                         end_inset(os);
4590                         context.check_layout(os);
4591                         // after a \loadgame follows a \showboard
4592                         if (p.get_token().asInput() == "showboard")
4593                                 p.get_token();
4594                         registerExternalTemplatePackages("ChessDiagram");
4595                 }
4596
4597                 else {
4598                         // try to see whether the string is in unicodesymbols
4599                         // Only use text mode commands, since we are in text mode here,
4600                         // and math commands may be invalid (bug 6797)
4601                         string name = t.asInput();
4602                         // handle the dingbats and Cyrillic
4603                         if (name == "\\ding" || name == "\\textcyr")
4604                                 name = name + '{' + p.getArg('{', '}') + '}';
4605                         // handle the ifsym characters
4606                         else if (name == "\\textifsymbol") {
4607                                 string const optif = p.getFullOpt();
4608                                 string const argif = p.getArg('{', '}');
4609                                 name = name + optif + '{' + argif + '}';
4610                         }
4611                         // handle the \ascii characters
4612                         // the case of \ascii within braces, as LyX outputs it, is already
4613                         // handled for t.cat() == catBegin
4614                         else if (name == "\\ascii") {
4615                                 // the code is "\asci\xxx"
4616                                 name = "{" + name + p.get_token().asInput() + "}";
4617                                 skip_braces(p);
4618                         }
4619                         // handle some TIPA special characters
4620                         else if (preamble.isPackageUsed("tipa")) {
4621                                 if (name == "\\textglobfall") {
4622                                         name = "End";
4623                                         skip_braces(p);
4624                                 } else if (name == "\\s") {
4625                                         // fromLaTeXCommand() does not yet
4626                                         // recognize tipa short cuts
4627                                         name = "\\textsyllabic";
4628                                 } else if (name == "\\=" &&
4629                                            p.next_token().asInput() == "*") {
4630                                         // fromLaTeXCommand() does not yet
4631                                         // recognize tipa short cuts
4632                                         p.get_token();
4633                                         name = "\\b";
4634                                 } else if (name == "\\textdoublevertline") {
4635                                         // FIXME: This is not correct,
4636                                         // \textvertline is higher than \textbardbl
4637                                         name = "\\textbardbl";
4638                                         skip_braces(p);
4639                                 } else if (name == "\\!" ) {
4640                                         if (p.next_token().asInput() == "b") {
4641                                                 p.get_token();  // eat 'b'
4642                                                 name = "\\texthtb";
4643                                                 skip_braces(p);
4644                                         } else if (p.next_token().asInput() == "d") {
4645                                                 p.get_token();
4646                                                 name = "\\texthtd";
4647                                                 skip_braces(p);
4648                                         } else if (p.next_token().asInput() == "g") {
4649                                                 p.get_token();
4650                                                 name = "\\texthtg";
4651                                                 skip_braces(p);
4652                                         } else if (p.next_token().asInput() == "G") {
4653                                                 p.get_token();
4654                                                 name = "\\texthtscg";
4655                                                 skip_braces(p);
4656                                         } else if (p.next_token().asInput() == "j") {
4657                                                 p.get_token();
4658                                                 name = "\\texthtbardotlessj";
4659                                                 skip_braces(p);
4660                                         } else if (p.next_token().asInput() == "o") {
4661                                                 p.get_token();
4662                                                 name = "\\textbullseye";
4663                                                 skip_braces(p);
4664                                         }
4665                                 } else if (name == "\\*" ) {
4666                                         if (p.next_token().asInput() == "k") {
4667                                                 p.get_token();
4668                                                 name = "\\textturnk";
4669                                                 skip_braces(p);
4670                                         } else if (p.next_token().asInput() == "r") {
4671                                                 p.get_token();  // eat 'b'
4672                                                 name = "\\textturnr";
4673                                                 skip_braces(p);
4674                                         } else if (p.next_token().asInput() == "t") {
4675                                                 p.get_token();
4676                                                 name = "\\textturnt";
4677                                                 skip_braces(p);
4678                                         } else if (p.next_token().asInput() == "w") {
4679                                                 p.get_token();
4680                                                 name = "\\textturnw";
4681                                                 skip_braces(p);
4682                                         }
4683                                 }
4684                         }
4685                         if ((name.size() == 2 &&
4686                              contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4687                              p.next_token().asInput() != "*") ||
4688                             is_known(name.substr(1), known_tipa_marks)) {
4689                                 // name is a command that corresponds to a
4690                                 // combining character in unicodesymbols.
4691                                 // Append the argument, fromLaTeXCommand()
4692                                 // will either convert it to a single
4693                                 // character or a combining sequence.
4694                                 name += '{' + p.verbatim_item() + '}';
4695                         }
4696                         // now get the character from unicodesymbols
4697                         bool termination;
4698                         docstring rem;
4699                         set<string> req;
4700                         docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4701                                         Encodings::TEXT_CMD, termination, rem, &req);
4702                         if (!s.empty()) {
4703                                 context.check_layout(os);
4704                                 os << to_utf8(s);
4705                                 if (!rem.empty())
4706                                         output_ert_inset(os, to_utf8(rem), context);
4707                                 if (termination)
4708                                         skip_spaces_braces(p);
4709                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4710                                         preamble.registerAutomaticallyLoadedPackage(*it);
4711                         }
4712                         //cerr << "#: " << t << " mode: " << mode << endl;
4713                         // heuristic: read up to next non-nested space
4714                         /*
4715                         string s = t.asInput();
4716                         string z = p.verbatim_item();
4717                         while (p.good() && z != " " && !z.empty()) {
4718                                 //cerr << "read: " << z << endl;
4719                                 s += z;
4720                                 z = p.verbatim_item();
4721                         }
4722                         cerr << "found ERT: " << s << endl;
4723                         output_ert_inset(os, s + ' ', context);
4724                         */
4725                         else {
4726                                 if (t.asInput() == name &&
4727                                     p.next_token().asInput() == "*") {
4728                                         // Starred commands like \vspace*{}
4729                                         p.get_token();  // Eat '*'
4730                                         name += '*';
4731                                 }
4732                                 if (!parse_command(name, p, os, outer, context))
4733                                         output_ert_inset(os, name, context);
4734                         }
4735                 }
4736
4737                 if (flags & FLAG_LEAVE) {
4738                         flags &= ~FLAG_LEAVE;
4739                         break;
4740                 }
4741         }
4742 }
4743
4744
4745 string guessLanguage(Parser & p, string const & lang)
4746 {
4747         typedef std::map<std::string, size_t> LangMap;
4748         // map from language names to number of characters
4749         LangMap used;
4750         used[lang] = 0;
4751         for (char const * const * i = supported_CJK_languages; *i; i++)
4752                 used[string(*i)] = 0;
4753
4754         while (p.good()) {
4755                 Token const t = p.get_token();
4756                 // comments are not counted for any language
4757                 if (t.cat() == catComment)
4758                         continue;
4759                 // commands are not counted as well, but we need to detect
4760                 // \begin{CJK} and switch encoding if needed
4761                 if (t.cat() == catEscape) {
4762                         if (t.cs() == "inputencoding") {
4763                                 string const enc = subst(p.verbatim_item(), "\n", " ");
4764                                 p.setEncoding(enc, Encoding::inputenc);
4765                                 continue;
4766                         }
4767                         if (t.cs() != "begin")
4768                                 continue;
4769                 } else {
4770                         // Non-CJK content is counted for lang.
4771                         // We do not care about the real language here:
4772                         // If we have more non-CJK contents than CJK contents,
4773                         // we simply use the language that was specified as
4774                         // babel main language.
4775                         used[lang] += t.asInput().length();
4776                         continue;
4777                 }
4778                 // Now we are starting an environment
4779                 p.pushPosition();
4780                 string const name = p.getArg('{', '}');
4781                 if (name != "CJK") {
4782                         p.popPosition();
4783                         continue;
4784                 }
4785                 // It is a CJK environment
4786                 p.popPosition();
4787                 /* name = */ p.getArg('{', '}');
4788                 string const encoding = p.getArg('{', '}');
4789                 /* mapping = */ p.getArg('{', '}');
4790                 string const encoding_old = p.getEncoding();
4791                 char const * const * const where =
4792                         is_known(encoding, supported_CJK_encodings);
4793                 if (where)
4794                         p.setEncoding(encoding, Encoding::CJK);
4795                 else
4796                         p.setEncoding("UTF-8");
4797                 string const text = p.ertEnvironment("CJK");
4798                 p.setEncoding(encoding_old);
4799                 p.skip_spaces();
4800                 if (!where) {
4801                         // ignore contents in unknown CJK encoding
4802                         continue;
4803                 }
4804                 // the language of the text
4805                 string const cjk =
4806                         supported_CJK_languages[where - supported_CJK_encodings];
4807                 used[cjk] += text.length();
4808         }
4809         LangMap::const_iterator use = used.begin();
4810         for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4811                 if (it->second > use->second)
4812                         use = it;
4813         }
4814         return use->first;
4815 }
4816
4817 // }])
4818
4819
4820 } // namespace lyx