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