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