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