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