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