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