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