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