]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
11bef62fa5944af705e0de1a48065715e0b0855f
[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         if (inner_type == "shaded") {
789                 eat_whitespace(p, os, parent_context, false);
790                 p.get_token();
791                 p.getArg('{', '}');
792         }
793         // If we already read the inner box we have to push the inner env
794         if (!outer_type.empty() && !inner_type.empty() &&
795             (inner_flags & FLAG_END))
796                 active_environments.push_back(inner_type);
797         // LyX can't handle length variables
798         bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
799         if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
800                 // Look whether there is some content after the end of the
801                 // inner box, but before the end of the outer box.
802                 // If yes, we need to output ERT.
803                 p.pushPosition();
804                 if (inner_flags & FLAG_END)
805                         p.verbatimEnvironment(inner_type);
806                 else
807                         p.verbatim_item();
808                 p.skip_spaces(true);
809                 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
810                 if ((outer_env && p.next_token().asInput() != "\\end") ||
811                     (!outer_env && p.next_token().cat() != catEnd)) {
812                         // something is between the end of the inner box and
813                         // the end of the outer box, so we need to use ERT.
814                         use_ert = true;
815                 }
816                 p.popPosition();
817         }
818         if (use_ert) {
819                 ostringstream ss;
820                 if (!outer_type.empty()) {
821                         if (outer_flags & FLAG_END)
822                                 ss << "\\begin{" << outer_type << '}';
823                         else {
824                                 ss << '\\' << outer_type << '{';
825                                 if (!special.empty())
826                                         ss << special;
827                         }
828                 }
829                 if (!inner_type.empty()) {
830                         if (inner_type != "shaded") {
831                                 if (inner_flags & FLAG_END)
832                                         ss << "\\begin{" << inner_type << '}';
833                                 else
834                                         ss << '\\' << inner_type;
835                         }
836                         if (!position.empty())
837                                 ss << '[' << position << ']';
838                         if (!latex_height.empty())
839                                 ss << '[' << latex_height << ']';
840                         if (!inner_pos.empty())
841                                 ss << '[' << inner_pos << ']';
842                         ss << '{' << latex_width << '}';
843                         if (!(inner_flags & FLAG_END))
844                                 ss << '{';
845                 }
846                 if (inner_type == "shaded")
847                         ss << "\\begin{shaded}";
848                 handle_ert(os, ss.str(), parent_context);
849                 if (!inner_type.empty()) {
850                         parse_text(p, os, inner_flags, outer, parent_context);
851                         if (inner_flags & FLAG_END)
852                                 handle_ert(os, "\\end{" + inner_type + '}',
853                                            parent_context);
854                         else
855                                 handle_ert(os, "}", parent_context);
856                 }
857                 if (!outer_type.empty()) {
858                         // If we already read the inner box we have to pop
859                         // the inner env
860                         if (!inner_type.empty() && (inner_flags & FLAG_END))
861                                 active_environments.pop_back();
862                         parse_text(p, os, outer_flags, outer, parent_context);
863                         if (outer_flags & FLAG_END)
864                                 handle_ert(os, "\\end{" + outer_type + '}',
865                                            parent_context);
866                         else
867                                 handle_ert(os, "}", parent_context);
868                 }
869         } else {
870                 // LyX does not like empty positions, so we have
871                 // to set them to the LaTeX default values here.
872                 if (position.empty())
873                         position = "c";
874                 if (inner_pos.empty())
875                         inner_pos = position;
876                 // FIXME: Support makebox
877                 bool const use_makebox = false;
878                 parent_context.check_layout(os);
879                 begin_inset(os, "Box ");
880                 if (outer_type == "framed")
881                         os << "Framed\n";
882                 else if (outer_type == "framebox")
883                         os << "Boxed\n";
884                 else if (outer_type == "shadowbox")
885                         os << "Shadowbox\n";
886                 else if ((outer_type == "shaded" && inner_type.empty()) ||
887                          (outer_type == "minipage" && inner_type == "shaded")) {
888                         os << "Shaded\n";
889                         preamble.registerAutomaticallyLoadedPackage("color");
890                 } else if (outer_type == "doublebox")
891                         os << "Doublebox\n";
892                 else if (outer_type.empty())
893                         os << "Frameless\n";
894                 else
895                         os << outer_type << '\n';
896                 os << "position \"" << position << "\"\n";
897                 os << "hor_pos \"" << hor_pos << "\"\n";
898                 os << "has_inner_box " << !inner_type.empty() << "\n";
899                 os << "inner_pos \"" << inner_pos << "\"\n";
900                 os << "use_parbox " << (inner_type == "parbox") << '\n';
901                 os << "use_makebox " << use_makebox << '\n';
902                 os << "width \"" << width_value << width_unit << "\"\n";
903                 os << "special \"none\"\n";
904                 os << "height \"" << height_value << height_unit << "\"\n";
905                 os << "height_special \"" << height_special << "\"\n";
906                 os << "status open\n\n";
907
908                 // Unfortunately we can't use parse_text_in_inset:
909                 // InsetBox::forcePlainLayout() is hard coded and does not
910                 // use the inset layout. Apart from that do we call parse_text
911                 // up to two times, but need only one check_end_layout.
912
913                 bool const forcePlainLayout =
914                         (!inner_type.empty() || use_makebox) &&
915                         outer_type != "shaded" && outer_type != "framed";
916                 Context context(true, parent_context.textclass);
917                 if (forcePlainLayout)
918                         context.layout = &context.textclass.plainLayout();
919                 else
920                         context.font = parent_context.font;
921
922                 // If we have no inner box the contents will be read with the outer box
923                 if (!inner_type.empty())
924                         parse_text(p, os, inner_flags, outer, context);
925
926                 // Ensure that the end of the outer box is parsed correctly:
927                 // The opening brace has been eaten by parse_outer_box()
928                 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
929                         outer_flags &= ~FLAG_ITEM;
930                         outer_flags |= FLAG_BRACE_LAST;
931                 }
932
933                 // Find end of outer box, output contents if inner_type is
934                 // empty and output possible comments
935                 if (!outer_type.empty()) {
936                         // If we already read the inner box we have to pop
937                         // the inner env
938                         if (!inner_type.empty() && (inner_flags & FLAG_END))
939                                 active_environments.pop_back();
940                         // This does not output anything but comments if
941                         // inner_type is not empty (see use_ert)
942                         parse_text(p, os, outer_flags, outer, context);
943                 }
944
945                 context.check_end_layout(os);
946                 end_inset(os);
947 #ifdef PRESERVE_LAYOUT
948                 // LyX puts a % after the end of the minipage
949                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
950                         // new paragraph
951                         //handle_comment(os, "%dummy", parent_context);
952                         p.get_token();
953                         p.skip_spaces();
954                         parent_context.new_paragraph(os);
955                 }
956                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
957                         //handle_comment(os, "%dummy", parent_context);
958                         p.get_token();
959                         p.skip_spaces();
960                         // We add a protected space if something real follows
961                         if (p.good() && p.next_token().cat() != catComment) {
962                                 begin_inset(os, "space ~\n");
963                                 end_inset(os);
964                         }
965                 }
966 #endif
967         }
968 }
969
970
971 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
972                      Context & parent_context, string const & outer_type,
973                      string const & special)
974 {
975         eat_whitespace(p, os, parent_context, false);
976         if (flags & FLAG_ITEM) {
977                 // Eat '{'
978                 if (p.next_token().cat() == catBegin)
979                         p.get_token();
980                 else
981                         cerr << "Warning: Ignoring missing '{' after \\"
982                              << outer_type << '.' << endl;
983                 eat_whitespace(p, os, parent_context, false);
984         }
985         string inner;
986         unsigned int inner_flags = 0;
987         p.pushPosition();
988         if (outer_type == "minipage") {
989                 p.skip_spaces(true);
990                 while (p.hasOpt()) {
991                         p.getArg('[', ']');
992                         p.skip_spaces(true);
993                 }
994                 p.getArg('{', '}');
995                 p.skip_spaces(true);
996         }
997         if (outer_type == "shaded") {
998                 // These boxes never have an inner box
999                 ;
1000         } else if (p.next_token().asInput() == "\\parbox") {
1001                 inner = p.get_token().cs();
1002                 inner_flags = FLAG_ITEM;
1003         } else if (p.next_token().asInput() == "\\begin") {
1004                 // Is this a minipage?
1005                 p.pushPosition();
1006                 p.get_token();
1007                 inner = p.getArg('{', '}');
1008                 p.popPosition();
1009                 if (inner == "minipage" || inner == "shaded")
1010                         inner_flags = FLAG_END;
1011                 else
1012                         inner = "";
1013         }
1014         p.popPosition();
1015         if (inner_flags == FLAG_END) {
1016                 if (inner != "shaded")
1017                 {
1018                         p.get_token();
1019                         p.getArg('{', '}');
1020                         eat_whitespace(p, os, parent_context, false);
1021                 }
1022                 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1023                           outer_type, special, inner);
1024         } else {
1025                 if (inner_flags == FLAG_ITEM) {
1026                         p.get_token();
1027                         eat_whitespace(p, os, parent_context, false);
1028                 }
1029                 parse_box(p, os, flags, inner_flags, outer, parent_context,
1030                           outer_type, special, inner);
1031         }
1032 }
1033
1034
1035 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1036 {
1037         parent_context.check_layout(os);
1038         begin_inset(os, "listings\n");
1039         os << "inline false\n"
1040            << "status collapsed\n";
1041         Context context(true, parent_context.textclass);
1042         context.layout = &parent_context.textclass.plainLayout();
1043         context.check_layout(os);
1044         string const s = p.verbatimEnvironment("lstlisting");
1045         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1046                 if (*it == '\\')
1047                         os << "\n\\backslash\n";
1048                 else if (*it == '\n') {
1049                         // avoid adding an empty paragraph at the end
1050                         if (it + 1 != et) {
1051                                 context.new_paragraph(os);
1052                                 context.check_layout(os);
1053                         }
1054                 } else
1055                         os << *it;
1056         }
1057         context.check_end_layout(os);
1058         end_inset(os);
1059 }
1060
1061
1062 /// parse an unknown environment
1063 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1064                                unsigned flags, bool outer,
1065                                Context & parent_context)
1066 {
1067         if (name == "tabbing")
1068                 // We need to remember that we have to handle '\=' specially
1069                 flags |= FLAG_TABBING;
1070
1071         // We need to translate font changes and paragraphs inside the
1072         // environment to ERT if we have a non standard font.
1073         // Otherwise things like
1074         // \large\begin{foo}\huge bar\end{foo}
1075         // will not work.
1076         bool const specialfont =
1077                 (parent_context.font != parent_context.normalfont);
1078         bool const new_layout_allowed = parent_context.new_layout_allowed;
1079         if (specialfont)
1080                 parent_context.new_layout_allowed = false;
1081         handle_ert(os, "\\begin{" + name + "}", parent_context);
1082         parse_text_snippet(p, os, flags, outer, parent_context);
1083         handle_ert(os, "\\end{" + name + "}", parent_context);
1084         if (specialfont)
1085                 parent_context.new_layout_allowed = new_layout_allowed;
1086 }
1087
1088
1089 void parse_environment(Parser & p, ostream & os, bool outer,
1090                        string & last_env, bool & title_layout_found,
1091                        Context & parent_context)
1092 {
1093         Layout const * newlayout;
1094         InsetLayout const * newinsetlayout = 0;
1095         string const name = p.getArg('{', '}');
1096         const bool is_starred = suffixIs(name, '*');
1097         string const unstarred_name = rtrim(name, "*");
1098         active_environments.push_back(name);
1099
1100         if (is_math_env(name)) {
1101                 parent_context.check_layout(os);
1102                 begin_inset(os, "Formula ");
1103                 os << "\\begin{" << name << "}";
1104                 parse_math(p, os, FLAG_END, MATH_MODE);
1105                 os << "\\end{" << name << "}";
1106                 end_inset(os);
1107         }
1108
1109         else if (name == "tabular" || name == "longtable") {
1110                 eat_whitespace(p, os, parent_context, false);
1111                 parent_context.check_layout(os);
1112                 begin_inset(os, "Tabular ");
1113                 handle_tabular(p, os, name == "longtable", parent_context);
1114                 end_inset(os);
1115                 p.skip_spaces();
1116         }
1117
1118         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1119                 eat_whitespace(p, os, parent_context, false);
1120                 parent_context.check_layout(os);
1121                 begin_inset(os, "Float " + unstarred_name + "\n");
1122                 // store the float type for subfloats
1123                 // subfloats only work with figures and tables
1124                 if (unstarred_name == "figure")
1125                         float_type = unstarred_name;
1126                 else if (unstarred_name == "table")
1127                         float_type = unstarred_name;
1128                 else
1129                         float_type = "";
1130                 if (p.hasOpt())
1131                         os << "placement " << p.getArg('[', ']') << '\n';
1132                 os << "wide " << convert<string>(is_starred)
1133                    << "\nsideways false"
1134                    << "\nstatus open\n\n";
1135                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1136                 end_inset(os);
1137                 // We don't need really a new paragraph, but
1138                 // we must make sure that the next item gets a \begin_layout.
1139                 parent_context.new_paragraph(os);
1140                 p.skip_spaces();
1141                 // the float is parsed thus delete the type
1142                 float_type = "";
1143         }
1144
1145         else if (unstarred_name == "sidewaysfigure"
1146                 || unstarred_name == "sidewaystable") {
1147                 eat_whitespace(p, os, parent_context, false);
1148                 parent_context.check_layout(os);
1149                 if (unstarred_name == "sidewaysfigure")
1150                         begin_inset(os, "Float figure\n");
1151                 else
1152                         begin_inset(os, "Float table\n");
1153                 os << "wide " << convert<string>(is_starred)
1154                    << "\nsideways true"
1155                    << "\nstatus open\n\n";
1156                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1157                 end_inset(os);
1158                 // We don't need really a new paragraph, but
1159                 // we must make sure that the next item gets a \begin_layout.
1160                 parent_context.new_paragraph(os);
1161                 p.skip_spaces();
1162         }
1163
1164         else if (name == "wrapfigure" || name == "wraptable") {
1165                 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1166                 eat_whitespace(p, os, parent_context, false);
1167                 parent_context.check_layout(os);
1168                 // default values
1169                 string lines = "0";
1170                 string overhang = "0col%";
1171                 // parse
1172                 if (p.hasOpt())
1173                         lines = p.getArg('[', ']');
1174                 string const placement = p.getArg('{', '}');
1175                 if (p.hasOpt())
1176                         overhang = p.getArg('[', ']');
1177                 string const width = p.getArg('{', '}');
1178                 // write
1179                 if (name == "wrapfigure")
1180                         begin_inset(os, "Wrap figure\n");
1181                 else
1182                         begin_inset(os, "Wrap table\n");
1183                 os << "lines " << lines
1184                    << "\nplacement " << placement
1185                    << "\noverhang " << lyx::translate_len(overhang)
1186                    << "\nwidth " << lyx::translate_len(width)
1187                    << "\nstatus open\n\n";
1188                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1189                 end_inset(os);
1190                 // We don't need really a new paragraph, but
1191                 // we must make sure that the next item gets a \begin_layout.
1192                 parent_context.new_paragraph(os);
1193                 p.skip_spaces();
1194         }
1195
1196         else if (name == "minipage") {
1197                 eat_whitespace(p, os, parent_context, false);
1198                 // Test whether this is an outer box of a shaded box
1199                 p.pushPosition();
1200                 // swallow arguments
1201                 while (p.hasOpt()) {
1202                         p.getArg('[', ']');
1203                         p.skip_spaces(true);
1204                 }
1205                 p.getArg('{', '}');
1206                 p.skip_spaces(true);
1207                 Token t = p.get_token();
1208                 bool shaded = false;
1209                 if (t.asInput() == "\\begin") {
1210                         p.skip_spaces(true);
1211                         if (p.getArg('{', '}') == "shaded")
1212                                 shaded = true;
1213                 }
1214                 p.popPosition();
1215                 if (shaded)
1216                         parse_outer_box(p, os, FLAG_END, outer,
1217                                         parent_context, name, "shaded");
1218                 else
1219                         parse_box(p, os, 0, FLAG_END, outer, parent_context,
1220                                   "", "", name);
1221                 p.skip_spaces();
1222         }
1223
1224         else if (name == "comment") {
1225                 eat_whitespace(p, os, parent_context, false);
1226                 parent_context.check_layout(os);
1227                 begin_inset(os, "Note Comment\n");
1228                 os << "status open\n";
1229                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1230                 end_inset(os);
1231                 p.skip_spaces();
1232                 skip_braces(p); // eat {} that might by set by LyX behind comments
1233         }
1234
1235         else if (name == "lyxgreyedout") {
1236                 eat_whitespace(p, os, parent_context, false);
1237                 parent_context.check_layout(os);
1238                 begin_inset(os, "Note Greyedout\n");
1239                 os << "status open\n";
1240                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1241                 end_inset(os);
1242                 p.skip_spaces();
1243                 if (!preamble.notefontcolor().empty())
1244                         preamble.registerAutomaticallyLoadedPackage("color");
1245         }
1246
1247         else if (name == "framed" || name == "shaded") {
1248                 eat_whitespace(p, os, parent_context, false);
1249                 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1250                 p.skip_spaces();
1251         }
1252
1253         else if (name == "lstlisting") {
1254                 eat_whitespace(p, os, parent_context, false);
1255                 // FIXME handle listings with parameters
1256                 //       If this is added, don't forgot to handle the
1257                 //       automatic color package loading
1258                 if (p.hasOpt())
1259                         parse_unknown_environment(p, name, os, FLAG_END,
1260                                                   outer, parent_context);
1261                 else
1262                         parse_listings(p, os, parent_context);
1263                 p.skip_spaces();
1264         }
1265
1266         else if (!parent_context.new_layout_allowed)
1267                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1268                                           parent_context);
1269
1270         // Alignment and spacing settings
1271         // FIXME (bug xxxx): These settings can span multiple paragraphs and
1272         //                                       therefore are totally broken!
1273         // Note that \centering, raggedright, and raggedleft cannot be handled, as
1274         // they are commands not environments. They are furthermore switches that
1275         // can be ended by another switches, but also by commands like \footnote or
1276         // \parbox. So the only safe way is to leave them untouched.
1277         else if (name == "center" || name == "centering" ||
1278                  name == "flushleft" || name == "flushright" ||
1279                  name == "singlespace" || name == "onehalfspace" ||
1280                  name == "doublespace" || name == "spacing") {
1281                 eat_whitespace(p, os, parent_context, false);
1282                 // We must begin a new paragraph if not already done
1283                 if (! parent_context.atParagraphStart()) {
1284                         parent_context.check_end_layout(os);
1285                         parent_context.new_paragraph(os);
1286                 }
1287                 if (name == "flushleft")
1288                         parent_context.add_extra_stuff("\\align left\n");
1289                 else if (name == "flushright")
1290                         parent_context.add_extra_stuff("\\align right\n");
1291                 else if (name == "center" || name == "centering")
1292                         parent_context.add_extra_stuff("\\align center\n");
1293                 else if (name == "singlespace")
1294                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1295                 else if (name == "onehalfspace")
1296                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1297                 else if (name == "doublespace")
1298                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1299                 else if (name == "spacing")
1300                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1301                 parse_text(p, os, FLAG_END, outer, parent_context);
1302                 // Just in case the environment is empty
1303                 parent_context.extra_stuff.erase();
1304                 // We must begin a new paragraph to reset the alignment
1305                 parent_context.new_paragraph(os);
1306                 p.skip_spaces();
1307         }
1308
1309         // The single '=' is meant here.
1310         else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1311                 eat_whitespace(p, os, parent_context, false);
1312                 Context context(true, parent_context.textclass, newlayout,
1313                                 parent_context.layout, parent_context.font);
1314                 if (parent_context.deeper_paragraph) {
1315                         // We are beginning a nested environment after a
1316                         // deeper paragraph inside the outer list environment.
1317                         // Therefore we don't need to output a "begin deeper".
1318                         context.need_end_deeper = true;
1319                 }
1320                 parent_context.check_end_layout(os);
1321                 if (last_env == name) {
1322                         // we need to output a separator since LyX would export
1323                         // the two environments as one otherwise (bug 5716)
1324                         docstring const sep = from_ascii("--Separator--");
1325                         TeX2LyXDocClass const & textclass(parent_context.textclass);
1326                         if (textclass.hasLayout(sep)) {
1327                                 Context newcontext(parent_context);
1328                                 newcontext.layout = &(textclass[sep]);
1329                                 newcontext.check_layout(os);
1330                                 newcontext.check_end_layout(os);
1331                         } else {
1332                                 parent_context.check_layout(os);
1333                                 begin_inset(os, "Note Note\n");
1334                                 os << "status closed\n";
1335                                 Context newcontext(true, textclass,
1336                                                 &(textclass.defaultLayout()));
1337                                 newcontext.check_layout(os);
1338                                 newcontext.check_end_layout(os);
1339                                 end_inset(os);
1340                                 parent_context.check_end_layout(os);
1341                         }
1342                 }
1343                 switch (context.layout->latextype) {
1344                 case  LATEX_LIST_ENVIRONMENT:
1345                         context.add_par_extra_stuff("\\labelwidthstring "
1346                                                     + p.verbatim_item() + '\n');
1347                         p.skip_spaces();
1348                         break;
1349                 case  LATEX_BIB_ENVIRONMENT:
1350                         p.verbatim_item(); // swallow next arg
1351                         p.skip_spaces();
1352                         break;
1353                 default:
1354                         break;
1355                 }
1356                 context.check_deeper(os);
1357                 // handle known optional and required arguments
1358                 // layouts require all optional arguments before the required ones
1359                 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1360                 // It is impossible to place anything after the environment name,
1361                 // but before the first \\item.
1362                 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1363                         bool need_layout = true;
1364                         unsigned int optargs = 0;
1365                         while (optargs < context.layout->optargs) {
1366                                 eat_whitespace(p, os, context, false);
1367                                 if (p.next_token().cat() == catEscape ||
1368                                     p.next_token().character() != '[') 
1369                                         break;
1370                                 p.get_token(); // eat '['
1371                                 if (need_layout) {
1372                                         context.check_layout(os);
1373                                         need_layout = false;
1374                                 }
1375                                 begin_inset(os, "Argument\n");
1376                                 os << "status collapsed\n\n";
1377                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1378                                 end_inset(os);
1379                                 eat_whitespace(p, os, context, false);
1380                                 ++optargs;
1381                         }
1382                         unsigned int reqargs = 0;
1383                         while (reqargs < context.layout->reqargs) {
1384                                 eat_whitespace(p, os, context, false);
1385                                 if (p.next_token().cat() != catBegin)
1386                                         break;
1387                                 p.get_token(); // eat '{'
1388                                 if (need_layout) {
1389                                         context.check_layout(os);
1390                                         need_layout = false;
1391                                 }
1392                                 begin_inset(os, "Argument\n");
1393                                 os << "status collapsed\n\n";
1394                                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1395                                 end_inset(os);
1396                                 eat_whitespace(p, os, context, false);
1397                                 ++reqargs;
1398                         }
1399                 }
1400                 parse_text(p, os, FLAG_END, outer, context);
1401                 context.check_end_layout(os);
1402                 if (parent_context.deeper_paragraph) {
1403                         // We must suppress the "end deeper" because we
1404                         // suppressed the "begin deeper" above.
1405                         context.need_end_deeper = false;
1406                 }
1407                 context.check_end_deeper(os);
1408                 parent_context.new_paragraph(os);
1409                 p.skip_spaces();
1410                 if (!title_layout_found)
1411                         title_layout_found = newlayout->intitle;
1412         }
1413
1414         // The single '=' is meant here.
1415         else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1416                 eat_whitespace(p, os, parent_context, false);
1417                 parent_context.check_layout(os);
1418                 begin_inset(os, "Flex ");
1419                 os << to_utf8(newinsetlayout->name()) << '\n'
1420                    << "status collapsed\n";
1421                 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1422                 end_inset(os);
1423         }
1424
1425         else if (name == "appendix") {
1426                 // This is no good latex style, but it works and is used in some documents...
1427                 eat_whitespace(p, os, parent_context, false);
1428                 parent_context.check_end_layout(os);
1429                 Context context(true, parent_context.textclass, parent_context.layout,
1430                                 parent_context.layout, parent_context.font);
1431                 context.check_layout(os);
1432                 os << "\\start_of_appendix\n";
1433                 parse_text(p, os, FLAG_END, outer, context);
1434                 context.check_end_layout(os);
1435                 p.skip_spaces();
1436         }
1437
1438         else if (known_environments.find(name) != known_environments.end()) {
1439                 vector<ArgumentType> arguments = known_environments[name];
1440                 // The last "argument" denotes wether we may translate the
1441                 // environment contents to LyX
1442                 // The default required if no argument is given makes us
1443                 // compatible with the reLyXre environment.
1444                 ArgumentType contents = arguments.empty() ?
1445                         required :
1446                         arguments.back();
1447                 if (!arguments.empty())
1448                         arguments.pop_back();
1449                 // See comment in parse_unknown_environment()
1450                 bool const specialfont =
1451                         (parent_context.font != parent_context.normalfont);
1452                 bool const new_layout_allowed =
1453                         parent_context.new_layout_allowed;
1454                 if (specialfont)
1455                         parent_context.new_layout_allowed = false;
1456                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1457                                 outer, parent_context);
1458                 if (contents == verbatim)
1459                         handle_ert(os, p.verbatimEnvironment(name),
1460                                    parent_context);
1461                 else
1462                         parse_text_snippet(p, os, FLAG_END, outer,
1463                                            parent_context);
1464                 handle_ert(os, "\\end{" + name + "}", parent_context);
1465                 if (specialfont)
1466                         parent_context.new_layout_allowed = new_layout_allowed;
1467         }
1468
1469         else
1470                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1471                                           parent_context);
1472
1473         last_env = name;
1474         active_environments.pop_back();
1475 }
1476
1477
1478 /// parses a comment and outputs it to \p os.
1479 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1480 {
1481         LASSERT(t.cat() == catComment, return);
1482         if (!t.cs().empty()) {
1483                 context.check_layout(os);
1484                 handle_comment(os, '%' + t.cs(), context);
1485                 if (p.next_token().cat() == catNewline) {
1486                         // A newline after a comment line starts a new
1487                         // paragraph
1488                         if (context.new_layout_allowed) {
1489                                 if(!context.atParagraphStart())
1490                                         // Only start a new paragraph if not already
1491                                         // done (we might get called recursively)
1492                                         context.new_paragraph(os);
1493                         } else
1494                                 handle_ert(os, "\n", context);
1495                         eat_whitespace(p, os, context, true);
1496                 }
1497         } else {
1498                 // "%\n" combination
1499                 p.skip_spaces();
1500         }
1501 }
1502
1503
1504 /*!
1505  * Reads spaces and comments until the first non-space, non-comment token.
1506  * New paragraphs (double newlines or \\par) are handled like simple spaces
1507  * if \p eatParagraph is true.
1508  * Spaces are skipped, but comments are written to \p os.
1509  */
1510 void eat_whitespace(Parser & p, ostream & os, Context & context,
1511                     bool eatParagraph)
1512 {
1513         while (p.good()) {
1514                 Token const & t = p.get_token();
1515                 if (t.cat() == catComment)
1516                         parse_comment(p, os, t, context);
1517                 else if ((! eatParagraph && p.isParagraph()) ||
1518                          (t.cat() != catSpace && t.cat() != catNewline)) {
1519                         p.putback();
1520                         return;
1521                 }
1522         }
1523 }
1524
1525
1526 /*!
1527  * Set a font attribute, parse text and reset the font attribute.
1528  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1529  * \param currentvalue Current value of the attribute. Is set to the new
1530  * value during parsing.
1531  * \param newvalue New value of the attribute
1532  */
1533 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1534                            Context & context, string const & attribute,
1535                            string & currentvalue, string const & newvalue)
1536 {
1537         context.check_layout(os);
1538         string const oldvalue = currentvalue;
1539         currentvalue = newvalue;
1540         os << '\n' << attribute << ' ' << newvalue << "\n";
1541         parse_text_snippet(p, os, flags, outer, context);
1542         context.check_layout(os);
1543         os << '\n' << attribute << ' ' << oldvalue << "\n";
1544         currentvalue = oldvalue;
1545 }
1546
1547
1548 /// get the arguments of a natbib or jurabib citation command
1549 void get_cite_arguments(Parser & p, bool natbibOrder,
1550         string & before, string & after)
1551 {
1552         // We need to distinguish "" and "[]", so we can't use p.getOpt().
1553
1554         // text before the citation
1555         before.clear();
1556         // text after the citation
1557         after = p.getFullOpt();
1558
1559         if (!after.empty()) {
1560                 before = p.getFullOpt();
1561                 if (natbibOrder && !before.empty())
1562                         swap(before, after);
1563         }
1564 }
1565
1566
1567 /// Convert filenames with TeX macros and/or quotes to something LyX
1568 /// can understand
1569 string const normalize_filename(string const & name)
1570 {
1571         Parser p(trim(name, "\""));
1572         ostringstream os;
1573         while (p.good()) {
1574                 Token const & t = p.get_token();
1575                 if (t.cat() != catEscape)
1576                         os << t.asInput();
1577                 else if (t.cs() == "lyxdot") {
1578                         // This is used by LyX for simple dots in relative
1579                         // names
1580                         os << '.';
1581                         p.skip_spaces();
1582                 } else if (t.cs() == "space") {
1583                         os << ' ';
1584                         p.skip_spaces();
1585                 } else
1586                         os << t.asInput();
1587         }
1588         return os.str();
1589 }
1590
1591
1592 /// Convert \p name from TeX convention (relative to master file) to LyX
1593 /// convention (relative to .lyx file) if it is relative
1594 void fix_relative_filename(string & name)
1595 {
1596         if (FileName::isAbsolute(name))
1597                 return;
1598
1599         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1600                                    from_utf8(getParentFilePath())));
1601 }
1602
1603
1604 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1605 void parse_noweb(Parser & p, ostream & os, Context & context)
1606 {
1607         // assemble the rest of the keyword
1608         string name("<<");
1609         bool scrap = false;
1610         while (p.good()) {
1611                 Token const & t = p.get_token();
1612                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1613                         name += ">>";
1614                         p.get_token();
1615                         scrap = (p.good() && p.next_token().asInput() == "=");
1616                         if (scrap)
1617                                 name += p.get_token().asInput();
1618                         break;
1619                 }
1620                 name += t.asInput();
1621         }
1622
1623         if (!scrap || !context.new_layout_allowed ||
1624             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1625                 cerr << "Warning: Could not interpret '" << name
1626                      << "'. Ignoring it." << endl;
1627                 return;
1628         }
1629
1630         // We use new_paragraph instead of check_end_layout because the stuff
1631         // following the noweb chunk needs to start with a \begin_layout.
1632         // This may create a new paragraph even if there was none in the
1633         // noweb file, but the alternative is an invalid LyX file. Since
1634         // noweb code chunks are implemented with a layout style in LyX they
1635         // always must be in an own paragraph.
1636         context.new_paragraph(os);
1637         Context newcontext(true, context.textclass,
1638                 &context.textclass[from_ascii("Scrap")]);
1639         newcontext.check_layout(os);
1640         os << name;
1641         while (p.good()) {
1642                 Token const & t = p.get_token();
1643                 // We abuse the parser a bit, because this is no TeX syntax
1644                 // at all.
1645                 if (t.cat() == catEscape)
1646                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1647                 else {
1648                         ostringstream oss;
1649                         Context tmp(false, context.textclass,
1650                                     &context.textclass[from_ascii("Scrap")]);
1651                         tmp.need_end_layout = true;
1652                         tmp.check_layout(oss);
1653                         os << subst(t.asInput(), "\n", oss.str());
1654                 }
1655                 // The scrap chunk is ended by an @ at the beginning of a line.
1656                 // After the @ the line may contain a comment and/or
1657                 // whitespace, but nothing else.
1658                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1659                     (p.next_token().cat() == catSpace ||
1660                      p.next_token().cat() == catNewline ||
1661                      p.next_token().cat() == catComment)) {
1662                         while (p.good() && p.next_token().cat() == catSpace)
1663                                 os << p.get_token().asInput();
1664                         if (p.next_token().cat() == catComment)
1665                                 // The comment includes a final '\n'
1666                                 os << p.get_token().asInput();
1667                         else {
1668                                 if (p.next_token().cat() == catNewline)
1669                                         p.get_token();
1670                                 os << '\n';
1671                         }
1672                         break;
1673                 }
1674         }
1675         newcontext.check_end_layout(os);
1676 }
1677
1678
1679 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1680 bool is_macro(Parser & p)
1681 {
1682         Token first = p.curr_token();
1683         if (first.cat() != catEscape || !p.good())
1684                 return false;
1685         if (first.cs() == "def")
1686                 return true;
1687         if (first.cs() != "global" && first.cs() != "long")
1688                 return false;
1689         Token second = p.get_token();
1690         int pos = 1;
1691         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1692                second.cat() == catNewline || second.cat() == catComment)) {
1693                 second = p.get_token();
1694                 pos++;
1695         }
1696         bool secondvalid = second.cat() == catEscape;
1697         Token third;
1698         bool thirdvalid = false;
1699         if (p.good() && first.cs() == "global" && secondvalid &&
1700             second.cs() == "long") {
1701                 third = p.get_token();
1702                 pos++;
1703                 while (p.good() && !p.isParagraph() &&
1704                        (third.cat() == catSpace ||
1705                         third.cat() == catNewline ||
1706                         third.cat() == catComment)) {
1707                         third = p.get_token();
1708                         pos++;
1709                 }
1710                 thirdvalid = third.cat() == catEscape;
1711         }
1712         for (int i = 0; i < pos; ++i)
1713                 p.putback();
1714         if (!secondvalid)
1715                 return false;
1716         if (!thirdvalid)
1717                 return (first.cs() == "global" || first.cs() == "long") &&
1718                        second.cs() == "def";
1719         return first.cs() == "global" && second.cs() == "long" &&
1720                third.cs() == "def";
1721 }
1722
1723
1724 /// Parse a macro definition (assumes that is_macro() returned true)
1725 void parse_macro(Parser & p, ostream & os, Context & context)
1726 {
1727         context.check_layout(os);
1728         Token first = p.curr_token();
1729         Token second;
1730         Token third;
1731         string command = first.asInput();
1732         if (first.cs() != "def") {
1733                 p.get_token();
1734                 eat_whitespace(p, os, context, false);
1735                 second = p.curr_token();
1736                 command += second.asInput();
1737                 if (second.cs() != "def") {
1738                         p.get_token();
1739                         eat_whitespace(p, os, context, false);
1740                         third = p.curr_token();
1741                         command += third.asInput();
1742                 }
1743         }
1744         eat_whitespace(p, os, context, false);
1745         string const name = p.get_token().cs();
1746         eat_whitespace(p, os, context, false);
1747
1748         // parameter text
1749         bool simple = true;
1750         string paramtext;
1751         int arity = 0;
1752         while (p.next_token().cat() != catBegin) {
1753                 if (p.next_token().cat() == catParameter) {
1754                         // # found
1755                         p.get_token();
1756                         paramtext += "#";
1757
1758                         // followed by number?
1759                         if (p.next_token().cat() == catOther) {
1760                                 char c = p.getChar();
1761                                 paramtext += c;
1762                                 // number = current arity + 1?
1763                                 if (c == arity + '0' + 1)
1764                                         ++arity;
1765                                 else
1766                                         simple = false;
1767                         } else
1768                                 paramtext += p.get_token().cs();
1769                 } else {
1770                         paramtext += p.get_token().cs();
1771                         simple = false;
1772                 }
1773         }
1774
1775         // only output simple (i.e. compatible) macro as FormulaMacros
1776         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1777         if (simple) {
1778                 context.check_layout(os);
1779                 begin_inset(os, "FormulaMacro");
1780                 os << "\n\\def" << ert;
1781                 end_inset(os);
1782         } else
1783                 handle_ert(os, command + ert, context);
1784 }
1785
1786 } // anonymous namespace
1787
1788
1789 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1790                 Context & context)
1791 {
1792         Layout const * newlayout = 0;
1793         InsetLayout const * newinsetlayout = 0;
1794         // Store the latest bibliographystyle and nocite{*} option
1795         // (needed for bibtex inset)
1796         string btprint;
1797         string bibliographystyle;
1798         bool const use_natbib = preamble.isPackageUsed("natbib");
1799         bool const use_jurabib = preamble.isPackageUsed("jurabib");
1800         string last_env;
1801         bool title_layout_found = false;
1802         while (p.good()) {
1803                 Token const & t = p.get_token();
1804
1805 #ifdef FILEDEBUG
1806                 debugToken(cerr, t, flags);
1807 #endif
1808
1809                 if (flags & FLAG_ITEM) {
1810                         if (t.cat() == catSpace)
1811                                 continue;
1812
1813                         flags &= ~FLAG_ITEM;
1814                         if (t.cat() == catBegin) {
1815                                 // skip the brace and collect everything to the next matching
1816                                 // closing brace
1817                                 flags |= FLAG_BRACE_LAST;
1818                                 continue;
1819                         }
1820
1821                         // handle only this single token, leave the loop if done
1822                         flags |= FLAG_LEAVE;
1823                 }
1824
1825                 if (t.cat() != catEscape && t.character() == ']' &&
1826                     (flags & FLAG_BRACK_LAST))
1827                         return;
1828                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1829                         return;
1830
1831                 // If there is anything between \end{env} and \begin{env} we
1832                 // don't need to output a separator.
1833                 if (t.cat() != catSpace && t.cat() != catNewline &&
1834                     t.asInput() != "\\begin")
1835                         last_env = "";
1836
1837                 //
1838                 // cat codes
1839                 //
1840                 if (t.cat() == catMath) {
1841                         // we are inside some text mode thingy, so opening new math is allowed
1842                         context.check_layout(os);
1843                         begin_inset(os, "Formula ");
1844                         Token const & n = p.get_token();
1845                         if (n.cat() == catMath && outer) {
1846                                 // TeX's $$...$$ syntax for displayed math
1847                                 os << "\\[";
1848                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1849                                 os << "\\]";
1850                                 p.get_token(); // skip the second '$' token
1851                         } else {
1852                                 // simple $...$  stuff
1853                                 p.putback();
1854                                 os << '$';
1855                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1856                                 os << '$';
1857                         }
1858                         end_inset(os);
1859                 }
1860
1861                 else if (t.cat() == catSuper || t.cat() == catSub)
1862                         cerr << "catcode " << t << " illegal in text mode\n";
1863
1864                 // Basic support for english quotes. This should be
1865                 // extended to other quotes, but is not so easy (a
1866                 // left english quote is the same as a right german
1867                 // quote...)
1868                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1869                         context.check_layout(os);
1870                         begin_inset(os, "Quotes ");
1871                         os << "eld";
1872                         end_inset(os);
1873                         p.get_token();
1874                         skip_braces(p);
1875                 }
1876                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1877                         context.check_layout(os);
1878                         begin_inset(os, "Quotes ");
1879                         os << "erd";
1880                         end_inset(os);
1881                         p.get_token();
1882                         skip_braces(p);
1883                 }
1884
1885                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1886                         context.check_layout(os);
1887                         begin_inset(os, "Quotes ");
1888                         os << "ald";
1889                         end_inset(os);
1890                         p.get_token();
1891                         skip_braces(p);
1892                 }
1893
1894                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1895                         context.check_layout(os);
1896                         begin_inset(os, "Quotes ");
1897                         os << "ard";
1898                         end_inset(os);
1899                         p.get_token();
1900                         skip_braces(p);
1901                 }
1902
1903                 else if (t.asInput() == "<"
1904                          && p.next_token().asInput() == "<" && noweb_mode) {
1905                         p.get_token();
1906                         parse_noweb(p, os, context);
1907                 }
1908
1909                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1910                         check_space(p, os, context);
1911
1912                 else if (t.character() == '[' && noweb_mode &&
1913                          p.next_token().character() == '[') {
1914                         // These can contain underscores
1915                         p.putback();
1916                         string const s = p.getFullOpt() + ']';
1917                         if (p.next_token().character() == ']')
1918                                 p.get_token();
1919                         else
1920                                 cerr << "Warning: Inserting missing ']' in '"
1921                                      << s << "'." << endl;
1922                         handle_ert(os, s, context);
1923                 }
1924
1925                 else if (t.cat() == catLetter) {
1926                         context.check_layout(os);
1927                         // Workaround for bug 4752.
1928                         // FIXME: This whole code block needs to be removed
1929                         //        when the bug is fixed and tex2lyx produces
1930                         //        the updated file format.
1931                         // The replacement algorithm in LyX is so stupid that
1932                         // it even translates a phrase if it is part of a word.
1933                         bool handled = false;
1934                         for (int const * l = known_phrase_lengths; *l; ++l) {
1935                                 string phrase = t.cs();
1936                                 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1937                                         phrase += p.get_token().cs();
1938                                 if (is_known(phrase, known_coded_phrases)) {
1939                                         handle_ert(os, phrase, context);
1940                                         handled = true;
1941                                         break;
1942                                 } else {
1943                                         for (size_t i = 1; i < phrase.length(); ++i)
1944                                                 p.putback();
1945                                 }
1946                         }
1947                         if (!handled)
1948                                 os << t.cs();
1949                 }
1950
1951                 else if (t.cat() == catOther ||
1952                                t.cat() == catAlign ||
1953                                t.cat() == catParameter) {
1954                         // This translates "&" to "\\&" which may be wrong...
1955                         context.check_layout(os);
1956                         os << t.cs();
1957                 }
1958
1959                 else if (p.isParagraph()) {
1960                         if (context.new_layout_allowed)
1961                                 context.new_paragraph(os);
1962                         else
1963                                 handle_ert(os, "\\par ", context);
1964                         eat_whitespace(p, os, context, true);
1965                 }
1966
1967                 else if (t.cat() == catActive) {
1968                         context.check_layout(os);
1969                         if (t.character() == '~') {
1970                                 if (context.layout->free_spacing)
1971                                         os << ' ';
1972                                 else {
1973                                         begin_inset(os, "space ~\n");
1974                                         end_inset(os);
1975                                 }
1976                         } else
1977                                 os << t.cs();
1978                 }
1979
1980                 else if (t.cat() == catBegin &&
1981                          p.next_token().cat() == catEnd) {
1982                         // {}
1983                         Token const prev = p.prev_token();
1984                         p.get_token();
1985                         if (p.next_token().character() == '`' ||
1986                             (prev.character() == '-' &&
1987                              p.next_token().character() == '-'))
1988                                 ; // ignore it in {}`` or -{}-
1989                         else
1990                                 handle_ert(os, "{}", context);
1991
1992                 }
1993
1994                 else if (t.cat() == catBegin) {
1995                         context.check_layout(os);
1996                         // special handling of font attribute changes
1997                         Token const prev = p.prev_token();
1998                         Token const next = p.next_token();
1999                         TeXFont const oldFont = context.font;
2000                         if (next.character() == '[' ||
2001                             next.character() == ']' ||
2002                             next.character() == '*') {
2003                                 p.get_token();
2004                                 if (p.next_token().cat() == catEnd) {
2005                                         os << next.cs();
2006                                         p.get_token();
2007                                 } else {
2008                                         p.putback();
2009                                         handle_ert(os, "{", context);
2010                                         parse_text_snippet(p, os,
2011                                                         FLAG_BRACE_LAST,
2012                                                         outer, context);
2013                                         handle_ert(os, "}", context);
2014                                 }
2015                         } else if (! context.new_layout_allowed) {
2016                                 handle_ert(os, "{", context);
2017                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2018                                                    outer, context);
2019                                 handle_ert(os, "}", context);
2020                         } else if (is_known(next.cs(), known_sizes)) {
2021                                 // next will change the size, so we must
2022                                 // reset it here
2023                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2024                                                    outer, context);
2025                                 if (!context.atParagraphStart())
2026                                         os << "\n\\size "
2027                                            << context.font.size << "\n";
2028                         } else if (is_known(next.cs(), known_font_families)) {
2029                                 // next will change the font family, so we
2030                                 // must reset it here
2031                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2032                                                    outer, context);
2033                                 if (!context.atParagraphStart())
2034                                         os << "\n\\family "
2035                                            << context.font.family << "\n";
2036                         } else if (is_known(next.cs(), known_font_series)) {
2037                                 // next will change the font series, so we
2038                                 // must reset it here
2039                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2040                                                    outer, context);
2041                                 if (!context.atParagraphStart())
2042                                         os << "\n\\series "
2043                                            << context.font.series << "\n";
2044                         } else if (is_known(next.cs(), known_font_shapes)) {
2045                                 // next will change the font shape, 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\\shape "
2051                                            << context.font.shape << "\n";
2052                         } else if (is_known(next.cs(), known_old_font_families) ||
2053                                    is_known(next.cs(), known_old_font_series) ||
2054                                    is_known(next.cs(), known_old_font_shapes)) {
2055                                 // next will change the font family, series
2056                                 // and shape, so we must reset it here
2057                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2058                                                    outer, context);
2059                                 if (!context.atParagraphStart())
2060                                         os <<  "\n\\family "
2061                                            << context.font.family
2062                                            << "\n\\series "
2063                                            << context.font.series
2064                                            << "\n\\shape "
2065                                            << context.font.shape << "\n";
2066                         } else {
2067                                 handle_ert(os, "{", context);
2068                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2069                                                    outer, context);
2070                                 handle_ert(os, "}", context);
2071                         }
2072                 }
2073
2074                 else if (t.cat() == catEnd) {
2075                         if (flags & FLAG_BRACE_LAST) {
2076                                 return;
2077                         }
2078                         cerr << "stray '}' in text\n";
2079                         handle_ert(os, "}", context);
2080                 }
2081
2082                 else if (t.cat() == catComment)
2083                         parse_comment(p, os, t, context);
2084
2085                 //
2086                 // control sequences
2087                 //
2088
2089                 else if (t.cs() == "(") {
2090                         context.check_layout(os);
2091                         begin_inset(os, "Formula");
2092                         os << " \\(";
2093                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2094                         os << "\\)";
2095                         end_inset(os);
2096                 }
2097
2098                 else if (t.cs() == "[") {
2099                         context.check_layout(os);
2100                         begin_inset(os, "Formula");
2101                         os << " \\[";
2102                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2103                         os << "\\]";
2104                         end_inset(os);
2105                 }
2106
2107                 else if (t.cs() == "begin")
2108                         parse_environment(p, os, outer, last_env,
2109                                           title_layout_found, context);
2110
2111                 else if (t.cs() == "end") {
2112                         if (flags & FLAG_END) {
2113                                 // eat environment name
2114                                 string const name = p.getArg('{', '}');
2115                                 if (name != active_environment())
2116                                         cerr << "\\end{" + name + "} does not match \\begin{"
2117                                                 + active_environment() + "}\n";
2118                                 return;
2119                         }
2120                         p.error("found 'end' unexpectedly");
2121                 }
2122
2123                 else if (t.cs() == "item") {
2124                         p.skip_spaces();
2125                         string s;
2126                         bool optarg = false;
2127                         if (p.next_token().cat() != catEscape &&
2128                             p.next_token().character() == '[') {
2129                                 p.get_token(); // eat '['
2130                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2131                                                        outer, context);
2132                                 optarg = true;
2133                         }
2134                         context.set_item();
2135                         context.check_layout(os);
2136                         if (context.has_item) {
2137                                 // An item in an unknown list-like environment
2138                                 // FIXME: Do this in check_layout()!
2139                                 context.has_item = false;
2140                                 if (optarg)
2141                                         handle_ert(os, "\\item", context);
2142                                 else
2143                                         handle_ert(os, "\\item ", context);
2144                         }
2145                         if (optarg) {
2146                                 if (context.layout->labeltype != LABEL_MANUAL) {
2147                                         // LyX does not support \item[\mybullet]
2148                                         // in itemize environments
2149                                         handle_ert(os, "[", context);
2150                                         os << s;
2151                                         handle_ert(os, "]", context);
2152                                 } else if (!s.empty()) {
2153                                         // The space is needed to separate the
2154                                         // item from the rest of the sentence.
2155                                         os << s << ' ';
2156                                         eat_whitespace(p, os, context, false);
2157                                 }
2158                         }
2159                 }
2160
2161                 else if (t.cs() == "bibitem") {
2162                         context.set_item();
2163                         context.check_layout(os);
2164                         string label = convert_command_inset_arg(p.getArg('[', ']'));
2165                         string key = convert_command_inset_arg(p.verbatim_item());
2166                         if (contains(label, '\\') || contains(key, '\\')) {
2167                                 // LyX can't handle LaTeX commands in labels or keys
2168                                 handle_ert(os, t.asInput() + '[' + label +
2169                                                "]{" + p.verbatim_item() + '}',
2170                                            context);
2171                         } else {
2172                                 begin_command_inset(os, "bibitem", "bibitem");
2173                                 os << "label \"" << label << "\"\n"
2174                                       "key \"" << key << "\"\n";
2175                                 end_inset(os);
2176                         }
2177                 }
2178
2179                 else if (is_macro(p))
2180                         parse_macro(p, os, context);
2181
2182                 else if (t.cs() == "noindent") {
2183                         p.skip_spaces();
2184                         context.add_par_extra_stuff("\\noindent\n");
2185                 }
2186
2187                 else if (t.cs() == "appendix") {
2188                         context.add_par_extra_stuff("\\start_of_appendix\n");
2189                         // We need to start a new paragraph. Otherwise the
2190                         // appendix in 'bla\appendix\chapter{' would start
2191                         // too late.
2192                         context.new_paragraph(os);
2193                         // We need to make sure that the paragraph is
2194                         // generated even if it is empty. Otherwise the
2195                         // appendix in '\par\appendix\par\chapter{' would
2196                         // start too late.
2197                         context.check_layout(os);
2198                         // FIXME: This is a hack to prevent paragraph
2199                         // deletion if it is empty. Handle this better!
2200                         handle_comment(os,
2201                                 "%dummy comment inserted by tex2lyx to "
2202                                 "ensure that this paragraph is not empty",
2203                                 context);
2204                         // Both measures above may generate an additional
2205                         // empty paragraph, but that does not hurt, because
2206                         // whitespace does not matter here.
2207                         eat_whitespace(p, os, context, true);
2208                 }
2209
2210                 // Must catch empty dates before findLayout is called below
2211                 else if (t.cs() == "date") {
2212                         string const date = p.verbatim_item();
2213                         if (date.empty())
2214                                 preamble.suppressDate(true);
2215                         else {
2216                                 preamble.suppressDate(false);
2217                                 if (context.new_layout_allowed &&
2218                                     (newlayout = findLayout(context.textclass,
2219                                                             t.cs(), true))) {
2220                                         // write the layout
2221                                         output_command_layout(os, p, outer,
2222                                                         context, newlayout);
2223                                         p.skip_spaces();
2224                                         if (!title_layout_found)
2225                                                 title_layout_found = newlayout->intitle;
2226                                 } else
2227                                         handle_ert(os, "\\date{" + date + '}',
2228                                                         context);
2229                         }
2230                 }
2231
2232                 // Starred section headings
2233                 // Must attempt to parse "Section*" before "Section".
2234                 else if ((p.next_token().asInput() == "*") &&
2235                          context.new_layout_allowed &&
2236                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2237                         // write the layout
2238                         p.get_token();
2239                         output_command_layout(os, p, outer, context, newlayout);
2240                         p.skip_spaces();
2241                         if (!title_layout_found)
2242                                 title_layout_found = newlayout->intitle;
2243                 }
2244
2245                 // Section headings and the like
2246                 else if (context.new_layout_allowed &&
2247                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2248                         // write the layout
2249                         output_command_layout(os, p, outer, context, newlayout);
2250                         p.skip_spaces();
2251                         if (!title_layout_found)
2252                                 title_layout_found = newlayout->intitle;
2253                 }
2254
2255                 else if (t.cs() == "caption") {
2256                         p.skip_spaces();
2257                         context.check_layout(os);
2258                         p.skip_spaces();
2259                         begin_inset(os, "Caption\n");
2260                         Context newcontext(true, context.textclass);
2261                         newcontext.font = context.font;
2262                         newcontext.check_layout(os);
2263                         if (p.next_token().cat() != catEscape &&
2264                             p.next_token().character() == '[') {
2265                                 p.get_token(); // eat '['
2266                                 begin_inset(os, "Argument\n");
2267                                 os << "status collapsed\n";
2268                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2269                                 end_inset(os);
2270                                 eat_whitespace(p, os, context, false);
2271                         }
2272                         parse_text(p, os, FLAG_ITEM, outer, context);
2273                         context.check_end_layout(os);
2274                         // We don't need really a new paragraph, but
2275                         // we must make sure that the next item gets a \begin_layout.
2276                         context.new_paragraph(os);
2277                         end_inset(os);
2278                         p.skip_spaces();
2279                         newcontext.check_end_layout(os);
2280                 }
2281
2282                 else if (t.cs() == "subfloat") {
2283                         // the syntax is \subfloat[caption]{content}
2284                         // if it is a table of figure depends on the surrounding float
2285                         bool has_caption = false;
2286                         p.skip_spaces();
2287                         // do nothing if there is no outer float
2288                         if (!float_type.empty()) {
2289                                 context.check_layout(os);
2290                                 p.skip_spaces();
2291                                 begin_inset(os, "Float " + float_type + "\n");
2292                                 os << "wide false"
2293                                    << "\nsideways false"
2294                                    << "\nstatus collapsed\n\n";
2295                                 // test for caption
2296                                 string caption;
2297                                 if (p.next_token().cat() != catEscape &&
2298                                                 p.next_token().character() == '[') {
2299                                                         p.get_token(); // eat '['
2300                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2301                                                         has_caption = true;
2302                                 }
2303                                 // the content
2304                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2305                                 // the caption comes always as the last
2306                                 if (has_caption) {
2307                                         // we must make sure that the caption gets a \begin_layout
2308                                         os << "\n\\begin_layout Plain Layout";
2309                                         p.skip_spaces();
2310                                         begin_inset(os, "Caption\n");
2311                                         Context newcontext(true, context.textclass);
2312                                         newcontext.font = context.font;
2313                                         newcontext.check_layout(os);
2314                                         os << caption << "\n";
2315                                         newcontext.check_end_layout(os);
2316                                         // We don't need really a new paragraph, but
2317                                         // we must make sure that the next item gets a \begin_layout.
2318                                         //newcontext.new_paragraph(os);
2319                                         end_inset(os);
2320                                         p.skip_spaces();
2321                                 }
2322                                 // We don't need really a new paragraph, but
2323                                 // we must make sure that the next item gets a \begin_layout.
2324                                 if (has_caption)
2325                                         context.new_paragraph(os);
2326                                 end_inset(os);
2327                                 p.skip_spaces();
2328                                 context.check_end_layout(os);
2329                                 // close the layout we opened
2330                                 if (has_caption)
2331                                         os << "\n\\end_layout\n";
2332                         } else {
2333                                 // if the float type is not supported or there is no surrounding float
2334                                 // output it as ERT
2335                                 if (p.hasOpt()) {
2336                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2337                                         handle_ert(os, t.asInput() + '[' + opt_arg +
2338                                                "]{" + p.verbatim_item() + '}', context);
2339                                 } else
2340                                         handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2341                         }
2342                 }
2343
2344                 else if (t.cs() == "includegraphics") {
2345                         bool const clip = p.next_token().asInput() == "*";
2346                         if (clip)
2347                                 p.get_token();
2348                         string const arg = p.getArg('[', ']');
2349                         map<string, string> opts;
2350                         vector<string> keys;
2351                         split_map(arg, opts, keys);
2352                         if (clip)
2353                                 opts["clip"] = string();
2354                         string name = normalize_filename(p.verbatim_item());
2355
2356                         string const path = getMasterFilePath();
2357                         // We want to preserve relative / absolute filenames,
2358                         // therefore path is only used for testing
2359                         if (!makeAbsPath(name, path).exists()) {
2360                                 // The file extension is probably missing.
2361                                 // Now try to find it out.
2362                                 string const dvips_name =
2363                                         find_file(name, path,
2364                                                   known_dvips_graphics_formats);
2365                                 string const pdftex_name =
2366                                         find_file(name, path,
2367                                                   known_pdftex_graphics_formats);
2368                                 if (!dvips_name.empty()) {
2369                                         if (!pdftex_name.empty()) {
2370                                                 cerr << "This file contains the "
2371                                                         "latex snippet\n"
2372                                                         "\"\\includegraphics{"
2373                                                      << name << "}\".\n"
2374                                                         "However, files\n\""
2375                                                      << dvips_name << "\" and\n\""
2376                                                      << pdftex_name << "\"\n"
2377                                                         "both exist, so I had to make a "
2378                                                         "choice and took the first one.\n"
2379                                                         "Please move the unwanted one "
2380                                                         "someplace else and try again\n"
2381                                                         "if my choice was wrong."
2382                                                      << endl;
2383                                         }
2384                                         name = dvips_name;
2385                                 } else if (!pdftex_name.empty()) {
2386                                         name = pdftex_name;
2387                                         pdflatex = true;
2388                                 }
2389                         }
2390
2391                         if (makeAbsPath(name, path).exists())
2392                                 fix_relative_filename(name);
2393                         else
2394                                 cerr << "Warning: Could not find graphics file '"
2395                                      << name << "'." << endl;
2396
2397                         context.check_layout(os);
2398                         begin_inset(os, "Graphics ");
2399                         os << "\n\tfilename " << name << '\n';
2400                         if (opts.find("width") != opts.end())
2401                                 os << "\twidth "
2402                                    << translate_len(opts["width"]) << '\n';
2403                         if (opts.find("height") != opts.end())
2404                                 os << "\theight "
2405                                    << translate_len(opts["height"]) << '\n';
2406                         if (opts.find("scale") != opts.end()) {
2407                                 istringstream iss(opts["scale"]);
2408                                 double val;
2409                                 iss >> val;
2410                                 val = val*100;
2411                                 os << "\tscale " << val << '\n';
2412                         }
2413                         if (opts.find("angle") != opts.end()) {
2414                                 os << "\trotateAngle "
2415                                    << opts["angle"] << '\n';
2416                                 vector<string>::const_iterator a =
2417                                         find(keys.begin(), keys.end(), "angle");
2418                                 vector<string>::const_iterator s =
2419                                         find(keys.begin(), keys.end(), "width");
2420                                 if (s == keys.end())
2421                                         s = find(keys.begin(), keys.end(), "height");
2422                                 if (s == keys.end())
2423                                         s = find(keys.begin(), keys.end(), "scale");
2424                                 if (s != keys.end() && distance(s, a) > 0)
2425                                         os << "\tscaleBeforeRotation\n";
2426                         }
2427                         if (opts.find("origin") != opts.end()) {
2428                                 ostringstream ss;
2429                                 string const opt = opts["origin"];
2430                                 if (opt.find('l') != string::npos) ss << "left";
2431                                 if (opt.find('r') != string::npos) ss << "right";
2432                                 if (opt.find('c') != string::npos) ss << "center";
2433                                 if (opt.find('t') != string::npos) ss << "Top";
2434                                 if (opt.find('b') != string::npos) ss << "Bottom";
2435                                 if (opt.find('B') != string::npos) ss << "Baseline";
2436                                 if (!ss.str().empty())
2437                                         os << "\trotateOrigin " << ss.str() << '\n';
2438                                 else
2439                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2440                         }
2441                         if (opts.find("keepaspectratio") != opts.end())
2442                                 os << "\tkeepAspectRatio\n";
2443                         if (opts.find("clip") != opts.end())
2444                                 os << "\tclip\n";
2445                         if (opts.find("draft") != opts.end())
2446                                 os << "\tdraft\n";
2447                         if (opts.find("bb") != opts.end())
2448                                 os << "\tBoundingBox "
2449                                    << opts["bb"] << '\n';
2450                         int numberOfbbOptions = 0;
2451                         if (opts.find("bbllx") != opts.end())
2452                                 numberOfbbOptions++;
2453                         if (opts.find("bblly") != opts.end())
2454                                 numberOfbbOptions++;
2455                         if (opts.find("bburx") != opts.end())
2456                                 numberOfbbOptions++;
2457                         if (opts.find("bbury") != opts.end())
2458                                 numberOfbbOptions++;
2459                         if (numberOfbbOptions == 4)
2460                                 os << "\tBoundingBox "
2461                                    << opts["bbllx"] << " " << opts["bblly"] << " "
2462                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
2463                         else if (numberOfbbOptions > 0)
2464                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2465                         numberOfbbOptions = 0;
2466                         if (opts.find("natwidth") != opts.end())
2467                                 numberOfbbOptions++;
2468                         if (opts.find("natheight") != opts.end())
2469                                 numberOfbbOptions++;
2470                         if (numberOfbbOptions == 2)
2471                                 os << "\tBoundingBox 0bp 0bp "
2472                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
2473                         else if (numberOfbbOptions > 0)
2474                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2475                         ostringstream special;
2476                         if (opts.find("hiresbb") != opts.end())
2477                                 special << "hiresbb,";
2478                         if (opts.find("trim") != opts.end())
2479                                 special << "trim,";
2480                         if (opts.find("viewport") != opts.end())
2481                                 special << "viewport=" << opts["viewport"] << ',';
2482                         if (opts.find("totalheight") != opts.end())
2483                                 special << "totalheight=" << opts["totalheight"] << ',';
2484                         if (opts.find("type") != opts.end())
2485                                 special << "type=" << opts["type"] << ',';
2486                         if (opts.find("ext") != opts.end())
2487                                 special << "ext=" << opts["ext"] << ',';
2488                         if (opts.find("read") != opts.end())
2489                                 special << "read=" << opts["read"] << ',';
2490                         if (opts.find("command") != opts.end())
2491                                 special << "command=" << opts["command"] << ',';
2492                         string s_special = special.str();
2493                         if (!s_special.empty()) {
2494                                 // We had special arguments. Remove the trailing ','.
2495                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2496                         }
2497                         // TODO: Handle the unknown settings better.
2498                         // Warn about invalid options.
2499                         // Check whether some option was given twice.
2500                         end_inset(os);
2501                 }
2502
2503                 else if (t.cs() == "footnote" ||
2504                          (t.cs() == "thanks" && context.layout->intitle)) {
2505                         p.skip_spaces();
2506                         context.check_layout(os);
2507                         begin_inset(os, "Foot\n");
2508                         os << "status collapsed\n\n";
2509                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2510                         end_inset(os);
2511                 }
2512
2513                 else if (t.cs() == "marginpar") {
2514                         p.skip_spaces();
2515                         context.check_layout(os);
2516                         begin_inset(os, "Marginal\n");
2517                         os << "status collapsed\n\n";
2518                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2519                         end_inset(os);
2520                 }
2521
2522                 else if (t.cs() == "ensuremath") {
2523                         p.skip_spaces();
2524                         context.check_layout(os);
2525                         string const s = p.verbatim_item();
2526                         //FIXME: this never triggers in UTF8
2527                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2528                                 os << s;
2529                         else
2530                                 handle_ert(os, "\\ensuremath{" + s + "}",
2531                                            context);
2532                 }
2533
2534                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2535                         if (title_layout_found) {
2536                                 // swallow this
2537                                 skip_spaces_braces(p);
2538                         } else
2539                                 handle_ert(os, t.asInput(), context);
2540                 }
2541
2542                 else if (t.cs() == "tableofcontents") {
2543                         context.check_layout(os);
2544                         begin_command_inset(os, "toc", "tableofcontents");
2545                         end_inset(os);
2546                         skip_spaces_braces(p);
2547                 }
2548
2549                 else if (t.cs() == "listoffigures") {
2550                         context.check_layout(os);
2551                         begin_inset(os, "FloatList figure\n");
2552                         end_inset(os);
2553                         skip_spaces_braces(p);
2554                 }
2555
2556                 else if (t.cs() == "listoftables") {
2557                         context.check_layout(os);
2558                         begin_inset(os, "FloatList table\n");
2559                         end_inset(os);
2560                         skip_spaces_braces(p);
2561                 }
2562
2563                 else if (t.cs() == "listof") {
2564                         p.skip_spaces(true);
2565                         string const name = p.get_token().cs();
2566                         if (context.textclass.floats().typeExist(name)) {
2567                                 context.check_layout(os);
2568                                 begin_inset(os, "FloatList ");
2569                                 os << name << "\n";
2570                                 end_inset(os);
2571                                 p.get_token(); // swallow second arg
2572                         } else
2573                                 handle_ert(os, "\\listof{" + name + "}", context);
2574                 }
2575
2576                 else if (t.cs() == "textrm")
2577                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2578                                               context, "\\family",
2579                                               context.font.family, "roman");
2580
2581                 else if (t.cs() == "textsf")
2582                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2583                                               context, "\\family",
2584                                               context.font.family, "sans");
2585
2586                 else if (t.cs() == "texttt")
2587                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2588                                               context, "\\family",
2589                                               context.font.family, "typewriter");
2590
2591                 else if (t.cs() == "textmd")
2592                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2593                                               context, "\\series",
2594                                               context.font.series, "medium");
2595
2596                 else if (t.cs() == "textbf")
2597                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2598                                               context, "\\series",
2599                                               context.font.series, "bold");
2600
2601                 else if (t.cs() == "textup")
2602                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2603                                               context, "\\shape",
2604                                               context.font.shape, "up");
2605
2606                 else if (t.cs() == "textit")
2607                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2608                                               context, "\\shape",
2609                                               context.font.shape, "italic");
2610
2611                 else if (t.cs() == "textsl")
2612                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2613                                               context, "\\shape",
2614                                               context.font.shape, "slanted");
2615
2616                 else if (t.cs() == "textsc")
2617                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2618                                               context, "\\shape",
2619                                               context.font.shape, "smallcaps");
2620
2621                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2622                         context.check_layout(os);
2623                         TeXFont oldFont = context.font;
2624                         context.font.init();
2625                         context.font.size = oldFont.size;
2626                         os << "\n\\family " << context.font.family << "\n";
2627                         os << "\n\\series " << context.font.series << "\n";
2628                         os << "\n\\shape " << context.font.shape << "\n";
2629                         if (t.cs() == "textnormal") {
2630                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2631                                 output_font_change(os, context.font, oldFont);
2632                                 context.font = oldFont;
2633                         } else
2634                                 eat_whitespace(p, os, context, false);
2635                 }
2636
2637                 else if (t.cs() == "textcolor") {
2638                         // scheme is \textcolor{color name}{text}
2639                         string const color = p.verbatim_item();
2640                         // we only support the predefined colors of the color package
2641                         if (color == "black" || color == "blue" || color == "cyan"
2642                                 || color == "green" || color == "magenta" || color == "red"
2643                                 || color == "white" || color == "yellow") {
2644                                         context.check_layout(os);
2645                                         os << "\n\\color " << color << "\n";
2646                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2647                                         context.check_layout(os);
2648                                         os << "\n\\color inherit\n";
2649                                         preamble.registerAutomaticallyLoadedPackage("color");
2650                         } else
2651                                 // for custom defined colors
2652                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
2653                 }
2654
2655                 else if (t.cs() == "underbar" || t.cs() == "uline") {
2656                         // \underbar is not 100% correct (LyX outputs \uline
2657                         // of ulem.sty). The difference is that \ulem allows
2658                         // line breaks, and \underbar does not.
2659                         // Do NOT handle \underline.
2660                         // \underbar cuts through y, g, q, p etc.,
2661                         // \underline does not.
2662                         context.check_layout(os);
2663                         os << "\n\\bar under\n";
2664                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2665                         context.check_layout(os);
2666                         os << "\n\\bar default\n";
2667                         preamble.registerAutomaticallyLoadedPackage("ulem");
2668                 }
2669
2670                 else if (t.cs() == "sout") {
2671                         context.check_layout(os);
2672                         os << "\n\\strikeout on\n";
2673                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2674                         context.check_layout(os);
2675                         os << "\n\\strikeout default\n";
2676                         preamble.registerAutomaticallyLoadedPackage("ulem");
2677                 }
2678
2679                 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2680                          t.cs() == "emph" || t.cs() == "noun") {
2681                         context.check_layout(os);
2682                         os << "\n\\" << t.cs() << " on\n";
2683                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2684                         context.check_layout(os);
2685                         os << "\n\\" << t.cs() << " default\n";
2686                         if (t.cs() == "uuline" || t.cs() == "uwave")
2687                                 preamble.registerAutomaticallyLoadedPackage("ulem");
2688                 }
2689
2690                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2691                              t.cs() == "vphantom") {
2692                         context.check_layout(os);
2693                         if (t.cs() == "phantom")
2694                                 begin_inset(os, "Phantom Phantom\n");
2695                         if (t.cs() == "hphantom")
2696                                 begin_inset(os, "Phantom HPhantom\n");
2697                         if (t.cs() == "vphantom")
2698                                 begin_inset(os, "Phantom VPhantom\n");
2699                         os << "status open\n";
2700                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2701                                             "Phantom");
2702                         end_inset(os);
2703                 }
2704
2705                 else if (t.cs() == "href") {
2706                         context.check_layout(os);
2707                         string target = p.getArg('{', '}');
2708                         string name = p.getArg('{', '}');
2709                         string type;
2710                         size_t i = target.find(':');
2711                         if (i != string::npos) {
2712                                 type = target.substr(0, i + 1);
2713                                 if (type == "mailto:" || type == "file:")
2714                                         target = target.substr(i + 1);
2715                                 // handle the case that name is equal to target, except of "http://"
2716                                 else if (target.substr(i + 3) == name && type == "http:")
2717                                         target = name;
2718                         }
2719                         begin_command_inset(os, "href", "href");
2720                         if (name != target)
2721                                 os << "name \"" << name << "\"\n";
2722                         os << "target \"" << target << "\"\n";
2723                         if (type == "mailto:" || type == "file:")
2724                                 os << "type \"" << type << "\"\n";
2725                         end_inset(os);
2726                         skip_spaces_braces(p);
2727                 }
2728                 
2729                 else if (t.cs() == "lyxline") {
2730                         // swallow size argument (it is not used anyway)
2731                         p.getArg('{', '}');
2732                         if (!context.atParagraphStart()) {
2733                                 // so our line is in the middle of a paragraph
2734                                 // we need to add a new line, lest this line
2735                                 // follow the other content on that line and
2736                                 // run off the side of the page
2737                                 // FIXME: This may create an empty paragraph,
2738                                 //        but without that it would not be
2739                                 //        possible to set noindent below.
2740                                 //        Fortunately LaTeX does not care
2741                                 //        about the empty paragraph.
2742                                 context.new_paragraph(os);
2743                         }
2744                         if (preamble.indentParagraphs()) {
2745                                 // we need to unindent, lest the line be too long
2746                                 context.add_par_extra_stuff("\\noindent\n");
2747                         }
2748                         context.check_layout(os);
2749                         begin_command_inset(os, "line", "rule");
2750                         os << "offset \"0.5ex\"\n"
2751                               "width \"100line%\"\n"
2752                               "height \"1pt\"\n";
2753                         end_inset(os);
2754                 }
2755
2756                 else if (t.cs() == "rule") {
2757                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2758                         string const width = p.getArg('{', '}');
2759                         string const thickness = p.getArg('{', '}');
2760                         context.check_layout(os);
2761                         begin_command_inset(os, "line", "rule");
2762                         if (!offset.empty())
2763                                 os << "offset \"" << translate_len(offset) << "\"\n";
2764                         os << "width \"" << translate_len(width) << "\"\n"
2765                                   "height \"" << translate_len(thickness) << "\"\n";
2766                         end_inset(os);
2767                 }
2768
2769                 else if (is_known(t.cs(), known_phrases) ||
2770                          (t.cs() == "protect" &&
2771                           p.next_token().cat() == catEscape &&
2772                           is_known(p.next_token().cs(), known_phrases))) {
2773                         // LyX sometimes puts a \protect in front, so we have to ignore it
2774                         // FIXME: This needs to be changed when bug 4752 is fixed.
2775                         char const * const * where = is_known(
2776                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2777                                 known_phrases);
2778                         context.check_layout(os);
2779                         os << known_coded_phrases[where - known_phrases];
2780                         skip_spaces_braces(p);
2781                 }
2782
2783                 else if (is_known(t.cs(), known_ref_commands)) {
2784                         string const opt = p.getOpt();
2785                         if (opt.empty()) {
2786                                 context.check_layout(os);
2787                                 char const * const * where = is_known(t.cs(),
2788                                         known_ref_commands);
2789                                 begin_command_inset(os, "ref",
2790                                         known_coded_ref_commands[where - known_ref_commands]);
2791                                 os << "reference \""
2792                                    << convert_command_inset_arg(p.verbatim_item())
2793                                    << "\"\n";
2794                                 end_inset(os);
2795                         } else {
2796                                 // LyX does not support optional arguments of ref commands
2797                                 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2798                                                p.verbatim_item() + "}", context);
2799                         }
2800                 }
2801
2802                 else if (use_natbib &&
2803                          is_known(t.cs(), known_natbib_commands) &&
2804                          ((t.cs() != "citefullauthor" &&
2805                            t.cs() != "citeyear" &&
2806                            t.cs() != "citeyearpar") ||
2807                           p.next_token().asInput() != "*")) {
2808                         context.check_layout(os);
2809                         string command = t.cs();
2810                         if (p.next_token().asInput() == "*") {
2811                                 command += '*';
2812                                 p.get_token();
2813                         }
2814                         if (command == "citefullauthor")
2815                                 // alternative name for "\\citeauthor*"
2816                                 command = "citeauthor*";
2817
2818                         // text before the citation
2819                         string before;
2820                         // text after the citation
2821                         string after;
2822                         get_cite_arguments(p, true, before, after);
2823
2824                         if (command == "cite") {
2825                                 // \cite without optional argument means
2826                                 // \citet, \cite with at least one optional
2827                                 // argument means \citep.
2828                                 if (before.empty() && after.empty())
2829                                         command = "citet";
2830                                 else
2831                                         command = "citep";
2832                         }
2833                         if (before.empty() && after == "[]")
2834                                 // avoid \citet[]{a}
2835                                 after.erase();
2836                         else if (before == "[]" && after == "[]") {
2837                                 // avoid \citet[][]{a}
2838                                 before.erase();
2839                                 after.erase();
2840                         }
2841                         // remove the brackets around after and before
2842                         if (!after.empty()) {
2843                                 after.erase(0, 1);
2844                                 after.erase(after.length() - 1, 1);
2845                                 after = convert_command_inset_arg(after);
2846                         }
2847                         if (!before.empty()) {
2848                                 before.erase(0, 1);
2849                                 before.erase(before.length() - 1, 1);
2850                                 before = convert_command_inset_arg(before);
2851                         }
2852                         begin_command_inset(os, "citation", command);
2853                         os << "after " << '"' << after << '"' << "\n";
2854                         os << "before " << '"' << before << '"' << "\n";
2855                         os << "key \""
2856                            << convert_command_inset_arg(p.verbatim_item())
2857                            << "\"\n";
2858                         end_inset(os);
2859                 }
2860
2861                 else if (use_jurabib &&
2862                          is_known(t.cs(), known_jurabib_commands) &&
2863                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2864                         context.check_layout(os);
2865                         string command = t.cs();
2866                         if (p.next_token().asInput() == "*") {
2867                                 command += '*';
2868                                 p.get_token();
2869                         }
2870                         char argumentOrder = '\0';
2871                         vector<string> const options =
2872                                 preamble.getPackageOptions("jurabib");
2873                         if (find(options.begin(), options.end(),
2874                                       "natbiborder") != options.end())
2875                                 argumentOrder = 'n';
2876                         else if (find(options.begin(), options.end(),
2877                                            "jurabiborder") != options.end())
2878                                 argumentOrder = 'j';
2879
2880                         // text before the citation
2881                         string before;
2882                         // text after the citation
2883                         string after;
2884                         get_cite_arguments(p, argumentOrder != 'j', before, after);
2885
2886                         string const citation = p.verbatim_item();
2887                         if (!before.empty() && argumentOrder == '\0') {
2888                                 cerr << "Warning: Assuming argument order "
2889                                         "of jurabib version 0.6 for\n'"
2890                                      << command << before << after << '{'
2891                                      << citation << "}'.\n"
2892                                         "Add 'jurabiborder' to the jurabib "
2893                                         "package options if you used an\n"
2894                                         "earlier jurabib version." << endl;
2895                         }
2896                         if (!after.empty()) {
2897                                 after.erase(0, 1);
2898                                 after.erase(after.length() - 1, 1);
2899                         }
2900                         if (!before.empty()) {
2901                                 before.erase(0, 1);
2902                                 before.erase(before.length() - 1, 1);
2903                         }
2904                         begin_command_inset(os, "citation", command);
2905                         os << "after " << '"' << after << '"' << "\n";
2906                         os << "before " << '"' << before << '"' << "\n";
2907                         os << "key " << '"' << citation << '"' << "\n";
2908                         end_inset(os);
2909                 }
2910
2911                 else if (t.cs() == "cite"
2912                         || t.cs() == "nocite") {
2913                         context.check_layout(os);
2914                         string after = convert_command_inset_arg(p.getArg('[', ']'));
2915                         string key = convert_command_inset_arg(p.verbatim_item());
2916                         // store the case that it is "\nocite{*}" to use it later for
2917                         // the BibTeX inset
2918                         if (key != "*") {
2919                                 begin_command_inset(os, "citation", t.cs());
2920                                 os << "after " << '"' << after << '"' << "\n";
2921                                 os << "key " << '"' << key << '"' << "\n";
2922                                 end_inset(os);
2923                         } else if (t.cs() == "nocite")
2924                                 btprint = key;
2925                 }
2926
2927                 else if (t.cs() == "index") {
2928                         context.check_layout(os);
2929                         begin_inset(os, "Index idx\n");
2930                         os << "status collapsed\n";
2931                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2932                         end_inset(os);
2933                 }
2934
2935                 else if (t.cs() == "nomenclature") {
2936                         context.check_layout(os);
2937                         begin_command_inset(os, "nomenclature", "nomenclature");
2938                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2939                         if (!prefix.empty())
2940                                 os << "prefix " << '"' << prefix << '"' << "\n";
2941                         os << "symbol " << '"'
2942                            << convert_command_inset_arg(p.verbatim_item());
2943                         os << "\"\ndescription \""
2944                            << convert_command_inset_arg(p.verbatim_item())
2945                            << "\"\n";
2946                         end_inset(os);
2947                 }
2948                 
2949                 else if (t.cs() == "label") {
2950                         context.check_layout(os);
2951                         begin_command_inset(os, "label", "label");
2952                         os << "name \""
2953                            << convert_command_inset_arg(p.verbatim_item())
2954                            << "\"\n";
2955                         end_inset(os);
2956                 }
2957
2958                 else if (t.cs() == "printindex") {
2959                         context.check_layout(os);
2960                         begin_command_inset(os, "index_print", "printindex");
2961                         os << "type \"idx\"\n";
2962                         end_inset(os);
2963                         skip_spaces_braces(p);
2964                 }
2965
2966                 else if (t.cs() == "printnomenclature") {
2967                         string width = "";
2968                         string width_type = "";
2969                         context.check_layout(os);
2970                         begin_command_inset(os, "nomencl_print", "printnomenclature");
2971                         // case of a custom width
2972                         if (p.hasOpt()) {
2973                                 width = p.getArg('[', ']');
2974                                 width = translate_len(width);
2975                                 width_type = "custom";
2976                         }
2977                         // case of no custom width
2978                         // the case of no custom width but the width set
2979                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
2980                         // because the user could have set anything, not only the width
2981                         // of the longest label (which would be width_type = "auto")
2982                         string label = convert_command_inset_arg(p.getArg('{', '}'));
2983                         if (label.empty() && width_type.empty())
2984                                 width_type = "none";
2985                         os << "set_width \"" << width_type << "\"\n";
2986                         if (width_type == "custom")
2987                                 os << "width \"" << width << '\"';
2988                         end_inset(os);
2989                         skip_spaces_braces(p);
2990                 }
2991
2992                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2993                         context.check_layout(os);
2994                         begin_inset(os, "script ");
2995                         os << t.cs().substr(4) << '\n';
2996                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2997                         end_inset(os);
2998                         if (t.cs() == "textsubscript")
2999                                 preamble.registerAutomaticallyLoadedPackage("subscript");
3000                 }
3001
3002                 else if (is_known(t.cs(), known_quotes)) {
3003                         char const * const * where = is_known(t.cs(), known_quotes);
3004                         context.check_layout(os);
3005                         begin_inset(os, "Quotes ");
3006                         os << known_coded_quotes[where - known_quotes];
3007                         end_inset(os);
3008                         // LyX adds {} after the quote, so we have to eat
3009                         // spaces here if there are any before a possible
3010                         // {} pair.
3011                         eat_whitespace(p, os, context, false);
3012                         skip_braces(p);
3013                 }
3014
3015                 else if (is_known(t.cs(), known_sizes) &&
3016                          context.new_layout_allowed) {
3017                         char const * const * where = is_known(t.cs(), known_sizes);
3018                         context.check_layout(os);
3019                         TeXFont const oldFont = context.font;
3020                         context.font.size = known_coded_sizes[where - known_sizes];
3021                         output_font_change(os, oldFont, context.font);
3022                         eat_whitespace(p, os, context, false);
3023                 }
3024
3025                 else if (is_known(t.cs(), known_font_families) &&
3026                          context.new_layout_allowed) {
3027                         char const * const * where =
3028                                 is_known(t.cs(), known_font_families);
3029                         context.check_layout(os);
3030                         TeXFont const oldFont = context.font;
3031                         context.font.family =
3032                                 known_coded_font_families[where - known_font_families];
3033                         output_font_change(os, oldFont, context.font);
3034                         eat_whitespace(p, os, context, false);
3035                 }
3036
3037                 else if (is_known(t.cs(), known_font_series) &&
3038                          context.new_layout_allowed) {
3039                         char const * const * where =
3040                                 is_known(t.cs(), known_font_series);
3041                         context.check_layout(os);
3042                         TeXFont const oldFont = context.font;
3043                         context.font.series =
3044                                 known_coded_font_series[where - known_font_series];
3045                         output_font_change(os, oldFont, context.font);
3046                         eat_whitespace(p, os, context, false);
3047                 }
3048
3049                 else if (is_known(t.cs(), known_font_shapes) &&
3050                          context.new_layout_allowed) {
3051                         char const * const * where =
3052                                 is_known(t.cs(), known_font_shapes);
3053                         context.check_layout(os);
3054                         TeXFont const oldFont = context.font;
3055                         context.font.shape =
3056                                 known_coded_font_shapes[where - known_font_shapes];
3057                         output_font_change(os, oldFont, context.font);
3058                         eat_whitespace(p, os, context, false);
3059                 }
3060                 else if (is_known(t.cs(), known_old_font_families) &&
3061                          context.new_layout_allowed) {
3062                         char const * const * where =
3063                                 is_known(t.cs(), known_old_font_families);
3064                         context.check_layout(os);
3065                         TeXFont const oldFont = context.font;
3066                         context.font.init();
3067                         context.font.size = oldFont.size;
3068                         context.font.family =
3069                                 known_coded_font_families[where - known_old_font_families];
3070                         output_font_change(os, oldFont, context.font);
3071                         eat_whitespace(p, os, context, false);
3072                 }
3073
3074                 else if (is_known(t.cs(), known_old_font_series) &&
3075                          context.new_layout_allowed) {
3076                         char const * const * where =
3077                                 is_known(t.cs(), known_old_font_series);
3078                         context.check_layout(os);
3079                         TeXFont const oldFont = context.font;
3080                         context.font.init();
3081                         context.font.size = oldFont.size;
3082                         context.font.series =
3083                                 known_coded_font_series[where - known_old_font_series];
3084                         output_font_change(os, oldFont, context.font);
3085                         eat_whitespace(p, os, context, false);
3086                 }
3087
3088                 else if (is_known(t.cs(), known_old_font_shapes) &&
3089                          context.new_layout_allowed) {
3090                         char const * const * where =
3091                                 is_known(t.cs(), known_old_font_shapes);
3092                         context.check_layout(os);
3093                         TeXFont const oldFont = context.font;
3094                         context.font.init();
3095                         context.font.size = oldFont.size;
3096                         context.font.shape =
3097                                 known_coded_font_shapes[where - known_old_font_shapes];
3098                         output_font_change(os, oldFont, context.font);
3099                         eat_whitespace(p, os, context, false);
3100                 }
3101
3102                 else if (t.cs() == "selectlanguage") {
3103                         context.check_layout(os);
3104                         // save the language for the case that a
3105                         // \foreignlanguage is used 
3106
3107                         context.font.language = babel2lyx(p.verbatim_item());
3108                         os << "\n\\lang " << context.font.language << "\n";
3109                 }
3110
3111                 else if (t.cs() == "foreignlanguage") {
3112                         string const lang = babel2lyx(p.verbatim_item());
3113                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3114                                               context, "\\lang",
3115                                               context.font.language, lang);
3116                 }
3117
3118                 else if (t.cs() == "inputencoding") {
3119                         // nothing to write here
3120                         string const enc = subst(p.verbatim_item(), "\n", " ");
3121                         p.setEncoding(enc);
3122                 }
3123
3124                 else if (t.cs() == "ldots") {
3125                         context.check_layout(os);
3126                         os << "\\SpecialChar \\ldots{}\n";
3127                         skip_spaces_braces(p);
3128                 }
3129
3130                 else if (t.cs() == "lyxarrow") {
3131                         context.check_layout(os);
3132                         os << "\\SpecialChar \\menuseparator\n";
3133                         skip_spaces_braces(p);
3134                 }
3135
3136                 else if (t.cs() == "textcompwordmark") {
3137                         context.check_layout(os);
3138                         os << "\\SpecialChar \\textcompwordmark{}\n";
3139                         skip_spaces_braces(p);
3140                 }
3141
3142                 else if (t.cs() == "slash") {
3143                         context.check_layout(os);
3144                         os << "\\SpecialChar \\slash{}\n";
3145                         skip_spaces_braces(p);
3146                 }
3147
3148                 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3149                         context.check_layout(os);
3150                         os << "\\SpecialChar \\nobreakdash-\n";
3151                         p.get_token();
3152                 }
3153
3154                 else if (t.cs() == "textquotedbl") {
3155                         context.check_layout(os);
3156                         os << "\"";
3157                         skip_braces(p);
3158                 }
3159
3160                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3161                         context.check_layout(os);
3162                         os << "\\SpecialChar \\@.\n";
3163                         p.get_token();
3164                 }
3165
3166                 else if (t.cs() == "-") {
3167                         context.check_layout(os);
3168                         os << "\\SpecialChar \\-\n";
3169                 }
3170
3171                 else if (t.cs() == "textasciitilde") {
3172                         context.check_layout(os);
3173                         os << '~';
3174                         skip_spaces_braces(p);
3175                 }
3176
3177                 else if (t.cs() == "textasciicircum") {
3178                         context.check_layout(os);
3179                         os << '^';
3180                         skip_spaces_braces(p);
3181                 }
3182
3183                 else if (t.cs() == "textbackslash") {
3184                         context.check_layout(os);
3185                         os << "\n\\backslash\n";
3186                         skip_spaces_braces(p);
3187                 }
3188
3189                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3190                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3191                             || t.cs() == "%") {
3192                         context.check_layout(os);
3193                         os << t.cs();
3194                 }
3195
3196                 else if (t.cs() == "char") {
3197                         context.check_layout(os);
3198                         if (p.next_token().character() == '`') {
3199                                 p.get_token();
3200                                 if (p.next_token().cs() == "\"") {
3201                                         p.get_token();
3202                                         os << '"';
3203                                         skip_braces(p);
3204                                 } else {
3205                                         handle_ert(os, "\\char`", context);
3206                                 }
3207                         } else {
3208                                 handle_ert(os, "\\char", context);
3209                         }
3210                 }
3211
3212                 else if (t.cs() == "verb") {
3213                         context.check_layout(os);
3214                         char const delimiter = p.next_token().character();
3215                         string const arg = p.getArg(delimiter, delimiter);
3216                         ostringstream oss;
3217                         oss << "\\verb" << delimiter << arg << delimiter;
3218                         handle_ert(os, oss.str(), context);
3219                 }
3220
3221                 // Problem: \= creates a tabstop inside the tabbing environment
3222                 // and else an accent. In the latter case we really would want
3223                 // \={o} instead of \= o.
3224                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3225                         handle_ert(os, t.asInput(), context);
3226
3227                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3228                 else if (t.cs().size() == 1 
3229                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3230                         context.check_layout(os);
3231                         // try to see whether the string is in unicodesymbols
3232                         docstring rem;
3233                         string command = t.asInput() + "{" 
3234                                 + trimSpaceAndEol(p.verbatim_item())
3235                                 + "}";
3236                         docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3237                         if (!s.empty()) {
3238                                 if (!rem.empty())
3239                                         cerr << "When parsing " << command 
3240                                              << ", result is " << to_utf8(s)
3241                                              << "+" << to_utf8(rem) << endl;
3242                                 os << to_utf8(s);
3243                         } else
3244                                 // we did not find a non-ert version
3245                                 handle_ert(os, command, context);
3246                 }
3247
3248                 else if (t.cs() == "\\") {
3249                         context.check_layout(os);
3250                         if (p.hasOpt())
3251                                 handle_ert(os, "\\\\" + p.getOpt(), context);
3252                         else if (p.next_token().asInput() == "*") {
3253                                 p.get_token();
3254                                 // getOpt() eats the following space if there
3255                                 // is no optional argument, but that is OK
3256                                 // here since it has no effect in the output.
3257                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
3258                         }
3259                         else {
3260                                 begin_inset(os, "Newline newline");
3261                                 end_inset(os);
3262                         }
3263                 }
3264
3265                 else if (t.cs() == "newline" ||
3266                          (t.cs() == "linebreak" && !p.hasOpt())) {
3267                         context.check_layout(os);
3268                         begin_inset(os, "Newline ");
3269                         os << t.cs();
3270                         end_inset(os);
3271                         skip_spaces_braces(p);
3272                 }
3273
3274                 else if (t.cs() == "input" || t.cs() == "include"
3275                          || t.cs() == "verbatiminput") {
3276                         string name = t.cs();
3277                         if (t.cs() == "verbatiminput"
3278                             && p.next_token().asInput() == "*")
3279                                 name += p.get_token().asInput();
3280                         context.check_layout(os);
3281                         string filename(normalize_filename(p.getArg('{', '}')));
3282                         string const path = getMasterFilePath();
3283                         // We want to preserve relative / absolute filenames,
3284                         // therefore path is only used for testing
3285                         if ((t.cs() == "include" || t.cs() == "input") &&
3286                             !makeAbsPath(filename, path).exists()) {
3287                                 // The file extension is probably missing.
3288                                 // Now try to find it out.
3289                                 string const tex_name =
3290                                         find_file(filename, path,
3291                                                   known_tex_extensions);
3292                                 if (!tex_name.empty())
3293                                         filename = tex_name;
3294                         }
3295                         bool external = false;
3296                         string outname;
3297                         if (makeAbsPath(filename, path).exists()) {
3298                                 string const abstexname =
3299                                         makeAbsPath(filename, path).absFileName();
3300                                 string const abslyxname =
3301                                         changeExtension(abstexname, ".lyx");
3302                                 string const absfigname =
3303                                         changeExtension(abstexname, ".fig");
3304                                 fix_relative_filename(filename);
3305                                 string const lyxname =
3306                                         changeExtension(filename, ".lyx");
3307                                 bool xfig = false;
3308                                 external = FileName(absfigname).exists();
3309                                 if (t.cs() == "input") {
3310                                         string const ext = getExtension(abstexname);
3311
3312                                         // Combined PS/LaTeX:
3313                                         // x.eps, x.pstex_t (old xfig)
3314                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3315                                         FileName const absepsname(
3316                                                 changeExtension(abstexname, ".eps"));
3317                                         FileName const abspstexname(
3318                                                 changeExtension(abstexname, ".pstex"));
3319                                         bool const xfigeps =
3320                                                 (absepsname.exists() ||
3321                                                  abspstexname.exists()) &&
3322                                                 ext == "pstex_t";
3323
3324                                         // Combined PDF/LaTeX:
3325                                         // x.pdf, x.pdftex_t (old xfig)
3326                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3327                                         FileName const abspdfname(
3328                                                 changeExtension(abstexname, ".pdf"));
3329                                         bool const xfigpdf =
3330                                                 abspdfname.exists() &&
3331                                                 (ext == "pdftex_t" || ext == "pdf_t");
3332                                         if (xfigpdf)
3333                                                 pdflatex = true;
3334
3335                                         // Combined PS/PDF/LaTeX:
3336                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3337                                         string const absbase2(
3338                                                 removeExtension(abstexname) + "_pspdftex");
3339                                         FileName const abseps2name(
3340                                                 addExtension(absbase2, ".eps"));
3341                                         FileName const abspdf2name(
3342                                                 addExtension(absbase2, ".pdf"));
3343                                         bool const xfigboth =
3344                                                 abspdf2name.exists() &&
3345                                                 abseps2name.exists() && ext == "pspdftex";
3346
3347                                         xfig = xfigpdf || xfigeps || xfigboth;
3348                                         external = external && xfig;
3349                                 }
3350                                 if (external) {
3351                                         outname = changeExtension(filename, ".fig");
3352                                 } else if (xfig) {
3353                                         // Don't try to convert, the result
3354                                         // would be full of ERT.
3355                                         outname = filename;
3356                                 } else if (t.cs() != "verbatiminput" &&
3357                                     tex2lyx(abstexname, FileName(abslyxname),
3358                                             p.getEncoding())) {
3359                                         outname = lyxname;
3360                                 } else {
3361                                         outname = filename;
3362                                 }
3363                         } else {
3364                                 cerr << "Warning: Could not find included file '"
3365                                      << filename << "'." << endl;
3366                                 outname = filename;
3367                         }
3368                         if (external) {
3369                                 begin_inset(os, "External\n");
3370                                 os << "\ttemplate XFig\n"
3371                                    << "\tfilename " << outname << '\n';
3372                         } else {
3373                                 begin_command_inset(os, "include", name);
3374                                 os << "preview false\n"
3375                                       "filename \"" << outname << "\"\n";
3376                         }
3377                         end_inset(os);
3378                 }
3379
3380                 else if (t.cs() == "bibliographystyle") {
3381                         // store new bibliographystyle
3382                         bibliographystyle = p.verbatim_item();
3383                         // If any other command than \bibliography and
3384                         // \nocite{*} follows, we need to output the style
3385                         // (because it might be used by that command).
3386                         // Otherwise, it will automatically be output by LyX.
3387                         p.pushPosition();
3388                         bool output = true;
3389                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3390                                 if (t2.cat() == catBegin)
3391                                         break;
3392                                 if (t2.cat() != catEscape)
3393                                         continue;
3394                                 if (t2.cs() == "nocite") {
3395                                         if (p.getArg('{', '}') == "*")
3396                                                 continue;
3397                                 } else if (t2.cs() == "bibliography")
3398                                         output = false;
3399                                 break;
3400                         }
3401                         p.popPosition();
3402                         if (output) {
3403                                 handle_ert(os,
3404                                         "\\bibliographystyle{" + bibliographystyle + '}',
3405                                         context);
3406                         }
3407                 }
3408
3409                 else if (t.cs() == "bibliography") {
3410                         context.check_layout(os);
3411                         begin_command_inset(os, "bibtex", "bibtex");
3412                         if (!btprint.empty()) {
3413                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3414                                 // clear the string because the next BibTeX inset can be without the
3415                                 // \nocite{*} option
3416                                 btprint.clear();
3417                         }
3418                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3419                         // Do we have a bibliographystyle set?
3420                         if (!bibliographystyle.empty())
3421                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
3422                         end_inset(os);
3423                 }
3424
3425                 else if (t.cs() == "parbox")
3426                         parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3427
3428                 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3429                          t.cs() == "shadowbox" || t.cs() == "doublebox")
3430                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3431
3432                 else if (t.cs() == "framebox") {
3433                         string special = p.getFullOpt();
3434                         special += p.getOpt();
3435                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3436                 }
3437
3438                 //\makebox() is part of the picture environment and different from \makebox{}
3439                 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3440                 else if (t.cs() == "makebox") {
3441                         string arg = t.asInput();
3442                         if (p.next_token().character() == '(')
3443                                 //the syntax is: \makebox(x,y)[position]{content}
3444                                 arg += p.getFullParentheseArg();
3445                         else
3446                                 //the syntax is: \makebox[width][position]{content}
3447                                 arg += p.getFullOpt();
3448                         handle_ert(os, arg + p.getFullOpt(), context);
3449                 }
3450
3451                 else if (t.cs() == "smallskip" ||
3452                          t.cs() == "medskip" ||
3453                          t.cs() == "bigskip" ||
3454                          t.cs() == "vfill") {
3455                         context.check_layout(os);
3456                         begin_inset(os, "VSpace ");
3457                         os << t.cs();
3458                         end_inset(os);
3459                         skip_spaces_braces(p);
3460                 }
3461
3462                 else if (is_known(t.cs(), known_spaces)) {
3463                         char const * const * where = is_known(t.cs(), known_spaces);
3464                         context.check_layout(os);
3465                         begin_inset(os, "space ");
3466                         os << '\\' << known_coded_spaces[where - known_spaces]
3467                            << '\n';
3468                         end_inset(os);
3469                         // LaTeX swallows whitespace after all spaces except
3470                         // "\\,". We have to do that here, too, because LyX
3471                         // adds "{}" which would make the spaces significant.
3472                         if (t.cs() !=  ",")
3473                                 eat_whitespace(p, os, context, false);
3474                         // LyX adds "{}" after all spaces except "\\ " and
3475                         // "\\,", so we have to remove "{}".
3476                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
3477                         // remove the braces after "\\,", too.
3478                         if (t.cs() != " ")
3479                                 skip_braces(p);
3480                 }
3481
3482                 else if (t.cs() == "newpage" ||
3483                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
3484                          t.cs() == "clearpage" ||
3485                          t.cs() == "cleardoublepage") {
3486                         context.check_layout(os);
3487                         begin_inset(os, "Newpage ");
3488                         os << t.cs();
3489                         end_inset(os);
3490                         skip_spaces_braces(p);
3491                 }
3492
3493                 else if (t.cs() == "DeclareRobustCommand" ||
3494                          t.cs() == "DeclareRobustCommandx" ||
3495                          t.cs() == "newcommand" ||
3496                          t.cs() == "newcommandx" ||
3497                          t.cs() == "providecommand" ||
3498                          t.cs() == "providecommandx" ||
3499                          t.cs() == "renewcommand" ||
3500                          t.cs() == "renewcommandx") {
3501                         // DeclareRobustCommand, DeclareRobustCommandx,
3502                         // providecommand and providecommandx could be handled
3503                         // by parse_command(), but we need to call
3504                         // add_known_command() here.
3505                         string name = t.asInput();
3506                         if (p.next_token().asInput() == "*") {
3507                                 // Starred form. Eat '*'
3508                                 p.get_token();
3509                                 name += '*';
3510                         }
3511                         string const command = p.verbatim_item();
3512                         string const opt1 = p.getFullOpt();
3513                         string const opt2 = p.getFullOpt();
3514                         add_known_command(command, opt1, !opt2.empty());
3515                         string const ert = name + '{' + command + '}' +
3516                                            opt1 + opt2 +
3517                                            '{' + p.verbatim_item() + '}';
3518
3519                         if (t.cs() == "DeclareRobustCommand" ||
3520                             t.cs() == "DeclareRobustCommandx" ||
3521                             t.cs() == "providecommand" ||
3522                             t.cs() == "providecommandx" ||
3523                             name[name.length()-1] == '*')
3524                                 handle_ert(os, ert, context);
3525                         else {
3526                                 context.check_layout(os);
3527                                 begin_inset(os, "FormulaMacro");
3528                                 os << "\n" << ert;
3529                                 end_inset(os);
3530                         }
3531                 }
3532
3533                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3534                         // let could be handled by parse_command(),
3535                         // but we need to call add_known_command() here.
3536                         string ert = t.asInput();
3537                         string name;
3538                         p.skip_spaces();
3539                         if (p.next_token().cat() == catBegin) {
3540                                 name = p.verbatim_item();
3541                                 ert += '{' + name + '}';
3542                         } else {
3543                                 name = p.verbatim_item();
3544                                 ert += name;
3545                         }
3546                         string command;
3547                         p.skip_spaces();
3548                         if (p.next_token().cat() == catBegin) {
3549                                 command = p.verbatim_item();
3550                                 ert += '{' + command + '}';
3551                         } else {
3552                                 command = p.verbatim_item();
3553                                 ert += command;
3554                         }
3555                         // If command is known, make name known too, to parse
3556                         // its arguments correctly. For this reason we also
3557                         // have commands in syntax.default that are hardcoded.
3558                         CommandMap::iterator it = known_commands.find(command);
3559                         if (it != known_commands.end())
3560                                 known_commands[t.asInput()] = it->second;
3561                         handle_ert(os, ert, context);
3562                 }
3563
3564                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3565                         bool starred = false;
3566                         if (p.next_token().asInput() == "*") {
3567                                 p.get_token();
3568                                 starred = true;
3569                         }
3570                         string name = t.asInput();
3571                         string const length = p.verbatim_item();
3572                         string unit;
3573                         string valstring;
3574                         bool valid = splitLatexLength(length, valstring, unit);
3575                         bool known_hspace = false;
3576                         bool known_vspace = false;
3577                         bool known_unit = false;
3578                         double value;
3579                         if (valid) {
3580                                 istringstream iss(valstring);
3581                                 iss >> value;
3582                                 if (value == 1.0) {
3583                                         if (t.cs()[0] == 'h') {
3584                                                 if (unit == "\\fill") {
3585                                                         if (!starred) {
3586                                                                 unit = "";
3587                                                                 name = "\\hfill";
3588                                                         }
3589                                                         known_hspace = true;
3590                                                 }
3591                                         } else {
3592                                                 if (unit == "\\smallskipamount") {
3593                                                         unit = "smallskip";
3594                                                         known_vspace = true;
3595                                                 } else if (unit == "\\medskipamount") {
3596                                                         unit = "medskip";
3597                                                         known_vspace = true;
3598                                                 } else if (unit == "\\bigskipamount") {
3599                                                         unit = "bigskip";
3600                                                         known_vspace = true;
3601                                                 } else if (unit == "\\fill") {
3602                                                         unit = "vfill";
3603                                                         known_vspace = true;
3604                                                 }
3605                                         }
3606                                 }
3607                                 if (!known_hspace && !known_vspace) {
3608                                         switch (unitFromString(unit)) {
3609                                         case Length::SP:
3610                                         case Length::PT:
3611                                         case Length::BP:
3612                                         case Length::DD:
3613                                         case Length::MM:
3614                                         case Length::PC:
3615                                         case Length::CC:
3616                                         case Length::CM:
3617                                         case Length::IN:
3618                                         case Length::EX:
3619                                         case Length::EM:
3620                                         case Length::MU:
3621                                                 known_unit = true;
3622                                                 break;
3623                                         default:
3624                                                 break;
3625                                         }
3626                                 }
3627                         }
3628
3629                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3630                                 // Literal horizontal length or known variable
3631                                 context.check_layout(os);
3632                                 begin_inset(os, "space ");
3633                                 os << name;
3634                                 if (starred)
3635                                         os << '*';
3636                                 os << '{';
3637                                 if (known_hspace)
3638                                         os << unit;
3639                                 os << "}";
3640                                 if (known_unit && !known_hspace)
3641                                         os << "\n\\length "
3642                                            << translate_len(length);
3643                                 end_inset(os);
3644                         } else if (known_unit || known_vspace) {
3645                                 // Literal vertical length or known variable
3646                                 context.check_layout(os);
3647                                 begin_inset(os, "VSpace ");
3648                                 if (known_unit)
3649                                         os << value;
3650                                 os << unit;
3651                                 if (starred)
3652                                         os << '*';
3653                                 end_inset(os);
3654                         } else {
3655                                 // LyX can't handle other length variables in Inset VSpace/space
3656                                 if (starred)
3657                                         name += '*';
3658                                 if (valid) {
3659                                         if (value == 1.0)
3660                                                 handle_ert(os, name + '{' + unit + '}', context);
3661                                         else if (value == -1.0)
3662                                                 handle_ert(os, name + "{-" + unit + '}', context);
3663                                         else
3664                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
3665                                 } else
3666                                         handle_ert(os, name + '{' + length + '}', context);
3667                         }
3668                 }
3669
3670                 // The single '=' is meant here.
3671                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3672                         p.skip_spaces();
3673                         context.check_layout(os);
3674                         begin_inset(os, "Flex ");
3675                         os << to_utf8(newinsetlayout->name()) << '\n'
3676                            << "status collapsed\n";
3677                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3678                         end_inset(os);
3679                 }
3680
3681                 else {
3682                         // try to see whether the string is in unicodesymbols
3683                         // Only use text mode commands, since we are in text mode here,
3684                         // and math commands may be invalid (bug 6797)
3685                         docstring rem;
3686                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3687                                                                  rem, Encodings::TEXT_CMD);
3688                         if (!s.empty()) {
3689                                 if (!rem.empty())
3690                                         cerr << "When parsing " << t.cs() 
3691                                              << ", result is " << to_utf8(s)
3692                                              << "+" << to_utf8(rem) << endl;
3693                                 context.check_layout(os);
3694                                 os << to_utf8(s);
3695                                 skip_spaces_braces(p);
3696                         }
3697                         //cerr << "#: " << t << " mode: " << mode << endl;
3698                         // heuristic: read up to next non-nested space
3699                         /*
3700                         string s = t.asInput();
3701                         string z = p.verbatim_item();
3702                         while (p.good() && z != " " && z.size()) {
3703                                 //cerr << "read: " << z << endl;
3704                                 s += z;
3705                                 z = p.verbatim_item();
3706                         }
3707                         cerr << "found ERT: " << s << endl;
3708                         handle_ert(os, s + ' ', context);
3709                         */
3710                         else {
3711                                 string name = t.asInput();
3712                                 if (p.next_token().asInput() == "*") {
3713                                         // Starred commands like \vspace*{}
3714                                         p.get_token();  // Eat '*'
3715                                         name += '*';
3716                                 }
3717                                 if (!parse_command(name, p, os, outer, context))
3718                                         handle_ert(os, name, context);
3719                         }
3720                 }
3721
3722                 if (flags & FLAG_LEAVE) {
3723                         flags &= ~FLAG_LEAVE;
3724                         break;
3725                 }
3726         }
3727 }
3728
3729 // }])
3730
3731
3732 } // namespace lyx