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