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