]> git.lyx.org Git - features.git/blob - src/tex2lyx/text.cpp
d0956c36a8d1db6fb82e74bfb6f864a871ef2d13
[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)
1122 {
1123         parent_context.check_layout(os);
1124         begin_inset(os, "listings\n");
1125         if (p.hasOpt()) {
1126                 // there can be a [] pair inside the argument for the language
1127                 string arg = p.getArg('[', ']');
1128                 if (arg.find("language={[") != string::npos) {
1129                         char start = p.next_token().character();
1130                         arg += ']';
1131                         arg += start;
1132                         arg += p.getArg(start, ']');
1133                 }
1134                 os << "lstparams " << '"' << arg << '"' << '\n';
1135         }
1136         os << "inline false\n"
1137            << "status collapsed\n";
1138         Context context(true, parent_context.textclass);
1139         context.layout = &parent_context.textclass.plainLayout();
1140         string const s = p.plainEnvironment("lstlisting");
1141         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1142                 if (*it == '\\')
1143                         os << "\n\\backslash\n";
1144                 else if (*it == '\n') {
1145                         // avoid adding an empty paragraph at the end
1146                         if (it + 1 != et) {
1147                                 context.new_paragraph(os);
1148                                 context.check_layout(os);
1149                         }
1150                 } else
1151                         os << *it;
1152         }
1153         context.check_end_layout(os);
1154         end_inset(os);
1155 }
1156
1157
1158 /// parse an unknown environment
1159 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1160                                unsigned flags, bool outer,
1161                                Context & parent_context)
1162 {
1163         if (name == "tabbing")
1164                 // We need to remember that we have to handle '\=' specially
1165                 flags |= FLAG_TABBING;
1166
1167         // We need to translate font changes and paragraphs inside the
1168         // environment to ERT if we have a non standard font.
1169         // Otherwise things like
1170         // \large\begin{foo}\huge bar\end{foo}
1171         // will not work.
1172         bool const specialfont =
1173                 (parent_context.font != parent_context.normalfont);
1174         bool const new_layout_allowed = parent_context.new_layout_allowed;
1175         if (specialfont)
1176                 parent_context.new_layout_allowed = false;
1177         handle_ert(os, "\\begin{" + name + "}", parent_context);
1178         parse_text_snippet(p, os, flags, outer, parent_context);
1179         handle_ert(os, "\\end{" + name + "}", parent_context);
1180         if (specialfont)
1181                 parent_context.new_layout_allowed = new_layout_allowed;
1182 }
1183
1184
1185 void parse_environment(Parser & p, ostream & os, bool outer,
1186                        string & last_env, bool & title_layout_found,
1187                        Context & parent_context)
1188 {
1189         Layout const * newlayout;
1190         InsetLayout const * newinsetlayout = 0;
1191         string const name = p.getArg('{', '}');
1192         const bool is_starred = suffixIs(name, '*');
1193         string const unstarred_name = rtrim(name, "*");
1194         active_environments.push_back(name);
1195
1196         if (is_math_env(name)) {
1197                 parent_context.check_layout(os);
1198                 begin_inset(os, "Formula ");
1199                 os << "\\begin{" << name << "}";
1200                 parse_math(p, os, FLAG_END, MATH_MODE);
1201                 os << "\\end{" << name << "}";
1202                 end_inset(os);
1203                 if (is_display_math_env(name)) {
1204                         // Prevent the conversion of a line break to a space
1205                         // (bug 7668). This does not change the output, but
1206                         // looks ugly in LyX.
1207                         eat_whitespace(p, os, parent_context, false);
1208                 }
1209         }
1210
1211         else if (unstarred_name == "tabular" || name == "longtable") {
1212                 eat_whitespace(p, os, parent_context, false);
1213                 string width = "0pt";
1214                 if (name == "tabular*") {
1215                         width = lyx::translate_len(p.getArg('{', '}'));
1216                         eat_whitespace(p, os, parent_context, false);
1217                 }
1218                 parent_context.check_layout(os);
1219                 begin_inset(os, "Tabular ");
1220                 handle_tabular(p, os, name, width, parent_context);
1221                 end_inset(os);
1222                 p.skip_spaces();
1223         }
1224
1225         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1226                 eat_whitespace(p, os, parent_context, false);
1227                 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1228                 eat_whitespace(p, os, parent_context, false);
1229                 parent_context.check_layout(os);
1230                 begin_inset(os, "Float " + unstarred_name + "\n");
1231                 // store the float type for subfloats
1232                 // subfloats only work with figures and tables
1233                 if (unstarred_name == "figure")
1234                         float_type = unstarred_name;
1235                 else if (unstarred_name == "table")
1236                         float_type = unstarred_name;
1237                 else
1238                         float_type = "";
1239                 if (!opt.empty())
1240                         os << "placement " << opt << '\n';
1241                 if (contains(opt, "H"))
1242                         preamble.registerAutomaticallyLoadedPackage("float");
1243                 else {
1244                         Floating const & fl = parent_context.textclass.floats()
1245                                 .getType(unstarred_name);
1246                         if (!fl.floattype().empty() && fl.usesFloatPkg())
1247                                 preamble.registerAutomaticallyLoadedPackage("float");
1248                 }
1249
1250                 os << "wide " << convert<string>(is_starred)
1251                    << "\nsideways false"
1252                    << "\nstatus open\n\n";
1253                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1254                 end_inset(os);
1255                 // We don't need really a new paragraph, but
1256                 // we must make sure that the next item gets a \begin_layout.
1257                 parent_context.new_paragraph(os);
1258                 p.skip_spaces();
1259                 // the float is parsed thus delete the type
1260                 float_type = "";
1261         }
1262
1263         else if (unstarred_name == "sidewaysfigure"
1264                 || unstarred_name == "sidewaystable") {
1265                 eat_whitespace(p, os, parent_context, false);
1266                 parent_context.check_layout(os);
1267                 if (unstarred_name == "sidewaysfigure")
1268                         begin_inset(os, "Float figure\n");
1269                 else
1270                         begin_inset(os, "Float table\n");
1271                 os << "wide " << convert<string>(is_starred)
1272                    << "\nsideways true"
1273                    << "\nstatus open\n\n";
1274                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1275                 end_inset(os);
1276                 // We don't need really a new paragraph, but
1277                 // we must make sure that the next item gets a \begin_layout.
1278                 parent_context.new_paragraph(os);
1279                 p.skip_spaces();
1280                 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1281         }
1282
1283         else if (name == "wrapfigure" || name == "wraptable") {
1284                 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1285                 eat_whitespace(p, os, parent_context, false);
1286                 parent_context.check_layout(os);
1287                 // default values
1288                 string lines = "0";
1289                 string overhang = "0col%";
1290                 // parse
1291                 if (p.hasOpt())
1292                         lines = p.getArg('[', ']');
1293                 string const placement = p.getArg('{', '}');
1294                 if (p.hasOpt())
1295                         overhang = p.getArg('[', ']');
1296                 string const width = p.getArg('{', '}');
1297                 // write
1298                 if (name == "wrapfigure")
1299                         begin_inset(os, "Wrap figure\n");
1300                 else
1301                         begin_inset(os, "Wrap table\n");
1302                 os << "lines " << lines
1303                    << "\nplacement " << placement
1304                    << "\noverhang " << lyx::translate_len(overhang)
1305                    << "\nwidth " << lyx::translate_len(width)
1306                    << "\nstatus open\n\n";
1307                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1308                 end_inset(os);
1309                 // We don't need really a new paragraph, but
1310                 // we must make sure that the next item gets a \begin_layout.
1311                 parent_context.new_paragraph(os);
1312                 p.skip_spaces();
1313                 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1314         }
1315
1316         else if (name == "minipage") {
1317                 eat_whitespace(p, os, parent_context, false);
1318                 // Test whether this is an outer box of a shaded box
1319                 p.pushPosition();
1320                 // swallow arguments
1321                 while (p.hasOpt()) {
1322                         p.getArg('[', ']');
1323                         p.skip_spaces(true);
1324                 }
1325                 p.getArg('{', '}');
1326                 p.skip_spaces(true);
1327                 Token t = p.get_token();
1328                 bool shaded = false;
1329                 if (t.asInput() == "\\begin") {
1330                         p.skip_spaces(true);
1331                         if (p.getArg('{', '}') == "shaded")
1332                                 shaded = true;
1333                 }
1334                 p.popPosition();
1335                 if (shaded)
1336                         parse_outer_box(p, os, FLAG_END, outer,
1337                                         parent_context, name, "shaded");
1338                 else
1339                         parse_box(p, os, 0, FLAG_END, outer, parent_context,
1340                                   "", "", name);
1341                 p.skip_spaces();
1342         }
1343
1344         else if (name == "comment") {
1345                 eat_whitespace(p, os, parent_context, false);
1346                 parent_context.check_layout(os);
1347                 begin_inset(os, "Note Comment\n");
1348                 os << "status open\n";
1349                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1350                 end_inset(os);
1351                 p.skip_spaces();
1352                 skip_braces(p); // eat {} that might by set by LyX behind comments
1353                 preamble.registerAutomaticallyLoadedPackage("verbatim");
1354         }
1355
1356         else if (name == "verbatim") {
1357                 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1358                 string const s = p.plainEnvironment("verbatim");
1359                 string::const_iterator it2 = s.begin();
1360                 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1361                         if (*it == '\\')
1362                                 os << "\\backslash ";
1363                         else if (*it == '\n') {
1364                                 it2 = it + 1;
1365                                 // avoid adding an empty paragraph at the end
1366                                 // FIXME: if there are 2 consecutive spaces at the end ignore it
1367                                 // because LyX will re-add a \n
1368                                 // This hack must be removed once bug 8049 is fixed!
1369                                 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1370                                         os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1371                         } else 
1372                                 os << *it;
1373                 }
1374                 os << "\n\\end_layout\n\n";
1375                 p.skip_spaces();
1376                 // reset to Standard layout
1377                 os << "\n\\begin_layout Standard\n";
1378         }
1379
1380         else if (name == "lyxgreyedout") {
1381                 eat_whitespace(p, os, parent_context, false);
1382                 parent_context.check_layout(os);
1383                 begin_inset(os, "Note Greyedout\n");
1384                 os << "status open\n";
1385                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1386                 end_inset(os);
1387                 p.skip_spaces();
1388                 if (!preamble.notefontcolor().empty())
1389                         preamble.registerAutomaticallyLoadedPackage("color");
1390         }
1391
1392         else if (name == "framed" || name == "shaded") {
1393                 eat_whitespace(p, os, parent_context, false);
1394                 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1395                 p.skip_spaces();
1396         }
1397
1398         else if (name == "lstlisting") {
1399                 eat_whitespace(p, os, parent_context, false);
1400                 // FIXME handle listings with parameters
1401                 //       If this is added, don't forgot to handle the
1402                 //       automatic color package loading
1403                 parse_listings(p, os, parent_context);
1404                 p.skip_spaces();
1405         }
1406
1407         else if (!parent_context.new_layout_allowed)
1408                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1409                                           parent_context);
1410
1411         // Alignment and spacing settings
1412         // FIXME (bug xxxx): These settings can span multiple paragraphs and
1413         //                                       therefore are totally broken!
1414         // Note that \centering, raggedright, and raggedleft cannot be handled, as
1415         // they are commands not environments. They are furthermore switches that
1416         // can be ended by another switches, but also by commands like \footnote or
1417         // \parbox. So the only safe way is to leave them untouched.
1418         else if (name == "center" || name == "centering" ||
1419                  name == "flushleft" || name == "flushright" ||
1420                  name == "singlespace" || name == "onehalfspace" ||
1421                  name == "doublespace" || name == "spacing") {
1422                 eat_whitespace(p, os, parent_context, false);
1423                 // We must begin a new paragraph if not already done
1424                 if (! parent_context.atParagraphStart()) {
1425                         parent_context.check_end_layout(os);
1426                         parent_context.new_paragraph(os);
1427                 }
1428                 if (name == "flushleft")
1429                         parent_context.add_extra_stuff("\\align left\n");
1430                 else if (name == "flushright")
1431                         parent_context.add_extra_stuff("\\align right\n");
1432                 else if (name == "center" || name == "centering")
1433                         parent_context.add_extra_stuff("\\align center\n");
1434                 else if (name == "singlespace")
1435                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1436                 else if (name == "onehalfspace") {
1437                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1438                         preamble.registerAutomaticallyLoadedPackage("setspace");
1439                 } else if (name == "doublespace") {
1440                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1441                         preamble.registerAutomaticallyLoadedPackage("setspace");
1442                 } else if (name == "spacing") {
1443                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1444                         preamble.registerAutomaticallyLoadedPackage("setspace");
1445                 }
1446                 parse_text(p, os, FLAG_END, outer, parent_context);
1447                 // Just in case the environment is empty
1448                 parent_context.extra_stuff.erase();
1449                 // We must begin a new paragraph to reset the alignment
1450                 parent_context.new_paragraph(os);
1451                 p.skip_spaces();
1452         }
1453
1454         // The single '=' is meant here.
1455         else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1456                 eat_whitespace(p, os, parent_context, false);
1457                 Context context(true, parent_context.textclass, newlayout,
1458                                 parent_context.layout, parent_context.font);
1459                 if (parent_context.deeper_paragraph) {
1460                         // We are beginning a nested environment after a
1461                         // deeper paragraph inside the outer list environment.
1462                         // Therefore we don't need to output a "begin deeper".
1463                         context.need_end_deeper = true;
1464                 }
1465                 parent_context.check_end_layout(os);
1466                 if (last_env == name) {
1467                         // we need to output a separator since LyX would export
1468                         // the two environments as one otherwise (bug 5716)
1469                         docstring const sep = from_ascii("--Separator--");
1470                         TeX2LyXDocClass const & textclass(parent_context.textclass);
1471                         if (textclass.hasLayout(sep)) {
1472                                 Context newcontext(parent_context);
1473                                 newcontext.layout = &(textclass[sep]);
1474                                 newcontext.check_layout(os);
1475                                 newcontext.check_end_layout(os);
1476                         } else {
1477                                 parent_context.check_layout(os);
1478                                 begin_inset(os, "Note Note\n");
1479                                 os << "status closed\n";
1480                                 Context newcontext(true, textclass,
1481                                                 &(textclass.defaultLayout()));
1482                                 newcontext.check_layout(os);
1483                                 newcontext.check_end_layout(os);
1484                                 end_inset(os);
1485                                 parent_context.check_end_layout(os);
1486                         }
1487                 }
1488                 switch (context.layout->latextype) {
1489                 case  LATEX_LIST_ENVIRONMENT:
1490                         context.add_par_extra_stuff("\\labelwidthstring "
1491                                                     + p.verbatim_item() + '\n');
1492                         p.skip_spaces();
1493                         break;
1494                 case  LATEX_BIB_ENVIRONMENT:
1495                         p.verbatim_item(); // swallow next arg
1496                         p.skip_spaces();
1497                         break;
1498                 default:
1499                         break;
1500                 }
1501                 context.check_deeper(os);
1502                 // handle known optional and required arguments
1503                 // layouts require all optional arguments before the required ones
1504                 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1505                 // It is impossible to place anything after the environment name,
1506                 // but before the first \\item.
1507                 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1508                         bool need_layout = true;
1509                         unsigned int optargs = 0;
1510                         while (optargs < context.layout->optargs) {
1511                                 eat_whitespace(p, os, context, false);
1512                                 if (p.next_token().cat() == catEscape ||
1513                                     p.next_token().character() != '[')
1514                                         break;
1515                                 p.get_token(); // eat '['
1516                                 if (need_layout) {
1517                                         context.check_layout(os);
1518                                         need_layout = false;
1519                                 }
1520                                 begin_inset(os, "Argument\n");
1521                                 os << "status collapsed\n\n";
1522                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1523                                 end_inset(os);
1524                                 eat_whitespace(p, os, context, false);
1525                                 ++optargs;
1526                         }
1527                         unsigned int reqargs = 0;
1528                         while (reqargs < context.layout->reqargs) {
1529                                 eat_whitespace(p, os, context, false);
1530                                 if (p.next_token().cat() != catBegin)
1531                                         break;
1532                                 p.get_token(); // eat '{'
1533                                 if (need_layout) {
1534                                         context.check_layout(os);
1535                                         need_layout = false;
1536                                 }
1537                                 begin_inset(os, "Argument\n");
1538                                 os << "status collapsed\n\n";
1539                                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1540                                 end_inset(os);
1541                                 eat_whitespace(p, os, context, false);
1542                                 ++reqargs;
1543                         }
1544                 }
1545                 parse_text(p, os, FLAG_END, outer, context);
1546                 context.check_end_layout(os);
1547                 if (parent_context.deeper_paragraph) {
1548                         // We must suppress the "end deeper" because we
1549                         // suppressed the "begin deeper" above.
1550                         context.need_end_deeper = false;
1551                 }
1552                 context.check_end_deeper(os);
1553                 parent_context.new_paragraph(os);
1554                 p.skip_spaces();
1555                 if (!title_layout_found)
1556                         title_layout_found = newlayout->intitle;
1557                 set<string> const & req = newlayout->requires();
1558                 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
1559                         preamble.registerAutomaticallyLoadedPackage(*it);
1560         }
1561
1562         // The single '=' is meant here.
1563         else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1564                 eat_whitespace(p, os, parent_context, false);
1565                 parent_context.check_layout(os);
1566                 begin_inset(os, "Flex ");
1567                 os << to_utf8(newinsetlayout->name()) << '\n'
1568                    << "status collapsed\n";
1569                 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1570                 end_inset(os);
1571         }
1572
1573         else if (name == "appendix") {
1574                 // This is no good latex style, but it works and is used in some documents...
1575                 eat_whitespace(p, os, parent_context, false);
1576                 parent_context.check_end_layout(os);
1577                 Context context(true, parent_context.textclass, parent_context.layout,
1578                                 parent_context.layout, parent_context.font);
1579                 context.check_layout(os);
1580                 os << "\\start_of_appendix\n";
1581                 parse_text(p, os, FLAG_END, outer, context);
1582                 context.check_end_layout(os);
1583                 p.skip_spaces();
1584         }
1585
1586         else if (known_environments.find(name) != known_environments.end()) {
1587                 vector<ArgumentType> arguments = known_environments[name];
1588                 // The last "argument" denotes wether we may translate the
1589                 // environment contents to LyX
1590                 // The default required if no argument is given makes us
1591                 // compatible with the reLyXre environment.
1592                 ArgumentType contents = arguments.empty() ?
1593                         required :
1594                         arguments.back();
1595                 if (!arguments.empty())
1596                         arguments.pop_back();
1597                 // See comment in parse_unknown_environment()
1598                 bool const specialfont =
1599                         (parent_context.font != parent_context.normalfont);
1600                 bool const new_layout_allowed =
1601                         parent_context.new_layout_allowed;
1602                 if (specialfont)
1603                         parent_context.new_layout_allowed = false;
1604                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1605                                 outer, parent_context);
1606                 if (contents == verbatim)
1607                         handle_ert(os, p.verbatimEnvironment(name),
1608                                    parent_context);
1609                 else
1610                         parse_text_snippet(p, os, FLAG_END, outer,
1611                                            parent_context);
1612                 handle_ert(os, "\\end{" + name + "}", parent_context);
1613                 if (specialfont)
1614                         parent_context.new_layout_allowed = new_layout_allowed;
1615         }
1616
1617         else
1618                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1619                                           parent_context);
1620
1621         last_env = name;
1622         active_environments.pop_back();
1623 }
1624
1625
1626 /// parses a comment and outputs it to \p os.
1627 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1628 {
1629         LASSERT(t.cat() == catComment, return);
1630         if (!t.cs().empty()) {
1631                 context.check_layout(os);
1632                 handle_comment(os, '%' + t.cs(), context);
1633                 if (p.next_token().cat() == catNewline) {
1634                         // A newline after a comment line starts a new
1635                         // paragraph
1636                         if (context.new_layout_allowed) {
1637                                 if(!context.atParagraphStart())
1638                                         // Only start a new paragraph if not already
1639                                         // done (we might get called recursively)
1640                                         context.new_paragraph(os);
1641                         } else
1642                                 handle_ert(os, "\n", context);
1643                         eat_whitespace(p, os, context, true);
1644                 }
1645         } else {
1646                 // "%\n" combination
1647                 p.skip_spaces();
1648         }
1649 }
1650
1651
1652 /*!
1653  * Reads spaces and comments until the first non-space, non-comment token.
1654  * New paragraphs (double newlines or \\par) are handled like simple spaces
1655  * if \p eatParagraph is true.
1656  * Spaces are skipped, but comments are written to \p os.
1657  */
1658 void eat_whitespace(Parser & p, ostream & os, Context & context,
1659                     bool eatParagraph)
1660 {
1661         while (p.good()) {
1662                 Token const & t = p.get_token();
1663                 if (t.cat() == catComment)
1664                         parse_comment(p, os, t, context);
1665                 else if ((! eatParagraph && p.isParagraph()) ||
1666                          (t.cat() != catSpace && t.cat() != catNewline)) {
1667                         p.putback();
1668                         return;
1669                 }
1670         }
1671 }
1672
1673
1674 /*!
1675  * Set a font attribute, parse text and reset the font attribute.
1676  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1677  * \param currentvalue Current value of the attribute. Is set to the new
1678  * value during parsing.
1679  * \param newvalue New value of the attribute
1680  */
1681 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1682                            Context & context, string const & attribute,
1683                            string & currentvalue, string const & newvalue)
1684 {
1685         context.check_layout(os);
1686         string const oldvalue = currentvalue;
1687         currentvalue = newvalue;
1688         os << '\n' << attribute << ' ' << newvalue << "\n";
1689         parse_text_snippet(p, os, flags, outer, context);
1690         context.check_layout(os);
1691         os << '\n' << attribute << ' ' << oldvalue << "\n";
1692         currentvalue = oldvalue;
1693 }
1694
1695
1696 /// get the arguments of a natbib or jurabib citation command
1697 void get_cite_arguments(Parser & p, bool natbibOrder,
1698         string & before, string & after)
1699 {
1700         // We need to distinguish "" and "[]", so we can't use p.getOpt().
1701
1702         // text before the citation
1703         before.clear();
1704         // text after the citation
1705         after = p.getFullOpt();
1706
1707         if (!after.empty()) {
1708                 before = p.getFullOpt();
1709                 if (natbibOrder && !before.empty())
1710                         swap(before, after);
1711         }
1712 }
1713
1714
1715 /// Convert filenames with TeX macros and/or quotes to something LyX
1716 /// can understand
1717 string const normalize_filename(string const & name)
1718 {
1719         Parser p(trim(name, "\""));
1720         ostringstream os;
1721         while (p.good()) {
1722                 Token const & t = p.get_token();
1723                 if (t.cat() != catEscape)
1724                         os << t.asInput();
1725                 else if (t.cs() == "lyxdot") {
1726                         // This is used by LyX for simple dots in relative
1727                         // names
1728                         os << '.';
1729                         p.skip_spaces();
1730                 } else if (t.cs() == "space") {
1731                         os << ' ';
1732                         p.skip_spaces();
1733                 } else
1734                         os << t.asInput();
1735         }
1736         return os.str();
1737 }
1738
1739
1740 /// Convert \p name from TeX convention (relative to master file) to LyX
1741 /// convention (relative to .lyx file) if it is relative
1742 void fix_relative_filename(string & name)
1743 {
1744         if (FileName::isAbsolute(name))
1745                 return;
1746
1747         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1748                                    from_utf8(getParentFilePath())));
1749 }
1750
1751
1752 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1753 void parse_noweb(Parser & p, ostream & os, Context & context)
1754 {
1755         // assemble the rest of the keyword
1756         string name("<<");
1757         bool scrap = false;
1758         while (p.good()) {
1759                 Token const & t = p.get_token();
1760                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1761                         name += ">>";
1762                         p.get_token();
1763                         scrap = (p.good() && p.next_token().asInput() == "=");
1764                         if (scrap)
1765                                 name += p.get_token().asInput();
1766                         break;
1767                 }
1768                 name += t.asInput();
1769         }
1770
1771         if (!scrap || !context.new_layout_allowed ||
1772             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1773                 cerr << "Warning: Could not interpret '" << name
1774                      << "'. Ignoring it." << endl;
1775                 return;
1776         }
1777
1778         // We use new_paragraph instead of check_end_layout because the stuff
1779         // following the noweb chunk needs to start with a \begin_layout.
1780         // This may create a new paragraph even if there was none in the
1781         // noweb file, but the alternative is an invalid LyX file. Since
1782         // noweb code chunks are implemented with a layout style in LyX they
1783         // always must be in an own paragraph.
1784         context.new_paragraph(os);
1785         Context newcontext(true, context.textclass,
1786                 &context.textclass[from_ascii("Scrap")]);
1787         newcontext.check_layout(os);
1788         os << name;
1789         while (p.good()) {
1790                 Token const & t = p.get_token();
1791                 // We abuse the parser a bit, because this is no TeX syntax
1792                 // at all.
1793                 if (t.cat() == catEscape)
1794                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1795                 else {
1796                         ostringstream oss;
1797                         Context tmp(false, context.textclass,
1798                                     &context.textclass[from_ascii("Scrap")]);
1799                         tmp.need_end_layout = true;
1800                         tmp.check_layout(oss);
1801                         os << subst(t.asInput(), "\n", oss.str());
1802                 }
1803                 // The scrap chunk is ended by an @ at the beginning of a line.
1804                 // After the @ the line may contain a comment and/or
1805                 // whitespace, but nothing else.
1806                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1807                     (p.next_token().cat() == catSpace ||
1808                      p.next_token().cat() == catNewline ||
1809                      p.next_token().cat() == catComment)) {
1810                         while (p.good() && p.next_token().cat() == catSpace)
1811                                 os << p.get_token().asInput();
1812                         if (p.next_token().cat() == catComment)
1813                                 // The comment includes a final '\n'
1814                                 os << p.get_token().asInput();
1815                         else {
1816                                 if (p.next_token().cat() == catNewline)
1817                                         p.get_token();
1818                                 os << '\n';
1819                         }
1820                         break;
1821                 }
1822         }
1823         newcontext.check_end_layout(os);
1824 }
1825
1826
1827 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1828 bool is_macro(Parser & p)
1829 {
1830         Token first = p.curr_token();
1831         if (first.cat() != catEscape || !p.good())
1832                 return false;
1833         if (first.cs() == "def")
1834                 return true;
1835         if (first.cs() != "global" && first.cs() != "long")
1836                 return false;
1837         Token second = p.get_token();
1838         int pos = 1;
1839         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1840                second.cat() == catNewline || second.cat() == catComment)) {
1841                 second = p.get_token();
1842                 pos++;
1843         }
1844         bool secondvalid = second.cat() == catEscape;
1845         Token third;
1846         bool thirdvalid = false;
1847         if (p.good() && first.cs() == "global" && secondvalid &&
1848             second.cs() == "long") {
1849                 third = p.get_token();
1850                 pos++;
1851                 while (p.good() && !p.isParagraph() &&
1852                        (third.cat() == catSpace ||
1853                         third.cat() == catNewline ||
1854                         third.cat() == catComment)) {
1855                         third = p.get_token();
1856                         pos++;
1857                 }
1858                 thirdvalid = third.cat() == catEscape;
1859         }
1860         for (int i = 0; i < pos; ++i)
1861                 p.putback();
1862         if (!secondvalid)
1863                 return false;
1864         if (!thirdvalid)
1865                 return (first.cs() == "global" || first.cs() == "long") &&
1866                        second.cs() == "def";
1867         return first.cs() == "global" && second.cs() == "long" &&
1868                third.cs() == "def";
1869 }
1870
1871
1872 /// Parse a macro definition (assumes that is_macro() returned true)
1873 void parse_macro(Parser & p, ostream & os, Context & context)
1874 {
1875         context.check_layout(os);
1876         Token first = p.curr_token();
1877         Token second;
1878         Token third;
1879         string command = first.asInput();
1880         if (first.cs() != "def") {
1881                 p.get_token();
1882                 eat_whitespace(p, os, context, false);
1883                 second = p.curr_token();
1884                 command += second.asInput();
1885                 if (second.cs() != "def") {
1886                         p.get_token();
1887                         eat_whitespace(p, os, context, false);
1888                         third = p.curr_token();
1889                         command += third.asInput();
1890                 }
1891         }
1892         eat_whitespace(p, os, context, false);
1893         string const name = p.get_token().cs();
1894         eat_whitespace(p, os, context, false);
1895
1896         // parameter text
1897         bool simple = true;
1898         string paramtext;
1899         int arity = 0;
1900         while (p.next_token().cat() != catBegin) {
1901                 if (p.next_token().cat() == catParameter) {
1902                         // # found
1903                         p.get_token();
1904                         paramtext += "#";
1905
1906                         // followed by number?
1907                         if (p.next_token().cat() == catOther) {
1908                                 char c = p.getChar();
1909                                 paramtext += c;
1910                                 // number = current arity + 1?
1911                                 if (c == arity + '0' + 1)
1912                                         ++arity;
1913                                 else
1914                                         simple = false;
1915                         } else
1916                                 paramtext += p.get_token().cs();
1917                 } else {
1918                         paramtext += p.get_token().cs();
1919                         simple = false;
1920                 }
1921         }
1922
1923         // only output simple (i.e. compatible) macro as FormulaMacros
1924         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1925         if (simple) {
1926                 context.check_layout(os);
1927                 begin_inset(os, "FormulaMacro");
1928                 os << "\n\\def" << ert;
1929                 end_inset(os);
1930         } else
1931                 handle_ert(os, command + ert, context);
1932 }
1933
1934
1935 void registerExternalTemplatePackages(string const & name)
1936 {
1937         external::TemplateManager const & etm = external::TemplateManager::get();
1938         external::Template const * const et = etm.getTemplateByName(name);
1939         if (!et)
1940                 return;
1941         external::Template::Formats::const_iterator cit = et->formats.end();
1942         if (pdflatex)
1943                 cit = et->formats.find("PDFLaTeX");
1944         if (cit == et->formats.end())
1945                 // If the template has not specified a PDFLaTeX output,
1946                 // we try the LaTeX format.
1947                 cit = et->formats.find("LaTeX");
1948         if (cit == et->formats.end())
1949                 return;
1950         vector<string>::const_iterator qit = cit->second.requirements.begin();
1951         vector<string>::const_iterator qend = cit->second.requirements.end();
1952         for (; qit != qend; ++qit)
1953                 preamble.registerAutomaticallyLoadedPackage(*qit);
1954 }
1955
1956 } // anonymous namespace
1957
1958
1959 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1960                 Context & context)
1961 {
1962         Layout const * newlayout = 0;
1963         InsetLayout const * newinsetlayout = 0;
1964         char const * const * where = 0;
1965         // Store the latest bibliographystyle and nocite{*} option
1966         // (needed for bibtex inset)
1967         string btprint;
1968         string bibliographystyle = "default";
1969         bool const use_natbib = preamble.isPackageUsed("natbib");
1970         bool const use_jurabib = preamble.isPackageUsed("jurabib");
1971         string last_env;
1972         bool title_layout_found = false;
1973         while (p.good()) {
1974                 Token const & t = p.get_token();
1975
1976 #ifdef FILEDEBUG
1977                 debugToken(cerr, t, flags);
1978 #endif
1979
1980                 if (flags & FLAG_ITEM) {
1981                         if (t.cat() == catSpace)
1982                                 continue;
1983
1984                         flags &= ~FLAG_ITEM;
1985                         if (t.cat() == catBegin) {
1986                                 // skip the brace and collect everything to the next matching
1987                                 // closing brace
1988                                 flags |= FLAG_BRACE_LAST;
1989                                 continue;
1990                         }
1991
1992                         // handle only this single token, leave the loop if done
1993                         flags |= FLAG_LEAVE;
1994                 }
1995
1996                 if (t.cat() != catEscape && t.character() == ']' &&
1997                     (flags & FLAG_BRACK_LAST))
1998                         return;
1999                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2000                         return;
2001
2002                 // If there is anything between \end{env} and \begin{env} we
2003                 // don't need to output a separator.
2004                 if (t.cat() != catSpace && t.cat() != catNewline &&
2005                     t.asInput() != "\\begin")
2006                         last_env = "";
2007
2008                 //
2009                 // cat codes
2010                 //
2011                 if (t.cat() == catMath) {
2012                         // we are inside some text mode thingy, so opening new math is allowed
2013                         context.check_layout(os);
2014                         begin_inset(os, "Formula ");
2015                         Token const & n = p.get_token();
2016                         bool const display(n.cat() == catMath && outer);
2017                         if (display) {
2018                                 // TeX's $$...$$ syntax for displayed math
2019                                 os << "\\[";
2020                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2021                                 os << "\\]";
2022                                 p.get_token(); // skip the second '$' token
2023                         } else {
2024                                 // simple $...$  stuff
2025                                 p.putback();
2026                                 os << '$';
2027                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2028                                 os << '$';
2029                         }
2030                         end_inset(os);
2031                         if (display) {
2032                                 // Prevent the conversion of a line break to a
2033                                 // space (bug 7668). This does not change the
2034                                 // output, but looks ugly in LyX.
2035                                 eat_whitespace(p, os, context, false);
2036                         }
2037                 }
2038
2039                 else if (t.cat() == catSuper || t.cat() == catSub)
2040                         cerr << "catcode " << t << " illegal in text mode\n";
2041
2042                 // Basic support for english quotes. This should be
2043                 // extended to other quotes, but is not so easy (a
2044                 // left english quote is the same as a right german
2045                 // quote...)
2046                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2047                         context.check_layout(os);
2048                         begin_inset(os, "Quotes ");
2049                         os << "eld";
2050                         end_inset(os);
2051                         p.get_token();
2052                         skip_braces(p);
2053                 }
2054                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2055                         context.check_layout(os);
2056                         begin_inset(os, "Quotes ");
2057                         os << "erd";
2058                         end_inset(os);
2059                         p.get_token();
2060                         skip_braces(p);
2061                 }
2062
2063                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2064                         context.check_layout(os);
2065                         begin_inset(os, "Quotes ");
2066                         os << "ald";
2067                         end_inset(os);
2068                         p.get_token();
2069                         skip_braces(p);
2070                 }
2071
2072                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2073                         context.check_layout(os);
2074                         begin_inset(os, "Quotes ");
2075                         os << "ard";
2076                         end_inset(os);
2077                         p.get_token();
2078                         skip_braces(p);
2079                 }
2080
2081                 else if (t.asInput() == "<"
2082                          && p.next_token().asInput() == "<" && noweb_mode) {
2083                         p.get_token();
2084                         parse_noweb(p, os, context);
2085                 }
2086
2087                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2088                         check_space(p, os, context);
2089
2090                 else if (t.character() == '[' && noweb_mode &&
2091                          p.next_token().character() == '[') {
2092                         // These can contain underscores
2093                         p.putback();
2094                         string const s = p.getFullOpt() + ']';
2095                         if (p.next_token().character() == ']')
2096                                 p.get_token();
2097                         else
2098                                 cerr << "Warning: Inserting missing ']' in '"
2099                                      << s << "'." << endl;
2100                         handle_ert(os, s, context);
2101                 }
2102
2103                 else if (t.cat() == catLetter) {
2104                         context.check_layout(os);
2105                         // Workaround for bug 4752.
2106                         // FIXME: This whole code block needs to be removed
2107                         //        when the bug is fixed and tex2lyx produces
2108                         //        the updated file format.
2109                         // The replacement algorithm in LyX is so stupid that
2110                         // it even translates a phrase if it is part of a word.
2111                         bool handled = false;
2112                         for (int const * l = known_phrase_lengths; *l; ++l) {
2113                                 string phrase = t.cs();
2114                                 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2115                                         phrase += p.get_token().cs();
2116                                 if (is_known(phrase, known_coded_phrases)) {
2117                                         handle_ert(os, phrase, context);
2118                                         handled = true;
2119                                         break;
2120                                 } else {
2121                                         for (size_t i = 1; i < phrase.length(); ++i)
2122                                                 p.putback();
2123                                 }
2124                         }
2125                         if (!handled)
2126                                 os << t.cs();
2127                 }
2128
2129                 else if (t.cat() == catOther ||
2130                                t.cat() == catAlign ||
2131                                t.cat() == catParameter) {
2132                         // This translates "&" to "\\&" which may be wrong...
2133                         context.check_layout(os);
2134                         os << t.cs();
2135                 }
2136
2137                 else if (p.isParagraph()) {
2138                         if (context.new_layout_allowed)
2139                                 context.new_paragraph(os);
2140                         else
2141                                 handle_ert(os, "\\par ", context);
2142                         eat_whitespace(p, os, context, true);
2143                 }
2144
2145                 else if (t.cat() == catActive) {
2146                         context.check_layout(os);
2147                         if (t.character() == '~') {
2148                                 if (context.layout->free_spacing)
2149                                         os << ' ';
2150                                 else {
2151                                         begin_inset(os, "space ~\n");
2152                                         end_inset(os);
2153                                 }
2154                         } else
2155                                 os << t.cs();
2156                 }
2157
2158                 else if (t.cat() == catBegin) {
2159                         Token const next = p.next_token();
2160                         Token const end = p.next_next_token();
2161                         if (next.cat() == catEnd) {
2162                         // {}
2163                         Token const prev = p.prev_token();
2164                         p.get_token();
2165                         if (p.next_token().character() == '`' ||
2166                             (prev.character() == '-' &&
2167                              p.next_token().character() == '-'))
2168                                 ; // ignore it in {}`` or -{}-
2169                         else
2170                                 handle_ert(os, "{}", context);
2171                         } else if (next.cat() == catEscape &&
2172                                    is_known(next.cs(), known_quotes) &&
2173                                    end.cat() == catEnd) {
2174                                 // Something like {\textquoteright} (e.g.
2175                                 // from writer2latex). LyX writes
2176                                 // \textquoteright{}, so we may skip the
2177                                 // braces here for better readability.
2178                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2179                                                    outer, context);
2180                         } else {
2181                         context.check_layout(os);
2182                         // special handling of font attribute changes
2183                         Token const prev = p.prev_token();
2184                         TeXFont const oldFont = context.font;
2185                         if (next.character() == '[' ||
2186                             next.character() == ']' ||
2187                             next.character() == '*') {
2188                                 p.get_token();
2189                                 if (p.next_token().cat() == catEnd) {
2190                                         os << next.cs();
2191                                         p.get_token();
2192                                 } else {
2193                                         p.putback();
2194                                         handle_ert(os, "{", context);
2195                                         parse_text_snippet(p, os,
2196                                                         FLAG_BRACE_LAST,
2197                                                         outer, context);
2198                                         handle_ert(os, "}", context);
2199                                 }
2200                         } else if (! context.new_layout_allowed) {
2201                                 handle_ert(os, "{", context);
2202                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2203                                                    outer, context);
2204                                 handle_ert(os, "}", context);
2205                         } else if (is_known(next.cs(), known_sizes)) {
2206                                 // next will change the size, so we must
2207                                 // reset it here
2208                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2209                                                    outer, context);
2210                                 if (!context.atParagraphStart())
2211                                         os << "\n\\size "
2212                                            << context.font.size << "\n";
2213                         } else if (is_known(next.cs(), known_font_families)) {
2214                                 // next will change the font family, so we
2215                                 // must reset it here
2216                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2217                                                    outer, context);
2218                                 if (!context.atParagraphStart())
2219                                         os << "\n\\family "
2220                                            << context.font.family << "\n";
2221                         } else if (is_known(next.cs(), known_font_series)) {
2222                                 // next will change the font series, so we
2223                                 // must reset it here
2224                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2225                                                    outer, context);
2226                                 if (!context.atParagraphStart())
2227                                         os << "\n\\series "
2228                                            << context.font.series << "\n";
2229                         } else if (is_known(next.cs(), known_font_shapes)) {
2230                                 // next will change the font shape, so we
2231                                 // must reset it here
2232                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2233                                                    outer, context);
2234                                 if (!context.atParagraphStart())
2235                                         os << "\n\\shape "
2236                                            << context.font.shape << "\n";
2237                         } else if (is_known(next.cs(), known_old_font_families) ||
2238                                    is_known(next.cs(), known_old_font_series) ||
2239                                    is_known(next.cs(), known_old_font_shapes)) {
2240                                 // next will change the font family, series
2241                                 // and shape, so we must reset it here
2242                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2243                                                    outer, context);
2244                                 if (!context.atParagraphStart())
2245                                         os <<  "\n\\family "
2246                                            << context.font.family
2247                                            << "\n\\series "
2248                                            << context.font.series
2249                                            << "\n\\shape "
2250                                            << context.font.shape << "\n";
2251                         } else {
2252                                 handle_ert(os, "{", context);
2253                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2254                                                    outer, context);
2255                                 handle_ert(os, "}", context);
2256                                 }
2257                         }
2258                 }
2259
2260                 else if (t.cat() == catEnd) {
2261                         if (flags & FLAG_BRACE_LAST) {
2262                                 return;
2263                         }
2264                         cerr << "stray '}' in text\n";
2265                         handle_ert(os, "}", context);
2266                 }
2267
2268                 else if (t.cat() == catComment)
2269                         parse_comment(p, os, t, context);
2270
2271                 //
2272                 // control sequences
2273                 //
2274
2275                 else if (t.cs() == "(") {
2276                         context.check_layout(os);
2277                         begin_inset(os, "Formula");
2278                         os << " \\(";
2279                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2280                         os << "\\)";
2281                         end_inset(os);
2282                 }
2283
2284                 else if (t.cs() == "[") {
2285                         context.check_layout(os);
2286                         begin_inset(os, "Formula");
2287                         os << " \\[";
2288                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2289                         os << "\\]";
2290                         end_inset(os);
2291                         // Prevent the conversion of a line break to a space
2292                         // (bug 7668). This does not change the output, but
2293                         // looks ugly in LyX.
2294                         eat_whitespace(p, os, context, false);
2295                 }
2296
2297                 else if (t.cs() == "begin")
2298                         parse_environment(p, os, outer, last_env,
2299                                           title_layout_found, context);
2300
2301                 else if (t.cs() == "end") {
2302                         if (flags & FLAG_END) {
2303                                 // eat environment name
2304                                 string const name = p.getArg('{', '}');
2305                                 if (name != active_environment())
2306                                         cerr << "\\end{" + name + "} does not match \\begin{"
2307                                                 + active_environment() + "}\n";
2308                                 return;
2309                         }
2310                         p.error("found 'end' unexpectedly");
2311                 }
2312
2313                 else if (t.cs() == "item") {
2314                         string s;
2315                         bool const optarg = p.hasOpt();
2316                         if (optarg) {
2317                                 // FIXME: This swallows comments, but we cannot use
2318                                 //        eat_whitespace() since we must not output
2319                                 //        anything before the item.
2320                                 p.skip_spaces(true);
2321                                 s = p.verbatimOption();
2322                         } else
2323                                 p.skip_spaces(false);
2324                         context.set_item();
2325                         context.check_layout(os);
2326                         if (context.has_item) {
2327                                 // An item in an unknown list-like environment
2328                                 // FIXME: Do this in check_layout()!
2329                                 context.has_item = false;
2330                                 if (optarg)
2331                                         handle_ert(os, "\\item", context);
2332                                 else
2333                                         handle_ert(os, "\\item ", context);
2334                         }
2335                         if (optarg) {
2336                                 if (context.layout->labeltype != LABEL_MANUAL) {
2337                                         // LyX does not support \item[\mybullet]
2338                                         // in itemize environments
2339                                         Parser p2(s + ']');
2340                                         os << parse_text_snippet(p2,
2341                                                 FLAG_BRACK_LAST, outer, context);
2342                                 } else if (!s.empty()) {
2343                                         // LyX adds braces around the argument,
2344                                         // so we need to remove them here.
2345                                         if (s.size() > 2 && s[0] == '{' &&
2346                                             s[s.size()-1] == '}')
2347                                                 s = s.substr(1, s.size()-2);
2348                                         // If the argument contains a space we
2349                                         // must put it into ERT: Otherwise LyX
2350                                         // would misinterpret the space as
2351                                         // item delimiter (bug 7663)
2352                                         if (contains(s, ' ')) {
2353                                                 handle_ert(os, s, context);
2354                                         } else {
2355                                                 Parser p2(s + ']');
2356                                                 os << parse_text_snippet(p2,
2357                                                         FLAG_BRACK_LAST,
2358                                                         outer, context);
2359                                         }
2360                                         // The space is needed to separate the
2361                                         // item from the rest of the sentence.
2362                                         os << ' ';
2363                                         eat_whitespace(p, os, context, false);
2364                                 }
2365                         }
2366                 }
2367
2368                 else if (t.cs() == "bibitem") {
2369                         context.set_item();
2370                         context.check_layout(os);
2371                         eat_whitespace(p, os, context, false);
2372                         string label = convert_command_inset_arg(p.verbatimOption());
2373                         string key = convert_command_inset_arg(p.verbatim_item());
2374                         if (contains(label, '\\') || contains(key, '\\')) {
2375                                 // LyX can't handle LaTeX commands in labels or keys
2376                                 handle_ert(os, t.asInput() + '[' + label +
2377                                                "]{" + p.verbatim_item() + '}',
2378                                            context);
2379                         } else {
2380                                 begin_command_inset(os, "bibitem", "bibitem");
2381                                 os << "label \"" << label << "\"\n"
2382                                       "key \"" << key << "\"\n";
2383                                 end_inset(os);
2384                         }
2385                 }
2386
2387                 else if (is_macro(p)) {
2388                         // catch the case of \def\inputGnumericTable
2389                         bool macro = true;
2390                         if (t.cs() == "def") {
2391                                 Token second = p.next_token();
2392                                 if (second.cs() == "inputGnumericTable") {
2393                                         p.pushPosition();
2394                                         p.get_token();
2395                                         skip_braces(p);
2396                                         Token third = p.get_token();
2397                                         p.popPosition();
2398                                         if (third.cs() == "input") {
2399                                                 p.get_token();
2400                                                 skip_braces(p);
2401                                                 p.get_token();
2402                                                 string name = normalize_filename(p.verbatim_item());
2403                                                 string const path = getMasterFilePath();
2404                                                 // We want to preserve relative / absolute filenames,
2405                                                 // therefore path is only used for testing
2406                                                 // The file extension is in every case ".tex".
2407                                                 // So we need to remove this extension and check for
2408                                                 // the original one.
2409                                                 name = removeExtension(name);
2410                                                 if (!makeAbsPath(name, path).exists()) {
2411                                                         char const * const Gnumeric_formats[] = {"gnumeric",
2412                                                                 "ods", "xls", 0};
2413                                                         string const Gnumeric_name =
2414                                                                 find_file(name, path, Gnumeric_formats);
2415                                                         if (!Gnumeric_name.empty())
2416                                                                 name = Gnumeric_name;
2417                                                 }
2418                                                 if (makeAbsPath(name, path).exists())
2419                                                         fix_relative_filename(name);
2420                                                 else
2421                                                         cerr << "Warning: Could not find file '"
2422                                                              << name << "'." << endl;
2423                                                 context.check_layout(os);
2424                                                 begin_inset(os, "External\n\ttemplate ");
2425                                                 os << "GnumericSpreadsheet\n\tfilename "
2426                                                    << name << "\n";
2427                                                 end_inset(os);
2428                                                 context.check_layout(os);
2429                                                 macro = false;
2430                                                 // register the packages that are automatically reloaded
2431                                                 // by the Gnumeric template
2432                                                 registerExternalTemplatePackages("GnumericSpreadsheet");
2433                                         }
2434                                 }
2435                         }
2436                         if (macro)
2437                                 parse_macro(p, os, context);
2438                 }
2439
2440                 else if (t.cs() == "noindent") {
2441                         p.skip_spaces();
2442                         context.add_par_extra_stuff("\\noindent\n");
2443                 }
2444
2445                 else if (t.cs() == "appendix") {
2446                         context.add_par_extra_stuff("\\start_of_appendix\n");
2447                         // We need to start a new paragraph. Otherwise the
2448                         // appendix in 'bla\appendix\chapter{' would start
2449                         // too late.
2450                         context.new_paragraph(os);
2451                         // We need to make sure that the paragraph is
2452                         // generated even if it is empty. Otherwise the
2453                         // appendix in '\par\appendix\par\chapter{' would
2454                         // start too late.
2455                         context.check_layout(os);
2456                         // FIXME: This is a hack to prevent paragraph
2457                         // deletion if it is empty. Handle this better!
2458                         handle_comment(os,
2459                                 "%dummy comment inserted by tex2lyx to "
2460                                 "ensure that this paragraph is not empty",
2461                                 context);
2462                         // Both measures above may generate an additional
2463                         // empty paragraph, but that does not hurt, because
2464                         // whitespace does not matter here.
2465                         eat_whitespace(p, os, context, true);
2466                 }
2467
2468                 // Must catch empty dates before findLayout is called below
2469                 else if (t.cs() == "date") {
2470                         string const date = p.verbatim_item();
2471                         if (date.empty())
2472                                 preamble.suppressDate(true);
2473                         else {
2474                                 preamble.suppressDate(false);
2475                                 if (context.new_layout_allowed &&
2476                                     (newlayout = findLayout(context.textclass,
2477                                                             t.cs(), true))) {
2478                                         // write the layout
2479                                         output_command_layout(os, p, outer,
2480                                                         context, newlayout);
2481                                         p.skip_spaces();
2482                                         if (!title_layout_found)
2483                                                 title_layout_found = newlayout->intitle;
2484                                         set<string> const & req = newlayout->requires();
2485                                         for (set<string>::const_iterator it = req.begin();
2486                                              it != req.end(); it++)
2487                                                 preamble.registerAutomaticallyLoadedPackage(*it);
2488                                 } else
2489                                         handle_ert(os, "\\date{" + date + '}',
2490                                                         context);
2491                         }
2492                 }
2493
2494                 // Starred section headings
2495                 // Must attempt to parse "Section*" before "Section".
2496                 else if ((p.next_token().asInput() == "*") &&
2497                          context.new_layout_allowed &&
2498                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2499                         // write the layout
2500                         p.get_token();
2501                         output_command_layout(os, p, outer, context, newlayout);
2502                         p.skip_spaces();
2503                         if (!title_layout_found)
2504                                 title_layout_found = newlayout->intitle;
2505                         set<string> const & req = newlayout->requires();
2506                         for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2507                                 preamble.registerAutomaticallyLoadedPackage(*it);
2508                 }
2509
2510                 // Section headings and the like
2511                 else if (context.new_layout_allowed &&
2512                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2513                         // write the layout
2514                         output_command_layout(os, p, outer, context, newlayout);
2515                         p.skip_spaces();
2516                         if (!title_layout_found)
2517                                 title_layout_found = newlayout->intitle;
2518                         set<string> const & req = newlayout->requires();
2519                         for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2520                                 preamble.registerAutomaticallyLoadedPackage(*it);
2521                 }
2522
2523                 else if (t.cs() == "caption") {
2524                         p.skip_spaces();
2525                         context.check_layout(os);
2526                         p.skip_spaces();
2527                         begin_inset(os, "Caption\n");
2528                         Context newcontext(true, context.textclass);
2529                         newcontext.font = context.font;
2530                         newcontext.check_layout(os);
2531                         if (p.next_token().cat() != catEscape &&
2532                             p.next_token().character() == '[') {
2533                                 p.get_token(); // eat '['
2534                                 begin_inset(os, "Argument\n");
2535                                 os << "status collapsed\n";
2536                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2537                                 end_inset(os);
2538                                 eat_whitespace(p, os, context, false);
2539                         }
2540                         parse_text(p, os, FLAG_ITEM, outer, context);
2541                         context.check_end_layout(os);
2542                         // We don't need really a new paragraph, but
2543                         // we must make sure that the next item gets a \begin_layout.
2544                         context.new_paragraph(os);
2545                         end_inset(os);
2546                         p.skip_spaces();
2547                         newcontext.check_end_layout(os);
2548                 }
2549
2550                 else if (t.cs() == "subfloat") {
2551                         // the syntax is \subfloat[caption]{content}
2552                         // if it is a table of figure depends on the surrounding float
2553                         bool has_caption = false;
2554                         p.skip_spaces();
2555                         // do nothing if there is no outer float
2556                         if (!float_type.empty()) {
2557                                 context.check_layout(os);
2558                                 p.skip_spaces();
2559                                 begin_inset(os, "Float " + float_type + "\n");
2560                                 os << "wide false"
2561                                    << "\nsideways false"
2562                                    << "\nstatus collapsed\n\n";
2563                                 // test for caption
2564                                 string caption;
2565                                 if (p.next_token().cat() != catEscape &&
2566                                                 p.next_token().character() == '[') {
2567                                                         p.get_token(); // eat '['
2568                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2569                                                         has_caption = true;
2570                                 }
2571                                 // the content
2572                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2573                                 // the caption comes always as the last
2574                                 if (has_caption) {
2575                                         // we must make sure that the caption gets a \begin_layout
2576                                         os << "\n\\begin_layout Plain Layout";
2577                                         p.skip_spaces();
2578                                         begin_inset(os, "Caption\n");
2579                                         Context newcontext(true, context.textclass);
2580                                         newcontext.font = context.font;
2581                                         newcontext.check_layout(os);
2582                                         os << caption << "\n";
2583                                         newcontext.check_end_layout(os);
2584                                         // We don't need really a new paragraph, but
2585                                         // we must make sure that the next item gets a \begin_layout.
2586                                         //newcontext.new_paragraph(os);
2587                                         end_inset(os);
2588                                         p.skip_spaces();
2589                                 }
2590                                 // We don't need really a new paragraph, but
2591                                 // we must make sure that the next item gets a \begin_layout.
2592                                 if (has_caption)
2593                                         context.new_paragraph(os);
2594                                 end_inset(os);
2595                                 p.skip_spaces();
2596                                 context.check_end_layout(os);
2597                                 // close the layout we opened
2598                                 if (has_caption)
2599                                         os << "\n\\end_layout\n";
2600                         } else {
2601                                 // if the float type is not supported or there is no surrounding float
2602                                 // output it as ERT
2603                                 if (p.hasOpt()) {
2604                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2605                                         handle_ert(os, t.asInput() + '[' + opt_arg +
2606                                                "]{" + p.verbatim_item() + '}', context);
2607                                 } else
2608                                         handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2609                         }
2610                 }
2611
2612                 else if (t.cs() == "includegraphics") {
2613                         bool const clip = p.next_token().asInput() == "*";
2614                         if (clip)
2615                                 p.get_token();
2616                         string const arg = p.getArg('[', ']');
2617                         map<string, string> opts;
2618                         vector<string> keys;
2619                         split_map(arg, opts, keys);
2620                         if (clip)
2621                                 opts["clip"] = string();
2622                         string name = normalize_filename(p.verbatim_item());
2623
2624                         string const path = getMasterFilePath();
2625                         // We want to preserve relative / absolute filenames,
2626                         // therefore path is only used for testing
2627                         if (!makeAbsPath(name, path).exists()) {
2628                                 // The file extension is probably missing.
2629                                 // Now try to find it out.
2630                                 string const dvips_name =
2631                                         find_file(name, path,
2632                                                   known_dvips_graphics_formats);
2633                                 string const pdftex_name =
2634                                         find_file(name, path,
2635                                                   known_pdftex_graphics_formats);
2636                                 if (!dvips_name.empty()) {
2637                                         if (!pdftex_name.empty()) {
2638                                                 cerr << "This file contains the "
2639                                                         "latex snippet\n"
2640                                                         "\"\\includegraphics{"
2641                                                      << name << "}\".\n"
2642                                                         "However, files\n\""
2643                                                      << dvips_name << "\" and\n\""
2644                                                      << pdftex_name << "\"\n"
2645                                                         "both exist, so I had to make a "
2646                                                         "choice and took the first one.\n"
2647                                                         "Please move the unwanted one "
2648                                                         "someplace else and try again\n"
2649                                                         "if my choice was wrong."
2650                                                      << endl;
2651                                         }
2652                                         name = dvips_name;
2653                                 } else if (!pdftex_name.empty()) {
2654                                         name = pdftex_name;
2655                                         pdflatex = true;
2656                                 }
2657                         }
2658
2659                         if (makeAbsPath(name, path).exists())
2660                                 fix_relative_filename(name);
2661                         else
2662                                 cerr << "Warning: Could not find graphics file '"
2663                                      << name << "'." << endl;
2664
2665                         context.check_layout(os);
2666                         begin_inset(os, "Graphics ");
2667                         os << "\n\tfilename " << name << '\n';
2668                         if (opts.find("width") != opts.end())
2669                                 os << "\twidth "
2670                                    << translate_len(opts["width"]) << '\n';
2671                         if (opts.find("height") != opts.end())
2672                                 os << "\theight "
2673                                    << translate_len(opts["height"]) << '\n';
2674                         if (opts.find("scale") != opts.end()) {
2675                                 istringstream iss(opts["scale"]);
2676                                 double val;
2677                                 iss >> val;
2678                                 val = val*100;
2679                                 os << "\tscale " << val << '\n';
2680                         }
2681                         if (opts.find("angle") != opts.end()) {
2682                                 os << "\trotateAngle "
2683                                    << opts["angle"] << '\n';
2684                                 vector<string>::const_iterator a =
2685                                         find(keys.begin(), keys.end(), "angle");
2686                                 vector<string>::const_iterator s =
2687                                         find(keys.begin(), keys.end(), "width");
2688                                 if (s == keys.end())
2689                                         s = find(keys.begin(), keys.end(), "height");
2690                                 if (s == keys.end())
2691                                         s = find(keys.begin(), keys.end(), "scale");
2692                                 if (s != keys.end() && distance(s, a) > 0)
2693                                         os << "\tscaleBeforeRotation\n";
2694                         }
2695                         if (opts.find("origin") != opts.end()) {
2696                                 ostringstream ss;
2697                                 string const opt = opts["origin"];
2698                                 if (opt.find('l') != string::npos) ss << "left";
2699                                 if (opt.find('r') != string::npos) ss << "right";
2700                                 if (opt.find('c') != string::npos) ss << "center";
2701                                 if (opt.find('t') != string::npos) ss << "Top";
2702                                 if (opt.find('b') != string::npos) ss << "Bottom";
2703                                 if (opt.find('B') != string::npos) ss << "Baseline";
2704                                 if (!ss.str().empty())
2705                                         os << "\trotateOrigin " << ss.str() << '\n';
2706                                 else
2707                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2708                         }
2709                         if (opts.find("keepaspectratio") != opts.end())
2710                                 os << "\tkeepAspectRatio\n";
2711                         if (opts.find("clip") != opts.end())
2712                                 os << "\tclip\n";
2713                         if (opts.find("draft") != opts.end())
2714                                 os << "\tdraft\n";
2715                         if (opts.find("bb") != opts.end())
2716                                 os << "\tBoundingBox "
2717                                    << opts["bb"] << '\n';
2718                         int numberOfbbOptions = 0;
2719                         if (opts.find("bbllx") != opts.end())
2720                                 numberOfbbOptions++;
2721                         if (opts.find("bblly") != opts.end())
2722                                 numberOfbbOptions++;
2723                         if (opts.find("bburx") != opts.end())
2724                                 numberOfbbOptions++;
2725                         if (opts.find("bbury") != opts.end())
2726                                 numberOfbbOptions++;
2727                         if (numberOfbbOptions == 4)
2728                                 os << "\tBoundingBox "
2729                                    << opts["bbllx"] << " " << opts["bblly"] << " "
2730                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
2731                         else if (numberOfbbOptions > 0)
2732                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2733                         numberOfbbOptions = 0;
2734                         if (opts.find("natwidth") != opts.end())
2735                                 numberOfbbOptions++;
2736                         if (opts.find("natheight") != opts.end())
2737                                 numberOfbbOptions++;
2738                         if (numberOfbbOptions == 2)
2739                                 os << "\tBoundingBox 0bp 0bp "
2740                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
2741                         else if (numberOfbbOptions > 0)
2742                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2743                         ostringstream special;
2744                         if (opts.find("hiresbb") != opts.end())
2745                                 special << "hiresbb,";
2746                         if (opts.find("trim") != opts.end())
2747                                 special << "trim,";
2748                         if (opts.find("viewport") != opts.end())
2749                                 special << "viewport=" << opts["viewport"] << ',';
2750                         if (opts.find("totalheight") != opts.end())
2751                                 special << "totalheight=" << opts["totalheight"] << ',';
2752                         if (opts.find("type") != opts.end())
2753                                 special << "type=" << opts["type"] << ',';
2754                         if (opts.find("ext") != opts.end())
2755                                 special << "ext=" << opts["ext"] << ',';
2756                         if (opts.find("read") != opts.end())
2757                                 special << "read=" << opts["read"] << ',';
2758                         if (opts.find("command") != opts.end())
2759                                 special << "command=" << opts["command"] << ',';
2760                         string s_special = special.str();
2761                         if (!s_special.empty()) {
2762                                 // We had special arguments. Remove the trailing ','.
2763                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2764                         }
2765                         // TODO: Handle the unknown settings better.
2766                         // Warn about invalid options.
2767                         // Check whether some option was given twice.
2768                         end_inset(os);
2769                         preamble.registerAutomaticallyLoadedPackage("graphicx");
2770                 }
2771
2772                 else if (t.cs() == "footnote" ||
2773                          (t.cs() == "thanks" && context.layout->intitle)) {
2774                         p.skip_spaces();
2775                         context.check_layout(os);
2776                         begin_inset(os, "Foot\n");
2777                         os << "status collapsed\n\n";
2778                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2779                         end_inset(os);
2780                 }
2781
2782                 else if (t.cs() == "marginpar") {
2783                         p.skip_spaces();
2784                         context.check_layout(os);
2785                         begin_inset(os, "Marginal\n");
2786                         os << "status collapsed\n\n";
2787                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2788                         end_inset(os);
2789                 }
2790
2791                 else if (t.cs() == "ensuremath") {
2792                         p.skip_spaces();
2793                         context.check_layout(os);
2794                         string const s = p.verbatim_item();
2795                         //FIXME: this never triggers in UTF8
2796                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2797                                 os << s;
2798                         else
2799                                 handle_ert(os, "\\ensuremath{" + s + "}",
2800                                            context);
2801                 }
2802
2803                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2804                         if (title_layout_found) {
2805                                 // swallow this
2806                                 skip_spaces_braces(p);
2807                         } else
2808                                 handle_ert(os, t.asInput(), context);
2809                 }
2810
2811                 else if (t.cs() == "tableofcontents") {
2812                         context.check_layout(os);
2813                         begin_command_inset(os, "toc", "tableofcontents");
2814                         end_inset(os);
2815                         skip_spaces_braces(p);
2816                 }
2817
2818                 else if (t.cs() == "listoffigures") {
2819                         context.check_layout(os);
2820                         begin_inset(os, "FloatList figure\n");
2821                         end_inset(os);
2822                         skip_spaces_braces(p);
2823                 }
2824
2825                 else if (t.cs() == "listoftables") {
2826                         context.check_layout(os);
2827                         begin_inset(os, "FloatList table\n");
2828                         end_inset(os);
2829                         skip_spaces_braces(p);
2830                 }
2831
2832                 else if (t.cs() == "listof") {
2833                         p.skip_spaces(true);
2834                         string const name = p.get_token().cs();
2835                         if (context.textclass.floats().typeExist(name)) {
2836                                 context.check_layout(os);
2837                                 begin_inset(os, "FloatList ");
2838                                 os << name << "\n";
2839                                 end_inset(os);
2840                                 p.get_token(); // swallow second arg
2841                         } else
2842                                 handle_ert(os, "\\listof{" + name + "}", context);
2843                 }
2844
2845                 else if ((where = is_known(t.cs(), known_text_font_families)))
2846                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2847                                 context, "\\family", context.font.family,
2848                                 known_coded_font_families[where - known_text_font_families]);
2849
2850                 else if ((where = is_known(t.cs(), known_text_font_series)))
2851                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2852                                 context, "\\series", context.font.series,
2853                                 known_coded_font_series[where - known_text_font_series]);
2854
2855                 else if ((where = is_known(t.cs(), known_text_font_shapes)))
2856                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2857                                 context, "\\shape", context.font.shape,
2858                                 known_coded_font_shapes[where - known_text_font_shapes]);
2859
2860                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2861                         context.check_layout(os);
2862                         TeXFont oldFont = context.font;
2863                         context.font.init();
2864                         context.font.size = oldFont.size;
2865                         os << "\n\\family " << context.font.family << "\n";
2866                         os << "\n\\series " << context.font.series << "\n";
2867                         os << "\n\\shape " << context.font.shape << "\n";
2868                         if (t.cs() == "textnormal") {
2869                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2870                                 output_font_change(os, context.font, oldFont);
2871                                 context.font = oldFont;
2872                         } else
2873                                 eat_whitespace(p, os, context, false);
2874                 }
2875
2876                 else if (t.cs() == "textcolor") {
2877                         // scheme is \textcolor{color name}{text}
2878                         string const color = p.verbatim_item();
2879                         // we only support the predefined colors of the color package
2880                         if (color == "black" || color == "blue" || color == "cyan"
2881                                 || color == "green" || color == "magenta" || color == "red"
2882                                 || color == "white" || color == "yellow") {
2883                                         context.check_layout(os);
2884                                         os << "\n\\color " << color << "\n";
2885                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2886                                         context.check_layout(os);
2887                                         os << "\n\\color inherit\n";
2888                                         preamble.registerAutomaticallyLoadedPackage("color");
2889                         } else
2890                                 // for custom defined colors
2891                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
2892                 }
2893
2894                 else if (t.cs() == "underbar" || t.cs() == "uline") {
2895                         // \underbar is not 100% correct (LyX outputs \uline
2896                         // of ulem.sty). The difference is that \ulem allows
2897                         // line breaks, and \underbar does not.
2898                         // Do NOT handle \underline.
2899                         // \underbar cuts through y, g, q, p etc.,
2900                         // \underline does not.
2901                         context.check_layout(os);
2902                         os << "\n\\bar under\n";
2903                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2904                         context.check_layout(os);
2905                         os << "\n\\bar default\n";
2906                         preamble.registerAutomaticallyLoadedPackage("ulem");
2907                 }
2908
2909                 else if (t.cs() == "sout") {
2910                         context.check_layout(os);
2911                         os << "\n\\strikeout on\n";
2912                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2913                         context.check_layout(os);
2914                         os << "\n\\strikeout default\n";
2915                         preamble.registerAutomaticallyLoadedPackage("ulem");
2916                 }
2917
2918                 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2919                          t.cs() == "emph" || t.cs() == "noun") {
2920                         context.check_layout(os);
2921                         os << "\n\\" << t.cs() << " on\n";
2922                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2923                         context.check_layout(os);
2924                         os << "\n\\" << t.cs() << " default\n";
2925                         if (t.cs() == "uuline" || t.cs() == "uwave")
2926                                 preamble.registerAutomaticallyLoadedPackage("ulem");
2927                 }
2928
2929                 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2930                         context.check_layout(os);
2931                         string name = p.getArg('{', '}');
2932                         string localtime = p.getArg('{', '}');
2933                         preamble.registerAuthor(name);
2934                         Author const & author = preamble.getAuthor(name);
2935                         // from_ctime() will fail if LyX decides to output the
2936                         // time in the text language. It might also use a wrong
2937                         // time zone (if the original LyX document was exported
2938                         // with a different time zone).
2939                         time_t ptime = from_ctime(localtime);
2940                         if (ptime == static_cast<time_t>(-1)) {
2941                                 cerr << "Warning: Could not parse time `" << localtime
2942                                      << "´ for change tracking, using current time instead.\n";
2943                                 ptime = current_time();
2944                         }
2945                         if (t.cs() == "lyxadded")
2946                                 os << "\n\\change_inserted ";
2947                         else
2948                                 os << "\n\\change_deleted ";
2949                         os << author.bufferId() << ' ' << ptime << '\n';
2950                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2951                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
2952                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2953                                           LaTeXPackages::isAvailable("xcolor");
2954                         // No need to test for luatex, since luatex comes in
2955                         // two flavours (dvi and pdf), like latex, and those
2956                         // are detected by pdflatex.
2957                         if (pdflatex || xetex) {
2958                                 if (xcolorulem) {
2959                                         preamble.registerAutomaticallyLoadedPackage("ulem");
2960                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
2961                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2962                                 }
2963                         } else {
2964                                 if (dvipost) {
2965                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
2966                                 } else if (xcolorulem) {
2967                                         preamble.registerAutomaticallyLoadedPackage("ulem");
2968                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
2969                                 }
2970                         }
2971                 }
2972
2973                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2974                              t.cs() == "vphantom") {
2975                         context.check_layout(os);
2976                         if (t.cs() == "phantom")
2977                                 begin_inset(os, "Phantom Phantom\n");
2978                         if (t.cs() == "hphantom")
2979                                 begin_inset(os, "Phantom HPhantom\n");
2980                         if (t.cs() == "vphantom")
2981                                 begin_inset(os, "Phantom VPhantom\n");
2982                         os << "status open\n";
2983                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2984                                             "Phantom");
2985                         end_inset(os);
2986                 }
2987
2988                 else if (t.cs() == "href") {
2989                         context.check_layout(os);
2990                         string target = p.getArg('{', '}');
2991                         string name = p.getArg('{', '}');
2992                         string type;
2993                         size_t i = target.find(':');
2994                         if (i != string::npos) {
2995                                 type = target.substr(0, i + 1);
2996                                 if (type == "mailto:" || type == "file:")
2997                                         target = target.substr(i + 1);
2998                                 // handle the case that name is equal to target, except of "http://"
2999                                 else if (target.substr(i + 3) == name && type == "http:")
3000                                         target = name;
3001                         }
3002                         begin_command_inset(os, "href", "href");
3003                         if (name != target)
3004                                 os << "name \"" << name << "\"\n";
3005                         os << "target \"" << target << "\"\n";
3006                         if (type == "mailto:" || type == "file:")
3007                                 os << "type \"" << type << "\"\n";
3008                         end_inset(os);
3009                         skip_spaces_braces(p);
3010                 }
3011
3012                 else if (t.cs() == "lyxline") {
3013                         // swallow size argument (it is not used anyway)
3014                         p.getArg('{', '}');
3015                         if (!context.atParagraphStart()) {
3016                                 // so our line is in the middle of a paragraph
3017                                 // we need to add a new line, lest this line
3018                                 // follow the other content on that line and
3019                                 // run off the side of the page
3020                                 // FIXME: This may create an empty paragraph,
3021                                 //        but without that it would not be
3022                                 //        possible to set noindent below.
3023                                 //        Fortunately LaTeX does not care
3024                                 //        about the empty paragraph.
3025                                 context.new_paragraph(os);
3026                         }
3027                         if (preamble.indentParagraphs()) {
3028                                 // we need to unindent, lest the line be too long
3029                                 context.add_par_extra_stuff("\\noindent\n");
3030                         }
3031                         context.check_layout(os);
3032                         begin_command_inset(os, "line", "rule");
3033                         os << "offset \"0.5ex\"\n"
3034                               "width \"100line%\"\n"
3035                               "height \"1pt\"\n";
3036                         end_inset(os);
3037                 }
3038
3039                 else if (t.cs() == "rule") {
3040                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3041                         string const width = p.getArg('{', '}');
3042                         string const thickness = p.getArg('{', '}');
3043                         context.check_layout(os);
3044                         begin_command_inset(os, "line", "rule");
3045                         if (!offset.empty())
3046                                 os << "offset \"" << translate_len(offset) << "\"\n";
3047                         os << "width \"" << translate_len(width) << "\"\n"
3048                                   "height \"" << translate_len(thickness) << "\"\n";
3049                         end_inset(os);
3050                 }
3051
3052                 else if (is_known(t.cs(), known_phrases) ||
3053                          (t.cs() == "protect" &&
3054                           p.next_token().cat() == catEscape &&
3055                           is_known(p.next_token().cs(), known_phrases))) {
3056                         // LyX sometimes puts a \protect in front, so we have to ignore it
3057                         // FIXME: This needs to be changed when bug 4752 is fixed.
3058                         where = is_known(
3059                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3060                                 known_phrases);
3061                         context.check_layout(os);
3062                         os << known_coded_phrases[where - known_phrases];
3063                         skip_spaces_braces(p);
3064                 }
3065
3066                 else if ((where = is_known(t.cs(), known_ref_commands))) {
3067                         string const opt = p.getOpt();
3068                         if (opt.empty()) {
3069                                 context.check_layout(os);
3070                                 begin_command_inset(os, "ref",
3071                                         known_coded_ref_commands[where - known_ref_commands]);
3072                                 os << "reference \""
3073                                    << convert_command_inset_arg(p.verbatim_item())
3074                                    << "\"\n";
3075                                 end_inset(os);
3076                                 if (t.cs() == "vref" || t.cs() == "vpageref")
3077                                         preamble.registerAutomaticallyLoadedPackage("varioref");
3078
3079                         } else {
3080                                 // LyX does not support optional arguments of ref commands
3081                                 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3082                                                p.verbatim_item() + "}", context);
3083                         }
3084                 }
3085
3086                 else if (use_natbib &&
3087                          is_known(t.cs(), known_natbib_commands) &&
3088                          ((t.cs() != "citefullauthor" &&
3089                            t.cs() != "citeyear" &&
3090                            t.cs() != "citeyearpar") ||
3091                           p.next_token().asInput() != "*")) {
3092                         context.check_layout(os);
3093                         string command = t.cs();
3094                         if (p.next_token().asInput() == "*") {
3095                                 command += '*';
3096                                 p.get_token();
3097                         }
3098                         if (command == "citefullauthor")
3099                                 // alternative name for "\\citeauthor*"
3100                                 command = "citeauthor*";
3101
3102                         // text before the citation
3103                         string before;
3104                         // text after the citation
3105                         string after;
3106                         get_cite_arguments(p, true, before, after);
3107
3108                         if (command == "cite") {
3109                                 // \cite without optional argument means
3110                                 // \citet, \cite with at least one optional
3111                                 // argument means \citep.
3112                                 if (before.empty() && after.empty())
3113                                         command = "citet";
3114                                 else
3115                                         command = "citep";
3116                         }
3117                         if (before.empty() && after == "[]")
3118                                 // avoid \citet[]{a}
3119                                 after.erase();
3120                         else if (before == "[]" && after == "[]") {
3121                                 // avoid \citet[][]{a}
3122                                 before.erase();
3123                                 after.erase();
3124                         }
3125                         // remove the brackets around after and before
3126                         if (!after.empty()) {
3127                                 after.erase(0, 1);
3128                                 after.erase(after.length() - 1, 1);
3129                                 after = convert_command_inset_arg(after);
3130                         }
3131                         if (!before.empty()) {
3132                                 before.erase(0, 1);
3133                                 before.erase(before.length() - 1, 1);
3134                                 before = convert_command_inset_arg(before);
3135                         }
3136                         begin_command_inset(os, "citation", command);
3137                         os << "after " << '"' << after << '"' << "\n";
3138                         os << "before " << '"' << before << '"' << "\n";
3139                         os << "key \""
3140                            << convert_command_inset_arg(p.verbatim_item())
3141                            << "\"\n";
3142                         end_inset(os);
3143                 }
3144
3145                 else if (use_jurabib &&
3146                          is_known(t.cs(), known_jurabib_commands) &&
3147                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3148                         context.check_layout(os);
3149                         string command = t.cs();
3150                         if (p.next_token().asInput() == "*") {
3151                                 command += '*';
3152                                 p.get_token();
3153                         }
3154                         char argumentOrder = '\0';
3155                         vector<string> const options =
3156                                 preamble.getPackageOptions("jurabib");
3157                         if (find(options.begin(), options.end(),
3158                                       "natbiborder") != options.end())
3159                                 argumentOrder = 'n';
3160                         else if (find(options.begin(), options.end(),
3161                                            "jurabiborder") != options.end())
3162                                 argumentOrder = 'j';
3163
3164                         // text before the citation
3165                         string before;
3166                         // text after the citation
3167                         string after;
3168                         get_cite_arguments(p, argumentOrder != 'j', before, after);
3169
3170                         string const citation = p.verbatim_item();
3171                         if (!before.empty() && argumentOrder == '\0') {
3172                                 cerr << "Warning: Assuming argument order "
3173                                         "of jurabib version 0.6 for\n'"
3174                                      << command << before << after << '{'
3175                                      << citation << "}'.\n"
3176                                         "Add 'jurabiborder' to the jurabib "
3177                                         "package options if you used an\n"
3178                                         "earlier jurabib version." << endl;
3179                         }
3180                         if (!after.empty()) {
3181                                 after.erase(0, 1);
3182                                 after.erase(after.length() - 1, 1);
3183                         }
3184                         if (!before.empty()) {
3185                                 before.erase(0, 1);
3186                                 before.erase(before.length() - 1, 1);
3187                         }
3188                         begin_command_inset(os, "citation", command);
3189                         os << "after " << '"' << after << '"' << "\n";
3190                         os << "before " << '"' << before << '"' << "\n";
3191                         os << "key " << '"' << citation << '"' << "\n";
3192                         end_inset(os);
3193                 }
3194
3195                 else if (t.cs() == "cite"
3196                         || t.cs() == "nocite") {
3197                         context.check_layout(os);
3198                         string after = convert_command_inset_arg(p.getArg('[', ']'));
3199                         string key = convert_command_inset_arg(p.verbatim_item());
3200                         // store the case that it is "\nocite{*}" to use it later for
3201                         // the BibTeX inset
3202                         if (key != "*") {
3203                                 begin_command_inset(os, "citation", t.cs());
3204                                 os << "after " << '"' << after << '"' << "\n";
3205                                 os << "key " << '"' << key << '"' << "\n";
3206                                 end_inset(os);
3207                         } else if (t.cs() == "nocite")
3208                                 btprint = key;
3209                 }
3210
3211                 else if (t.cs() == "index" ||
3212                          (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3213                         context.check_layout(os);
3214                         string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3215                                 p.getArg('[', ']') : "";
3216                         string const kind = arg.empty() ? "idx" : arg;
3217                         begin_inset(os, "Index ");
3218                         os << kind << "\nstatus collapsed\n";
3219                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3220                         end_inset(os);
3221                         if (kind != "idx")
3222                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3223                 }
3224
3225                 else if (t.cs() == "nomenclature") {
3226                         context.check_layout(os);
3227                         begin_command_inset(os, "nomenclature", "nomenclature");
3228                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3229                         if (!prefix.empty())
3230                                 os << "prefix " << '"' << prefix << '"' << "\n";
3231                         os << "symbol " << '"'
3232                            << convert_command_inset_arg(p.verbatim_item());
3233                         os << "\"\ndescription \""
3234                            << convert_command_inset_arg(p.verbatim_item())
3235                            << "\"\n";
3236                         end_inset(os);
3237                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3238                 }
3239
3240                 else if (t.cs() == "label") {
3241                         context.check_layout(os);
3242                         begin_command_inset(os, "label", "label");
3243                         os << "name \""
3244                            << convert_command_inset_arg(p.verbatim_item())
3245                            << "\"\n";
3246                         end_inset(os);
3247                 }
3248
3249                 else if (t.cs() == "printindex") {
3250                         context.check_layout(os);
3251                         begin_command_inset(os, "index_print", "printindex");
3252                         os << "type \"idx\"\n";
3253                         end_inset(os);
3254                         skip_spaces_braces(p);
3255                         preamble.registerAutomaticallyLoadedPackage("makeidx");
3256                         if (preamble.use_indices() == "true")
3257                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3258                 }
3259
3260                 else if (t.cs() == "printnomenclature") {
3261                         string width = "";
3262                         string width_type = "";
3263                         context.check_layout(os);
3264                         begin_command_inset(os, "nomencl_print", "printnomenclature");
3265                         // case of a custom width
3266                         if (p.hasOpt()) {
3267                                 width = p.getArg('[', ']');
3268                                 width = translate_len(width);
3269                                 width_type = "custom";
3270                         }
3271                         // case of no custom width
3272                         // the case of no custom width but the width set
3273                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
3274                         // because the user could have set anything, not only the width
3275                         // of the longest label (which would be width_type = "auto")
3276                         string label = convert_command_inset_arg(p.getArg('{', '}'));
3277                         if (label.empty() && width_type.empty())
3278                                 width_type = "none";
3279                         os << "set_width \"" << width_type << "\"\n";
3280                         if (width_type == "custom")
3281                                 os << "width \"" << width << '\"';
3282                         end_inset(os);
3283                         skip_spaces_braces(p);
3284                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3285                 }
3286
3287                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3288                         context.check_layout(os);
3289                         begin_inset(os, "script ");
3290                         os << t.cs().substr(4) << '\n';
3291                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3292                         end_inset(os);
3293                         if (t.cs() == "textsubscript")
3294                                 preamble.registerAutomaticallyLoadedPackage("subscript");
3295                 }
3296
3297                 else if ((where = is_known(t.cs(), known_quotes))) {
3298                         context.check_layout(os);
3299                         begin_inset(os, "Quotes ");
3300                         os << known_coded_quotes[where - known_quotes];
3301                         end_inset(os);
3302                         // LyX adds {} after the quote, so we have to eat
3303                         // spaces here if there are any before a possible
3304                         // {} pair.
3305                         eat_whitespace(p, os, context, false);
3306                         skip_braces(p);
3307                 }
3308
3309                 else if ((where = is_known(t.cs(), known_sizes)) &&
3310                          context.new_layout_allowed) {
3311                         context.check_layout(os);
3312                         TeXFont const oldFont = context.font;
3313                         context.font.size = known_coded_sizes[where - known_sizes];
3314                         output_font_change(os, oldFont, context.font);
3315                         eat_whitespace(p, os, context, false);
3316                 }
3317
3318                 else if ((where = is_known(t.cs(), known_font_families)) &&
3319                          context.new_layout_allowed) {
3320                         context.check_layout(os);
3321                         TeXFont const oldFont = context.font;
3322                         context.font.family =
3323                                 known_coded_font_families[where - known_font_families];
3324                         output_font_change(os, oldFont, context.font);
3325                         eat_whitespace(p, os, context, false);
3326                 }
3327
3328                 else if ((where = is_known(t.cs(), known_font_series)) &&
3329                          context.new_layout_allowed) {
3330                         context.check_layout(os);
3331                         TeXFont const oldFont = context.font;
3332                         context.font.series =
3333                                 known_coded_font_series[where - known_font_series];
3334                         output_font_change(os, oldFont, context.font);
3335                         eat_whitespace(p, os, context, false);
3336                 }
3337
3338                 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3339                          context.new_layout_allowed) {
3340                         context.check_layout(os);
3341                         TeXFont const oldFont = context.font;
3342                         context.font.shape =
3343                                 known_coded_font_shapes[where - known_font_shapes];
3344                         output_font_change(os, oldFont, context.font);
3345                         eat_whitespace(p, os, context, false);
3346                 }
3347                 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3348                          context.new_layout_allowed) {
3349                         context.check_layout(os);
3350                         TeXFont const oldFont = context.font;
3351                         context.font.init();
3352                         context.font.size = oldFont.size;
3353                         context.font.family =
3354                                 known_coded_font_families[where - known_old_font_families];
3355                         output_font_change(os, oldFont, context.font);
3356                         eat_whitespace(p, os, context, false);
3357                 }
3358
3359                 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3360                          context.new_layout_allowed) {
3361                         context.check_layout(os);
3362                         TeXFont const oldFont = context.font;
3363                         context.font.init();
3364                         context.font.size = oldFont.size;
3365                         context.font.series =
3366                                 known_coded_font_series[where - known_old_font_series];
3367                         output_font_change(os, oldFont, context.font);
3368                         eat_whitespace(p, os, context, false);
3369                 }
3370
3371                 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3372                          context.new_layout_allowed) {
3373                         context.check_layout(os);
3374                         TeXFont const oldFont = context.font;
3375                         context.font.init();
3376                         context.font.size = oldFont.size;
3377                         context.font.shape =
3378                                 known_coded_font_shapes[where - known_old_font_shapes];
3379                         output_font_change(os, oldFont, context.font);
3380                         eat_whitespace(p, os, context, false);
3381                 }
3382
3383                 else if (t.cs() == "selectlanguage") {
3384                         context.check_layout(os);
3385                         // save the language for the case that a
3386                         // \foreignlanguage is used
3387
3388                         context.font.language = babel2lyx(p.verbatim_item());
3389                         os << "\n\\lang " << context.font.language << "\n";
3390                 }
3391
3392                 else if (t.cs() == "foreignlanguage") {
3393                         string const lang = babel2lyx(p.verbatim_item());
3394                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3395                                               context, "\\lang",
3396                                               context.font.language, lang);
3397                 }
3398
3399                 else if (t.cs() == "inputencoding") {
3400                         // nothing to write here
3401                         string const enc = subst(p.verbatim_item(), "\n", " ");
3402                         p.setEncoding(enc);
3403                 }
3404
3405                 else if ((where = is_known(t.cs(), known_special_chars))) {
3406                         context.check_layout(os);
3407                         os << "\\SpecialChar \\"
3408                            << known_coded_special_chars[where - known_special_chars]
3409                            << '\n';
3410                         skip_spaces_braces(p);
3411                 }
3412
3413                 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3414                         context.check_layout(os);
3415                         os << "\\SpecialChar \\nobreakdash-\n";
3416                         p.get_token();
3417                 }
3418
3419                 else if (t.cs() == "textquotedbl") {
3420                         context.check_layout(os);
3421                         os << "\"";
3422                         skip_braces(p);
3423                 }
3424
3425                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3426                         context.check_layout(os);
3427                         os << "\\SpecialChar \\@.\n";
3428                         p.get_token();
3429                 }
3430
3431                 else if (t.cs() == "-") {
3432                         context.check_layout(os);
3433                         os << "\\SpecialChar \\-\n";
3434                 }
3435
3436                 else if (t.cs() == "textasciitilde") {
3437                         context.check_layout(os);
3438                         os << '~';
3439                         skip_spaces_braces(p);
3440                 }
3441
3442                 else if (t.cs() == "textasciicircum") {
3443                         context.check_layout(os);
3444                         os << '^';
3445                         skip_spaces_braces(p);
3446                 }
3447
3448                 else if (t.cs() == "textbackslash") {
3449                         context.check_layout(os);
3450                         os << "\n\\backslash\n";
3451                         skip_spaces_braces(p);
3452                 }
3453
3454                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3455                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3456                             || t.cs() == "%") {
3457                         context.check_layout(os);
3458                         os << t.cs();
3459                 }
3460
3461                 else if (t.cs() == "char") {
3462                         context.check_layout(os);
3463                         if (p.next_token().character() == '`') {
3464                                 p.get_token();
3465                                 if (p.next_token().cs() == "\"") {
3466                                         p.get_token();
3467                                         os << '"';
3468                                         skip_braces(p);
3469                                 } else {
3470                                         handle_ert(os, "\\char`", context);
3471                                 }
3472                         } else {
3473                                 handle_ert(os, "\\char", context);
3474                         }
3475                 }
3476
3477                 else if (t.cs() == "verb") {
3478                         context.check_layout(os);
3479                         char const delimiter = p.next_token().character();
3480                         string const arg = p.getArg(delimiter, delimiter);
3481                         ostringstream oss;
3482                         oss << "\\verb" << delimiter << arg << delimiter;
3483                         handle_ert(os, oss.str(), context);
3484                 }
3485
3486                 // Problem: \= creates a tabstop inside the tabbing environment
3487                 // and else an accent. In the latter case we really would want
3488                 // \={o} instead of \= o.
3489                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3490                         handle_ert(os, t.asInput(), context);
3491
3492                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3493                 else if (t.cs().size() == 1
3494                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3495                         context.check_layout(os);
3496                         // try to see whether the string is in unicodesymbols
3497                         docstring rem;
3498                         string command = t.asInput() + "{"
3499                                 + trimSpaceAndEol(p.verbatim_item())
3500                                 + "}";
3501                         set<string> req;
3502                         docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3503                                 Encodings::TEXT_CMD | Encodings::MATH_CMD, rem, &req);
3504                         if (!s.empty()) {
3505                                 if (!rem.empty())
3506                                         cerr << "When parsing " << command
3507                                              << ", result is " << to_utf8(s)
3508                                              << "+" << to_utf8(rem) << endl;
3509                                 os << to_utf8(s);
3510                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
3511                                         preamble.registerAutomaticallyLoadedPackage(*it);
3512                         } else
3513                                 // we did not find a non-ert version
3514                                 handle_ert(os, command, context);
3515                 }
3516
3517                 else if (t.cs() == "\\") {
3518                         context.check_layout(os);
3519                         if (p.hasOpt())
3520                                 handle_ert(os, "\\\\" + p.getOpt(), context);
3521                         else if (p.next_token().asInput() == "*") {
3522                                 p.get_token();
3523                                 // getOpt() eats the following space if there
3524                                 // is no optional argument, but that is OK
3525                                 // here since it has no effect in the output.
3526                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
3527                         }
3528                         else {
3529                                 begin_inset(os, "Newline newline");
3530                                 end_inset(os);
3531                         }
3532                 }
3533
3534                 else if (t.cs() == "newline" ||
3535                          (t.cs() == "linebreak" && !p.hasOpt())) {
3536                         context.check_layout(os);
3537                         begin_inset(os, "Newline ");
3538                         os << t.cs();
3539                         end_inset(os);
3540                         skip_spaces_braces(p);
3541                 }
3542
3543                 else if (t.cs() == "input" || t.cs() == "include"
3544                          || t.cs() == "verbatiminput") {
3545                         string name = t.cs();
3546                         if (t.cs() == "verbatiminput"
3547                             && p.next_token().asInput() == "*")
3548                                 name += p.get_token().asInput();
3549                         context.check_layout(os);
3550                         string filename(normalize_filename(p.getArg('{', '}')));
3551                         string const path = getMasterFilePath();
3552                         // We want to preserve relative / absolute filenames,
3553                         // therefore path is only used for testing
3554                         if ((t.cs() == "include" || t.cs() == "input") &&
3555                             !makeAbsPath(filename, path).exists()) {
3556                                 // The file extension is probably missing.
3557                                 // Now try to find it out.
3558                                 string const tex_name =
3559                                         find_file(filename, path,
3560                                                   known_tex_extensions);
3561                                 if (!tex_name.empty())
3562                                         filename = tex_name;
3563                         }
3564                         bool external = false;
3565                         string outname;
3566                         if (makeAbsPath(filename, path).exists()) {
3567                                 string const abstexname =
3568                                         makeAbsPath(filename, path).absFileName();
3569                                 string const abslyxname =
3570                                         changeExtension(abstexname, ".lyx");
3571                                 string const absfigname =
3572                                         changeExtension(abstexname, ".fig");
3573                                 fix_relative_filename(filename);
3574                                 string const lyxname =
3575                                         changeExtension(filename, ".lyx");
3576                                 bool xfig = false;
3577                                 external = FileName(absfigname).exists();
3578                                 if (t.cs() == "input") {
3579                                         string const ext = getExtension(abstexname);
3580
3581                                         // Combined PS/LaTeX:
3582                                         // x.eps, x.pstex_t (old xfig)
3583                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3584                                         FileName const absepsname(
3585                                                 changeExtension(abstexname, ".eps"));
3586                                         FileName const abspstexname(
3587                                                 changeExtension(abstexname, ".pstex"));
3588                                         bool const xfigeps =
3589                                                 (absepsname.exists() ||
3590                                                  abspstexname.exists()) &&
3591                                                 ext == "pstex_t";
3592
3593                                         // Combined PDF/LaTeX:
3594                                         // x.pdf, x.pdftex_t (old xfig)
3595                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3596                                         FileName const abspdfname(
3597                                                 changeExtension(abstexname, ".pdf"));
3598                                         bool const xfigpdf =
3599                                                 abspdfname.exists() &&
3600                                                 (ext == "pdftex_t" || ext == "pdf_t");
3601                                         if (xfigpdf)
3602                                                 pdflatex = true;
3603
3604                                         // Combined PS/PDF/LaTeX:
3605                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3606                                         string const absbase2(
3607                                                 removeExtension(abstexname) + "_pspdftex");
3608                                         FileName const abseps2name(
3609                                                 addExtension(absbase2, ".eps"));
3610                                         FileName const abspdf2name(
3611                                                 addExtension(absbase2, ".pdf"));
3612                                         bool const xfigboth =
3613                                                 abspdf2name.exists() &&
3614                                                 abseps2name.exists() && ext == "pspdftex";
3615
3616                                         xfig = xfigpdf || xfigeps || xfigboth;
3617                                         external = external && xfig;
3618                                 }
3619                                 if (external) {
3620                                         outname = changeExtension(filename, ".fig");
3621                                 } else if (xfig) {
3622                                         // Don't try to convert, the result
3623                                         // would be full of ERT.
3624                                         outname = filename;
3625                                 } else if (t.cs() != "verbatiminput" &&
3626                                     tex2lyx(abstexname, FileName(abslyxname),
3627                                             p.getEncoding())) {
3628                                         outname = lyxname;
3629                                 } else {
3630                                         outname = filename;
3631                                 }
3632                         } else {
3633                                 cerr << "Warning: Could not find included file '"
3634                                      << filename << "'." << endl;
3635                                 outname = filename;
3636                         }
3637                         if (external) {
3638                                 begin_inset(os, "External\n");
3639                                 os << "\ttemplate XFig\n"
3640                                    << "\tfilename " << outname << '\n';
3641                                 registerExternalTemplatePackages("XFig");
3642                         } else {
3643                                 begin_command_inset(os, "include", name);
3644                                 os << "preview false\n"
3645                                       "filename \"" << outname << "\"\n";
3646                                 if (t.cs() == "verbatiminput")
3647                                         preamble.registerAutomaticallyLoadedPackage("verbatim");
3648                         }
3649                         end_inset(os);
3650                 }
3651
3652                 else if (t.cs() == "bibliographystyle") {
3653                         // store new bibliographystyle
3654                         bibliographystyle = p.verbatim_item();
3655                         // If any other command than \bibliography and
3656                         // \nocite{*} follows, we need to output the style
3657                         // (because it might be used by that command).
3658                         // Otherwise, it will automatically be output by LyX.
3659                         p.pushPosition();
3660                         bool output = true;
3661                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3662                                 if (t2.cat() == catBegin)
3663                                         break;
3664                                 if (t2.cat() != catEscape)
3665                                         continue;
3666                                 if (t2.cs() == "nocite") {
3667                                         if (p.getArg('{', '}') == "*")
3668                                                 continue;
3669                                 } else if (t2.cs() == "bibliography")
3670                                         output = false;
3671                                 break;
3672                         }
3673                         p.popPosition();
3674                         if (output) {
3675                                 handle_ert(os,
3676                                         "\\bibliographystyle{" + bibliographystyle + '}',
3677                                         context);
3678                         }
3679                 }
3680
3681                 else if (t.cs() == "bibliography") {
3682                         context.check_layout(os);
3683                         begin_command_inset(os, "bibtex", "bibtex");
3684                         if (!btprint.empty()) {
3685                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3686                                 // clear the string because the next BibTeX inset can be without the
3687                                 // \nocite{*} option
3688                                 btprint.clear();
3689                         }
3690                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3691                         // Do we have a bibliographystyle set?
3692                         if (!bibliographystyle.empty())
3693                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
3694                         end_inset(os);
3695                 }
3696
3697                 else if (t.cs() == "parbox") {
3698                         // Test whether this is an outer box of a shaded box
3699                         p.pushPosition();
3700                         // swallow arguments
3701                         while (p.hasOpt()) {
3702                                 p.getArg('[', ']');
3703                                 p.skip_spaces(true);
3704                         }
3705                         p.getArg('{', '}');
3706                         p.skip_spaces(true);
3707                         // eat the '{'
3708                         if (p.next_token().cat() == catBegin)
3709                                 p.get_token();
3710                         p.skip_spaces(true);
3711                         Token to = p.get_token();
3712                         bool shaded = false;
3713                         if (to.asInput() == "\\begin") {
3714                                 p.skip_spaces(true);
3715                                 if (p.getArg('{', '}') == "shaded")
3716                                         shaded = true;
3717                         }
3718                         p.popPosition();
3719                         if (shaded) {
3720                                 parse_outer_box(p, os, FLAG_ITEM, outer,
3721                                                 context, "parbox", "shaded");
3722                         } else
3723                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3724                                           "", "", t.cs());
3725                 }
3726
3727                 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3728                          t.cs() == "shadowbox" || t.cs() == "doublebox")
3729                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3730
3731                 else if (t.cs() == "framebox") {
3732                         if (p.next_token().character() == '(') {
3733                                 //the syntax is: \framebox(x,y)[position]{content}
3734                                 string arg = t.asInput();
3735                                 arg += p.getFullParentheseArg();
3736                                 arg += p.getFullOpt();
3737                                 eat_whitespace(p, os, context, false);
3738                                 handle_ert(os, arg + '{', context);
3739                                 eat_whitespace(p, os, context, false);
3740                                 parse_text(p, os, FLAG_ITEM, outer, context);
3741                                 handle_ert(os, "}", context);
3742                         } else {
3743                                 string special = p.getFullOpt();
3744                                 special += p.getOpt();
3745                                 parse_outer_box(p, os, FLAG_ITEM, outer,
3746                                                 context, t.cs(), special);
3747                         }
3748                 }
3749
3750                 //\makebox() is part of the picture environment and different from \makebox{}
3751                 //\makebox{} will be parsed by parse_box
3752                 else if (t.cs() == "makebox") {
3753                         if (p.next_token().character() == '(') {
3754                                 //the syntax is: \makebox(x,y)[position]{content}
3755                                 string arg = t.asInput();
3756                                 arg += p.getFullParentheseArg();
3757                                 arg += p.getFullOpt();
3758                                 eat_whitespace(p, os, context, false);
3759                                 handle_ert(os, arg + '{', context);
3760                                 eat_whitespace(p, os, context, false);
3761                                 parse_text(p, os, FLAG_ITEM, outer, context);
3762                                 handle_ert(os, "}", context);
3763                         } else
3764                                 //the syntax is: \makebox[width][position]{content}
3765                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3766                                           "", "", t.cs());
3767                 }
3768
3769                 else if (t.cs() == "smallskip" ||
3770                          t.cs() == "medskip" ||
3771                          t.cs() == "bigskip" ||
3772                          t.cs() == "vfill") {
3773                         context.check_layout(os);
3774                         begin_inset(os, "VSpace ");
3775                         os << t.cs();
3776                         end_inset(os);
3777                         skip_spaces_braces(p);
3778                 }
3779
3780                 else if ((where = is_known(t.cs(), known_spaces))) {
3781                         context.check_layout(os);
3782                         begin_inset(os, "space ");
3783                         os << '\\' << known_coded_spaces[where - known_spaces]
3784                            << '\n';
3785                         end_inset(os);
3786                         // LaTeX swallows whitespace after all spaces except
3787                         // "\\,". We have to do that here, too, because LyX
3788                         // adds "{}" which would make the spaces significant.
3789                         if (t.cs() !=  ",")
3790                                 eat_whitespace(p, os, context, false);
3791                         // LyX adds "{}" after all spaces except "\\ " and
3792                         // "\\,", so we have to remove "{}".
3793                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
3794                         // remove the braces after "\\,", too.
3795                         if (t.cs() != " ")
3796                                 skip_braces(p);
3797                 }
3798
3799                 else if (t.cs() == "newpage" ||
3800                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
3801                          t.cs() == "clearpage" ||
3802                          t.cs() == "cleardoublepage") {
3803                         context.check_layout(os);
3804                         begin_inset(os, "Newpage ");
3805                         os << t.cs();
3806                         end_inset(os);
3807                         skip_spaces_braces(p);
3808                 }
3809
3810                 else if (t.cs() == "DeclareRobustCommand" ||
3811                          t.cs() == "DeclareRobustCommandx" ||
3812                          t.cs() == "newcommand" ||
3813                          t.cs() == "newcommandx" ||
3814                          t.cs() == "providecommand" ||
3815                          t.cs() == "providecommandx" ||
3816                          t.cs() == "renewcommand" ||
3817                          t.cs() == "renewcommandx") {
3818                         // DeclareRobustCommand, DeclareRobustCommandx,
3819                         // providecommand and providecommandx could be handled
3820                         // by parse_command(), but we need to call
3821                         // add_known_command() here.
3822                         string name = t.asInput();
3823                         if (p.next_token().asInput() == "*") {
3824                                 // Starred form. Eat '*'
3825                                 p.get_token();
3826                                 name += '*';
3827                         }
3828                         string const command = p.verbatim_item();
3829                         string const opt1 = p.getFullOpt();
3830                         string const opt2 = p.getFullOpt();
3831                         add_known_command(command, opt1, !opt2.empty());
3832                         string const ert = name + '{' + command + '}' +
3833                                            opt1 + opt2 +
3834                                            '{' + p.verbatim_item() + '}';
3835
3836                         if (t.cs() == "DeclareRobustCommand" ||
3837                             t.cs() == "DeclareRobustCommandx" ||
3838                             t.cs() == "providecommand" ||
3839                             t.cs() == "providecommandx" ||
3840                             name[name.length()-1] == '*')
3841                                 handle_ert(os, ert, context);
3842                         else {
3843                                 context.check_layout(os);
3844                                 begin_inset(os, "FormulaMacro");
3845                                 os << "\n" << ert;
3846                                 end_inset(os);
3847                         }
3848                 }
3849
3850                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3851                         // let could be handled by parse_command(),
3852                         // but we need to call add_known_command() here.
3853                         string ert = t.asInput();
3854                         string name;
3855                         p.skip_spaces();
3856                         if (p.next_token().cat() == catBegin) {
3857                                 name = p.verbatim_item();
3858                                 ert += '{' + name + '}';
3859                         } else {
3860                                 name = p.verbatim_item();
3861                                 ert += name;
3862                         }
3863                         string command;
3864                         p.skip_spaces();
3865                         if (p.next_token().cat() == catBegin) {
3866                                 command = p.verbatim_item();
3867                                 ert += '{' + command + '}';
3868                         } else {
3869                                 command = p.verbatim_item();
3870                                 ert += command;
3871                         }
3872                         // If command is known, make name known too, to parse
3873                         // its arguments correctly. For this reason we also
3874                         // have commands in syntax.default that are hardcoded.
3875                         CommandMap::iterator it = known_commands.find(command);
3876                         if (it != known_commands.end())
3877                                 known_commands[t.asInput()] = it->second;
3878                         handle_ert(os, ert, context);
3879                 }
3880
3881                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3882                         bool starred = false;
3883                         if (p.next_token().asInput() == "*") {
3884                                 p.get_token();
3885                                 starred = true;
3886                         }
3887                         string name = t.asInput();
3888                         string const length = p.verbatim_item();
3889                         string unit;
3890                         string valstring;
3891                         bool valid = splitLatexLength(length, valstring, unit);
3892                         bool known_hspace = false;
3893                         bool known_vspace = false;
3894                         bool known_unit = false;
3895                         double value;
3896                         if (valid) {
3897                                 istringstream iss(valstring);
3898                                 iss >> value;
3899                                 if (value == 1.0) {
3900                                         if (t.cs()[0] == 'h') {
3901                                                 if (unit == "\\fill") {
3902                                                         if (!starred) {
3903                                                                 unit = "";
3904                                                                 name = "\\hfill";
3905                                                         }
3906                                                         known_hspace = true;
3907                                                 }
3908                                         } else {
3909                                                 if (unit == "\\smallskipamount") {
3910                                                         unit = "smallskip";
3911                                                         known_vspace = true;
3912                                                 } else if (unit == "\\medskipamount") {
3913                                                         unit = "medskip";
3914                                                         known_vspace = true;
3915                                                 } else if (unit == "\\bigskipamount") {
3916                                                         unit = "bigskip";
3917                                                         known_vspace = true;
3918                                                 } else if (unit == "\\fill") {
3919                                                         unit = "vfill";
3920                                                         known_vspace = true;
3921                                                 }
3922                                         }
3923                                 }
3924                                 if (!known_hspace && !known_vspace) {
3925                                         switch (unitFromString(unit)) {
3926                                         case Length::SP:
3927                                         case Length::PT:
3928                                         case Length::BP:
3929                                         case Length::DD:
3930                                         case Length::MM:
3931                                         case Length::PC:
3932                                         case Length::CC:
3933                                         case Length::CM:
3934                                         case Length::IN:
3935                                         case Length::EX:
3936                                         case Length::EM:
3937                                         case Length::MU:
3938                                                 known_unit = true;
3939                                                 break;
3940                                         default:
3941                                                 break;
3942                                         }
3943                                 }
3944                         }
3945
3946                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3947                                 // Literal horizontal length or known variable
3948                                 context.check_layout(os);
3949                                 begin_inset(os, "space ");
3950                                 os << name;
3951                                 if (starred)
3952                                         os << '*';
3953                                 os << '{';
3954                                 if (known_hspace)
3955                                         os << unit;
3956                                 os << "}";
3957                                 if (known_unit && !known_hspace)
3958                                         os << "\n\\length "
3959                                            << translate_len(length);
3960                                 end_inset(os);
3961                         } else if (known_unit || known_vspace) {
3962                                 // Literal vertical length or known variable
3963                                 context.check_layout(os);
3964                                 begin_inset(os, "VSpace ");
3965                                 if (known_unit)
3966                                         os << value;
3967                                 os << unit;
3968                                 if (starred)
3969                                         os << '*';
3970                                 end_inset(os);
3971                         } else {
3972                                 // LyX can't handle other length variables in Inset VSpace/space
3973                                 if (starred)
3974                                         name += '*';
3975                                 if (valid) {
3976                                         if (value == 1.0)
3977                                                 handle_ert(os, name + '{' + unit + '}', context);
3978                                         else if (value == -1.0)
3979                                                 handle_ert(os, name + "{-" + unit + '}', context);
3980                                         else
3981                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
3982                                 } else
3983                                         handle_ert(os, name + '{' + length + '}', context);
3984                         }
3985                 }
3986
3987                 // The single '=' is meant here.
3988                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3989                         p.skip_spaces();
3990                         context.check_layout(os);
3991                         begin_inset(os, "Flex ");
3992                         os << to_utf8(newinsetlayout->name()) << '\n'
3993                            << "status collapsed\n";
3994                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3995                         end_inset(os);
3996                 }
3997
3998                 else if (t.cs() == "includepdf") {
3999                         p.skip_spaces();
4000                         string const arg = p.getArg('[', ']');
4001                         map<string, string> opts;
4002                         vector<string> keys;
4003                         split_map(arg, opts, keys);
4004                         string name = normalize_filename(p.verbatim_item());
4005                         string const path = getMasterFilePath();
4006                         // We want to preserve relative / absolute filenames,
4007                         // therefore path is only used for testing
4008                         if (!makeAbsPath(name, path).exists()) {
4009                                 // The file extension is probably missing.
4010                                 // Now try to find it out.
4011                                 char const * const pdfpages_format[] = {"pdf", 0};
4012                                 string const pdftex_name =
4013                                         find_file(name, path, pdfpages_format);
4014                                 if (!pdftex_name.empty()) {
4015                                         name = pdftex_name;
4016                                         pdflatex = true;
4017                                 }
4018                         }
4019                         if (makeAbsPath(name, path).exists())
4020                                 fix_relative_filename(name);
4021                         else
4022                                 cerr << "Warning: Could not find file '"
4023                                      << name << "'." << endl;
4024                         // write output
4025                         context.check_layout(os);
4026                         begin_inset(os, "External\n\ttemplate ");
4027                         os << "PDFPages\n\tfilename "
4028                            << name << "\n";
4029                         // parse the options
4030                         if (opts.find("pages") != opts.end())
4031                                 os << "\textra LaTeX \"pages="
4032                                    << opts["pages"] << "\"\n";
4033                         if (opts.find("angle") != opts.end())
4034                                 os << "\trotateAngle "
4035                                    << opts["angle"] << '\n';
4036                         if (opts.find("origin") != opts.end()) {
4037                                 ostringstream ss;
4038                                 string const opt = opts["origin"];
4039                                 if (opt == "tl") ss << "topleft";
4040                                 if (opt == "bl") ss << "bottomleft";
4041                                 if (opt == "Bl") ss << "baselineleft";
4042                                 if (opt == "c") ss << "center";
4043                                 if (opt == "tc") ss << "topcenter";
4044                                 if (opt == "bc") ss << "bottomcenter";
4045                                 if (opt == "Bc") ss << "baselinecenter";
4046                                 if (opt == "tr") ss << "topright";
4047                                 if (opt == "br") ss << "bottomright";
4048                                 if (opt == "Br") ss << "baselineright";
4049                                 if (!ss.str().empty())
4050                                         os << "\trotateOrigin " << ss.str() << '\n';
4051                                 else
4052                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4053                         }
4054                         if (opts.find("width") != opts.end())
4055                                 os << "\twidth "
4056                                    << translate_len(opts["width"]) << '\n';
4057                         if (opts.find("height") != opts.end())
4058                                 os << "\theight "
4059                                    << translate_len(opts["height"]) << '\n';
4060                         if (opts.find("keepaspectratio") != opts.end())
4061                                 os << "\tkeepAspectRatio\n";
4062                         end_inset(os);
4063                         context.check_layout(os);
4064                         registerExternalTemplatePackages("PDFPages");
4065                 }
4066
4067                 else if (t.cs() == "loadgame") {
4068                         p.skip_spaces();
4069                         string name = normalize_filename(p.verbatim_item());
4070                         string const path = getMasterFilePath();
4071                         // We want to preserve relative / absolute filenames,
4072                         // therefore path is only used for testing
4073                         if (!makeAbsPath(name, path).exists()) {
4074                                 // The file extension is probably missing.
4075                                 // Now try to find it out.
4076                                 char const * const lyxskak_format[] = {"fen", 0};
4077                                 string const lyxskak_name =
4078                                         find_file(name, path, lyxskak_format);
4079                                 if (!lyxskak_name.empty())
4080                                         name = lyxskak_name;
4081                         }
4082                         if (makeAbsPath(name, path).exists())
4083                                 fix_relative_filename(name);
4084                         else
4085                                 cerr << "Warning: Could not find file '"
4086                                      << name << "'." << endl;
4087                         context.check_layout(os);
4088                         begin_inset(os, "External\n\ttemplate ");
4089                         os << "ChessDiagram\n\tfilename "
4090                            << name << "\n";
4091                         end_inset(os);
4092                         context.check_layout(os);
4093                         // after a \loadgame follows a \showboard
4094                         if (p.get_token().asInput() == "showboard")
4095                                 p.get_token();
4096                         registerExternalTemplatePackages("ChessDiagram");
4097                 }
4098
4099                 else {
4100                         // try to see whether the string is in unicodesymbols
4101                         // Only use text mode commands, since we are in text mode here,
4102                         // and math commands may be invalid (bug 6797)
4103                         docstring rem;
4104                         set<string> req;
4105                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4106                                                                  Encodings::TEXT_CMD, rem, &req);
4107                         if (!s.empty()) {
4108                                 if (!rem.empty())
4109                                         cerr << "When parsing " << t.cs()
4110                                              << ", result is " << to_utf8(s)
4111                                              << "+" << to_utf8(rem) << endl;
4112                                 context.check_layout(os);
4113                                 os << to_utf8(s);
4114                                 skip_spaces_braces(p);
4115                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
4116                                         preamble.registerAutomaticallyLoadedPackage(*it);
4117                         }
4118                         //cerr << "#: " << t << " mode: " << mode << endl;
4119                         // heuristic: read up to next non-nested space
4120                         /*
4121                         string s = t.asInput();
4122                         string z = p.verbatim_item();
4123                         while (p.good() && z != " " && z.size()) {
4124                                 //cerr << "read: " << z << endl;
4125                                 s += z;
4126                                 z = p.verbatim_item();
4127                         }
4128                         cerr << "found ERT: " << s << endl;
4129                         handle_ert(os, s + ' ', context);
4130                         */
4131                         else {
4132                                 string name = t.asInput();
4133                                 if (p.next_token().asInput() == "*") {
4134                                         // Starred commands like \vspace*{}
4135                                         p.get_token();  // Eat '*'
4136                                         name += '*';
4137                                 }
4138                                 if (!parse_command(name, p, os, outer, context))
4139                                         handle_ert(os, name, context);
4140                         }
4141                 }
4142
4143                 if (flags & FLAG_LEAVE) {
4144                         flags &= ~FLAG_LEAVE;
4145                         break;
4146                 }
4147         }
4148 }
4149
4150 // }])
4151
4152
4153 } // namespace lyx