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