]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
compile fix
[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 "FloatList.h"
21 #include "Layout.h"
22 #include "Length.h"
23
24 #include "support/convert.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/lstrings.h"
28
29 #include <iostream>
30 #include <map>
31 #include <sstream>
32 #include <vector>
33
34 using namespace std;
35 using namespace lyx::support;
36
37 namespace lyx {
38
39
40 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
41                 Context const & context)
42 {
43         Context newcontext(true, context.textclass);
44         newcontext.font = context.font;
45         parse_text(p, os, flags, outer, newcontext);
46         newcontext.check_end_layout(os);
47 }
48
49
50 namespace {
51
52 /// parses a paragraph snippet, useful for example for \\emph{...}
53 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
54                 Context & context)
55 {
56         Context newcontext(context);
57         // Don't inherit the extra stuff
58         newcontext.extra_stuff.clear();
59         parse_text(p, os, flags, outer, newcontext);
60         // Make sure that we don't create invalid .lyx files
61         context.need_layout = newcontext.need_layout;
62         context.need_end_layout = newcontext.need_end_layout;
63 }
64
65
66 /*!
67  * Thin wrapper around parse_text_snippet() using a string.
68  *
69  * We completely ignore \c context.need_layout and \c context.need_end_layout,
70  * because our return value is not used directly (otherwise the stream version
71  * of parse_text_snippet() could be used). That means that the caller needs
72  * to do layout management manually.
73  * This is intended to parse text that does not create any layout changes.
74  */
75 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
76                   Context & context)
77 {
78         Context newcontext(context);
79         newcontext.need_layout = false;
80         newcontext.need_end_layout = false;
81         newcontext.new_layout_allowed = false;
82         // Avoid warning by Context::~Context()
83         newcontext.extra_stuff.clear();
84         ostringstream os;
85         parse_text_snippet(p, os, flags, outer, newcontext);
86         return os.str();
87 }
88
89
90 char const * const known_latex_commands[] = { "ref", "cite", "nocite", "label",
91  "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
92  "eqref", 0 };
93
94 /*!
95  * natbib commands.
96  * We can't put these into known_latex_commands because the argument order
97  * is reversed in lyx if there are 2 arguments.
98  * The starred forms are also known.
99  */
100 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
101 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
102 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
103
104 /*!
105  * jurabib commands.
106  * We can't put these into known_latex_commands because the argument order
107  * is reversed in lyx if there are 2 arguments.
108  * No starred form other than "cite*" known.
109  */
110 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
111 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
112 // jurabib commands not (yet) supported by LyX:
113 // "fullcite",
114 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
115 // "footciteauthor", "footciteyear", "footciteyearpar",
116 "citefield", "citetitle", "cite*", 0 };
117
118 /// LaTeX names for quotes
119 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
120 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
121 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
122 "guilsinglleft", "frq", "guilsinglright", 0};
123
124 /// the same as known_quotes with .lyx names
125 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
126 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
127 "gld", "grd", "gls", "ers", "fls",
128 "fls", "frs", "frs", 0};
129
130 /// LaTeX names for font sizes
131 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
132 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
133
134 /// the same as known_sizes with .lyx names
135 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
136 "small", "normal", "large", "larger", "largest",  "huge", "giant", 0};
137
138 /// LaTeX 2.09 names for font families
139 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
140
141 /// LaTeX names for font families
142 char const * const known_font_families[] = { "rmfamily", "sffamily",
143 "ttfamily", 0};
144
145 /// the same as known_old_font_families and known_font_families with .lyx names
146 char const * const known_coded_font_families[] = { "roman", "sans",
147 "typewriter", 0};
148
149 /// LaTeX 2.09 names for font series
150 char const * const known_old_font_series[] = { "bf", 0};
151
152 /// LaTeX names for font series
153 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
154
155 /// the same as known_old_font_series and known_font_series with .lyx names
156 char const * const known_coded_font_series[] = { "bold", "medium", 0};
157
158 /// LaTeX 2.09 names for font shapes
159 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
160
161 /// LaTeX names for font shapes
162 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
163 "upshape", 0};
164
165 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
166 char const * const known_coded_font_shapes[] = { "italic", "slanted",
167 "smallcaps", "up", 0};
168
169 /*!
170  * Graphics file extensions known by the dvips driver of the graphics package.
171  * These extensions are used to complete the filename of an included
172  * graphics file if it does not contain an extension.
173  * The order must be the same that latex uses to find a file, because we
174  * will use the first extension that matches.
175  * This is only an approximation for the common cases. If we would want to
176  * do it right in all cases, we would need to know which graphics driver is
177  * used and know the extensions of every driver of the graphics package.
178  */
179 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
180 "ps.gz", "eps.Z", "ps.Z", 0};
181
182 /*!
183  * Graphics file extensions known by the pdftex driver of the graphics package.
184  * \sa known_dvips_graphics_formats
185  */
186 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
187 "mps", "tif", 0};
188
189 /*!
190  * Known file extensions for TeX files as used by \\include.
191  */
192 char const * const known_tex_extensions[] = {"tex", 0};
193
194 /// spaces known by InsetSpace
195 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
196 "qquad", "enspace", "enskip", "negthinspace", 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{}", 0};
202
203
204 /// splits "x=z, y=b" into a map
205 map<string, string> split_map(string const & s)
206 {
207         map<string, string> res;
208         vector<string> v;
209         split(s, v);
210         for (size_t i = 0; i < v.size(); ++i) {
211                 size_t const pos   = v[i].find('=');
212                 string const index = v[i].substr(0, pos);
213                 string const value = v[i].substr(pos + 1, string::npos);
214                 res[trim(index)] = trim(value);
215         }
216         return res;
217 }
218
219
220 /*!
221  * Split a LaTeX length into value and unit.
222  * The latter can be a real unit like "pt", or a latex length variable
223  * like "\textwidth". The unit may contain additional stuff like glue
224  * lengths, but we don't care, because such lengths are ERT anyway.
225  * \returns true if \p value and \p unit are valid.
226  */
227 bool splitLatexLength(string const & len, string & value, string & unit)
228 {
229         if (len.empty())
230                 return false;
231         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
232         //'4,5' is a valid LaTeX length number. Change it to '4.5'
233         string const length = subst(len, ',', '.');
234         if (i == string::npos)
235                 return false;
236         if (i == 0) {
237                 if (len[0] == '\\') {
238                         // We had something like \textwidth without a factor
239                         value = "1.0";
240                 } else {
241                         return false;
242                 }
243         } else {
244                 value = trim(string(length, 0, i));
245         }
246         if (value == "-")
247                 value = "-1.0";
248         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
249         if (contains(len, '\\'))
250                 unit = trim(string(len, i));
251         else
252                 unit = ascii_lowercase(trim(string(len, i)));
253         return true;
254 }
255
256
257 /// A simple function to translate a latex length to something lyx can
258 /// understand. Not perfect, but rather best-effort.
259 bool translate_len(string const & length, string & valstring, string & unit)
260 {
261         if (!splitLatexLength(length, valstring, unit))
262                 return false;
263         // LyX uses percent values
264         double value;
265         istringstream iss(valstring);
266         iss >> value;
267         value *= 100;
268         ostringstream oss;
269         oss << value;
270         string const percentval = oss.str();
271         // a normal length
272         if (unit.empty() || unit[0] != '\\')
273                 return true;
274         string::size_type const i = unit.find(' ');
275         string const endlen = (i == string::npos) ? string() : string(unit, i);
276         if (unit == "\\textwidth") {
277                 valstring = percentval;
278                 unit = "text%" + endlen;
279         } else if (unit == "\\columnwidth") {
280                 valstring = percentval;
281                 unit = "col%" + endlen;
282         } else if (unit == "\\paperwidth") {
283                 valstring = percentval;
284                 unit = "page%" + endlen;
285         } else if (unit == "\\linewidth") {
286                 valstring = percentval;
287                 unit = "line%" + endlen;
288         } else if (unit == "\\paperheight") {
289                 valstring = percentval;
290                 unit = "pheight%" + endlen;
291         } else if (unit == "\\textheight") {
292                 valstring = percentval;
293                 unit = "theight%" + endlen;
294         }
295         return true;
296 }
297
298 }
299
300
301 string translate_len(string const & length)
302 {
303         string unit;
304         string value;
305         if (translate_len(length, value, unit))
306                 return value + unit;
307         // If the input is invalid, return what we have.
308         return length;
309 }
310
311
312 namespace {
313
314 /*!
315  * Translates a LaTeX length into \p value, \p unit and
316  * \p special parts suitable for a box inset.
317  * The difference from translate_len() is that a box inset knows about
318  * some special "units" that are stored in \p special.
319  */
320 void translate_box_len(string const & length, string & value, string & unit, string & special)
321 {
322         if (translate_len(length, value, unit)) {
323                 if (unit == "\\height" || unit == "\\depth" ||
324                     unit == "\\totalheight" || unit == "\\width") {
325                         special = unit.substr(1);
326                         // The unit is not used, but LyX requires a dummy setting
327                         unit = "in";
328                 } else
329                         special = "none";
330         } else {
331                 value.clear();
332                 unit = length;
333                 special = "none";
334         }
335 }
336
337
338 /*!
339  * Find a file with basename \p name in path \p path and an extension
340  * in \p extensions.
341  */
342 string find_file(string const & name, string const & path,
343                  char const * const * extensions)
344 {
345         // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
346         // expects utf8)
347         for (char const * const * what = extensions; *what; ++what) {
348                 string const trial = addExtension(name, *what);
349                 if (makeAbsPath(trial, path).exists())
350                         return trial;
351         }
352         return string();
353 }
354
355
356 void begin_inset(ostream & os, string const & name)
357 {
358         os << "\n\\begin_inset " << name;
359 }
360
361
362 void end_inset(ostream & os)
363 {
364         os << "\n\\end_inset\n\n";
365 }
366
367
368 void skip_braces(Parser & p)
369 {
370         if (p.next_token().cat() != catBegin)
371                 return;
372         p.get_token();
373         if (p.next_token().cat() == catEnd) {
374                 p.get_token();
375                 return;
376         }
377         p.putback();
378 }
379
380
381 void handle_ert(ostream & os, string const & s, Context & context)
382 {
383         // We must have a valid layout before outputting the ERT inset.
384         context.check_layout(os);
385         Context newcontext(true, context.textclass);
386         begin_inset(os, "ERT");
387         os << "\nstatus collapsed\n";
388         newcontext.check_layout(os);
389         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
390                 if (*it == '\\')
391                         os << "\n\\backslash\n";
392                 else if (*it == '\n') {
393                         newcontext.new_paragraph(os);
394                         newcontext.check_layout(os);
395                 } else
396                         os << *it;
397         }
398         newcontext.check_end_layout(os);
399         end_inset(os);
400 }
401
402
403 void handle_comment(ostream & os, string const & s, Context & context)
404 {
405         // TODO: Handle this better
406         Context newcontext(true, context.textclass);
407         begin_inset(os, "ERT");
408         os << "\nstatus collapsed\n";
409         newcontext.check_layout(os);
410         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
411                 if (*it == '\\')
412                         os << "\n\\backslash\n";
413                 else
414                         os << *it;
415         }
416         // make sure that our comment is the last thing on the line
417         newcontext.new_paragraph(os);
418         newcontext.check_layout(os);
419         newcontext.check_end_layout(os);
420         end_inset(os);
421 }
422
423
424 LayoutPtr findLayout(TextClass const & textclass, string const & name)
425 {
426         for (size_t i = 0; i != textclass.layoutCount(); ++i)
427                 if (textclass.layout(i)->latexname() == name)
428                         return textclass.layout(i);
429         return LayoutPtr();
430 }
431
432
433 void eat_whitespace(Parser &, ostream &, Context &, bool);
434
435
436 void output_command_layout(ostream & os, Parser & p, bool outer,
437                            Context & parent_context,
438                            LayoutPtr newlayout)
439 {
440         parent_context.check_end_layout(os);
441         Context context(true, parent_context.textclass, newlayout,
442                         parent_context.layout, parent_context.font);
443         if (parent_context.deeper_paragraph) {
444                 // We are beginning a nested environment after a
445                 // deeper paragraph inside the outer list environment.
446                 // Therefore we don't need to output a "begin deeper".
447                 context.need_end_deeper = true;
448         }
449         context.check_deeper(os);
450         context.check_layout(os);
451         if (context.layout->optionalargs > 0) {
452                 eat_whitespace(p, os, context, false);
453                 if (p.next_token().character() == '[') {
454                         p.get_token(); // eat '['
455                         begin_inset(os, "OptArg\n");
456                         os << "status collapsed\n\n";
457                         parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
458                         end_inset(os);
459                         eat_whitespace(p, os, context, false);
460                 }
461         }
462         parse_text(p, os, FLAG_ITEM, outer, context);
463         context.check_end_layout(os);
464         if (parent_context.deeper_paragraph) {
465                 // We must suppress the "end deeper" because we
466                 // suppressed the "begin deeper" above.
467                 context.need_end_deeper = false;
468         }
469         context.check_end_deeper(os);
470         // We don't need really a new paragraph, but
471         // we must make sure that the next item gets a \begin_layout.
472         parent_context.new_paragraph(os);
473 }
474
475
476 /*!
477  * Output a space if necessary.
478  * This function gets called for every whitespace token.
479  *
480  * We have three cases here:
481  * 1. A space must be suppressed. Example: The lyxcode case below
482  * 2. A space may be suppressed. Example: Spaces before "\par"
483  * 3. A space must not be suppressed. Example: A space between two words
484  *
485  * We currently handle only 1. and 3 and from 2. only the case of
486  * spaces before newlines as a side effect.
487  *
488  * 2. could be used to suppress as many spaces as possible. This has two effects:
489  * - Reimporting LyX generated LaTeX files changes almost no whitespace
490  * - Superflous whitespace from non LyX generated LaTeX files is removed.
491  * The drawback is that the logic inside the function becomes
492  * complicated, and that is the reason why it is not implemented.
493  */
494 void check_space(Parser const & p, ostream & os, Context & context)
495 {
496         Token const next = p.next_token();
497         Token const curr = p.curr_token();
498         // A space before a single newline and vice versa must be ignored
499         // LyX emits a newline before \end{lyxcode}.
500         // This newline must be ignored,
501         // otherwise LyX will add an additional protected space.
502         if (next.cat() == catSpace ||
503             next.cat() == catNewline ||
504             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
505                 return;
506         }
507         context.check_layout(os);
508         os << ' ';
509 }
510
511
512 /*!
513  * Parse all arguments of \p command
514  */
515 void parse_arguments(string const & command,
516                      vector<ArgumentType> const & template_arguments,
517                      Parser & p, ostream & os, bool outer, Context & context)
518 {
519         string ert = command;
520         size_t no_arguments = template_arguments.size();
521         for (size_t i = 0; i < no_arguments; ++i) {
522                 switch (template_arguments[i]) {
523                 case required:
524                         // This argument contains regular LaTeX
525                         handle_ert(os, ert + '{', context);
526                         eat_whitespace(p, os, context, false);
527                         parse_text(p, os, FLAG_ITEM, outer, context);
528                         ert = "}";
529                         break;
530                 case verbatim:
531                         // This argument may contain special characters
532                         ert += '{' + p.verbatim_item() + '}';
533                         break;
534                 case optional:
535                         ert += p.getOpt();
536                         break;
537                 }
538         }
539         handle_ert(os, ert, context);
540 }
541
542
543 /*!
544  * Check whether \p command is a known command. If yes,
545  * handle the command with all arguments.
546  * \return true if the command was parsed, false otherwise.
547  */
548 bool parse_command(string const & command, Parser & p, ostream & os,
549                    bool outer, Context & context)
550 {
551         if (known_commands.find(command) != known_commands.end()) {
552                 parse_arguments(command, known_commands[command], p, os,
553                                 outer, context);
554                 return true;
555         }
556         return false;
557 }
558
559
560 /// Parses a minipage or parbox
561 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
562                Context & parent_context, bool use_parbox)
563 {
564         string position;
565         string inner_pos;
566         // We need to set the height to the LaTeX default of 1\\totalheight
567         // for the case when no height argument is given
568         string height_value = "1";
569         string height_unit = "in";
570         string height_special = "totalheight";
571         string latex_height;
572         if (p.next_token().asInput() == "[") {
573                 position = p.getArg('[', ']');
574                 if (position != "t" && position != "c" && position != "b") {
575                         position = "c";
576                         cerr << "invalid position for minipage/parbox" << endl;
577                 }
578                 if (p.next_token().asInput() == "[") {
579                         latex_height = p.getArg('[', ']');
580                         translate_box_len(latex_height, height_value, height_unit, height_special);
581
582                         if (p.next_token().asInput() == "[") {
583                                 inner_pos = p.getArg('[', ']');
584                                 if (inner_pos != "c" && inner_pos != "t" &&
585                                     inner_pos != "b" && inner_pos != "s") {
586                                         inner_pos = position;
587                                         cerr << "invalid inner_pos for minipage/parbox"
588                                              << endl;
589                                 }
590                         }
591                 }
592         }
593         string width_value;
594         string width_unit;
595         string const latex_width = p.verbatim_item();
596         translate_len(latex_width, width_value, width_unit);
597         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
598                 // LyX can't handle length variables
599                 ostringstream ss;
600                 if (use_parbox)
601                         ss << "\\parbox";
602                 else
603                         ss << "\\begin{minipage}";
604                 if (!position.empty())
605                         ss << '[' << position << ']';
606                 if (!latex_height.empty())
607                         ss << '[' << latex_height << ']';
608                 if (!inner_pos.empty())
609                         ss << '[' << inner_pos << ']';
610                 ss << "{" << latex_width << "}";
611                 if (use_parbox)
612                         ss << '{';
613                 handle_ert(os, ss.str(), parent_context);
614                 parent_context.new_paragraph(os);
615                 parse_text_in_inset(p, os, flags, outer, parent_context);
616                 if (use_parbox)
617                         handle_ert(os, "}", parent_context);
618                 else
619                         handle_ert(os, "\\end{minipage}", parent_context);
620         } else {
621                 // LyX does not like empty positions, so we have
622                 // to set them to the LaTeX default values here.
623                 if (position.empty())
624                         position = "c";
625                 if (inner_pos.empty())
626                         inner_pos = position;
627                 parent_context.check_layout(os);
628                 begin_inset(os, "Box Frameless\n");
629                 os << "position \"" << position << "\"\n";
630                 os << "hor_pos \"c\"\n";
631                 os << "has_inner_box 1\n";
632                 os << "inner_pos \"" << inner_pos << "\"\n";
633                 os << "use_parbox " << use_parbox << "\n";
634                 os << "width \"" << width_value << width_unit << "\"\n";
635                 os << "special \"none\"\n";
636                 os << "height \"" << height_value << height_unit << "\"\n";
637                 os << "height_special \"" << height_special << "\"\n";
638                 os << "status open\n\n";
639                 parse_text_in_inset(p, os, flags, outer, parent_context);
640                 end_inset(os);
641 #ifdef PRESERVE_LAYOUT
642                 // lyx puts a % after the end of the minipage
643                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
644                         // new paragraph
645                         //handle_comment(os, "%dummy", parent_context);
646                         p.get_token();
647                         p.skip_spaces();
648                         parent_context.new_paragraph(os);
649                 }
650                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
651                         //handle_comment(os, "%dummy", parent_context);
652                         p.get_token();
653                         p.skip_spaces();
654                         // We add a protected space if something real follows
655                         if (p.good() && p.next_token().cat() != catComment) {
656                                 os << "\\InsetSpace ~\n";
657                         }
658                 }
659 #endif
660         }
661 }
662
663
664 /// parse an unknown environment
665 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
666                                unsigned flags, bool outer,
667                                Context & parent_context)
668 {
669         if (name == "tabbing")
670                 // We need to remember that we have to handle '\=' specially
671                 flags |= FLAG_TABBING;
672
673         // We need to translate font changes and paragraphs inside the
674         // environment to ERT if we have a non standard font.
675         // Otherwise things like
676         // \large\begin{foo}\huge bar\end{foo}
677         // will not work.
678         bool const specialfont =
679                 (parent_context.font != parent_context.normalfont);
680         bool const new_layout_allowed = parent_context.new_layout_allowed;
681         if (specialfont)
682                 parent_context.new_layout_allowed = false;
683         handle_ert(os, "\\begin{" + name + "}", parent_context);
684         parse_text_snippet(p, os, flags, outer, parent_context);
685         handle_ert(os, "\\end{" + name + "}", parent_context);
686         if (specialfont)
687                 parent_context.new_layout_allowed = new_layout_allowed;
688 }
689
690
691 void parse_environment(Parser & p, ostream & os, bool outer,
692                        Context & parent_context)
693 {
694         LayoutPtr newlayout;
695         string const name = p.getArg('{', '}');
696         const bool is_starred = suffixIs(name, '*');
697         string const unstarred_name = rtrim(name, "*");
698         active_environments.push_back(name);
699
700         if (is_math_env(name)) {
701                 parent_context.check_layout(os);
702                 begin_inset(os, "Formula ");
703                 os << "\\begin{" << name << "}";
704                 parse_math(p, os, FLAG_END, MATH_MODE);
705                 os << "\\end{" << name << "}";
706                 end_inset(os);
707         }
708
709         else if (name == "tabular" || name == "longtable") {
710                 eat_whitespace(p, os, parent_context, false);
711                 parent_context.check_layout(os);
712                 begin_inset(os, "Tabular ");
713                 handle_tabular(p, os, name == "longtable", parent_context);
714                 end_inset(os);
715                 p.skip_spaces();
716         }
717
718         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
719                 eat_whitespace(p, os, parent_context, false);
720                 parent_context.check_layout(os);
721                 begin_inset(os, "Float " + unstarred_name + "\n");
722                 if (p.next_token().asInput() == "[") {
723                         os << "placement " << p.getArg('[', ']') << '\n';
724                 }
725                 os << "wide " << convert<string>(is_starred)
726                    << "\nsideways false"
727                    << "\nstatus open\n\n";
728                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
729                 end_inset(os);
730                 // We don't need really a new paragraph, but
731                 // we must make sure that the next item gets a \begin_layout.
732                 parent_context.new_paragraph(os);
733                 p.skip_spaces();
734         }
735
736         else if (name == "minipage") {
737                 eat_whitespace(p, os, parent_context, false);
738                 parse_box(p, os, FLAG_END, outer, parent_context, false);
739                 p.skip_spaces();
740         }
741
742         else if (name == "comment") {
743                 eat_whitespace(p, os, parent_context, false);
744                 parent_context.check_layout(os);
745                 begin_inset(os, "Note Comment\n");
746                 os << "status open\n";
747                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
748                 end_inset(os);
749                 p.skip_spaces();
750         }
751
752         else if (name == "lyxgreyedout") {
753                 eat_whitespace(p, os, parent_context, false);
754                 parent_context.check_layout(os);
755                 begin_inset(os, "Note Greyedout\n");
756                 os << "status open\n";
757                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
758                 end_inset(os);
759                 p.skip_spaces();
760         }
761
762         else if (name == "framed") {
763                 eat_whitespace(p, os, parent_context, false);
764                 parent_context.check_layout(os);
765                 begin_inset(os, "Note Framed\n");
766                 os << "status open\n";
767                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
768                 end_inset(os);
769                 p.skip_spaces();
770         }
771
772         else if (name == "shaded") {
773                 eat_whitespace(p, os, parent_context, false);
774                 parent_context.check_layout(os);
775                 begin_inset(os, "Note Shaded\n");
776                 os << "status open\n";
777                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
778                 end_inset(os);
779                 p.skip_spaces();
780         }
781
782         else if (!parent_context.new_layout_allowed)
783                 parse_unknown_environment(p, name, os, FLAG_END, outer,
784                                           parent_context);
785
786         // Alignment settings
787         else if (name == "center" || name == "flushleft" || name == "flushright" ||
788                  name == "centering" || name == "raggedright" || name == "raggedleft") {
789                 eat_whitespace(p, os, parent_context, false);
790                 // We must begin a new paragraph if not already done
791                 if (! parent_context.atParagraphStart()) {
792                         parent_context.check_end_layout(os);
793                         parent_context.new_paragraph(os);
794                 }
795                 if (name == "flushleft" || name == "raggedright")
796                         parent_context.add_extra_stuff("\\align left\n");
797                 else if (name == "flushright" || name == "raggedleft")
798                         parent_context.add_extra_stuff("\\align right\n");
799                 else
800                         parent_context.add_extra_stuff("\\align center\n");
801                 parse_text(p, os, FLAG_END, outer, parent_context);
802                 // Just in case the environment is empty ..
803                 parent_context.extra_stuff.erase();
804                 // We must begin a new paragraph to reset the alignment
805                 parent_context.new_paragraph(os);
806                 p.skip_spaces();
807         }
808
809         // The single '=' is meant here.
810         else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
811                   newlayout->isEnvironment()) {
812                 eat_whitespace(p, os, parent_context, false);
813                 Context context(true, parent_context.textclass, newlayout,
814                                 parent_context.layout, parent_context.font);
815                 if (parent_context.deeper_paragraph) {
816                         // We are beginning a nested environment after a
817                         // deeper paragraph inside the outer list environment.
818                         // Therefore we don't need to output a "begin deeper".
819                         context.need_end_deeper = true;
820                 }
821                 parent_context.check_end_layout(os);
822                 switch (context.layout->latextype) {
823                 case  LATEX_LIST_ENVIRONMENT:
824                         context.extra_stuff = "\\labelwidthstring "
825                                 + p.verbatim_item() + '\n';
826                         p.skip_spaces();
827                         break;
828                 case  LATEX_BIB_ENVIRONMENT:
829                         p.verbatim_item(); // swallow next arg
830                         p.skip_spaces();
831                         break;
832                 default:
833                         break;
834                 }
835                 context.check_deeper(os);
836                 parse_text(p, os, FLAG_END, outer, context);
837                 context.check_end_layout(os);
838                 if (parent_context.deeper_paragraph) {
839                         // We must suppress the "end deeper" because we
840                         // suppressed the "begin deeper" above.
841                         context.need_end_deeper = false;
842                 }
843                 context.check_end_deeper(os);
844                 parent_context.new_paragraph(os);
845                 p.skip_spaces();
846         }
847
848         else if (name == "appendix") {
849                 // This is no good latex style, but it works and is used in some documents...
850                 eat_whitespace(p, os, parent_context, false);
851                 parent_context.check_end_layout(os);
852                 Context context(true, parent_context.textclass, parent_context.layout,
853                                 parent_context.layout, parent_context.font);
854                 context.check_layout(os);
855                 os << "\\start_of_appendix\n";
856                 parse_text(p, os, FLAG_END, outer, context);
857                 context.check_end_layout(os);
858                 p.skip_spaces();
859         }
860
861         else if (known_environments.find(name) != known_environments.end()) {
862                 vector<ArgumentType> arguments = known_environments[name];
863                 // The last "argument" denotes wether we may translate the
864                 // environment contents to LyX
865                 // The default required if no argument is given makes us
866                 // compatible with the reLyXre environment.
867                 ArgumentType contents = arguments.empty() ?
868                         required :
869                         arguments.back();
870                 if (!arguments.empty())
871                         arguments.pop_back();
872                 // See comment in parse_unknown_environment()
873                 bool const specialfont =
874                         (parent_context.font != parent_context.normalfont);
875                 bool const new_layout_allowed =
876                         parent_context.new_layout_allowed;
877                 if (specialfont)
878                         parent_context.new_layout_allowed = false;
879                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
880                                 outer, parent_context);
881                 if (contents == verbatim)
882                         handle_ert(os, p.verbatimEnvironment(name),
883                                    parent_context);
884                 else
885                         parse_text_snippet(p, os, FLAG_END, outer,
886                                            parent_context);
887                 handle_ert(os, "\\end{" + name + "}", parent_context);
888                 if (specialfont)
889                         parent_context.new_layout_allowed = new_layout_allowed;
890         }
891
892         else
893                 parse_unknown_environment(p, name, os, FLAG_END, outer,
894                                           parent_context);
895
896         active_environments.pop_back();
897 }
898
899
900 /// parses a comment and outputs it to \p os.
901 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
902 {
903         BOOST_ASSERT(t.cat() == catComment);
904         if (!t.cs().empty()) {
905                 context.check_layout(os);
906                 handle_comment(os, '%' + t.cs(), context);
907                 if (p.next_token().cat() == catNewline) {
908                         // A newline after a comment line starts a new
909                         // paragraph
910                         if (context.new_layout_allowed) {
911                                 if(!context.atParagraphStart())
912                                         // Only start a new paragraph if not already
913                                         // done (we might get called recursively)
914                                         context.new_paragraph(os);
915                         } else
916                                 handle_ert(os, "\n", context);
917                         eat_whitespace(p, os, context, true);
918                 }
919         } else {
920                 // "%\n" combination
921                 p.skip_spaces();
922         }
923 }
924
925
926 /*!
927  * Reads spaces and comments until the first non-space, non-comment token.
928  * New paragraphs (double newlines or \\par) are handled like simple spaces
929  * if \p eatParagraph is true.
930  * Spaces are skipped, but comments are written to \p os.
931  */
932 void eat_whitespace(Parser & p, ostream & os, Context & context,
933                     bool eatParagraph)
934 {
935         while (p.good()) {
936                 Token const & t = p.get_token();
937                 if (t.cat() == catComment)
938                         parse_comment(p, os, t, context);
939                 else if ((! eatParagraph && p.isParagraph()) ||
940                          (t.cat() != catSpace && t.cat() != catNewline)) {
941                         p.putback();
942                         return;
943                 }
944         }
945 }
946
947
948 /*!
949  * Set a font attribute, parse text and reset the font attribute.
950  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
951  * \param currentvalue Current value of the attribute. Is set to the new
952  * value during parsing.
953  * \param newvalue New value of the attribute
954  */
955 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
956                            Context & context, string const & attribute,
957                            string & currentvalue, string const & newvalue)
958 {
959         context.check_layout(os);
960         string const oldvalue = currentvalue;
961         currentvalue = newvalue;
962         os << '\n' << attribute << ' ' << newvalue << "\n";
963         parse_text_snippet(p, os, flags, outer, context);
964         context.check_layout(os);
965         os << '\n' << attribute << ' ' << oldvalue << "\n";
966         currentvalue = oldvalue;
967 }
968
969
970 /// get the arguments of a natbib or jurabib citation command
971 void get_cite_arguments(Parser & p, bool natbibOrder,
972         string & before, string & after)
973 {
974         // We need to distinguish "" and "[]", so we can't use p.getOpt().
975
976         // text before the citation
977         before.clear();
978         // text after the citation
979         after = p.getFullOpt();
980
981         if (!after.empty()) {
982                 before = p.getFullOpt();
983                 if (natbibOrder && !before.empty())
984                         swap(before, after);
985         }
986 }
987
988
989 /// Convert filenames with TeX macros and/or quotes to something LyX
990 /// can understand
991 string const normalize_filename(string const & name)
992 {
993         Parser p(trim(name, "\""));
994         ostringstream os;
995         while (p.good()) {
996                 Token const & t = p.get_token();
997                 if (t.cat() != catEscape)
998                         os << t.asInput();
999                 else if (t.cs() == "lyxdot") {
1000                         // This is used by LyX for simple dots in relative
1001                         // names
1002                         os << '.';
1003                         p.skip_spaces();
1004                 } else if (t.cs() == "space") {
1005                         os << ' ';
1006                         p.skip_spaces();
1007                 } else
1008                         os << t.asInput();
1009         }
1010         return os.str();
1011 }
1012
1013
1014 /// Convert \p name from TeX convention (relative to master file) to LyX
1015 /// convention (relative to .lyx file) if it is relative
1016 void fix_relative_filename(string & name)
1017 {
1018         FileName fname(name);
1019         if (fname.isAbsolute())
1020                 return;
1021
1022         // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1023         // utf8)
1024         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1025                                    from_utf8(getParentFilePath())));
1026 }
1027
1028
1029 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1030 void parse_noweb(Parser & p, ostream & os, Context & context)
1031 {
1032         // assemble the rest of the keyword
1033         string name("<<");
1034         bool scrap = false;
1035         while (p.good()) {
1036                 Token const & t = p.get_token();
1037                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1038                         name += ">>";
1039                         p.get_token();
1040                         scrap = (p.good() && p.next_token().asInput() == "=");
1041                         if (scrap)
1042                                 name += p.get_token().asInput();
1043                         break;
1044                 }
1045                 name += t.asInput();
1046         }
1047
1048         if (!scrap || !context.new_layout_allowed ||
1049             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1050                 cerr << "Warning: Could not interpret '" << name
1051                      << "'. Ignoring it." << endl;
1052                 return;
1053         }
1054
1055         // We use new_paragraph instead of check_end_layout because the stuff
1056         // following the noweb chunk needs to start with a \begin_layout.
1057         // This may create a new paragraph even if there was none in the
1058         // noweb file, but the alternative is an invalid LyX file. Since
1059         // noweb code chunks are implemented with a layout style in LyX they
1060         // always must be in an own paragraph.
1061         context.new_paragraph(os);
1062         Context newcontext(true, context.textclass,
1063                 context.textclass[from_ascii("Scrap")]);
1064         newcontext.check_layout(os);
1065         os << name;
1066         while (p.good()) {
1067                 Token const & t = p.get_token();
1068                 // We abuse the parser a bit, because this is no TeX syntax
1069                 // at all.
1070                 if (t.cat() == catEscape)
1071                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1072                 else
1073                         os << subst(t.asInput(), "\n", "\n\\newline\n");
1074                 // The scrap chunk is ended by an @ at the beginning of a line.
1075                 // After the @ the line may contain a comment and/or
1076                 // whitespace, but nothing else.
1077                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1078                     (p.next_token().cat() == catSpace ||
1079                      p.next_token().cat() == catNewline ||
1080                      p.next_token().cat() == catComment)) {
1081                         while (p.good() && p.next_token().cat() == catSpace)
1082                                 os << p.get_token().asInput();
1083                         if (p.next_token().cat() == catComment)
1084                                 // The comment includes a final '\n'
1085                                 os << p.get_token().asInput();
1086                         else {
1087                                 if (p.next_token().cat() == catNewline)
1088                                         p.get_token();
1089                                 os << '\n';
1090                         }
1091                         break;
1092                 }
1093         }
1094         newcontext.check_end_layout(os);
1095 }
1096
1097 } // anonymous namespace
1098
1099
1100 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1101                 Context & context)
1102 {
1103         LayoutPtr newlayout;
1104         // store the current selectlanguage to be used after \foreignlanguage
1105         string selectlang;
1106         // Store the latest bibliographystyle (needed for bibtex inset)
1107         string bibliographystyle;
1108         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1109         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1110         while (p.good()) {
1111                 Token const & t = p.get_token();
1112
1113 #ifdef FILEDEBUG
1114                 cerr << "t: " << t << " flags: " << flags << "\n";
1115 #endif
1116
1117                 if (flags & FLAG_ITEM) {
1118                         if (t.cat() == catSpace)
1119                                 continue;
1120
1121                         flags &= ~FLAG_ITEM;
1122                         if (t.cat() == catBegin) {
1123                                 // skip the brace and collect everything to the next matching
1124                                 // closing brace
1125                                 flags |= FLAG_BRACE_LAST;
1126                                 continue;
1127                         }
1128
1129                         // handle only this single token, leave the loop if done
1130                         flags |= FLAG_LEAVE;
1131                 }
1132
1133                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1134                         return;
1135
1136                 //
1137                 // cat codes
1138                 //
1139                 if (t.cat() == catMath) {
1140                         // we are inside some text mode thingy, so opening new math is allowed
1141                         context.check_layout(os);
1142                         begin_inset(os, "Formula ");
1143                         Token const & n = p.get_token();
1144                         if (n.cat() == catMath && outer) {
1145                                 // TeX's $$...$$ syntax for displayed math
1146                                 os << "\\[";
1147                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1148                                 os << "\\]";
1149                                 p.get_token(); // skip the second '$' token
1150                         } else {
1151                                 // simple $...$  stuff
1152                                 p.putback();
1153                                 os << '$';
1154                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1155                                 os << '$';
1156                         }
1157                         end_inset(os);
1158                 }
1159
1160                 else if (t.cat() == catSuper || t.cat() == catSub)
1161                         cerr << "catcode " << t << " illegal in text mode\n";
1162
1163                 // Basic support for english quotes. This should be
1164                 // extended to other quotes, but is not so easy (a
1165                 // left english quote is the same as a right german
1166                 // quote...)
1167                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1168                         context.check_layout(os);
1169                         begin_inset(os, "Quotes ");
1170                         os << "eld";
1171                         end_inset(os);
1172                         p.get_token();
1173                         skip_braces(p);
1174                 }
1175                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1176                         context.check_layout(os);
1177                         begin_inset(os, "Quotes ");
1178                         os << "erd";
1179                         end_inset(os);
1180                         p.get_token();
1181                         skip_braces(p);
1182                 }
1183
1184                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1185                         context.check_layout(os);
1186                         begin_inset(os, "Quotes ");
1187                         os << "ald";
1188                         end_inset(os);
1189                         p.get_token();
1190                         skip_braces(p);
1191                 }
1192
1193                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1194                         context.check_layout(os);
1195                         begin_inset(os, "Quotes ");
1196                         os << "ard";
1197                         end_inset(os);
1198                         p.get_token();
1199                         skip_braces(p);
1200                 }
1201
1202                 else if (t.asInput() == "<"
1203                          && p.next_token().asInput() == "<" && noweb_mode) {
1204                         p.get_token();
1205                         parse_noweb(p, os, context);
1206                 }
1207
1208                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1209                         check_space(p, os, context);
1210
1211                 else if (t.character() == '[' && noweb_mode &&
1212                          p.next_token().character() == '[') {
1213                         // These can contain underscores
1214                         p.putback();
1215                         string const s = p.getFullOpt() + ']';
1216                         if (p.next_token().character() == ']')
1217                                 p.get_token();
1218                         else
1219                                 cerr << "Warning: Inserting missing ']' in '"
1220                                      << s << "'." << endl;
1221                         handle_ert(os, s, context);
1222                 }
1223
1224                 else if (t.cat() == catLetter ||
1225                                t.cat() == catOther ||
1226                                t.cat() == catAlign ||
1227                                t.cat() == catParameter) {
1228                         // This translates "&" to "\\&" which may be wrong...
1229                         context.check_layout(os);
1230                         os << t.character();
1231                 }
1232
1233                 else if (p.isParagraph()) {
1234                         if (context.new_layout_allowed)
1235                                 context.new_paragraph(os);
1236                         else
1237                                 handle_ert(os, "\\par ", context);
1238                         eat_whitespace(p, os, context, true);
1239                 }
1240
1241                 else if (t.cat() == catActive) {
1242                         context.check_layout(os);
1243                         if (t.character() == '~') {
1244                                 if (context.layout->free_spacing)
1245                                         os << ' ';
1246                                 else
1247                                         os << "\\InsetSpace ~\n";
1248                         } else
1249                                 os << t.character();
1250                 }
1251
1252                 else if (t.cat() == catBegin &&
1253                          p.next_token().cat() == catEnd) {
1254                         // {}
1255                         Token const prev = p.prev_token();
1256                         p.get_token();
1257                         if (p.next_token().character() == '`' ||
1258                             (prev.character() == '-' &&
1259                              p.next_token().character() == '-'))
1260                                 ; // ignore it in {}`` or -{}-
1261                         else
1262                                 handle_ert(os, "{}", context);
1263
1264                 }
1265
1266                 else if (t.cat() == catBegin) {
1267                         context.check_layout(os);
1268                         // special handling of font attribute changes
1269                         Token const prev = p.prev_token();
1270                         Token const next = p.next_token();
1271                         TeXFont const oldFont = context.font;
1272                         if (next.character() == '[' ||
1273                             next.character() == ']' ||
1274                             next.character() == '*') {
1275                                 p.get_token();
1276                                 if (p.next_token().cat() == catEnd) {
1277                                         os << next.character();
1278                                         p.get_token();
1279                                 } else {
1280                                         p.putback();
1281                                         handle_ert(os, "{", context);
1282                                         parse_text_snippet(p, os,
1283                                                         FLAG_BRACE_LAST,
1284                                                         outer, context);
1285                                         handle_ert(os, "}", context);
1286                                 }
1287                         } else if (! context.new_layout_allowed) {
1288                                 handle_ert(os, "{", context);
1289                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1290                                                    outer, context);
1291                                 handle_ert(os, "}", context);
1292                         } else if (is_known(next.cs(), known_sizes)) {
1293                                 // next will change the size, so we must
1294                                 // reset it here
1295                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1296                                                    outer, context);
1297                                 if (!context.atParagraphStart())
1298                                         os << "\n\\size "
1299                                            << context.font.size << "\n";
1300                         } else if (is_known(next.cs(), known_font_families)) {
1301                                 // next will change the font family, so we
1302                                 // must reset it here
1303                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1304                                                    outer, context);
1305                                 if (!context.atParagraphStart())
1306                                         os << "\n\\family "
1307                                            << context.font.family << "\n";
1308                         } else if (is_known(next.cs(), known_font_series)) {
1309                                 // next will change the font series, so we
1310                                 // must reset it here
1311                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1312                                                    outer, context);
1313                                 if (!context.atParagraphStart())
1314                                         os << "\n\\series "
1315                                            << context.font.series << "\n";
1316                         } else if (is_known(next.cs(), known_font_shapes)) {
1317                                 // next will change the font shape, so we
1318                                 // must reset it here
1319                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1320                                                    outer, context);
1321                                 if (!context.atParagraphStart())
1322                                         os << "\n\\shape "
1323                                            << context.font.shape << "\n";
1324                         } else if (is_known(next.cs(), known_old_font_families) ||
1325                                    is_known(next.cs(), known_old_font_series) ||
1326                                    is_known(next.cs(), known_old_font_shapes)) {
1327                                 // next will change the font family, series
1328                                 // and shape, so we must reset it here
1329                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1330                                                    outer, context);
1331                                 if (!context.atParagraphStart())
1332                                         os <<  "\n\\family "
1333                                            << context.font.family
1334                                            << "\n\\series "
1335                                            << context.font.series
1336                                            << "\n\\shape "
1337                                            << context.font.shape << "\n";
1338                         } else {
1339                                 handle_ert(os, "{", context);
1340                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1341                                                    outer, context);
1342                                 handle_ert(os, "}", context);
1343                         }
1344                 }
1345
1346                 else if (t.cat() == catEnd) {
1347                         if (flags & FLAG_BRACE_LAST) {
1348                                 return;
1349                         }
1350                         cerr << "stray '}' in text\n";
1351                         handle_ert(os, "}", context);
1352                 }
1353
1354                 else if (t.cat() == catComment)
1355                         parse_comment(p, os, t, context);
1356
1357                 //
1358                 // control sequences
1359                 //
1360
1361                 else if (t.cs() == "(") {
1362                         context.check_layout(os);
1363                         begin_inset(os, "Formula");
1364                         os << " \\(";
1365                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1366                         os << "\\)";
1367                         end_inset(os);
1368                 }
1369
1370                 else if (t.cs() == "[") {
1371                         context.check_layout(os);
1372                         begin_inset(os, "Formula");
1373                         os << " \\[";
1374                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1375                         os << "\\]";
1376                         end_inset(os);
1377                 }
1378
1379                 else if (t.cs() == "begin")
1380                         parse_environment(p, os, outer, context);
1381
1382                 else if (t.cs() == "end") {
1383                         if (flags & FLAG_END) {
1384                                 // eat environment name
1385                                 string const name = p.getArg('{', '}');
1386                                 if (name != active_environment())
1387                                         cerr << "\\end{" + name + "} does not match \\begin{"
1388                                                 + active_environment() + "}\n";
1389                                 return;
1390                         }
1391                         p.error("found 'end' unexpectedly");
1392                 }
1393
1394                 else if (t.cs() == "item") {
1395                         p.skip_spaces();
1396                         string s;
1397                         bool optarg = false;
1398                         if (p.next_token().character() == '[') {
1399                                 p.get_token(); // eat '['
1400                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1401                                                        outer, context);
1402                                 optarg = true;
1403                         }
1404                         context.set_item();
1405                         context.check_layout(os);
1406                         if (context.has_item) {
1407                                 // An item in an unknown list-like environment
1408                                 // FIXME: Do this in check_layout()!
1409                                 context.has_item = false;
1410                                 if (optarg)
1411                                         handle_ert(os, "\\item", context);
1412                                 else
1413                                         handle_ert(os, "\\item ", context);
1414                         }
1415                         if (optarg) {
1416                                 if (context.layout->labeltype != LABEL_MANUAL) {
1417                                         // lyx does not support \item[\mybullet]
1418                                         // in itemize environments
1419                                         handle_ert(os, "[", context);
1420                                         os << s;
1421                                         handle_ert(os, "]", context);
1422                                 } else if (!s.empty()) {
1423                                         // The space is needed to separate the
1424                                         // item from the rest of the sentence.
1425                                         os << s << ' ';
1426                                         eat_whitespace(p, os, context, false);
1427                                 }
1428                         }
1429                 }
1430
1431                 else if (t.cs() == "bibitem") {
1432                         context.set_item();
1433                         context.check_layout(os);
1434                         os << "\\bibitem ";
1435                         os << p.getOpt();
1436                         os << '{' << p.verbatim_item() << '}' << "\n";
1437                 }
1438
1439                 else if (t.cs() == "def") {
1440                         context.check_layout(os);
1441                         eat_whitespace(p, os, context, false);
1442                         string name = p.get_token().cs();
1443                         eat_whitespace(p, os, context, false);
1444
1445                         // parameter text
1446                         bool simple = true;
1447                         string paramtext;
1448                         int arity = 0;
1449                         while (p.next_token().cat() != catBegin) {
1450                                 if (p.next_token().cat() == catParameter) {
1451                                         // # found
1452                                         p.get_token();
1453                                         paramtext += "#";
1454
1455                                         // followed by number?
1456                                         if (p.next_token().cat() == catOther) {
1457                                                 char c = p.getChar();
1458                                                 paramtext += c;
1459                                                 // number = current arity + 1?
1460                                                 if (c == arity + '0' + 1)
1461                                                         ++arity;
1462                                                 else
1463                                                         simple = false;
1464                                         } else
1465                                                 paramtext += p.get_token().asString();
1466                                 } else {
1467                                         paramtext += p.get_token().asString();
1468                                         simple = false;
1469                                 }
1470                         }
1471
1472                         // only output simple (i.e. compatible) macro as FormulaMacros
1473                         string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1474                         if (simple) {
1475                                 context.check_layout(os);
1476                                 begin_inset(os, "FormulaMacro");
1477                                 os << "\n" << ert;
1478                                 end_inset(os);
1479                         } else
1480                                 handle_ert(os, ert, context);
1481                 }
1482
1483                 else if (t.cs() == "noindent") {
1484                         p.skip_spaces();
1485                         context.add_extra_stuff("\\noindent\n");
1486                 }
1487
1488                 else if (t.cs() == "appendix") {
1489                         context.add_extra_stuff("\\start_of_appendix\n");
1490                         // We need to start a new paragraph. Otherwise the
1491                         // appendix in 'bla\appendix\chapter{' would start
1492                         // too late.
1493                         context.new_paragraph(os);
1494                         // We need to make sure that the paragraph is
1495                         // generated even if it is empty. Otherwise the
1496                         // appendix in '\par\appendix\par\chapter{' would
1497                         // start too late.
1498                         context.check_layout(os);
1499                         // FIXME: This is a hack to prevent paragraph
1500                         // deletion if it is empty. Handle this better!
1501                         handle_comment(os,
1502                                 "%dummy comment inserted by tex2lyx to "
1503                                 "ensure that this paragraph is not empty",
1504                                 context);
1505                         // Both measures above may generate an additional
1506                         // empty paragraph, but that does not hurt, because
1507                         // whitespace does not matter here.
1508                         eat_whitespace(p, os, context, true);
1509                 }
1510
1511                 // Must attempt to parse "Section*" before "Section".
1512                 else if ((p.next_token().asInput() == "*") &&
1513                          context.new_layout_allowed &&
1514                          // The single '=' is meant here.
1515                          (newlayout = findLayout(context.textclass,
1516                                                  t.cs() + '*')).get() &&
1517                          newlayout->isCommand()) {
1518                         p.get_token();
1519                         output_command_layout(os, p, outer, context, newlayout);
1520                         p.skip_spaces();
1521                 }
1522
1523                 // The single '=' is meant here.
1524                 else if (context.new_layout_allowed &&
1525                          (newlayout = findLayout(context.textclass, t.cs())).get() &&
1526                          newlayout->isCommand()) {
1527                         output_command_layout(os, p, outer, context, newlayout);
1528                         p.skip_spaces();
1529                 }
1530
1531                 // Special handling for \caption
1532                 // FIXME: remove this when InsetCaption is supported.
1533                 else if (context.new_layout_allowed &&
1534                          t.cs() == captionlayout->latexname()) {
1535                         output_command_layout(os, p, outer, context, 
1536                                               captionlayout);
1537                         p.skip_spaces();
1538                 }
1539
1540                 else if (t.cs() == "includegraphics") {
1541                         bool const clip = p.next_token().asInput() == "*";
1542                         if (clip)
1543                                 p.get_token();
1544                         map<string, string> opts = split_map(p.getArg('[', ']'));
1545                         if (clip)
1546                                 opts["clip"] = string();
1547                         string name = normalize_filename(p.verbatim_item());
1548
1549                         string const path = getMasterFilePath();
1550                         // We want to preserve relative / absolute filenames,
1551                         // therefore path is only used for testing
1552                         // FIXME UNICODE encoding of name and path may be
1553                         // wrong (makeAbsPath expects utf8)
1554                         if (!makeAbsPath(name, path).exists()) {
1555                                 // The file extension is probably missing.
1556                                 // Now try to find it out.
1557                                 string const dvips_name =
1558                                         find_file(name, path,
1559                                                   known_dvips_graphics_formats);
1560                                 string const pdftex_name =
1561                                         find_file(name, path,
1562                                                   known_pdftex_graphics_formats);
1563                                 if (!dvips_name.empty()) {
1564                                         if (!pdftex_name.empty()) {
1565                                                 cerr << "This file contains the "
1566                                                         "latex snippet\n"
1567                                                         "\"\\includegraphics{"
1568                                                      << name << "}\".\n"
1569                                                         "However, files\n\""
1570                                                      << dvips_name << "\" and\n\""
1571                                                      << pdftex_name << "\"\n"
1572                                                         "both exist, so I had to make a "
1573                                                         "choice and took the first one.\n"
1574                                                         "Please move the unwanted one "
1575                                                         "someplace else and try again\n"
1576                                                         "if my choice was wrong."
1577                                                      << endl;
1578                                         }
1579                                         name = dvips_name;
1580                                 } else if (!pdftex_name.empty())
1581                                         name = pdftex_name;
1582                         }
1583
1584                         // FIXME UNICODE encoding of name and path may be
1585                         // wrong (makeAbsPath expects utf8)
1586                         if (makeAbsPath(name, path).exists())
1587                                 fix_relative_filename(name);
1588                         else
1589                                 cerr << "Warning: Could not find graphics file '"
1590                                      << name << "'." << endl;
1591
1592                         context.check_layout(os);
1593                         begin_inset(os, "Graphics ");
1594                         os << "\n\tfilename " << name << '\n';
1595                         if (opts.find("width") != opts.end())
1596                                 os << "\twidth "
1597                                    << translate_len(opts["width"]) << '\n';
1598                         if (opts.find("height") != opts.end())
1599                                 os << "\theight "
1600                                    << translate_len(opts["height"]) << '\n';
1601                         if (opts.find("scale") != opts.end()) {
1602                                 istringstream iss(opts["scale"]);
1603                                 double val;
1604                                 iss >> val;
1605                                 val = val*100;
1606                                 os << "\tscale " << val << '\n';
1607                         }
1608                         if (opts.find("angle") != opts.end())
1609                                 os << "\trotateAngle "
1610                                    << opts["angle"] << '\n';
1611                         if (opts.find("origin") != opts.end()) {
1612                                 ostringstream ss;
1613                                 string const opt = opts["origin"];
1614                                 if (opt.find('l') != string::npos) ss << "left";
1615                                 if (opt.find('r') != string::npos) ss << "right";
1616                                 if (opt.find('c') != string::npos) ss << "center";
1617                                 if (opt.find('t') != string::npos) ss << "Top";
1618                                 if (opt.find('b') != string::npos) ss << "Bottom";
1619                                 if (opt.find('B') != string::npos) ss << "Baseline";
1620                                 if (!ss.str().empty())
1621                                         os << "\trotateOrigin " << ss.str() << '\n';
1622                                 else
1623                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1624                         }
1625                         if (opts.find("keepaspectratio") != opts.end())
1626                                 os << "\tkeepAspectRatio\n";
1627                         if (opts.find("clip") != opts.end())
1628                                 os << "\tclip\n";
1629                         if (opts.find("draft") != opts.end())
1630                                 os << "\tdraft\n";
1631                         if (opts.find("bb") != opts.end())
1632                                 os << "\tBoundingBox "
1633                                    << opts["bb"] << '\n';
1634                         int numberOfbbOptions = 0;
1635                         if (opts.find("bbllx") != opts.end())
1636                                 numberOfbbOptions++;
1637                         if (opts.find("bblly") != opts.end())
1638                                 numberOfbbOptions++;
1639                         if (opts.find("bburx") != opts.end())
1640                                 numberOfbbOptions++;
1641                         if (opts.find("bbury") != opts.end())
1642                                 numberOfbbOptions++;
1643                         if (numberOfbbOptions == 4)
1644                                 os << "\tBoundingBox "
1645                                    << opts["bbllx"] << " " << opts["bblly"] << " "
1646                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
1647                         else if (numberOfbbOptions > 0)
1648                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1649                         numberOfbbOptions = 0;
1650                         if (opts.find("natwidth") != opts.end())
1651                                 numberOfbbOptions++;
1652                         if (opts.find("natheight") != opts.end())
1653                                 numberOfbbOptions++;
1654                         if (numberOfbbOptions == 2)
1655                                 os << "\tBoundingBox 0bp 0bp "
1656                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
1657                         else if (numberOfbbOptions > 0)
1658                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1659                         ostringstream special;
1660                         if (opts.find("hiresbb") != opts.end())
1661                                 special << "hiresbb,";
1662                         if (opts.find("trim") != opts.end())
1663                                 special << "trim,";
1664                         if (opts.find("viewport") != opts.end())
1665                                 special << "viewport=" << opts["viewport"] << ',';
1666                         if (opts.find("totalheight") != opts.end())
1667                                 special << "totalheight=" << opts["totalheight"] << ',';
1668                         if (opts.find("type") != opts.end())
1669                                 special << "type=" << opts["type"] << ',';
1670                         if (opts.find("ext") != opts.end())
1671                                 special << "ext=" << opts["ext"] << ',';
1672                         if (opts.find("read") != opts.end())
1673                                 special << "read=" << opts["read"] << ',';
1674                         if (opts.find("command") != opts.end())
1675                                 special << "command=" << opts["command"] << ',';
1676                         string s_special = special.str();
1677                         if (!s_special.empty()) {
1678                                 // We had special arguments. Remove the trailing ','.
1679                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1680                         }
1681                         // TODO: Handle the unknown settings better.
1682                         // Warn about invalid options.
1683                         // Check whether some option was given twice.
1684                         end_inset(os);
1685                 }
1686
1687                 else if (t.cs() == "footnote" ||
1688                          (t.cs() == "thanks" && context.layout->intitle)) {
1689                         p.skip_spaces();
1690                         context.check_layout(os);
1691                         begin_inset(os, "Foot\n");
1692                         os << "status collapsed\n\n";
1693                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1694                         end_inset(os);
1695                 }
1696
1697                 else if (t.cs() == "marginpar") {
1698                         p.skip_spaces();
1699                         context.check_layout(os);
1700                         begin_inset(os, "Marginal\n");
1701                         os << "status collapsed\n\n";
1702                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1703                         end_inset(os);
1704                 }
1705
1706                 else if (t.cs() == "ensuremath") {
1707                         p.skip_spaces();
1708                         context.check_layout(os);
1709                         string const s = p.verbatim_item();
1710                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1711                                 os << s;
1712                         else
1713                                 handle_ert(os, "\\ensuremath{" + s + "}",
1714                                            context);
1715                 }
1716
1717                 else if (t.cs() == "hfill") {
1718                         context.check_layout(os);
1719                         os << "\n\\hfill\n";
1720                         skip_braces(p);
1721                         p.skip_spaces();
1722                 }
1723
1724                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1725                         // FIXME: Somehow prevent title layouts if
1726                         // "maketitle" was not found
1727                         p.skip_spaces();
1728                         skip_braces(p); // swallow this
1729                 }
1730
1731                 else if (t.cs() == "tableofcontents") {
1732                         p.skip_spaces();
1733                         context.check_layout(os);
1734                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1735                         end_inset(os);
1736                         skip_braces(p); // swallow this
1737                 }
1738
1739                 else if (t.cs() == "listoffigures") {
1740                         p.skip_spaces();
1741                         context.check_layout(os);
1742                         begin_inset(os, "FloatList figure\n");
1743                         end_inset(os);
1744                         skip_braces(p); // swallow this
1745                 }
1746
1747                 else if (t.cs() == "listoftables") {
1748                         p.skip_spaces();
1749                         context.check_layout(os);
1750                         begin_inset(os, "FloatList table\n");
1751                         end_inset(os);
1752                         skip_braces(p); // swallow this
1753                 }
1754
1755                 else if (t.cs() == "listof") {
1756                         p.skip_spaces(true);
1757                         string const name = p.get_token().asString();
1758                         if (context.textclass.floats().typeExist(name)) {
1759                                 context.check_layout(os);
1760                                 begin_inset(os, "FloatList ");
1761                                 os << name << "\n";
1762                                 end_inset(os);
1763                                 p.get_token(); // swallow second arg
1764                         } else
1765                                 handle_ert(os, "\\listof{" + name + "}", context);
1766                 }
1767
1768                 else if (t.cs() == "textrm")
1769                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1770                                               context, "\\family",
1771                                               context.font.family, "roman");
1772
1773                 else if (t.cs() == "textsf")
1774                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1775                                               context, "\\family",
1776                                               context.font.family, "sans");
1777
1778                 else if (t.cs() == "texttt")
1779                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1780                                               context, "\\family",
1781                                               context.font.family, "typewriter");
1782
1783                 else if (t.cs() == "textmd")
1784                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1785                                               context, "\\series",
1786                                               context.font.series, "medium");
1787
1788                 else if (t.cs() == "textbf")
1789                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1790                                               context, "\\series",
1791                                               context.font.series, "bold");
1792
1793                 else if (t.cs() == "textup")
1794                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1795                                               context, "\\shape",
1796                                               context.font.shape, "up");
1797
1798                 else if (t.cs() == "textit")
1799                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1800                                               context, "\\shape",
1801                                               context.font.shape, "italic");
1802
1803                 else if (t.cs() == "textsl")
1804                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1805                                               context, "\\shape",
1806                                               context.font.shape, "slanted");
1807
1808                 else if (t.cs() == "textsc")
1809                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1810                                               context, "\\shape",
1811                                               context.font.shape, "smallcaps");
1812
1813                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1814                         context.check_layout(os);
1815                         TeXFont oldFont = context.font;
1816                         context.font.init();
1817                         context.font.size = oldFont.size;
1818                         os << "\n\\family " << context.font.family << "\n";
1819                         os << "\n\\series " << context.font.series << "\n";
1820                         os << "\n\\shape " << context.font.shape << "\n";
1821                         if (t.cs() == "textnormal") {
1822                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1823                                 output_font_change(os, context.font, oldFont);
1824                                 context.font = oldFont;
1825                         } else
1826                                 eat_whitespace(p, os, context, false);
1827                 }
1828
1829                 else if (t.cs() == "underbar") {
1830                         // Do NOT handle \underline.
1831                         // \underbar cuts through y, g, q, p etc.,
1832                         // \underline does not.
1833                         context.check_layout(os);
1834                         os << "\n\\bar under\n";
1835                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1836                         context.check_layout(os);
1837                         os << "\n\\bar default\n";
1838                 }
1839
1840                 else if (t.cs() == "emph" || t.cs() == "noun") {
1841                         context.check_layout(os);
1842                         os << "\n\\" << t.cs() << " on\n";
1843                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1844                         context.check_layout(os);
1845                         os << "\n\\" << t.cs() << " default\n";
1846                 }
1847
1848                 else if (use_natbib &&
1849                          is_known(t.cs(), known_natbib_commands) &&
1850                          ((t.cs() != "citefullauthor" &&
1851                            t.cs() != "citeyear" &&
1852                            t.cs() != "citeyearpar") ||
1853                           p.next_token().asInput() != "*")) {
1854                         context.check_layout(os);
1855                         // tex                       lyx
1856                         // \citet[before][after]{a}  \citet[after][before]{a}
1857                         // \citet[before][]{a}       \citet[][before]{a}
1858                         // \citet[after]{a}          \citet[after]{a}
1859                         // \citet{a}                 \citet{a}
1860                         string command = '\\' + t.cs();
1861                         if (p.next_token().asInput() == "*") {
1862                                 command += '*';
1863                                 p.get_token();
1864                         }
1865                         if (command == "\\citefullauthor")
1866                                 // alternative name for "\\citeauthor*"
1867                                 command = "\\citeauthor*";
1868
1869                         // text before the citation
1870                         string before;
1871                         // text after the citation
1872                         string after;
1873                         get_cite_arguments(p, true, before, after);
1874
1875                         if (command == "\\cite") {
1876                                 // \cite without optional argument means
1877                                 // \citet, \cite with at least one optional
1878                                 // argument means \citep.
1879                                 if (before.empty() && after.empty())
1880                                         command = "\\citet";
1881                                 else
1882                                         command = "\\citep";
1883                         }
1884                         if (before.empty() && after == "[]")
1885                                 // avoid \citet[]{a}
1886                                 after.erase();
1887                         else if (before == "[]" && after == "[]") {
1888                                 // avoid \citet[][]{a}
1889                                 before.erase();
1890                                 after.erase();
1891                         }
1892                         begin_inset(os, "LatexCommand ");
1893                         os << command << after << before
1894                            << '{' << p.verbatim_item() << "}\n";
1895                         end_inset(os);
1896                 }
1897
1898                 else if (use_jurabib &&
1899                          is_known(t.cs(), known_jurabib_commands)) {
1900                         context.check_layout(os);
1901                         string const command = '\\' + t.cs();
1902                         char argumentOrder = '\0';
1903                         vector<string> const & options = used_packages["jurabib"];
1904                         if (find(options.begin(), options.end(),
1905                                       "natbiborder") != options.end())
1906                                 argumentOrder = 'n';
1907                         else if (find(options.begin(), options.end(),
1908                                            "jurabiborder") != options.end())
1909                                 argumentOrder = 'j';
1910
1911                         // text before the citation
1912                         string before;
1913                         // text after the citation
1914                         string after;
1915                         get_cite_arguments(p, argumentOrder != 'j', before, after);
1916
1917                         string const citation = p.verbatim_item();
1918                         if (!before.empty() && argumentOrder == '\0') {
1919                                 cerr << "Warning: Assuming argument order "
1920                                         "of jurabib version 0.6 for\n'"
1921                                      << command << before << after << '{'
1922                                      << citation << "}'.\n"
1923                                         "Add 'jurabiborder' to the jurabib "
1924                                         "package options if you used an\n"
1925                                         "earlier jurabib version." << endl;
1926                         }
1927                         begin_inset(os, "LatexCommand ");
1928                         os << command << after << before
1929                            << '{' << citation << "}\n";
1930                         end_inset(os);
1931                 }
1932
1933                 else if (is_known(t.cs(), known_latex_commands)) {
1934                         // This needs to be after the check for natbib and
1935                         // jurabib commands, because "cite" has different
1936                         // arguments with natbib and jurabib.
1937                         context.check_layout(os);
1938                         begin_inset(os, "LatexCommand ");
1939                         os << '\\' << t.cs();
1940                         // lyx cannot handle newlines in a latex command
1941                         // FIXME: Move the substitution into parser::getOpt()?
1942                         os << subst(p.getOpt(), "\n", " ");
1943                         os << subst(p.getOpt(), "\n", " ");
1944                         os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1945                         end_inset(os);
1946                 }
1947
1948                 else if (is_known(t.cs(), known_quotes)) {
1949                         char const * const * where = is_known(t.cs(), known_quotes);
1950                         context.check_layout(os);
1951                         begin_inset(os, "Quotes ");
1952                         os << known_coded_quotes[where - known_quotes];
1953                         end_inset(os);
1954                         // LyX adds {} after the quote, so we have to eat
1955                         // spaces here if there are any before a possible
1956                         // {} pair.
1957                         eat_whitespace(p, os, context, false);
1958                         skip_braces(p);
1959                 }
1960
1961                 else if (is_known(t.cs(), known_sizes) &&
1962                          context.new_layout_allowed) {
1963                         char const * const * where = is_known(t.cs(), known_sizes);
1964                         context.check_layout(os);
1965                         TeXFont const oldFont = context.font;
1966                         context.font.size = known_coded_sizes[where - known_sizes];
1967                         output_font_change(os, oldFont, context.font);
1968                         eat_whitespace(p, os, context, false);
1969                 }
1970
1971                 else if (is_known(t.cs(), known_font_families) &&
1972                          context.new_layout_allowed) {
1973                         char const * const * where =
1974                                 is_known(t.cs(), known_font_families);
1975                         context.check_layout(os);
1976                         TeXFont const oldFont = context.font;
1977                         context.font.family =
1978                                 known_coded_font_families[where - known_font_families];
1979                         output_font_change(os, oldFont, context.font);
1980                         eat_whitespace(p, os, context, false);
1981                 }
1982
1983                 else if (is_known(t.cs(), known_font_series) &&
1984                          context.new_layout_allowed) {
1985                         char const * const * where =
1986                                 is_known(t.cs(), known_font_series);
1987                         context.check_layout(os);
1988                         TeXFont const oldFont = context.font;
1989                         context.font.series =
1990                                 known_coded_font_series[where - known_font_series];
1991                         output_font_change(os, oldFont, context.font);
1992                         eat_whitespace(p, os, context, false);
1993                 }
1994
1995                 else if (is_known(t.cs(), known_font_shapes) &&
1996                          context.new_layout_allowed) {
1997                         char const * const * where =
1998                                 is_known(t.cs(), known_font_shapes);
1999                         context.check_layout(os);
2000                         TeXFont const oldFont = context.font;
2001                         context.font.shape =
2002                                 known_coded_font_shapes[where - known_font_shapes];
2003                         output_font_change(os, oldFont, context.font);
2004                         eat_whitespace(p, os, context, false);
2005                 }
2006                 else if (is_known(t.cs(), known_old_font_families) &&
2007                          context.new_layout_allowed) {
2008                         char const * const * where =
2009                                 is_known(t.cs(), known_old_font_families);
2010                         context.check_layout(os);
2011                         TeXFont const oldFont = context.font;
2012                         context.font.init();
2013                         context.font.size = oldFont.size;
2014                         context.font.family =
2015                                 known_coded_font_families[where - known_old_font_families];
2016                         output_font_change(os, oldFont, context.font);
2017                         eat_whitespace(p, os, context, false);
2018                 }
2019
2020                 else if (is_known(t.cs(), known_old_font_series) &&
2021                          context.new_layout_allowed) {
2022                         char const * const * where =
2023                                 is_known(t.cs(), known_old_font_series);
2024                         context.check_layout(os);
2025                         TeXFont const oldFont = context.font;
2026                         context.font.init();
2027                         context.font.size = oldFont.size;
2028                         context.font.series =
2029                                 known_coded_font_series[where - known_old_font_series];
2030                         output_font_change(os, oldFont, context.font);
2031                         eat_whitespace(p, os, context, false);
2032                 }
2033
2034                 else if (is_known(t.cs(), known_old_font_shapes) &&
2035                          context.new_layout_allowed) {
2036                         char const * const * where =
2037                                 is_known(t.cs(), known_old_font_shapes);
2038                         context.check_layout(os);
2039                         TeXFont const oldFont = context.font;
2040                         context.font.init();
2041                         context.font.size = oldFont.size;
2042                         context.font.shape =
2043                                 known_coded_font_shapes[where - known_old_font_shapes];
2044                         output_font_change(os, oldFont, context.font);
2045                         eat_whitespace(p, os, context, false);
2046                 }
2047
2048                 else if (t.cs() == "selectlanguage") {
2049                         context.check_layout(os);
2050                         // save the language for the case that a \foreignlanguage is used 
2051                         selectlang = subst(p.verbatim_item(), "\n", " ");
2052                         os << "\\lang " << selectlang << "\n";
2053                         
2054                 }
2055
2056                 else if (t.cs() == "foreignlanguage") {
2057                         context.check_layout(os);
2058                         os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2059                         os << subst(p.verbatim_item(), "\n", " ");
2060                         // set back to last selectlanguage
2061                         os << "\n\\lang " << selectlang << "\n";
2062                 }
2063
2064                 else if (t.cs() == "inputencoding")
2065                         // write nothing because this is done by LyX using the "\lang"
2066                         // information given by selectlanguage and foreignlanguage
2067                         subst(p.verbatim_item(), "\n", " ");
2068                 
2069                 else if (t.cs() == "LyX" || t.cs() == "TeX"
2070                          || t.cs() == "LaTeX") {
2071                         context.check_layout(os);
2072                         os << t.cs();
2073                         skip_braces(p); // eat {}
2074                 }
2075
2076                 else if (t.cs() == "LaTeXe") {
2077                         context.check_layout(os);
2078                         os << "LaTeX2e";
2079                         skip_braces(p); // eat {}
2080                 }
2081
2082                 else if (t.cs() == "ldots") {
2083                         context.check_layout(os);
2084                         skip_braces(p);
2085                         os << "\\SpecialChar \\ldots{}\n";
2086                 }
2087
2088                 else if (t.cs() == "lyxarrow") {
2089                         context.check_layout(os);
2090                         os << "\\SpecialChar \\menuseparator\n";
2091                         skip_braces(p);
2092                 }
2093
2094                 else if (t.cs() == "textcompwordmark") {
2095                         context.check_layout(os);
2096                         os << "\\SpecialChar \\textcompwordmark{}\n";
2097                         skip_braces(p);
2098                 }
2099
2100                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2101                         context.check_layout(os);
2102                         os << "\\SpecialChar \\@.\n";
2103                         p.get_token();
2104                 }
2105
2106                 else if (t.cs() == "-") {
2107                         context.check_layout(os);
2108                         os << "\\SpecialChar \\-\n";
2109                 }
2110
2111                 else if (t.cs() == "textasciitilde") {
2112                         context.check_layout(os);
2113                         os << '~';
2114                         skip_braces(p);
2115                 }
2116
2117                 else if (t.cs() == "textasciicircum") {
2118                         context.check_layout(os);
2119                         os << '^';
2120                         skip_braces(p);
2121                 }
2122
2123                 else if (t.cs() == "textbackslash") {
2124                         context.check_layout(os);
2125                         os << "\n\\backslash\n";
2126                         skip_braces(p);
2127                 }
2128
2129                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2130                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2131                             || t.cs() == "%") {
2132                         context.check_layout(os);
2133                         os << t.cs();
2134                 }
2135
2136                 else if (t.cs() == "char") {
2137                         context.check_layout(os);
2138                         if (p.next_token().character() == '`') {
2139                                 p.get_token();
2140                                 if (p.next_token().cs() == "\"") {
2141                                         p.get_token();
2142                                         os << '"';
2143                                         skip_braces(p);
2144                                 } else {
2145                                         handle_ert(os, "\\char`", context);
2146                                 }
2147                         } else {
2148                                 handle_ert(os, "\\char", context);
2149                         }
2150                 }
2151
2152                 else if (t.cs() == "verb") {
2153                         context.check_layout(os);
2154                         char const delimiter = p.next_token().character();
2155                         string const arg = p.getArg(delimiter, delimiter);
2156                         ostringstream oss;
2157                         oss << "\\verb" << delimiter << arg << delimiter;
2158                         handle_ert(os, oss.str(), context);
2159                 }
2160
2161                 else if (t.cs() == "\"") {
2162                         context.check_layout(os);
2163                         string const name = p.verbatim_item();
2164                              if (name == "a") os << '\xe4';
2165                         else if (name == "o") os << '\xf6';
2166                         else if (name == "u") os << '\xfc';
2167                         else if (name == "A") os << '\xc4';
2168                         else if (name == "O") os << '\xd6';
2169                         else if (name == "U") os << '\xdc';
2170                         else handle_ert(os, "\"{" + name + "}", context);
2171                 }
2172
2173                 // Problem: \= creates a tabstop inside the tabbing environment
2174                 // and else an accent. In the latter case we really would want
2175                 // \={o} instead of \= o.
2176                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2177                         handle_ert(os, t.asInput(), context);
2178
2179                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2180                          || t.cs() == "'" || t.cs() == "`"
2181                          || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2182                         // we need the trim as the LyX parser chokes on such spaces
2183                         // The argument of InsetLatexAccent is parsed as a
2184                         // subset of LaTeX, so don't parse anything here,
2185                         // but use the raw argument.
2186                         // Otherwise we would convert \~{\i} wrongly.
2187                         // This will of course not translate \~{\ss} to \~{ß},
2188                         // but that does at least compile and does only look
2189                         // strange on screen.
2190                         context.check_layout(os);
2191                         os << "\\i \\" << t.cs() << "{"
2192                            << trim(p.verbatim_item(), " ")
2193                            << "}\n";
2194                 }
2195
2196                 else if (t.cs() == "ss") {
2197                         context.check_layout(os);
2198                         os << "\xdf";
2199                         skip_braces(p); // eat {}
2200                 }
2201
2202                 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2203                          t.cs() == "L") {
2204                         context.check_layout(os);
2205                         os << "\\i \\" << t.cs() << "{}\n";
2206                         skip_braces(p); // eat {}
2207                 }
2208
2209                 else if (t.cs() == "\\") {
2210                         context.check_layout(os);
2211                         string const next = p.next_token().asInput();
2212                         if (next == "[")
2213                                 handle_ert(os, "\\\\" + p.getOpt(), context);
2214                         else if (next == "*") {
2215                                 p.get_token();
2216                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
2217                         }
2218                         else {
2219                                 os << "\n\\newline\n";
2220                         }
2221                 }
2222
2223                 else if (t.cs() == "newline" ||
2224                         t.cs() == "linebreak") {
2225                         context.check_layout(os);
2226                         os << "\n\\" << t.cs() << "\n";
2227                         skip_braces(p); // eat {}
2228                 }
2229
2230                 else if (t.cs() == "href") {
2231                         context.check_layout(os);
2232                         begin_inset(os, "CommandInset ");
2233                         os << t.cs() << "\n";
2234                         os << "LatexCommand " << t.cs() << "\n";
2235                         bool erase = false;
2236                         size_t pos;
2237                         // the first argument is "type:target", "type:" is optional
2238                         // the second argument the name
2239                         string href_target = subst(p.verbatim_item(), "\n", " ");
2240                         string href_name = subst(p.verbatim_item(), "\n", " ");
2241                         string href_type;
2242                         // serach for the ":" to divide type from target
2243                         if ((pos = href_target.find(":", 0)) != string::npos){
2244                                 href_type = href_target;
2245                                 href_type.erase(pos + 1, href_type.length());
2246                                 href_target.erase(0, pos + 1);
2247                             erase = true;                                                                                       
2248                         }
2249                         os << "name " << '"' << href_name << '"' << "\n";
2250                         os << "target " << '"' << href_target << '"' << "\n";
2251                         if(erase)
2252                                 os << "type " << '"' << href_type << '"' << "\n";
2253                         end_inset(os);
2254                 }
2255
2256                 else if (t.cs() == "input" || t.cs() == "include"
2257                          || t.cs() == "verbatiminput") {
2258                         string name = '\\' + t.cs();
2259                         if (t.cs() == "verbatiminput"
2260                             && p.next_token().asInput() == "*")
2261                                 name += p.get_token().asInput();
2262                         context.check_layout(os);
2263                         begin_inset(os, "Include ");
2264                         string filename(normalize_filename(p.getArg('{', '}')));
2265                         string const path = getMasterFilePath();
2266                         // We want to preserve relative / absolute filenames,
2267                         // therefore path is only used for testing
2268                         // FIXME UNICODE encoding of filename and path may be
2269                         // wrong (makeAbsPath expects utf8)
2270                         if ((t.cs() == "include" || t.cs() == "input") &&
2271                             !makeAbsPath(filename, path).exists()) {
2272                                 // The file extension is probably missing.
2273                                 // Now try to find it out.
2274                                 string const tex_name =
2275                                         find_file(filename, path,
2276                                                   known_tex_extensions);
2277                                 if (!tex_name.empty())
2278                                         filename = tex_name;
2279                         }
2280                         // FIXME UNICODE encoding of filename and path may be
2281                         // wrong (makeAbsPath expects utf8)
2282                         if (makeAbsPath(filename, path).exists()) {
2283                                 string const abstexname =
2284                                         makeAbsPath(filename, path).absFilename();
2285                                 string const abslyxname =
2286                                         changeExtension(abstexname, ".lyx");
2287                                 fix_relative_filename(filename);
2288                                 string const lyxname =
2289                                         changeExtension(filename, ".lyx");
2290                                 if (t.cs() != "verbatiminput" &&
2291                                     tex2lyx(abstexname, FileName(abslyxname))) {
2292                                         os << name << '{' << lyxname << "}\n";
2293                                 } else {
2294                                         os << name << '{' << filename << "}\n";
2295                                 }
2296                         } else {
2297                                 cerr << "Warning: Could not find included file '"
2298                                      << filename << "'." << endl;
2299                                 os << name << '{' << filename << "}\n";
2300                         }
2301                         os << "preview false\n";
2302                         end_inset(os);
2303                 }
2304
2305                 else if (t.cs() == "bibliographystyle") {
2306                         // store new bibliographystyle
2307                         bibliographystyle = p.verbatim_item();
2308                         // output new bibliographystyle.
2309                         // This is only necessary if used in some other macro than \bibliography.
2310                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2311                 }
2312
2313                 else if (t.cs() == "bibliography") {
2314                         context.check_layout(os);
2315                         begin_inset(os, "LatexCommand ");
2316                         os << "\\bibtex";
2317                         // Do we have a bibliographystyle set?
2318                         if (!bibliographystyle.empty()) {
2319                                 os << '[' << bibliographystyle << ']';
2320                         }
2321                         os << '{' << p.verbatim_item() << "}\n";
2322                         end_inset(os);
2323                 }
2324
2325                 else if (t.cs() == "parbox")
2326                         parse_box(p, os, FLAG_ITEM, outer, context, true);
2327
2328                 else if (t.cs() == "smallskip" ||
2329                          t.cs() == "medskip" ||
2330                          t.cs() == "bigskip" ||
2331                          t.cs() == "vfill") {
2332                         context.check_layout(os);
2333                         begin_inset(os, "VSpace ");
2334                         os << t.cs();
2335                         end_inset(os);
2336                         skip_braces(p);
2337                 }
2338
2339                 else if (is_known(t.cs(), known_spaces)) {
2340                         char const * const * where = is_known(t.cs(), known_spaces);
2341                         context.check_layout(os);
2342                         begin_inset(os, "InsetSpace ");
2343                         os << '\\' << known_coded_spaces[where - known_spaces]
2344                            << '\n';
2345                         // LaTeX swallows whitespace after all spaces except
2346                         // "\\,". We have to do that here, too, because LyX
2347                         // adds "{}" which would make the spaces significant.
2348                         if (t.cs() !=  ",")
2349                                 eat_whitespace(p, os, context, false);
2350                         // LyX adds "{}" after all spaces except "\\ " and
2351                         // "\\,", so we have to remove "{}".
2352                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
2353                         // remove the braces after "\\,", too.
2354                         if (t.cs() != " ")
2355                                 skip_braces(p);
2356                 }
2357
2358                 else if (t.cs() == "newpage" ||
2359                         t.cs() == "pagebreak" ||
2360                         t.cs() == "clearpage" ||
2361                         t.cs() == "cleardoublepage") {
2362                         context.check_layout(os);
2363                         os << "\n\\" << t.cs() << "\n";
2364                         skip_braces(p); // eat {}
2365                 }
2366
2367                 else if (t.cs() == "newcommand" ||
2368                          t.cs() == "providecommand" ||
2369                          t.cs() == "renewcommand" ||
2370                          t.cs() == "newlyxcommand") {
2371                         // these could be handled by parse_command(), but
2372                         // we need to call add_known_command() here.
2373                         string name = t.asInput();
2374                         if (p.next_token().asInput() == "*") {
2375                                 // Starred form. Eat '*'
2376                                 p.get_token();
2377                                 name += '*';
2378                         }
2379                         string const command = p.verbatim_item();
2380                         string const opt1 = p.getOpt();
2381                         string optionals;
2382                         unsigned optionalsNum = 0;
2383                         while (true) {
2384                                 string const opt = p.getFullOpt();
2385                                 if (opt.empty())
2386                                         break;
2387                                 optionalsNum++;
2388                                 optionals += opt;
2389                         }
2390                         add_known_command(command, opt1, optionalsNum);
2391                         string const ert = name + '{' + command + '}' + opt1
2392                                 + optionals + '{' + p.verbatim_item() + '}';
2393
2394                         context.check_layout(os);
2395                         begin_inset(os, "FormulaMacro");
2396                         os << "\n" << ert;
2397                         end_inset(os);
2398                 }
2399
2400                 else if (t.cs() == "vspace") {
2401                         bool starred = false;
2402                         if (p.next_token().asInput() == "*") {
2403                                 p.get_token();
2404                                 starred = true;
2405                         }
2406                         string const length = p.verbatim_item();
2407                         string unit;
2408                         string valstring;
2409                         bool valid = splitLatexLength(length, valstring, unit);
2410                         bool known_vspace = false;
2411                         bool known_unit = false;
2412                         double value;
2413                         if (valid) {
2414                                 istringstream iss(valstring);
2415                                 iss >> value;
2416                                 if (value == 1.0) {
2417                                         if (unit == "\\smallskipamount") {
2418                                                 unit = "smallskip";
2419                                                 known_vspace = true;
2420                                         } else if (unit == "\\medskipamount") {
2421                                                 unit = "medskip";
2422                                                 known_vspace = true;
2423                                         } else if (unit == "\\bigskipamount") {
2424                                                 unit = "bigskip";
2425                                                 known_vspace = true;
2426                                         } else if (unit == "\\fill") {
2427                                                 unit = "vfill";
2428                                                 known_vspace = true;
2429                                         }
2430                                 }
2431                                 if (!known_vspace) {
2432                                         switch (unitFromString(unit)) {
2433                                         case Length::SP:
2434                                         case Length::PT:
2435                                         case Length::BP:
2436                                         case Length::DD:
2437                                         case Length::MM:
2438                                         case Length::PC:
2439                                         case Length::CC:
2440                                         case Length::CM:
2441                                         case Length::IN:
2442                                         case Length::EX:
2443                                         case Length::EM:
2444                                         case Length::MU:
2445                                                 known_unit = true;
2446                                                 break;
2447                                         default:
2448                                                 break;
2449                                         }
2450                                 }
2451                         }
2452
2453                         if (known_unit || known_vspace) {
2454                                 // Literal length or known variable
2455                                 context.check_layout(os);
2456                                 begin_inset(os, "VSpace ");
2457                                 if (known_unit)
2458                                         os << value;
2459                                 os << unit;
2460                                 if (starred)
2461                                         os << '*';
2462                                 end_inset(os);
2463                         } else {
2464                                 // LyX can't handle other length variables in Inset VSpace
2465                                 string name = t.asInput();
2466                                 if (starred)
2467                                         name += '*';
2468                                 if (valid) {
2469                                         if (value == 1.0)
2470                                                 handle_ert(os, name + '{' + unit + '}', context);
2471                                         else if (value == -1.0)
2472                                                 handle_ert(os, name + "{-" + unit + '}', context);
2473                                         else
2474                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
2475                                 } else
2476                                         handle_ert(os, name + '{' + length + '}', context);
2477                         }
2478                 }
2479
2480                 else {
2481                         //cerr << "#: " << t << " mode: " << mode << endl;
2482                         // heuristic: read up to next non-nested space
2483                         /*
2484                         string s = t.asInput();
2485                         string z = p.verbatim_item();
2486                         while (p.good() && z != " " && z.size()) {
2487                                 //cerr << "read: " << z << endl;
2488                                 s += z;
2489                                 z = p.verbatim_item();
2490                         }
2491                         cerr << "found ERT: " << s << endl;
2492                         handle_ert(os, s + ' ', context);
2493                         */
2494                         string name = t.asInput();
2495                         if (p.next_token().asInput() == "*") {
2496                                 // Starred commands like \vspace*{}
2497                                 p.get_token();                          // Eat '*'
2498                                 name += '*';
2499                         }
2500                         if (! parse_command(name, p, os, outer, context))
2501                                 handle_ert(os, name, context);
2502                 }
2503
2504                 if (flags & FLAG_LEAVE) {
2505                         flags &= ~FLAG_LEAVE;
2506                         break;
2507                 }
2508         }
2509 }
2510
2511 // }])
2512
2513
2514 } // namespace lyx