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