]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
More no-math fonts
[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         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1843                                    from_utf8(getParentFilePath())));
1844 }
1845
1846
1847 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1848 void parse_noweb(Parser & p, ostream & os, Context & context)
1849 {
1850         // assemble the rest of the keyword
1851         string name("<<");
1852         bool scrap = false;
1853         while (p.good()) {
1854                 Token const & t = p.get_token();
1855                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1856                         name += ">>";
1857                         p.get_token();
1858                         scrap = (p.good() && p.next_token().asInput() == "=");
1859                         if (scrap)
1860                                 name += p.get_token().asInput();
1861                         break;
1862                 }
1863                 name += t.asInput();
1864         }
1865
1866         if (!scrap || !context.new_layout_allowed ||
1867             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1868                 cerr << "Warning: Could not interpret '" << name
1869                      << "'. Ignoring it." << endl;
1870                 return;
1871         }
1872
1873         // We use new_paragraph instead of check_end_layout because the stuff
1874         // following the noweb chunk needs to start with a \begin_layout.
1875         // This may create a new paragraph even if there was none in the
1876         // noweb file, but the alternative is an invalid LyX file. Since
1877         // noweb code chunks are implemented with a layout style in LyX they
1878         // always must be in an own paragraph.
1879         context.new_paragraph(os);
1880         Context newcontext(true, context.textclass,
1881                 &context.textclass[from_ascii("Scrap")]);
1882         newcontext.check_layout(os);
1883         os << name;
1884         while (p.good()) {
1885                 Token const & t = p.get_token();
1886                 // We abuse the parser a bit, because this is no TeX syntax
1887                 // at all.
1888                 if (t.cat() == catEscape)
1889                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1890                 else {
1891                         ostringstream oss;
1892                         Context tmp(false, context.textclass,
1893                                     &context.textclass[from_ascii("Scrap")]);
1894                         tmp.need_end_layout = true;
1895                         tmp.check_layout(oss);
1896                         os << subst(t.asInput(), "\n", oss.str());
1897                 }
1898                 // The scrap chunk is ended by an @ at the beginning of a line.
1899                 // After the @ the line may contain a comment and/or
1900                 // whitespace, but nothing else.
1901                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1902                     (p.next_token().cat() == catSpace ||
1903                      p.next_token().cat() == catNewline ||
1904                      p.next_token().cat() == catComment)) {
1905                         while (p.good() && p.next_token().cat() == catSpace)
1906                                 os << p.get_token().asInput();
1907                         if (p.next_token().cat() == catComment)
1908                                 // The comment includes a final '\n'
1909                                 os << p.get_token().asInput();
1910                         else {
1911                                 if (p.next_token().cat() == catNewline)
1912                                         p.get_token();
1913                                 os << '\n';
1914                         }
1915                         break;
1916                 }
1917         }
1918         newcontext.check_end_layout(os);
1919 }
1920
1921
1922 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1923 bool is_macro(Parser & p)
1924 {
1925         Token first = p.curr_token();
1926         if (first.cat() != catEscape || !p.good())
1927                 return false;
1928         if (first.cs() == "def")
1929                 return true;
1930         if (first.cs() != "global" && first.cs() != "long")
1931                 return false;
1932         Token second = p.get_token();
1933         int pos = 1;
1934         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1935                second.cat() == catNewline || second.cat() == catComment)) {
1936                 second = p.get_token();
1937                 pos++;
1938         }
1939         bool secondvalid = second.cat() == catEscape;
1940         Token third;
1941         bool thirdvalid = false;
1942         if (p.good() && first.cs() == "global" && secondvalid &&
1943             second.cs() == "long") {
1944                 third = p.get_token();
1945                 pos++;
1946                 while (p.good() && !p.isParagraph() &&
1947                        (third.cat() == catSpace ||
1948                         third.cat() == catNewline ||
1949                         third.cat() == catComment)) {
1950                         third = p.get_token();
1951                         pos++;
1952                 }
1953                 thirdvalid = third.cat() == catEscape;
1954         }
1955         for (int i = 0; i < pos; ++i)
1956                 p.putback();
1957         if (!secondvalid)
1958                 return false;
1959         if (!thirdvalid)
1960                 return (first.cs() == "global" || first.cs() == "long") &&
1961                        second.cs() == "def";
1962         return first.cs() == "global" && second.cs() == "long" &&
1963                third.cs() == "def";
1964 }
1965
1966
1967 /// Parse a macro definition (assumes that is_macro() returned true)
1968 void parse_macro(Parser & p, ostream & os, Context & context)
1969 {
1970         context.check_layout(os);
1971         Token first = p.curr_token();
1972         Token second;
1973         Token third;
1974         string command = first.asInput();
1975         if (first.cs() != "def") {
1976                 p.get_token();
1977                 eat_whitespace(p, os, context, false);
1978                 second = p.curr_token();
1979                 command += second.asInput();
1980                 if (second.cs() != "def") {
1981                         p.get_token();
1982                         eat_whitespace(p, os, context, false);
1983                         third = p.curr_token();
1984                         command += third.asInput();
1985                 }
1986         }
1987         eat_whitespace(p, os, context, false);
1988         string const name = p.get_token().cs();
1989         eat_whitespace(p, os, context, false);
1990
1991         // parameter text
1992         bool simple = true;
1993         string paramtext;
1994         int arity = 0;
1995         while (p.next_token().cat() != catBegin) {
1996                 if (p.next_token().cat() == catParameter) {
1997                         // # found
1998                         p.get_token();
1999                         paramtext += "#";
2000
2001                         // followed by number?
2002                         if (p.next_token().cat() == catOther) {
2003                                 char c = p.getChar();
2004                                 paramtext += c;
2005                                 // number = current arity + 1?
2006                                 if (c == arity + '0' + 1)
2007                                         ++arity;
2008                                 else
2009                                         simple = false;
2010                         } else
2011                                 paramtext += p.get_token().cs();
2012                 } else {
2013                         paramtext += p.get_token().cs();
2014                         simple = false;
2015                 }
2016         }
2017
2018         // only output simple (i.e. compatible) macro as FormulaMacros
2019         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2020         if (simple) {
2021                 context.check_layout(os);
2022                 begin_inset(os, "FormulaMacro");
2023                 os << "\n\\def" << ert;
2024                 end_inset(os);
2025         } else
2026                 handle_ert(os, command + ert, context);
2027 }
2028
2029
2030 void registerExternalTemplatePackages(string const & name)
2031 {
2032         external::TemplateManager const & etm = external::TemplateManager::get();
2033         external::Template const * const et = etm.getTemplateByName(name);
2034         if (!et)
2035                 return;
2036         external::Template::Formats::const_iterator cit = et->formats.end();
2037         if (pdflatex)
2038                 cit = et->formats.find("PDFLaTeX");
2039         if (cit == et->formats.end())
2040                 // If the template has not specified a PDFLaTeX output,
2041                 // we try the LaTeX format.
2042                 cit = et->formats.find("LaTeX");
2043         if (cit == et->formats.end())
2044                 return;
2045         vector<string>::const_iterator qit = cit->second.requirements.begin();
2046         vector<string>::const_iterator qend = cit->second.requirements.end();
2047         for (; qit != qend; ++qit)
2048                 preamble.registerAutomaticallyLoadedPackage(*qit);
2049 }
2050
2051 } // anonymous namespace
2052
2053
2054 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2055                 Context & context)
2056 {
2057         Layout const * newlayout = 0;
2058         InsetLayout const * newinsetlayout = 0;
2059         char const * const * where = 0;
2060         // Store the latest bibliographystyle and nocite{*} option
2061         // (needed for bibtex inset)
2062         string btprint;
2063         string bibliographystyle = "default";
2064         bool const use_natbib = preamble.isPackageUsed("natbib");
2065         bool const use_jurabib = preamble.isPackageUsed("jurabib");
2066         string last_env;
2067         while (p.good()) {
2068                 Token const & t = p.get_token();
2069
2070         // it is impossible to determine the correct document language if CJK is used.
2071         // Therefore write a note at the beginning of the document
2072         if (have_CJK) {
2073                 context.check_layout(os);
2074                 begin_inset(os, "Note Note\n");
2075                 os << "status open\n\\begin_layout Plain Layout\n"
2076                    << "\\series bold\n"
2077                    << "Important information:\n"
2078                    << "\\end_layout\n\n"
2079                    << "\\begin_layout Plain Layout\n"
2080                    << "This document contains text in Chinese, Japanese or Korean.\n"
2081                    << " It was therefore impossible for tex2lyx to set the correct document langue for your document."
2082                    << " Please set the language manually in the document settings.\n"
2083                    << "\\end_layout\n";
2084                 end_inset(os);
2085                 have_CJK = false;
2086         }
2087
2088         // it is impossible to determine the correct encoding for non-CJK Japanese.
2089         // Therefore write a note at the beginning of the document
2090         if (is_nonCJKJapanese) {
2091                 context.check_layout(os);
2092                 begin_inset(os, "Note Note\n");
2093                 os << "status open\n\\begin_layout Plain Layout\n"
2094                    << "\\series bold\n"
2095                    << "Important information:\n"
2096                    << "\\end_layout\n\n"
2097                    << "\\begin_layout Plain Layout\n"
2098                    << "This document is in Japanese (non-CJK).\n"
2099                    << " It was therefore impossible for tex2lyx to determine the correct encoding."
2100                    << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2101                    << " encoding in the document settings.\n"
2102                    << "\\end_layout\n";
2103                 end_inset(os);
2104                 is_nonCJKJapanese = false;
2105         }
2106
2107 #ifdef FILEDEBUG
2108                 debugToken(cerr, t, flags);
2109 #endif
2110
2111                 if (flags & FLAG_ITEM) {
2112                         if (t.cat() == catSpace)
2113                                 continue;
2114
2115                         flags &= ~FLAG_ITEM;
2116                         if (t.cat() == catBegin) {
2117                                 // skip the brace and collect everything to the next matching
2118                                 // closing brace
2119                                 flags |= FLAG_BRACE_LAST;
2120                                 continue;
2121                         }
2122
2123                         // handle only this single token, leave the loop if done
2124                         flags |= FLAG_LEAVE;
2125                 }
2126
2127                 if (t.cat() != catEscape && t.character() == ']' &&
2128                     (flags & FLAG_BRACK_LAST))
2129                         return;
2130                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2131                         return;
2132
2133                 // If there is anything between \end{env} and \begin{env} we
2134                 // don't need to output a separator.
2135                 if (t.cat() != catSpace && t.cat() != catNewline &&
2136                     t.asInput() != "\\begin")
2137                         last_env = "";
2138
2139                 //
2140                 // cat codes
2141                 //
2142                 if (t.cat() == catMath) {
2143                         // we are inside some text mode thingy, so opening new math is allowed
2144                         context.check_layout(os);
2145                         begin_inset(os, "Formula ");
2146                         Token const & n = p.get_token();
2147                         bool const display(n.cat() == catMath && outer);
2148                         if (display) {
2149                                 // TeX's $$...$$ syntax for displayed math
2150                                 os << "\\[";
2151                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2152                                 os << "\\]";
2153                                 p.get_token(); // skip the second '$' token
2154                         } else {
2155                                 // simple $...$  stuff
2156                                 p.putback();
2157                                 os << '$';
2158                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2159                                 os << '$';
2160                         }
2161                         end_inset(os);
2162                         if (display) {
2163                                 // Prevent the conversion of a line break to a
2164                                 // space (bug 7668). This does not change the
2165                                 // output, but looks ugly in LyX.
2166                                 eat_whitespace(p, os, context, false);
2167                         }
2168                 }
2169
2170                 else if (t.cat() == catSuper || t.cat() == catSub)
2171                         cerr << "catcode " << t << " illegal in text mode\n";
2172
2173                 // Basic support for english quotes. This should be
2174                 // extended to other quotes, but is not so easy (a
2175                 // left english quote is the same as a right german
2176                 // quote...)
2177                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2178                         context.check_layout(os);
2179                         begin_inset(os, "Quotes ");
2180                         os << "eld";
2181                         end_inset(os);
2182                         p.get_token();
2183                         skip_braces(p);
2184                 }
2185                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2186                         context.check_layout(os);
2187                         begin_inset(os, "Quotes ");
2188                         os << "erd";
2189                         end_inset(os);
2190                         p.get_token();
2191                         skip_braces(p);
2192                 }
2193
2194                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2195                         context.check_layout(os);
2196                         begin_inset(os, "Quotes ");
2197                         os << "ald";
2198                         end_inset(os);
2199                         p.get_token();
2200                         skip_braces(p);
2201                 }
2202
2203                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2204                         context.check_layout(os);
2205                         begin_inset(os, "Quotes ");
2206                         os << "ard";
2207                         end_inset(os);
2208                         p.get_token();
2209                         skip_braces(p);
2210                 }
2211
2212                 else if (t.asInput() == "<"
2213                          && p.next_token().asInput() == "<" && noweb_mode) {
2214                         p.get_token();
2215                         parse_noweb(p, os, context);
2216                 }
2217
2218                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2219                         check_space(p, os, context);
2220
2221                 else if (t.character() == '[' && noweb_mode &&
2222                          p.next_token().character() == '[') {
2223                         // These can contain underscores
2224                         p.putback();
2225                         string const s = p.getFullOpt() + ']';
2226                         if (p.next_token().character() == ']')
2227                                 p.get_token();
2228                         else
2229                                 cerr << "Warning: Inserting missing ']' in '"
2230                                      << s << "'." << endl;
2231                         handle_ert(os, s, context);
2232                 }
2233
2234                 else if (t.cat() == catLetter) {
2235                         context.check_layout(os);
2236                         // Workaround for bug 4752.
2237                         // FIXME: This whole code block needs to be removed
2238                         //        when the bug is fixed and tex2lyx produces
2239                         //        the updated file format.
2240                         // The replacement algorithm in LyX is so stupid that
2241                         // it even translates a phrase if it is part of a word.
2242                         bool handled = false;
2243                         for (int const * l = known_phrase_lengths; *l; ++l) {
2244                                 string phrase = t.cs();
2245                                 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2246                                         phrase += p.get_token().cs();
2247                                 if (is_known(phrase, known_coded_phrases)) {
2248                                         handle_ert(os, phrase, context);
2249                                         handled = true;
2250                                         break;
2251                                 } else {
2252                                         for (size_t i = 1; i < phrase.length(); ++i)
2253                                                 p.putback();
2254                                 }
2255                         }
2256                         if (!handled)
2257                                 os << t.cs();
2258                 }
2259
2260                 else if (t.cat() == catOther ||
2261                                t.cat() == catAlign ||
2262                                t.cat() == catParameter) {
2263                         // This translates "&" to "\\&" which may be wrong...
2264                         context.check_layout(os);
2265                         os << t.cs();
2266                 }
2267
2268                 else if (p.isParagraph()) {
2269                         if (context.new_layout_allowed)
2270                                 context.new_paragraph(os);
2271                         else
2272                                 handle_ert(os, "\\par ", context);
2273                         eat_whitespace(p, os, context, true);
2274                 }
2275
2276                 else if (t.cat() == catActive) {
2277                         context.check_layout(os);
2278                         if (t.character() == '~') {
2279                                 if (context.layout->free_spacing)
2280                                         os << ' ';
2281                                 else {
2282                                         begin_inset(os, "space ~\n");
2283                                         end_inset(os);
2284                                 }
2285                         } else
2286                                 os << t.cs();
2287                 }
2288
2289                 else if (t.cat() == catBegin) {
2290                         Token const next = p.next_token();
2291                         Token const end = p.next_next_token();
2292                         if (next.cat() == catEnd) {
2293                         // {}
2294                         Token const prev = p.prev_token();
2295                         p.get_token();
2296                         if (p.next_token().character() == '`' ||
2297                             (prev.character() == '-' &&
2298                              p.next_token().character() == '-'))
2299                                 ; // ignore it in {}`` or -{}-
2300                         else
2301                                 handle_ert(os, "{}", context);
2302                         } else if (next.cat() == catEscape &&
2303                                    is_known(next.cs(), known_quotes) &&
2304                                    end.cat() == catEnd) {
2305                                 // Something like {\textquoteright} (e.g.
2306                                 // from writer2latex). LyX writes
2307                                 // \textquoteright{}, so we may skip the
2308                                 // braces here for better readability.
2309                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2310                                                    outer, context);
2311                         } else {
2312                         context.check_layout(os);
2313                         // special handling of font attribute changes
2314                         Token const prev = p.prev_token();
2315                         TeXFont const oldFont = context.font;
2316                         if (next.character() == '[' ||
2317                             next.character() == ']' ||
2318                             next.character() == '*') {
2319                                 p.get_token();
2320                                 if (p.next_token().cat() == catEnd) {
2321                                         os << next.cs();
2322                                         p.get_token();
2323                                 } else {
2324                                         p.putback();
2325                                         handle_ert(os, "{", context);
2326                                         parse_text_snippet(p, os,
2327                                                         FLAG_BRACE_LAST,
2328                                                         outer, context);
2329                                         handle_ert(os, "}", context);
2330                                 }
2331                         } else if (! context.new_layout_allowed) {
2332                                 handle_ert(os, "{", context);
2333                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2334                                                    outer, context);
2335                                 handle_ert(os, "}", context);
2336                         } else if (is_known(next.cs(), known_sizes)) {
2337                                 // next will change the size, so we must
2338                                 // reset it here
2339                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2340                                                    outer, context);
2341                                 if (!context.atParagraphStart())
2342                                         os << "\n\\size "
2343                                            << context.font.size << "\n";
2344                         } else if (is_known(next.cs(), known_font_families)) {
2345                                 // next will change the font family, so we
2346                                 // must reset it here
2347                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2348                                                    outer, context);
2349                                 if (!context.atParagraphStart())
2350                                         os << "\n\\family "
2351                                            << context.font.family << "\n";
2352                         } else if (is_known(next.cs(), known_font_series)) {
2353                                 // next will change the font series, so we
2354                                 // must reset it here
2355                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2356                                                    outer, context);
2357                                 if (!context.atParagraphStart())
2358                                         os << "\n\\series "
2359                                            << context.font.series << "\n";
2360                         } else if (is_known(next.cs(), known_font_shapes)) {
2361                                 // next will change the font shape, so we
2362                                 // must reset it here
2363                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2364                                                    outer, context);
2365                                 if (!context.atParagraphStart())
2366                                         os << "\n\\shape "
2367                                            << context.font.shape << "\n";
2368                         } else if (is_known(next.cs(), known_old_font_families) ||
2369                                    is_known(next.cs(), known_old_font_series) ||
2370                                    is_known(next.cs(), known_old_font_shapes)) {
2371                                 // next will change the font family, series
2372                                 // and shape, so we must reset it here
2373                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2374                                                    outer, context);
2375                                 if (!context.atParagraphStart())
2376                                         os <<  "\n\\family "
2377                                            << context.font.family
2378                                            << "\n\\series "
2379                                            << context.font.series
2380                                            << "\n\\shape "
2381                                            << context.font.shape << "\n";
2382                         } else {
2383                                 handle_ert(os, "{", context);
2384                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2385                                                    outer, context);
2386                                 handle_ert(os, "}", context);
2387                                 }
2388                         }
2389                 }
2390
2391                 else if (t.cat() == catEnd) {
2392                         if (flags & FLAG_BRACE_LAST) {
2393                                 return;
2394                         }
2395                         cerr << "stray '}' in text\n";
2396                         handle_ert(os, "}", context);
2397                 }
2398
2399                 else if (t.cat() == catComment)
2400                         parse_comment(p, os, t, context);
2401
2402                 //
2403                 // control sequences
2404                 //
2405
2406                 else if (t.cs() == "(") {
2407                         context.check_layout(os);
2408                         begin_inset(os, "Formula");
2409                         os << " \\(";
2410                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2411                         os << "\\)";
2412                         end_inset(os);
2413                 }
2414
2415                 else if (t.cs() == "[") {
2416                         context.check_layout(os);
2417                         begin_inset(os, "Formula");
2418                         os << " \\[";
2419                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2420                         os << "\\]";
2421                         end_inset(os);
2422                         // Prevent the conversion of a line break to a space
2423                         // (bug 7668). This does not change the output, but
2424                         // looks ugly in LyX.
2425                         eat_whitespace(p, os, context, false);
2426                 }
2427
2428                 else if (t.cs() == "begin")
2429                         parse_environment(p, os, outer, last_env,
2430                                           context);
2431
2432                 else if (t.cs() == "end") {
2433                         if (flags & FLAG_END) {
2434                                 // eat environment name
2435                                 string const name = p.getArg('{', '}');
2436                                 if (name != active_environment())
2437                                         cerr << "\\end{" + name + "} does not match \\begin{"
2438                                                 + active_environment() + "}\n";
2439                                 return;
2440                         }
2441                         p.error("found 'end' unexpectedly");
2442                 }
2443
2444                 else if (t.cs() == "item") {
2445                         string s;
2446                         bool const optarg = p.hasOpt();
2447                         if (optarg) {
2448                                 // FIXME: This swallows comments, but we cannot use
2449                                 //        eat_whitespace() since we must not output
2450                                 //        anything before the item.
2451                                 p.skip_spaces(true);
2452                                 s = p.verbatimOption();
2453                         } else
2454                                 p.skip_spaces(false);
2455                         context.set_item();
2456                         context.check_layout(os);
2457                         if (context.has_item) {
2458                                 // An item in an unknown list-like environment
2459                                 // FIXME: Do this in check_layout()!
2460                                 context.has_item = false;
2461                                 if (optarg)
2462                                         handle_ert(os, "\\item", context);
2463                                 else
2464                                         handle_ert(os, "\\item ", context);
2465                         }
2466                         if (optarg) {
2467                                 if (context.layout->labeltype != LABEL_MANUAL) {
2468                                         // LyX does not support \item[\mybullet]
2469                                         // in itemize environments
2470                                         Parser p2(s + ']');
2471                                         os << parse_text_snippet(p2,
2472                                                 FLAG_BRACK_LAST, outer, context);
2473                                 } else if (!s.empty()) {
2474                                         // LyX adds braces around the argument,
2475                                         // so we need to remove them here.
2476                                         if (s.size() > 2 && s[0] == '{' &&
2477                                             s[s.size()-1] == '}')
2478                                                 s = s.substr(1, s.size()-2);
2479                                         // If the argument contains a space we
2480                                         // must put it into ERT: Otherwise LyX
2481                                         // would misinterpret the space as
2482                                         // item delimiter (bug 7663)
2483                                         if (contains(s, ' ')) {
2484                                                 handle_ert(os, s, context);
2485                                         } else {
2486                                                 Parser p2(s + ']');
2487                                                 os << parse_text_snippet(p2,
2488                                                         FLAG_BRACK_LAST,
2489                                                         outer, context);
2490                                         }
2491                                         // The space is needed to separate the
2492                                         // item from the rest of the sentence.
2493                                         os << ' ';
2494                                         eat_whitespace(p, os, context, false);
2495                                 }
2496                         }
2497                 }
2498
2499                 else if (t.cs() == "bibitem") {
2500                         context.set_item();
2501                         context.check_layout(os);
2502                         eat_whitespace(p, os, context, false);
2503                         string label = convert_command_inset_arg(p.verbatimOption());
2504                         string key = convert_command_inset_arg(p.verbatim_item());
2505                         if (contains(label, '\\') || contains(key, '\\')) {
2506                                 // LyX can't handle LaTeX commands in labels or keys
2507                                 handle_ert(os, t.asInput() + '[' + label +
2508                                                "]{" + p.verbatim_item() + '}',
2509                                            context);
2510                         } else {
2511                                 begin_command_inset(os, "bibitem", "bibitem");
2512                                 os << "label \"" << label << "\"\n"
2513                                       "key \"" << key << "\"\n";
2514                                 end_inset(os);
2515                         }
2516                 }
2517
2518                 else if (is_macro(p)) {
2519                         // catch the case of \def\inputGnumericTable
2520                         bool macro = true;
2521                         if (t.cs() == "def") {
2522                                 Token second = p.next_token();
2523                                 if (second.cs() == "inputGnumericTable") {
2524                                         p.pushPosition();
2525                                         p.get_token();
2526                                         skip_braces(p);
2527                                         Token third = p.get_token();
2528                                         p.popPosition();
2529                                         if (third.cs() == "input") {
2530                                                 p.get_token();
2531                                                 skip_braces(p);
2532                                                 p.get_token();
2533                                                 string name = normalize_filename(p.verbatim_item());
2534                                                 string const path = getMasterFilePath();
2535                                                 // We want to preserve relative / absolute filenames,
2536                                                 // therefore path is only used for testing
2537                                                 // The file extension is in every case ".tex".
2538                                                 // So we need to remove this extension and check for
2539                                                 // the original one.
2540                                                 name = removeExtension(name);
2541                                                 if (!makeAbsPath(name, path).exists()) {
2542                                                         char const * const Gnumeric_formats[] = {"gnumeric",
2543                                                                 "ods", "xls", 0};
2544                                                         string const Gnumeric_name =
2545                                                                 find_file(name, path, Gnumeric_formats);
2546                                                         if (!Gnumeric_name.empty())
2547                                                                 name = Gnumeric_name;
2548                                                 }
2549                                                 if (makeAbsPath(name, path).exists())
2550                                                         fix_relative_filename(name);
2551                                                 else
2552                                                         cerr << "Warning: Could not find file '"
2553                                                              << name << "'." << endl;
2554                                                 context.check_layout(os);
2555                                                 begin_inset(os, "External\n\ttemplate ");
2556                                                 os << "GnumericSpreadsheet\n\tfilename "
2557                                                    << name << "\n";
2558                                                 end_inset(os);
2559                                                 context.check_layout(os);
2560                                                 macro = false;
2561                                                 // register the packages that are automatically reloaded
2562                                                 // by the Gnumeric template
2563                                                 registerExternalTemplatePackages("GnumericSpreadsheet");
2564                                         }
2565                                 }
2566                         }
2567                         if (macro)
2568                                 parse_macro(p, os, context);
2569                 }
2570
2571                 else if (t.cs() == "noindent") {
2572                         p.skip_spaces();
2573                         context.add_par_extra_stuff("\\noindent\n");
2574                 }
2575
2576                 else if (t.cs() == "appendix") {
2577                         context.add_par_extra_stuff("\\start_of_appendix\n");
2578                         // We need to start a new paragraph. Otherwise the
2579                         // appendix in 'bla\appendix\chapter{' would start
2580                         // too late.
2581                         context.new_paragraph(os);
2582                         // We need to make sure that the paragraph is
2583                         // generated even if it is empty. Otherwise the
2584                         // appendix in '\par\appendix\par\chapter{' would
2585                         // start too late.
2586                         context.check_layout(os);
2587                         // FIXME: This is a hack to prevent paragraph
2588                         // deletion if it is empty. Handle this better!
2589                         handle_comment(os,
2590                                 "%dummy comment inserted by tex2lyx to "
2591                                 "ensure that this paragraph is not empty",
2592                                 context);
2593                         // Both measures above may generate an additional
2594                         // empty paragraph, but that does not hurt, because
2595                         // whitespace does not matter here.
2596                         eat_whitespace(p, os, context, true);
2597                 }
2598
2599                 // Must catch empty dates before findLayout is called below
2600                 else if (t.cs() == "date") {
2601                         eat_whitespace(p, os, context, false);
2602                         p.pushPosition();
2603                         string const date = p.verbatim_item();
2604                         p.popPosition();
2605                         if (date.empty()) {
2606                                 preamble.suppressDate(true);
2607                                 p.verbatim_item();
2608                         } else {
2609                                 preamble.suppressDate(false);
2610                                 if (context.new_layout_allowed &&
2611                                     (newlayout = findLayout(context.textclass,
2612                                                             t.cs(), true))) {
2613                                         // write the layout
2614                                         output_command_layout(os, p, outer,
2615                                                         context, newlayout);
2616                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2617                                         if (!preamble.titleLayoutFound())
2618                                                 preamble.titleLayoutFound(newlayout->intitle);
2619                                         set<string> const & req = newlayout->requires();
2620                                         set<string>::const_iterator it = req.begin();
2621                                         set<string>::const_iterator en = req.end();
2622                                         for (; it != en; ++it)
2623                                                 preamble.registerAutomaticallyLoadedPackage(*it);
2624                                 } else
2625                                         handle_ert(os,
2626                                                 "\\date{" + p.verbatim_item() + '}',
2627                                                 context);
2628                         }
2629                 }
2630
2631                 // Starred section headings
2632                 // Must attempt to parse "Section*" before "Section".
2633                 else if ((p.next_token().asInput() == "*") &&
2634                          context.new_layout_allowed &&
2635                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2636                         // write the layout
2637                         p.get_token();
2638                         output_command_layout(os, p, outer, context, newlayout);
2639                         p.skip_spaces();
2640                         if (!preamble.titleLayoutFound())
2641                                 preamble.titleLayoutFound(newlayout->intitle);
2642                         set<string> const & req = newlayout->requires();
2643                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2644                                 preamble.registerAutomaticallyLoadedPackage(*it);
2645                 }
2646
2647                 // Section headings and the like
2648                 else if (context.new_layout_allowed &&
2649                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2650                         // write the layout
2651                         output_command_layout(os, p, outer, context, newlayout);
2652                         p.skip_spaces();
2653                         if (!preamble.titleLayoutFound())
2654                                 preamble.titleLayoutFound(newlayout->intitle);
2655                         set<string> const & req = newlayout->requires();
2656                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2657                                 preamble.registerAutomaticallyLoadedPackage(*it);
2658                 }
2659
2660                 else if (t.cs() == "caption") {
2661                         p.skip_spaces();
2662                         context.check_layout(os);
2663                         p.skip_spaces();
2664                         begin_inset(os, "Caption\n");
2665                         Context newcontext(true, context.textclass);
2666                         newcontext.font = context.font;
2667                         newcontext.check_layout(os);
2668                         if (p.next_token().cat() != catEscape &&
2669                             p.next_token().character() == '[') {
2670                                 p.get_token(); // eat '['
2671                                 begin_inset(os, "Argument\n");
2672                                 os << "status collapsed\n";
2673                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2674                                 end_inset(os);
2675                                 eat_whitespace(p, os, context, false);
2676                         }
2677                         parse_text(p, os, FLAG_ITEM, outer, context);
2678                         context.check_end_layout(os);
2679                         // We don't need really a new paragraph, but
2680                         // we must make sure that the next item gets a \begin_layout.
2681                         context.new_paragraph(os);
2682                         end_inset(os);
2683                         p.skip_spaces();
2684                         newcontext.check_end_layout(os);
2685                 }
2686
2687                 else if (t.cs() == "subfloat") {
2688                         // the syntax is \subfloat[caption]{content}
2689                         // if it is a table of figure depends on the surrounding float
2690                         bool has_caption = false;
2691                         p.skip_spaces();
2692                         // do nothing if there is no outer float
2693                         if (!float_type.empty()) {
2694                                 context.check_layout(os);
2695                                 p.skip_spaces();
2696                                 begin_inset(os, "Float " + float_type + "\n");
2697                                 os << "wide false"
2698                                    << "\nsideways false"
2699                                    << "\nstatus collapsed\n\n";
2700                                 // test for caption
2701                                 string caption;
2702                                 if (p.next_token().cat() != catEscape &&
2703                                                 p.next_token().character() == '[') {
2704                                                         p.get_token(); // eat '['
2705                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2706                                                         has_caption = true;
2707                                 }
2708                                 // the content
2709                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2710                                 // the caption comes always as the last
2711                                 if (has_caption) {
2712                                         // we must make sure that the caption gets a \begin_layout
2713                                         os << "\n\\begin_layout Plain Layout";
2714                                         p.skip_spaces();
2715                                         begin_inset(os, "Caption\n");
2716                                         Context newcontext(true, context.textclass);
2717                                         newcontext.font = context.font;
2718                                         newcontext.check_layout(os);
2719                                         os << caption << "\n";
2720                                         newcontext.check_end_layout(os);
2721                                         // We don't need really a new paragraph, but
2722                                         // we must make sure that the next item gets a \begin_layout.
2723                                         //newcontext.new_paragraph(os);
2724                                         end_inset(os);
2725                                         p.skip_spaces();
2726                                 }
2727                                 // We don't need really a new paragraph, but
2728                                 // we must make sure that the next item gets a \begin_layout.
2729                                 if (has_caption)
2730                                         context.new_paragraph(os);
2731                                 end_inset(os);
2732                                 p.skip_spaces();
2733                                 context.check_end_layout(os);
2734                                 // close the layout we opened
2735                                 if (has_caption)
2736                                         os << "\n\\end_layout\n";
2737                         } else {
2738                                 // if the float type is not supported or there is no surrounding float
2739                                 // output it as ERT
2740                                 if (p.hasOpt()) {
2741                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2742                                         handle_ert(os, t.asInput() + '[' + opt_arg +
2743                                                "]{" + p.verbatim_item() + '}', context);
2744                                 } else
2745                                         handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2746                         }
2747                 }
2748
2749                 else if (t.cs() == "includegraphics") {
2750                         bool const clip = p.next_token().asInput() == "*";
2751                         if (clip)
2752                                 p.get_token();
2753                         string const arg = p.getArg('[', ']');
2754                         map<string, string> opts;
2755                         vector<string> keys;
2756                         split_map(arg, opts, keys);
2757                         if (clip)
2758                                 opts["clip"] = string();
2759                         string name = normalize_filename(p.verbatim_item());
2760
2761                         string const path = getMasterFilePath();
2762                         // We want to preserve relative / absolute filenames,
2763                         // therefore path is only used for testing
2764                         if (!makeAbsPath(name, path).exists()) {
2765                                 // The file extension is probably missing.
2766                                 // Now try to find it out.
2767                                 string const dvips_name =
2768                                         find_file(name, path,
2769                                                   known_dvips_graphics_formats);
2770                                 string const pdftex_name =
2771                                         find_file(name, path,
2772                                                   known_pdftex_graphics_formats);
2773                                 if (!dvips_name.empty()) {
2774                                         if (!pdftex_name.empty()) {
2775                                                 cerr << "This file contains the "
2776                                                         "latex snippet\n"
2777                                                         "\"\\includegraphics{"
2778                                                      << name << "}\".\n"
2779                                                         "However, files\n\""
2780                                                      << dvips_name << "\" and\n\""
2781                                                      << pdftex_name << "\"\n"
2782                                                         "both exist, so I had to make a "
2783                                                         "choice and took the first one.\n"
2784                                                         "Please move the unwanted one "
2785                                                         "someplace else and try again\n"
2786                                                         "if my choice was wrong."
2787                                                      << endl;
2788                                         }
2789                                         name = dvips_name;
2790                                 } else if (!pdftex_name.empty()) {
2791                                         name = pdftex_name;
2792                                         pdflatex = true;
2793                                 }
2794                         }
2795
2796                         if (makeAbsPath(name, path).exists())
2797                                 fix_relative_filename(name);
2798                         else
2799                                 cerr << "Warning: Could not find graphics file '"
2800                                      << name << "'." << endl;
2801
2802                         context.check_layout(os);
2803                         begin_inset(os, "Graphics ");
2804                         os << "\n\tfilename " << name << '\n';
2805                         if (opts.find("width") != opts.end())
2806                                 os << "\twidth "
2807                                    << translate_len(opts["width"]) << '\n';
2808                         if (opts.find("height") != opts.end())
2809                                 os << "\theight "
2810                                    << translate_len(opts["height"]) << '\n';
2811                         if (opts.find("scale") != opts.end()) {
2812                                 istringstream iss(opts["scale"]);
2813                                 double val;
2814                                 iss >> val;
2815                                 val = val*100;
2816                                 os << "\tscale " << val << '\n';
2817                         }
2818                         if (opts.find("angle") != opts.end()) {
2819                                 os << "\trotateAngle "
2820                                    << opts["angle"] << '\n';
2821                                 vector<string>::const_iterator a =
2822                                         find(keys.begin(), keys.end(), "angle");
2823                                 vector<string>::const_iterator s =
2824                                         find(keys.begin(), keys.end(), "width");
2825                                 if (s == keys.end())
2826                                         s = find(keys.begin(), keys.end(), "height");
2827                                 if (s == keys.end())
2828                                         s = find(keys.begin(), keys.end(), "scale");
2829                                 if (s != keys.end() && distance(s, a) > 0)
2830                                         os << "\tscaleBeforeRotation\n";
2831                         }
2832                         if (opts.find("origin") != opts.end()) {
2833                                 ostringstream ss;
2834                                 string const opt = opts["origin"];
2835                                 if (opt.find('l') != string::npos) ss << "left";
2836                                 if (opt.find('r') != string::npos) ss << "right";
2837                                 if (opt.find('c') != string::npos) ss << "center";
2838                                 if (opt.find('t') != string::npos) ss << "Top";
2839                                 if (opt.find('b') != string::npos) ss << "Bottom";
2840                                 if (opt.find('B') != string::npos) ss << "Baseline";
2841                                 if (!ss.str().empty())
2842                                         os << "\trotateOrigin " << ss.str() << '\n';
2843                                 else
2844                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2845                         }
2846                         if (opts.find("keepaspectratio") != opts.end())
2847                                 os << "\tkeepAspectRatio\n";
2848                         if (opts.find("clip") != opts.end())
2849                                 os << "\tclip\n";
2850                         if (opts.find("draft") != opts.end())
2851                                 os << "\tdraft\n";
2852                         if (opts.find("bb") != opts.end())
2853                                 os << "\tBoundingBox "
2854                                    << opts["bb"] << '\n';
2855                         int numberOfbbOptions = 0;
2856                         if (opts.find("bbllx") != opts.end())
2857                                 numberOfbbOptions++;
2858                         if (opts.find("bblly") != opts.end())
2859                                 numberOfbbOptions++;
2860                         if (opts.find("bburx") != opts.end())
2861                                 numberOfbbOptions++;
2862                         if (opts.find("bbury") != opts.end())
2863                                 numberOfbbOptions++;
2864                         if (numberOfbbOptions == 4)
2865                                 os << "\tBoundingBox "
2866                                    << opts["bbllx"] << " " << opts["bblly"] << " "
2867                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
2868                         else if (numberOfbbOptions > 0)
2869                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2870                         numberOfbbOptions = 0;
2871                         if (opts.find("natwidth") != opts.end())
2872                                 numberOfbbOptions++;
2873                         if (opts.find("natheight") != opts.end())
2874                                 numberOfbbOptions++;
2875                         if (numberOfbbOptions == 2)
2876                                 os << "\tBoundingBox 0bp 0bp "
2877                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
2878                         else if (numberOfbbOptions > 0)
2879                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2880                         ostringstream special;
2881                         if (opts.find("hiresbb") != opts.end())
2882                                 special << "hiresbb,";
2883                         if (opts.find("trim") != opts.end())
2884                                 special << "trim,";
2885                         if (opts.find("viewport") != opts.end())
2886                                 special << "viewport=" << opts["viewport"] << ',';
2887                         if (opts.find("totalheight") != opts.end())
2888                                 special << "totalheight=" << opts["totalheight"] << ',';
2889                         if (opts.find("type") != opts.end())
2890                                 special << "type=" << opts["type"] << ',';
2891                         if (opts.find("ext") != opts.end())
2892                                 special << "ext=" << opts["ext"] << ',';
2893                         if (opts.find("read") != opts.end())
2894                                 special << "read=" << opts["read"] << ',';
2895                         if (opts.find("command") != opts.end())
2896                                 special << "command=" << opts["command"] << ',';
2897                         string s_special = special.str();
2898                         if (!s_special.empty()) {
2899                                 // We had special arguments. Remove the trailing ','.
2900                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2901                         }
2902                         // TODO: Handle the unknown settings better.
2903                         // Warn about invalid options.
2904                         // Check whether some option was given twice.
2905                         end_inset(os);
2906                         preamble.registerAutomaticallyLoadedPackage("graphicx");
2907                 }
2908
2909                 else if (t.cs() == "footnote" ||
2910                          (t.cs() == "thanks" && context.layout->intitle)) {
2911                         p.skip_spaces();
2912                         context.check_layout(os);
2913                         begin_inset(os, "Foot\n");
2914                         os << "status collapsed\n\n";
2915                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2916                         end_inset(os);
2917                 }
2918
2919                 else if (t.cs() == "marginpar") {
2920                         p.skip_spaces();
2921                         context.check_layout(os);
2922                         begin_inset(os, "Marginal\n");
2923                         os << "status collapsed\n\n";
2924                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2925                         end_inset(os);
2926                 }
2927
2928                 else if (t.cs() == "lstinline") {
2929                         p.skip_spaces();
2930                         parse_listings(p, os, context, true);
2931                 }
2932
2933                 else if (t.cs() == "ensuremath") {
2934                         p.skip_spaces();
2935                         context.check_layout(os);
2936                         string const s = p.verbatim_item();
2937                         //FIXME: this never triggers in UTF8
2938                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2939                                 os << s;
2940                         else
2941                                 handle_ert(os, "\\ensuremath{" + s + "}",
2942                                            context);
2943                 }
2944
2945                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2946                         if (preamble.titleLayoutFound()) {
2947                                 // swallow this
2948                                 skip_spaces_braces(p);
2949                         } else
2950                                 handle_ert(os, t.asInput(), context);
2951                 }
2952
2953                 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
2954                         context.check_layout(os);
2955                         begin_command_inset(os, "toc", t.cs());
2956                         end_inset(os);
2957                         skip_spaces_braces(p);
2958                         if (t.cs() == "lstlistoflistings")
2959                                 preamble.registerAutomaticallyLoadedPackage("listings");
2960                 }
2961
2962                 else if (t.cs() == "listoffigures") {
2963                         context.check_layout(os);
2964                         begin_inset(os, "FloatList figure\n");
2965                         end_inset(os);
2966                         skip_spaces_braces(p);
2967                 }
2968
2969                 else if (t.cs() == "listoftables") {
2970                         context.check_layout(os);
2971                         begin_inset(os, "FloatList table\n");
2972                         end_inset(os);
2973                         skip_spaces_braces(p);
2974                 }
2975
2976                 else if (t.cs() == "listof") {
2977                         p.skip_spaces(true);
2978                         string const name = p.get_token().cs();
2979                         if (context.textclass.floats().typeExist(name)) {
2980                                 context.check_layout(os);
2981                                 begin_inset(os, "FloatList ");
2982                                 os << name << "\n";
2983                                 end_inset(os);
2984                                 p.get_token(); // swallow second arg
2985                         } else
2986                                 handle_ert(os, "\\listof{" + name + "}", context);
2987                 }
2988
2989                 else if ((where = is_known(t.cs(), known_text_font_families)))
2990                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2991                                 context, "\\family", context.font.family,
2992                                 known_coded_font_families[where - known_text_font_families]);
2993
2994                 else if ((where = is_known(t.cs(), known_text_font_series)))
2995                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2996                                 context, "\\series", context.font.series,
2997                                 known_coded_font_series[where - known_text_font_series]);
2998
2999                 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3000                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3001                                 context, "\\shape", context.font.shape,
3002                                 known_coded_font_shapes[where - known_text_font_shapes]);
3003
3004                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3005                         context.check_layout(os);
3006                         TeXFont oldFont = context.font;
3007                         context.font.init();
3008                         context.font.size = oldFont.size;
3009                         os << "\n\\family " << context.font.family << "\n";
3010                         os << "\n\\series " << context.font.series << "\n";
3011                         os << "\n\\shape " << context.font.shape << "\n";
3012                         if (t.cs() == "textnormal") {
3013                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3014                                 output_font_change(os, context.font, oldFont);
3015                                 context.font = oldFont;
3016                         } else
3017                                 eat_whitespace(p, os, context, false);
3018                 }
3019
3020                 else if (t.cs() == "textcolor") {
3021                         // scheme is \textcolor{color name}{text}
3022                         string const color = p.verbatim_item();
3023                         // we only support the predefined colors of the color package
3024                         if (color == "black" || color == "blue" || color == "cyan"
3025                                 || color == "green" || color == "magenta" || color == "red"
3026                                 || color == "white" || color == "yellow") {
3027                                         context.check_layout(os);
3028                                         os << "\n\\color " << color << "\n";
3029                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3030                                         context.check_layout(os);
3031                                         os << "\n\\color inherit\n";
3032                                         preamble.registerAutomaticallyLoadedPackage("color");
3033                         } else
3034                                 // for custom defined colors
3035                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
3036                 }
3037
3038                 else if (t.cs() == "underbar" || t.cs() == "uline") {
3039                         // \underbar is not 100% correct (LyX outputs \uline
3040                         // of ulem.sty). The difference is that \ulem allows
3041                         // line breaks, and \underbar does not.
3042                         // Do NOT handle \underline.
3043                         // \underbar cuts through y, g, q, p etc.,
3044                         // \underline does not.
3045                         context.check_layout(os);
3046                         os << "\n\\bar under\n";
3047                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3048                         context.check_layout(os);
3049                         os << "\n\\bar default\n";
3050                         preamble.registerAutomaticallyLoadedPackage("ulem");
3051                 }
3052
3053                 else if (t.cs() == "sout") {
3054                         context.check_layout(os);
3055                         os << "\n\\strikeout on\n";
3056                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3057                         context.check_layout(os);
3058                         os << "\n\\strikeout default\n";
3059                         preamble.registerAutomaticallyLoadedPackage("ulem");
3060                 }
3061
3062                 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3063                          t.cs() == "emph" || t.cs() == "noun") {
3064                         context.check_layout(os);
3065                         os << "\n\\" << t.cs() << " on\n";
3066                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3067                         context.check_layout(os);
3068                         os << "\n\\" << t.cs() << " default\n";
3069                         if (t.cs() == "uuline" || t.cs() == "uwave")
3070                                 preamble.registerAutomaticallyLoadedPackage("ulem");
3071                 }
3072
3073                 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3074                         context.check_layout(os);
3075                         string name = p.getArg('{', '}');
3076                         string localtime = p.getArg('{', '}');
3077                         preamble.registerAuthor(name);
3078                         Author const & author = preamble.getAuthor(name);
3079                         // from_ctime() will fail if LyX decides to output the
3080                         // time in the text language. It might also use a wrong
3081                         // time zone (if the original LyX document was exported
3082                         // with a different time zone).
3083                         time_t ptime = from_ctime(localtime);
3084                         if (ptime == static_cast<time_t>(-1)) {
3085                                 cerr << "Warning: Could not parse time `" << localtime
3086                                      << "´ for change tracking, using current time instead.\n";
3087                                 ptime = current_time();
3088                         }
3089                         if (t.cs() == "lyxadded")
3090                                 os << "\n\\change_inserted ";
3091                         else
3092                                 os << "\n\\change_deleted ";
3093                         os << author.bufferId() << ' ' << ptime << '\n';
3094                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3095                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
3096                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3097                                           LaTeXPackages::isAvailable("xcolor");
3098                         // No need to test for luatex, since luatex comes in
3099                         // two flavours (dvi and pdf), like latex, and those
3100                         // are detected by pdflatex.
3101                         if (pdflatex || xetex) {
3102                                 if (xcolorulem) {
3103                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3104                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3105                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3106                                 }
3107                         } else {
3108                                 if (dvipost) {
3109                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
3110                                 } else if (xcolorulem) {
3111                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3112                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3113                                 }
3114                         }
3115                 }
3116
3117                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3118                              t.cs() == "vphantom") {
3119                         context.check_layout(os);
3120                         if (t.cs() == "phantom")
3121                                 begin_inset(os, "Phantom Phantom\n");
3122                         if (t.cs() == "hphantom")
3123                                 begin_inset(os, "Phantom HPhantom\n");
3124                         if (t.cs() == "vphantom")
3125                                 begin_inset(os, "Phantom VPhantom\n");
3126                         os << "status open\n";
3127                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3128                                             "Phantom");
3129                         end_inset(os);
3130                 }
3131
3132                 else if (t.cs() == "href") {
3133                         context.check_layout(os);
3134                         string target = p.getArg('{', '}');
3135                         string name = p.getArg('{', '}');
3136                         string type;
3137                         size_t i = target.find(':');
3138                         if (i != string::npos) {
3139                                 type = target.substr(0, i + 1);
3140                                 if (type == "mailto:" || type == "file:")
3141                                         target = target.substr(i + 1);
3142                                 // handle the case that name is equal to target, except of "http://"
3143                                 else if (target.substr(i + 3) == name && type == "http:")
3144                                         target = name;
3145                         }
3146                         begin_command_inset(os, "href", "href");
3147                         if (name != target)
3148                                 os << "name \"" << name << "\"\n";
3149                         os << "target \"" << target << "\"\n";
3150                         if (type == "mailto:" || type == "file:")
3151                                 os << "type \"" << type << "\"\n";
3152                         end_inset(os);
3153                         skip_spaces_braces(p);
3154                 }
3155
3156                 else if (t.cs() == "lyxline") {
3157                         // swallow size argument (it is not used anyway)
3158                         p.getArg('{', '}');
3159                         if (!context.atParagraphStart()) {
3160                                 // so our line is in the middle of a paragraph
3161                                 // we need to add a new line, lest this line
3162                                 // follow the other content on that line and
3163                                 // run off the side of the page
3164                                 // FIXME: This may create an empty paragraph,
3165                                 //        but without that it would not be
3166                                 //        possible to set noindent below.
3167                                 //        Fortunately LaTeX does not care
3168                                 //        about the empty paragraph.
3169                                 context.new_paragraph(os);
3170                         }
3171                         if (preamble.indentParagraphs()) {
3172                                 // we need to unindent, lest the line be too long
3173                                 context.add_par_extra_stuff("\\noindent\n");
3174                         }
3175                         context.check_layout(os);
3176                         begin_command_inset(os, "line", "rule");
3177                         os << "offset \"0.5ex\"\n"
3178                               "width \"100line%\"\n"
3179                               "height \"1pt\"\n";
3180                         end_inset(os);
3181                 }
3182
3183                 else if (t.cs() == "rule") {
3184                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3185                         string const width = p.getArg('{', '}');
3186                         string const thickness = p.getArg('{', '}');
3187                         context.check_layout(os);
3188                         begin_command_inset(os, "line", "rule");
3189                         if (!offset.empty())
3190                                 os << "offset \"" << translate_len(offset) << "\"\n";
3191                         os << "width \"" << translate_len(width) << "\"\n"
3192                                   "height \"" << translate_len(thickness) << "\"\n";
3193                         end_inset(os);
3194                 }
3195
3196                 else if (is_known(t.cs(), known_phrases) ||
3197                          (t.cs() == "protect" &&
3198                           p.next_token().cat() == catEscape &&
3199                           is_known(p.next_token().cs(), known_phrases))) {
3200                         // LyX sometimes puts a \protect in front, so we have to ignore it
3201                         // FIXME: This needs to be changed when bug 4752 is fixed.
3202                         where = is_known(
3203                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3204                                 known_phrases);
3205                         context.check_layout(os);
3206                         os << known_coded_phrases[where - known_phrases];
3207                         skip_spaces_braces(p);
3208                 }
3209
3210                 else if ((where = is_known(t.cs(), known_ref_commands))) {
3211                         string const opt = p.getOpt();
3212                         if (opt.empty()) {
3213                                 context.check_layout(os);
3214                                 begin_command_inset(os, "ref",
3215                                         known_coded_ref_commands[where - known_ref_commands]);
3216                                 os << "reference \""
3217                                    << convert_command_inset_arg(p.verbatim_item())
3218                                    << "\"\n";
3219                                 end_inset(os);
3220                                 if (t.cs() == "vref" || t.cs() == "vpageref")
3221                                         preamble.registerAutomaticallyLoadedPackage("varioref");
3222
3223                         } else {
3224                                 // LyX does not support optional arguments of ref commands
3225                                 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3226                                                p.verbatim_item() + "}", context);
3227                         }
3228                 }
3229
3230                 else if (use_natbib &&
3231                          is_known(t.cs(), known_natbib_commands) &&
3232                          ((t.cs() != "citefullauthor" &&
3233                            t.cs() != "citeyear" &&
3234                            t.cs() != "citeyearpar") ||
3235                           p.next_token().asInput() != "*")) {
3236                         context.check_layout(os);
3237                         string command = t.cs();
3238                         if (p.next_token().asInput() == "*") {
3239                                 command += '*';
3240                                 p.get_token();
3241                         }
3242                         if (command == "citefullauthor")
3243                                 // alternative name for "\\citeauthor*"
3244                                 command = "citeauthor*";
3245
3246                         // text before the citation
3247                         string before;
3248                         // text after the citation
3249                         string after;
3250                         get_cite_arguments(p, true, before, after);
3251
3252                         if (command == "cite") {
3253                                 // \cite without optional argument means
3254                                 // \citet, \cite with at least one optional
3255                                 // argument means \citep.
3256                                 if (before.empty() && after.empty())
3257                                         command = "citet";
3258                                 else
3259                                         command = "citep";
3260                         }
3261                         if (before.empty() && after == "[]")
3262                                 // avoid \citet[]{a}
3263                                 after.erase();
3264                         else if (before == "[]" && after == "[]") {
3265                                 // avoid \citet[][]{a}
3266                                 before.erase();
3267                                 after.erase();
3268                         }
3269                         // remove the brackets around after and before
3270                         if (!after.empty()) {
3271                                 after.erase(0, 1);
3272                                 after.erase(after.length() - 1, 1);
3273                                 after = convert_command_inset_arg(after);
3274                         }
3275                         if (!before.empty()) {
3276                                 before.erase(0, 1);
3277                                 before.erase(before.length() - 1, 1);
3278                                 before = convert_command_inset_arg(before);
3279                         }
3280                         begin_command_inset(os, "citation", command);
3281                         os << "after " << '"' << after << '"' << "\n";
3282                         os << "before " << '"' << before << '"' << "\n";
3283                         os << "key \""
3284                            << convert_command_inset_arg(p.verbatim_item())
3285                            << "\"\n";
3286                         end_inset(os);
3287                 }
3288
3289                 else if (use_jurabib &&
3290                          is_known(t.cs(), known_jurabib_commands) &&
3291                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3292                         context.check_layout(os);
3293                         string command = t.cs();
3294                         if (p.next_token().asInput() == "*") {
3295                                 command += '*';
3296                                 p.get_token();
3297                         }
3298                         char argumentOrder = '\0';
3299                         vector<string> const options =
3300                                 preamble.getPackageOptions("jurabib");
3301                         if (find(options.begin(), options.end(),
3302                                       "natbiborder") != options.end())
3303                                 argumentOrder = 'n';
3304                         else if (find(options.begin(), options.end(),
3305                                            "jurabiborder") != options.end())
3306                                 argumentOrder = 'j';
3307
3308                         // text before the citation
3309                         string before;
3310                         // text after the citation
3311                         string after;
3312                         get_cite_arguments(p, argumentOrder != 'j', before, after);
3313
3314                         string const citation = p.verbatim_item();
3315                         if (!before.empty() && argumentOrder == '\0') {
3316                                 cerr << "Warning: Assuming argument order "
3317                                         "of jurabib version 0.6 for\n'"
3318                                      << command << before << after << '{'
3319                                      << citation << "}'.\n"
3320                                         "Add 'jurabiborder' to the jurabib "
3321                                         "package options if you used an\n"
3322                                         "earlier jurabib version." << endl;
3323                         }
3324                         if (!after.empty()) {
3325                                 after.erase(0, 1);
3326                                 after.erase(after.length() - 1, 1);
3327                         }
3328                         if (!before.empty()) {
3329                                 before.erase(0, 1);
3330                                 before.erase(before.length() - 1, 1);
3331                         }
3332                         begin_command_inset(os, "citation", command);
3333                         os << "after " << '"' << after << '"' << "\n";
3334                         os << "before " << '"' << before << '"' << "\n";
3335                         os << "key " << '"' << citation << '"' << "\n";
3336                         end_inset(os);
3337                 }
3338
3339                 else if (t.cs() == "cite"
3340                         || t.cs() == "nocite") {
3341                         context.check_layout(os);
3342                         string after = convert_command_inset_arg(p.getArg('[', ']'));
3343                         string key = convert_command_inset_arg(p.verbatim_item());
3344                         // store the case that it is "\nocite{*}" to use it later for
3345                         // the BibTeX inset
3346                         if (key != "*") {
3347                                 begin_command_inset(os, "citation", t.cs());
3348                                 os << "after " << '"' << after << '"' << "\n";
3349                                 os << "key " << '"' << key << '"' << "\n";
3350                                 end_inset(os);
3351                         } else if (t.cs() == "nocite")
3352                                 btprint = key;
3353                 }
3354
3355                 else if (t.cs() == "index" ||
3356                          (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3357                         context.check_layout(os);
3358                         string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3359                                 p.getArg('[', ']') : "";
3360                         string const kind = arg.empty() ? "idx" : arg;
3361                         begin_inset(os, "Index ");
3362                         os << kind << "\nstatus collapsed\n";
3363                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3364                         end_inset(os);
3365                         if (kind != "idx")
3366                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3367                 }
3368
3369                 else if (t.cs() == "nomenclature") {
3370                         context.check_layout(os);
3371                         begin_command_inset(os, "nomenclature", "nomenclature");
3372                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3373                         if (!prefix.empty())
3374                                 os << "prefix " << '"' << prefix << '"' << "\n";
3375                         os << "symbol " << '"'
3376                            << convert_command_inset_arg(p.verbatim_item());
3377                         os << "\"\ndescription \""
3378                            << convert_command_inset_arg(p.verbatim_item())
3379                            << "\"\n";
3380                         end_inset(os);
3381                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3382                 }
3383
3384                 else if (t.cs() == "label") {
3385                         context.check_layout(os);
3386                         begin_command_inset(os, "label", "label");
3387                         os << "name \""
3388                            << convert_command_inset_arg(p.verbatim_item())
3389                            << "\"\n";
3390                         end_inset(os);
3391                 }
3392
3393                 else if (t.cs() == "printindex") {
3394                         context.check_layout(os);
3395                         begin_command_inset(os, "index_print", "printindex");
3396                         os << "type \"idx\"\n";
3397                         end_inset(os);
3398                         skip_spaces_braces(p);
3399                         preamble.registerAutomaticallyLoadedPackage("makeidx");
3400                         if (preamble.use_indices() == "true")
3401                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3402                 }
3403
3404                 else if (t.cs() == "printnomenclature") {
3405                         string width = "";
3406                         string width_type = "";
3407                         context.check_layout(os);
3408                         begin_command_inset(os, "nomencl_print", "printnomenclature");
3409                         // case of a custom width
3410                         if (p.hasOpt()) {
3411                                 width = p.getArg('[', ']');
3412                                 width = translate_len(width);
3413                                 width_type = "custom";
3414                         }
3415                         // case of no custom width
3416                         // the case of no custom width but the width set
3417                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
3418                         // because the user could have set anything, not only the width
3419                         // of the longest label (which would be width_type = "auto")
3420                         string label = convert_command_inset_arg(p.getArg('{', '}'));
3421                         if (label.empty() && width_type.empty())
3422                                 width_type = "none";
3423                         os << "set_width \"" << width_type << "\"\n";
3424                         if (width_type == "custom")
3425                                 os << "width \"" << width << '\"';
3426                         end_inset(os);
3427                         skip_spaces_braces(p);
3428                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3429                 }
3430
3431                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3432                         context.check_layout(os);
3433                         begin_inset(os, "script ");
3434                         os << t.cs().substr(4) << '\n';
3435                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3436                         end_inset(os);
3437                         if (t.cs() == "textsubscript")
3438                                 preamble.registerAutomaticallyLoadedPackage("subscript");
3439                 }
3440
3441                 else if ((where = is_known(t.cs(), known_quotes))) {
3442                         context.check_layout(os);
3443                         begin_inset(os, "Quotes ");
3444                         os << known_coded_quotes[where - known_quotes];
3445                         end_inset(os);
3446                         // LyX adds {} after the quote, so we have to eat
3447                         // spaces here if there are any before a possible
3448                         // {} pair.
3449                         eat_whitespace(p, os, context, false);
3450                         skip_braces(p);
3451                 }
3452
3453                 else if ((where = is_known(t.cs(), known_sizes)) &&
3454                          context.new_layout_allowed) {
3455                         context.check_layout(os);
3456                         TeXFont const oldFont = context.font;
3457                         context.font.size = known_coded_sizes[where - known_sizes];
3458                         output_font_change(os, oldFont, context.font);
3459                         eat_whitespace(p, os, context, false);
3460                 }
3461
3462                 else if ((where = is_known(t.cs(), known_font_families)) &&
3463                          context.new_layout_allowed) {
3464                         context.check_layout(os);
3465                         TeXFont const oldFont = context.font;
3466                         context.font.family =
3467                                 known_coded_font_families[where - known_font_families];
3468                         output_font_change(os, oldFont, context.font);
3469                         eat_whitespace(p, os, context, false);
3470                 }
3471
3472                 else if ((where = is_known(t.cs(), known_font_series)) &&
3473                          context.new_layout_allowed) {
3474                         context.check_layout(os);
3475                         TeXFont const oldFont = context.font;
3476                         context.font.series =
3477                                 known_coded_font_series[where - known_font_series];
3478                         output_font_change(os, oldFont, context.font);
3479                         eat_whitespace(p, os, context, false);
3480                 }
3481
3482                 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3483                          context.new_layout_allowed) {
3484                         context.check_layout(os);
3485                         TeXFont const oldFont = context.font;
3486                         context.font.shape =
3487                                 known_coded_font_shapes[where - known_font_shapes];
3488                         output_font_change(os, oldFont, context.font);
3489                         eat_whitespace(p, os, context, false);
3490                 }
3491                 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3492                          context.new_layout_allowed) {
3493                         context.check_layout(os);
3494                         TeXFont const oldFont = context.font;
3495                         context.font.init();
3496                         context.font.size = oldFont.size;
3497                         context.font.family =
3498                                 known_coded_font_families[where - known_old_font_families];
3499                         output_font_change(os, oldFont, context.font);
3500                         eat_whitespace(p, os, context, false);
3501                 }
3502
3503                 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3504                          context.new_layout_allowed) {
3505                         context.check_layout(os);
3506                         TeXFont const oldFont = context.font;
3507                         context.font.init();
3508                         context.font.size = oldFont.size;
3509                         context.font.series =
3510                                 known_coded_font_series[where - known_old_font_series];
3511                         output_font_change(os, oldFont, context.font);
3512                         eat_whitespace(p, os, context, false);
3513                 }
3514
3515                 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3516                          context.new_layout_allowed) {
3517                         context.check_layout(os);
3518                         TeXFont const oldFont = context.font;
3519                         context.font.init();
3520                         context.font.size = oldFont.size;
3521                         context.font.shape =
3522                                 known_coded_font_shapes[where - known_old_font_shapes];
3523                         output_font_change(os, oldFont, context.font);
3524                         eat_whitespace(p, os, context, false);
3525                 }
3526
3527                 else if (t.cs() == "selectlanguage") {
3528                         context.check_layout(os);
3529                         // save the language for the case that a
3530                         // \foreignlanguage is used
3531                         context.font.language = babel2lyx(p.verbatim_item());
3532                         os << "\n\\lang " << context.font.language << "\n";
3533                 }
3534
3535                 else if (t.cs() == "foreignlanguage") {
3536                         string const lang = babel2lyx(p.verbatim_item());
3537                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3538                                               context, "\\lang",
3539                                               context.font.language, lang);
3540                 }
3541                 
3542                 else if (prefixIs(t.cs(), "text") 
3543                          && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3544                         // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3545                         string lang;
3546                         // We have to output the whole command if it has an option
3547                         // because LyX doesn't support this yet, see bug #8214,
3548                         // only if there is a single option specifying a variant, we can handle it.
3549                         if (p.hasOpt()) {
3550                                 string langopts = p.getOpt();
3551                                 // check if the option contains a variant, if yes, extract it
3552                                 string::size_type pos_var = langopts.find("variant");
3553                                 string::size_type i = langopts.find(',');
3554                                 string::size_type k = langopts.find('=', pos_var);
3555                                 if (pos_var != string::npos && i == string::npos) {
3556                                         string variant;
3557                                         variant = langopts.substr(k + 1, langopts.length() - k - 2);
3558                                         lang = preamble.polyglossia2lyx(variant);
3559                                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3560                                                                   context, "\\lang",
3561                                                                   context.font.language, lang);
3562                                 } else
3563                                         handle_ert(os, t.asInput() + langopts, context);
3564                         } else {
3565                                 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3566                                 parse_text_attributes(p, os, FLAG_ITEM, outer,
3567                                                           context, "\\lang",
3568                                                           context.font.language, lang);
3569                         }
3570                 }
3571
3572                 else if (t.cs() == "inputencoding") {
3573                         // nothing to write here
3574                         string const enc = subst(p.verbatim_item(), "\n", " ");
3575                         p.setEncoding(enc);
3576                 }
3577
3578                 else if ((where = is_known(t.cs(), known_special_chars))) {
3579                         context.check_layout(os);
3580                         os << "\\SpecialChar \\"
3581                            << known_coded_special_chars[where - known_special_chars]
3582                            << '\n';
3583                         skip_spaces_braces(p);
3584                 }
3585
3586                 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3587                         context.check_layout(os);
3588                         os << "\\SpecialChar \\nobreakdash-\n";
3589                         p.get_token();
3590                 }
3591
3592                 else if (t.cs() == "textquotedbl") {
3593                         context.check_layout(os);
3594                         os << "\"";
3595                         skip_braces(p);
3596                 }
3597
3598                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3599                         context.check_layout(os);
3600                         os << "\\SpecialChar \\@.\n";
3601                         p.get_token();
3602                 }
3603
3604                 else if (t.cs() == "-") {
3605                         context.check_layout(os);
3606                         os << "\\SpecialChar \\-\n";
3607                 }
3608
3609                 else if (t.cs() == "textasciitilde") {
3610                         context.check_layout(os);
3611                         os << '~';
3612                         skip_spaces_braces(p);
3613                 }
3614
3615                 else if (t.cs() == "textasciicircum") {
3616                         context.check_layout(os);
3617                         os << '^';
3618                         skip_spaces_braces(p);
3619                 }
3620
3621                 else if (t.cs() == "textbackslash") {
3622                         context.check_layout(os);
3623                         os << "\n\\backslash\n";
3624                         skip_spaces_braces(p);
3625                 }
3626
3627                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3628                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3629                             || t.cs() == "%") {
3630                         context.check_layout(os);
3631                         os << t.cs();
3632                 }
3633
3634                 else if (t.cs() == "char") {
3635                         context.check_layout(os);
3636                         if (p.next_token().character() == '`') {
3637                                 p.get_token();
3638                                 if (p.next_token().cs() == "\"") {
3639                                         p.get_token();
3640                                         os << '"';
3641                                         skip_braces(p);
3642                                 } else {
3643                                         handle_ert(os, "\\char`", context);
3644                                 }
3645                         } else {
3646                                 handle_ert(os, "\\char", context);
3647                         }
3648                 }
3649
3650                 else if (t.cs() == "verb") {
3651                         context.check_layout(os);
3652                         char const delimiter = p.next_token().character();
3653                         string const arg = p.getArg(delimiter, delimiter);
3654                         ostringstream oss;
3655                         oss << "\\verb" << delimiter << arg << delimiter;
3656                         handle_ert(os, oss.str(), context);
3657                 }
3658
3659                 // Problem: \= creates a tabstop inside the tabbing environment
3660                 // and else an accent. In the latter case we really would want
3661                 // \={o} instead of \= o.
3662                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3663                         handle_ert(os, t.asInput(), context);
3664
3665                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3666                 else if (t.cs().size() == 1
3667                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3668                         context.check_layout(os);
3669                         // try to see whether the string is in unicodesymbols
3670                         bool termination;
3671                         docstring rem;
3672                         string command = t.asInput() + "{"
3673                                 + trimSpaceAndEol(p.verbatim_item())
3674                                 + "}";
3675                         set<string> req;
3676                         docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3677                                 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3678                                 termination, rem, &req);
3679                         if (!s.empty()) {
3680                                 if (!rem.empty())
3681                                         cerr << "When parsing " << command
3682                                              << ", result is " << to_utf8(s)
3683                                              << "+" << to_utf8(rem) << endl;
3684                                 os << to_utf8(s);
3685                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3686                                         preamble.registerAutomaticallyLoadedPackage(*it);
3687                         } else
3688                                 // we did not find a non-ert version
3689                                 handle_ert(os, command, context);
3690                 }
3691
3692                 else if (t.cs() == "\\") {
3693                         context.check_layout(os);
3694                         if (p.hasOpt())
3695                                 handle_ert(os, "\\\\" + p.getOpt(), context);
3696                         else if (p.next_token().asInput() == "*") {
3697                                 p.get_token();
3698                                 // getOpt() eats the following space if there
3699                                 // is no optional argument, but that is OK
3700                                 // here since it has no effect in the output.
3701                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
3702                         }
3703                         else {
3704                                 begin_inset(os, "Newline newline");
3705                                 end_inset(os);
3706                         }
3707                 }
3708
3709                 else if (t.cs() == "newline" ||
3710                          (t.cs() == "linebreak" && !p.hasOpt())) {
3711                         context.check_layout(os);
3712                         begin_inset(os, "Newline ");
3713                         os << t.cs();
3714                         end_inset(os);
3715                         skip_spaces_braces(p);
3716                 }
3717
3718                 else if (t.cs() == "input" || t.cs() == "include"
3719                          || t.cs() == "verbatiminput") {
3720                         string name = t.cs();
3721                         if (t.cs() == "verbatiminput"
3722                             && p.next_token().asInput() == "*")
3723                                 name += p.get_token().asInput();
3724                         context.check_layout(os);
3725                         string filename(normalize_filename(p.getArg('{', '}')));
3726                         string const path = getMasterFilePath();
3727                         // We want to preserve relative / absolute filenames,
3728                         // therefore path is only used for testing
3729                         if ((t.cs() == "include" || t.cs() == "input") &&
3730                             !makeAbsPath(filename, path).exists()) {
3731                                 // The file extension is probably missing.
3732                                 // Now try to find it out.
3733                                 string const tex_name =
3734                                         find_file(filename, path,
3735                                                   known_tex_extensions);
3736                                 if (!tex_name.empty())
3737                                         filename = tex_name;
3738                         }
3739                         bool external = false;
3740                         string outname;
3741                         if (makeAbsPath(filename, path).exists()) {
3742                                 string const abstexname =
3743                                         makeAbsPath(filename, path).absFileName();
3744                                 string const abslyxname =
3745                                         changeExtension(abstexname, ".lyx");
3746                                 string const absfigname =
3747                                         changeExtension(abstexname, ".fig");
3748                                 fix_relative_filename(filename);
3749                                 string const lyxname =
3750                                         changeExtension(filename, ".lyx");
3751                                 bool xfig = false;
3752                                 external = FileName(absfigname).exists();
3753                                 if (t.cs() == "input") {
3754                                         string const ext = getExtension(abstexname);
3755
3756                                         // Combined PS/LaTeX:
3757                                         // x.eps, x.pstex_t (old xfig)
3758                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3759                                         FileName const absepsname(
3760                                                 changeExtension(abstexname, ".eps"));
3761                                         FileName const abspstexname(
3762                                                 changeExtension(abstexname, ".pstex"));
3763                                         bool const xfigeps =
3764                                                 (absepsname.exists() ||
3765                                                  abspstexname.exists()) &&
3766                                                 ext == "pstex_t";
3767
3768                                         // Combined PDF/LaTeX:
3769                                         // x.pdf, x.pdftex_t (old xfig)
3770                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3771                                         FileName const abspdfname(
3772                                                 changeExtension(abstexname, ".pdf"));
3773                                         bool const xfigpdf =
3774                                                 abspdfname.exists() &&
3775                                                 (ext == "pdftex_t" || ext == "pdf_t");
3776                                         if (xfigpdf)
3777                                                 pdflatex = true;
3778
3779                                         // Combined PS/PDF/LaTeX:
3780                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3781                                         string const absbase2(
3782                                                 removeExtension(abstexname) + "_pspdftex");
3783                                         FileName const abseps2name(
3784                                                 addExtension(absbase2, ".eps"));
3785                                         FileName const abspdf2name(
3786                                                 addExtension(absbase2, ".pdf"));
3787                                         bool const xfigboth =
3788                                                 abspdf2name.exists() &&
3789                                                 abseps2name.exists() && ext == "pspdftex";
3790
3791                                         xfig = xfigpdf || xfigeps || xfigboth;
3792                                         external = external && xfig;
3793                                 }
3794                                 if (external) {
3795                                         outname = changeExtension(filename, ".fig");
3796                                 } else if (xfig) {
3797                                         // Don't try to convert, the result
3798                                         // would be full of ERT.
3799                                         outname = filename;
3800                                 } else if (t.cs() != "verbatiminput" &&
3801                                     tex2lyx(abstexname, FileName(abslyxname),
3802                                             p.getEncoding())) {
3803                                         outname = lyxname;
3804                                 } else {
3805                                         outname = filename;
3806                                 }
3807                         } else {
3808                                 cerr << "Warning: Could not find included file '"
3809                                      << filename << "'." << endl;
3810                                 outname = filename;
3811                         }
3812                         if (external) {
3813                                 begin_inset(os, "External\n");
3814                                 os << "\ttemplate XFig\n"
3815                                    << "\tfilename " << outname << '\n';
3816                                 registerExternalTemplatePackages("XFig");
3817                         } else {
3818                                 begin_command_inset(os, "include", name);
3819                                 os << "preview false\n"
3820                                       "filename \"" << outname << "\"\n";
3821                                 if (t.cs() == "verbatiminput")
3822                                         preamble.registerAutomaticallyLoadedPackage("verbatim");
3823                         }
3824                         end_inset(os);
3825                 }
3826
3827                 else if (t.cs() == "bibliographystyle") {
3828                         // store new bibliographystyle
3829                         bibliographystyle = p.verbatim_item();
3830                         // If any other command than \bibliography and
3831                         // \nocite{*} follows, we need to output the style
3832                         // (because it might be used by that command).
3833                         // Otherwise, it will automatically be output by LyX.
3834                         p.pushPosition();
3835                         bool output = true;
3836                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3837                                 if (t2.cat() == catBegin)
3838                                         break;
3839                                 if (t2.cat() != catEscape)
3840                                         continue;
3841                                 if (t2.cs() == "nocite") {
3842                                         if (p.getArg('{', '}') == "*")
3843                                                 continue;
3844                                 } else if (t2.cs() == "bibliography")
3845                                         output = false;
3846                                 break;
3847                         }
3848                         p.popPosition();
3849                         if (output) {
3850                                 handle_ert(os,
3851                                         "\\bibliographystyle{" + bibliographystyle + '}',
3852                                         context);
3853                         }
3854                 }
3855
3856                 else if (t.cs() == "bibliography") {
3857                         context.check_layout(os);
3858                         begin_command_inset(os, "bibtex", "bibtex");
3859                         if (!btprint.empty()) {
3860                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3861                                 // clear the string because the next BibTeX inset can be without the
3862                                 // \nocite{*} option
3863                                 btprint.clear();
3864                         }
3865                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3866                         // Do we have a bibliographystyle set?
3867                         if (!bibliographystyle.empty())
3868                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
3869                         end_inset(os);
3870                 }
3871
3872                 else if (t.cs() == "parbox") {
3873                         // Test whether this is an outer box of a shaded box
3874                         p.pushPosition();
3875                         // swallow arguments
3876                         while (p.hasOpt()) {
3877                                 p.getArg('[', ']');
3878                                 p.skip_spaces(true);
3879                         }
3880                         p.getArg('{', '}');
3881                         p.skip_spaces(true);
3882                         // eat the '{'
3883                         if (p.next_token().cat() == catBegin)
3884                                 p.get_token();
3885                         p.skip_spaces(true);
3886                         Token to = p.get_token();
3887                         bool shaded = false;
3888                         if (to.asInput() == "\\begin") {
3889                                 p.skip_spaces(true);
3890                                 if (p.getArg('{', '}') == "shaded")
3891                                         shaded = true;
3892                         }
3893                         p.popPosition();
3894                         if (shaded) {
3895                                 parse_outer_box(p, os, FLAG_ITEM, outer,
3896                                                 context, "parbox", "shaded");
3897                         } else
3898                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3899                                           "", "", t.cs());
3900                 }
3901
3902                 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3903                          t.cs() == "shadowbox" || t.cs() == "doublebox")
3904                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3905
3906                 else if (t.cs() == "framebox") {
3907                         if (p.next_token().character() == '(') {
3908                                 //the syntax is: \framebox(x,y)[position]{content}
3909                                 string arg = t.asInput();
3910                                 arg += p.getFullParentheseArg();
3911                                 arg += p.getFullOpt();
3912                                 eat_whitespace(p, os, context, false);
3913                                 handle_ert(os, arg + '{', context);
3914                                 parse_text(p, os, FLAG_ITEM, outer, context);
3915                                 handle_ert(os, "}", context);
3916                         } else {
3917                                 string special = p.getFullOpt();
3918                                 special += p.getOpt();
3919                                 // LyX does not yet support \framebox without any option
3920                                 if (!special.empty())
3921                                         parse_outer_box(p, os, FLAG_ITEM, outer,
3922                                                         context, t.cs(), special);
3923                                 else {
3924                                         eat_whitespace(p, os, context, false);
3925                                         handle_ert(os, "\\framebox{", context);
3926                                         parse_text(p, os, FLAG_ITEM, outer, context);
3927                                         handle_ert(os, "}", context);
3928                                 }
3929                         }
3930                 }
3931
3932                 //\makebox() is part of the picture environment and different from \makebox{}
3933                 //\makebox{} will be parsed by parse_box
3934                 else if (t.cs() == "makebox") {
3935                         if (p.next_token().character() == '(') {
3936                                 //the syntax is: \makebox(x,y)[position]{content}
3937                                 string arg = t.asInput();
3938                                 arg += p.getFullParentheseArg();
3939                                 arg += p.getFullOpt();
3940                                 eat_whitespace(p, os, context, false);
3941                                 handle_ert(os, arg + '{', context);
3942                                 parse_text(p, os, FLAG_ITEM, outer, context);
3943                                 handle_ert(os, "}", context);
3944                         } else
3945                                 //the syntax is: \makebox[width][position]{content}
3946                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3947                                           "", "", t.cs());
3948                 }
3949
3950                 else if (t.cs() == "smallskip" ||
3951                          t.cs() == "medskip" ||
3952                          t.cs() == "bigskip" ||
3953                          t.cs() == "vfill") {
3954                         context.check_layout(os);
3955                         begin_inset(os, "VSpace ");
3956                         os << t.cs();
3957                         end_inset(os);
3958                         skip_spaces_braces(p);
3959                 }
3960
3961                 else if ((where = is_known(t.cs(), known_spaces))) {
3962                         context.check_layout(os);
3963                         begin_inset(os, "space ");
3964                         os << '\\' << known_coded_spaces[where - known_spaces]
3965                            << '\n';
3966                         end_inset(os);
3967                         // LaTeX swallows whitespace after all spaces except
3968                         // "\\,". We have to do that here, too, because LyX
3969                         // adds "{}" which would make the spaces significant.
3970                         if (t.cs() !=  ",")
3971                                 eat_whitespace(p, os, context, false);
3972                         // LyX adds "{}" after all spaces except "\\ " and
3973                         // "\\,", so we have to remove "{}".
3974                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
3975                         // remove the braces after "\\,", too.
3976                         if (t.cs() != " ")
3977                                 skip_braces(p);
3978                 }
3979
3980                 else if (t.cs() == "newpage" ||
3981                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
3982                          t.cs() == "clearpage" ||
3983                          t.cs() == "cleardoublepage") {
3984                         context.check_layout(os);
3985                         begin_inset(os, "Newpage ");
3986                         os << t.cs();
3987                         end_inset(os);
3988                         skip_spaces_braces(p);
3989                 }
3990
3991                 else if (t.cs() == "DeclareRobustCommand" ||
3992                          t.cs() == "DeclareRobustCommandx" ||
3993                          t.cs() == "newcommand" ||
3994                          t.cs() == "newcommandx" ||
3995                          t.cs() == "providecommand" ||
3996                          t.cs() == "providecommandx" ||
3997                          t.cs() == "renewcommand" ||
3998                          t.cs() == "renewcommandx") {
3999                         // DeclareRobustCommand, DeclareRobustCommandx,
4000                         // providecommand and providecommandx could be handled
4001                         // by parse_command(), but we need to call
4002                         // add_known_command() here.
4003                         string name = t.asInput();
4004                         if (p.next_token().asInput() == "*") {
4005                                 // Starred form. Eat '*'
4006                                 p.get_token();
4007                                 name += '*';
4008                         }
4009                         string const command = p.verbatim_item();
4010                         string const opt1 = p.getFullOpt();
4011                         string const opt2 = p.getFullOpt();
4012                         add_known_command(command, opt1, !opt2.empty());
4013                         string const ert = name + '{' + command + '}' +
4014                                            opt1 + opt2 +
4015                                            '{' + p.verbatim_item() + '}';
4016
4017                         if (t.cs() == "DeclareRobustCommand" ||
4018                             t.cs() == "DeclareRobustCommandx" ||
4019                             t.cs() == "providecommand" ||
4020                             t.cs() == "providecommandx" ||
4021                             name[name.length()-1] == '*')
4022                                 handle_ert(os, ert, context);
4023                         else {
4024                                 context.check_layout(os);
4025                                 begin_inset(os, "FormulaMacro");
4026                                 os << "\n" << ert;
4027                                 end_inset(os);
4028                         }
4029                 }
4030
4031                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4032                         // let could be handled by parse_command(),
4033                         // but we need to call add_known_command() here.
4034                         string ert = t.asInput();
4035                         string name;
4036                         p.skip_spaces();
4037                         if (p.next_token().cat() == catBegin) {
4038                                 name = p.verbatim_item();
4039                                 ert += '{' + name + '}';
4040                         } else {
4041                                 name = p.verbatim_item();
4042                                 ert += name;
4043                         }
4044                         string command;
4045                         p.skip_spaces();
4046                         if (p.next_token().cat() == catBegin) {
4047                                 command = p.verbatim_item();
4048                                 ert += '{' + command + '}';
4049                         } else {
4050                                 command = p.verbatim_item();
4051                                 ert += command;
4052                         }
4053                         // If command is known, make name known too, to parse
4054                         // its arguments correctly. For this reason we also
4055                         // have commands in syntax.default that are hardcoded.
4056                         CommandMap::iterator it = known_commands.find(command);
4057                         if (it != known_commands.end())
4058                                 known_commands[t.asInput()] = it->second;
4059                         handle_ert(os, ert, context);
4060                 }
4061
4062                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4063                         bool starred = false;
4064                         if (p.next_token().asInput() == "*") {
4065                                 p.get_token();
4066                                 starred = true;
4067                         }
4068                         string name = t.asInput();
4069                         string const length = p.verbatim_item();
4070                         string unit;
4071                         string valstring;
4072                         bool valid = splitLatexLength(length, valstring, unit);
4073                         bool known_hspace = false;
4074                         bool known_vspace = false;
4075                         bool known_unit = false;
4076                         double value;
4077                         if (valid) {
4078                                 istringstream iss(valstring);
4079                                 iss >> value;
4080                                 if (value == 1.0) {
4081                                         if (t.cs()[0] == 'h') {
4082                                                 if (unit == "\\fill") {
4083                                                         if (!starred) {
4084                                                                 unit = "";
4085                                                                 name = "\\hfill";
4086                                                         }
4087                                                         known_hspace = true;
4088                                                 }
4089                                         } else {
4090                                                 if (unit == "\\smallskipamount") {
4091                                                         unit = "smallskip";
4092                                                         known_vspace = true;
4093                                                 } else if (unit == "\\medskipamount") {
4094                                                         unit = "medskip";
4095                                                         known_vspace = true;
4096                                                 } else if (unit == "\\bigskipamount") {
4097                                                         unit = "bigskip";
4098                                                         known_vspace = true;
4099                                                 } else if (unit == "\\fill") {
4100                                                         unit = "vfill";
4101                                                         known_vspace = true;
4102                                                 }
4103                                         }
4104                                 }
4105                                 if (!known_hspace && !known_vspace) {
4106                                         switch (unitFromString(unit)) {
4107                                         case Length::SP:
4108                                         case Length::PT:
4109                                         case Length::BP:
4110                                         case Length::DD:
4111                                         case Length::MM:
4112                                         case Length::PC:
4113                                         case Length::CC:
4114                                         case Length::CM:
4115                                         case Length::IN:
4116                                         case Length::EX:
4117                                         case Length::EM:
4118                                         case Length::MU:
4119                                                 known_unit = true;
4120                                                 break;
4121                                         default:
4122                                                 break;
4123                                         }
4124                                 }
4125                         }
4126
4127                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4128                                 // Literal horizontal length or known variable
4129                                 context.check_layout(os);
4130                                 begin_inset(os, "space ");
4131                                 os << name;
4132                                 if (starred)
4133                                         os << '*';
4134                                 os << '{';
4135                                 if (known_hspace)
4136                                         os << unit;
4137                                 os << "}";
4138                                 if (known_unit && !known_hspace)
4139                                         os << "\n\\length "
4140                                            << translate_len(length);
4141                                 end_inset(os);
4142                         } else if (known_unit || known_vspace) {
4143                                 // Literal vertical length or known variable
4144                                 context.check_layout(os);
4145                                 begin_inset(os, "VSpace ");
4146                                 if (known_unit)
4147                                         os << value;
4148                                 os << unit;
4149                                 if (starred)
4150                                         os << '*';
4151                                 end_inset(os);
4152                         } else {
4153                                 // LyX can't handle other length variables in Inset VSpace/space
4154                                 if (starred)
4155                                         name += '*';
4156                                 if (valid) {
4157                                         if (value == 1.0)
4158                                                 handle_ert(os, name + '{' + unit + '}', context);
4159                                         else if (value == -1.0)
4160                                                 handle_ert(os, name + "{-" + unit + '}', context);
4161                                         else
4162                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
4163                                 } else
4164                                         handle_ert(os, name + '{' + length + '}', context);
4165                         }
4166                 }
4167
4168                 // The single '=' is meant here.
4169                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4170                         p.skip_spaces();
4171                         context.check_layout(os);
4172                         begin_inset(os, "Flex ");
4173                         os << to_utf8(newinsetlayout->name()) << '\n'
4174                            << "status collapsed\n";
4175                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4176                         end_inset(os);
4177                 }
4178
4179                 else if (t.cs() == "includepdf") {
4180                         p.skip_spaces();
4181                         string const arg = p.getArg('[', ']');
4182                         map<string, string> opts;
4183                         vector<string> keys;
4184                         split_map(arg, opts, keys);
4185                         string name = normalize_filename(p.verbatim_item());
4186                         string const path = getMasterFilePath();
4187                         // We want to preserve relative / absolute filenames,
4188                         // therefore path is only used for testing
4189                         if (!makeAbsPath(name, path).exists()) {
4190                                 // The file extension is probably missing.
4191                                 // Now try to find it out.
4192                                 char const * const pdfpages_format[] = {"pdf", 0};
4193                                 string const pdftex_name =
4194                                         find_file(name, path, pdfpages_format);
4195                                 if (!pdftex_name.empty()) {
4196                                         name = pdftex_name;
4197                                         pdflatex = true;
4198                                 }
4199                         }
4200                         if (makeAbsPath(name, path).exists())
4201                                 fix_relative_filename(name);
4202                         else
4203                                 cerr << "Warning: Could not find file '"
4204                                      << name << "'." << endl;
4205                         // write output
4206                         context.check_layout(os);
4207                         begin_inset(os, "External\n\ttemplate ");
4208                         os << "PDFPages\n\tfilename "
4209                            << name << "\n";
4210                         // parse the options
4211                         if (opts.find("pages") != opts.end())
4212                                 os << "\textra LaTeX \"pages="
4213                                    << opts["pages"] << "\"\n";
4214                         if (opts.find("angle") != opts.end())
4215                                 os << "\trotateAngle "
4216                                    << opts["angle"] << '\n';
4217                         if (opts.find("origin") != opts.end()) {
4218                                 ostringstream ss;
4219                                 string const opt = opts["origin"];
4220                                 if (opt == "tl") ss << "topleft";
4221                                 if (opt == "bl") ss << "bottomleft";
4222                                 if (opt == "Bl") ss << "baselineleft";
4223                                 if (opt == "c") ss << "center";
4224                                 if (opt == "tc") ss << "topcenter";
4225                                 if (opt == "bc") ss << "bottomcenter";
4226                                 if (opt == "Bc") ss << "baselinecenter";
4227                                 if (opt == "tr") ss << "topright";
4228                                 if (opt == "br") ss << "bottomright";
4229                                 if (opt == "Br") ss << "baselineright";
4230                                 if (!ss.str().empty())
4231                                         os << "\trotateOrigin " << ss.str() << '\n';
4232                                 else
4233                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4234                         }
4235                         if (opts.find("width") != opts.end())
4236                                 os << "\twidth "
4237                                    << translate_len(opts["width"]) << '\n';
4238                         if (opts.find("height") != opts.end())
4239                                 os << "\theight "
4240                                    << translate_len(opts["height"]) << '\n';
4241                         if (opts.find("keepaspectratio") != opts.end())
4242                                 os << "\tkeepAspectRatio\n";
4243                         end_inset(os);
4244                         context.check_layout(os);
4245                         registerExternalTemplatePackages("PDFPages");
4246                 }
4247
4248                 else if (t.cs() == "loadgame") {
4249                         p.skip_spaces();
4250                         string name = normalize_filename(p.verbatim_item());
4251                         string const path = getMasterFilePath();
4252                         // We want to preserve relative / absolute filenames,
4253                         // therefore path is only used for testing
4254                         if (!makeAbsPath(name, path).exists()) {
4255                                 // The file extension is probably missing.
4256                                 // Now try to find it out.
4257                                 char const * const lyxskak_format[] = {"fen", 0};
4258                                 string const lyxskak_name =
4259                                         find_file(name, path, lyxskak_format);
4260                                 if (!lyxskak_name.empty())
4261                                         name = lyxskak_name;
4262                         }
4263                         if (makeAbsPath(name, path).exists())
4264                                 fix_relative_filename(name);
4265                         else
4266                                 cerr << "Warning: Could not find file '"
4267                                      << name << "'." << endl;
4268                         context.check_layout(os);
4269                         begin_inset(os, "External\n\ttemplate ");
4270                         os << "ChessDiagram\n\tfilename "
4271                            << name << "\n";
4272                         end_inset(os);
4273                         context.check_layout(os);
4274                         // after a \loadgame follows a \showboard
4275                         if (p.get_token().asInput() == "showboard")
4276                                 p.get_token();
4277                         registerExternalTemplatePackages("ChessDiagram");
4278                 }
4279
4280                 else {
4281                         // try to see whether the string is in unicodesymbols
4282                         // Only use text mode commands, since we are in text mode here,
4283                         // and math commands may be invalid (bug 6797)
4284                         bool termination;
4285                         docstring rem;
4286                         set<string> req;
4287                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4288                                         Encodings::TEXT_CMD, termination, rem, &req);
4289                         if (!s.empty()) {
4290                                 if (!rem.empty())
4291                                         cerr << "When parsing " << t.cs()
4292                                              << ", result is " << to_utf8(s)
4293                                              << "+" << to_utf8(rem) << endl;
4294                                 context.check_layout(os);
4295                                 os << to_utf8(s);
4296                                 if (termination)
4297                                         skip_spaces_braces(p);
4298                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4299                                         preamble.registerAutomaticallyLoadedPackage(*it);
4300                         }
4301                         //cerr << "#: " << t << " mode: " << mode << endl;
4302                         // heuristic: read up to next non-nested space
4303                         /*
4304                         string s = t.asInput();
4305                         string z = p.verbatim_item();
4306                         while (p.good() && z != " " && z.size()) {
4307                                 //cerr << "read: " << z << endl;
4308                                 s += z;
4309                                 z = p.verbatim_item();
4310                         }
4311                         cerr << "found ERT: " << s << endl;
4312                         handle_ert(os, s + ' ', context);
4313                         */
4314                         else {
4315                                 string name = t.asInput();
4316                                 if (p.next_token().asInput() == "*") {
4317                                         // Starred commands like \vspace*{}
4318                                         p.get_token();  // Eat '*'
4319                                         name += '*';
4320                                 }
4321                                 if (!parse_command(name, p, os, outer, context))
4322                                         handle_ert(os, name, context);
4323                         }
4324                 }
4325
4326                 if (flags & FLAG_LEAVE) {
4327                         flags &= ~FLAG_LEAVE;
4328                         break;
4329                 }
4330         }
4331 }
4332
4333 // }])
4334
4335
4336 } // namespace lyx