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