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