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