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