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