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