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