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