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