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