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