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