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