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