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