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