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