]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
Fix bug 3750: this code is a kludge and should be removed when tex2lyx is
[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         // We need to set the height to the LaTeX default of 1\\totalheight
595         // for the case when no height argument is given
596         string height_value = "1";
597         string height_unit = "in";
598         string height_special = "totalheight";
599         string latex_height;
600         if (p.next_token().asInput() == "[") {
601                 position = p.getArg('[', ']');
602                 if (position != "t" && position != "c" && position != "b") {
603                         position = "c";
604                         cerr << "invalid position for minipage/parbox" << endl;
605                 }
606                 if (p.next_token().asInput() == "[") {
607                         latex_height = p.getArg('[', ']');
608                         translate_box_len(latex_height, height_value, height_unit, height_special);
609
610                         if (p.next_token().asInput() == "[") {
611                                 inner_pos = p.getArg('[', ']');
612                                 if (inner_pos != "c" && inner_pos != "t" &&
613                                     inner_pos != "b" && inner_pos != "s") {
614                                         inner_pos = position;
615                                         cerr << "invalid inner_pos for minipage/parbox"
616                                              << endl;
617                                 }
618                         }
619                 }
620         }
621         string width_value;
622         string width_unit;
623         string const latex_width = p.verbatim_item();
624         translate_len(latex_width, width_value, width_unit);
625         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
626                 // LyX can't handle length variables
627                 ostringstream ss;
628                 if (use_parbox)
629                         ss << "\\parbox";
630                 else
631                         ss << "\\begin{minipage}";
632                 if (!position.empty())
633                         ss << '[' << position << ']';
634                 if (!latex_height.empty())
635                         ss << '[' << latex_height << ']';
636                 if (!inner_pos.empty())
637                         ss << '[' << inner_pos << ']';
638                 ss << "{" << latex_width << "}";
639                 if (use_parbox)
640                         ss << '{';
641                 handle_ert(os, ss.str(), parent_context);
642                 parent_context.new_paragraph(os);
643                 parse_text_in_inset(p, os, flags, outer, parent_context);
644                 if (use_parbox)
645                         handle_ert(os, "}", parent_context);
646                 else
647                         handle_ert(os, "\\end{minipage}", parent_context);
648         } else {
649                 // LyX does not like empty positions, so we have
650                 // to set them to the LaTeX default values here.
651                 if (position.empty())
652                         position = "c";
653                 if (inner_pos.empty())
654                         inner_pos = position;
655                 parent_context.check_layout(os);
656                 begin_inset(os, "Box Frameless\n");
657                 os << "position \"" << position << "\"\n";
658                 os << "hor_pos \"c\"\n";
659                 os << "has_inner_box 1\n";
660                 os << "inner_pos \"" << inner_pos << "\"\n";
661                 os << "use_parbox " << use_parbox << "\n";
662                 os << "width \"" << width_value << width_unit << "\"\n";
663                 os << "special \"none\"\n";
664                 os << "height \"" << height_value << height_unit << "\"\n";
665                 os << "height_special \"" << height_special << "\"\n";
666                 os << "status open\n\n";
667                 parse_text_in_inset(p, os, flags, outer, parent_context);
668                 end_inset(os);
669 #ifdef PRESERVE_LAYOUT
670                 // lyx puts a % after the end of the minipage
671                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
672                         // new paragraph
673                         //handle_comment(os, "%dummy", parent_context);
674                         p.get_token();
675                         p.skip_spaces();
676                         parent_context.new_paragraph(os);
677                 }
678                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
679                         //handle_comment(os, "%dummy", parent_context);
680                         p.get_token();
681                         p.skip_spaces();
682                         // We add a protected space if something real follows
683                         if (p.good() && p.next_token().cat() != catComment) {
684                                 os << "\\InsetSpace ~\n";
685                         }
686                 }
687 #endif
688         }
689 }
690
691
692 /// parse an unknown environment
693 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
694                                unsigned flags, bool outer,
695                                Context & parent_context)
696 {
697         if (name == "tabbing")
698                 // We need to remember that we have to handle '\=' specially
699                 flags |= FLAG_TABBING;
700
701         // We need to translate font changes and paragraphs inside the
702         // environment to ERT if we have a non standard font.
703         // Otherwise things like
704         // \large\begin{foo}\huge bar\end{foo}
705         // will not work.
706         bool const specialfont =
707                 (parent_context.font != parent_context.normalfont);
708         bool const new_layout_allowed = parent_context.new_layout_allowed;
709         if (specialfont)
710                 parent_context.new_layout_allowed = false;
711         handle_ert(os, "\\begin{" + name + "}", parent_context);
712         parse_text_snippet(p, os, flags, outer, parent_context);
713         handle_ert(os, "\\end{" + name + "}", parent_context);
714         if (specialfont)
715                 parent_context.new_layout_allowed = new_layout_allowed;
716 }
717
718
719 void parse_environment(Parser & p, ostream & os, bool outer,
720                        Context & parent_context)
721 {
722         Layout_ptr newlayout;
723         string const name = p.getArg('{', '}');
724         const bool is_starred = suffixIs(name, '*');
725         string const unstarred_name = rtrim(name, "*");
726         active_environments.push_back(name);
727
728         if (is_math_env(name)) {
729                 parent_context.check_layout(os);
730                 begin_inset(os, "Formula ");
731                 os << "\\begin{" << name << "}";
732                 parse_math(p, os, FLAG_END, MATH_MODE);
733                 os << "\\end{" << name << "}";
734                 end_inset(os);
735         }
736
737         else if (name == "tabular" || name == "longtable") {
738                 eat_whitespace(p, os, parent_context, false);
739                 parent_context.check_layout(os);
740                 begin_inset(os, "Tabular ");
741                 handle_tabular(p, os, name == "longtable", parent_context);
742                 end_inset(os);
743                 p.skip_spaces();
744         }
745
746         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
747                 eat_whitespace(p, os, parent_context, false);
748                 parent_context.check_layout(os);
749                 begin_inset(os, "Float " + unstarred_name + "\n");
750                 if (p.next_token().asInput() == "[") {
751                         os << "placement " << p.getArg('[', ']') << '\n';
752                 }
753                 os << "wide " << convert<string>(is_starred)
754                    << "\nsideways false"
755                    << "\nstatus open\n\n";
756                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
757                 end_inset(os);
758                 // We don't need really a new paragraph, but
759                 // we must make sure that the next item gets a \begin_layout.
760                 parent_context.new_paragraph(os);
761                 p.skip_spaces();
762         }
763
764         else if (name == "minipage") {
765                 eat_whitespace(p, os, parent_context, false);
766                 parse_box(p, os, FLAG_END, outer, parent_context, false);
767                 p.skip_spaces();
768         }
769
770         else if (name == "comment") {
771                 eat_whitespace(p, os, parent_context, false);
772                 parent_context.check_layout(os);
773                 begin_inset(os, "Note Comment\n");
774                 os << "status open\n";
775                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
776                 end_inset(os);
777                 p.skip_spaces();
778         }
779
780         else if (name == "lyxgreyedout") {
781                 eat_whitespace(p, os, parent_context, false);
782                 parent_context.check_layout(os);
783                 begin_inset(os, "Note Greyedout\n");
784                 os << "status open\n";
785                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
786                 end_inset(os);
787                 p.skip_spaces();
788         }
789
790         else if (!parent_context.new_layout_allowed)
791                 parse_unknown_environment(p, name, os, FLAG_END, outer,
792                                           parent_context);
793
794         // Alignment settings
795         else if (name == "center" || name == "flushleft" || name == "flushright" ||
796                  name == "centering" || name == "raggedright" || name == "raggedleft") {
797                 eat_whitespace(p, os, parent_context, false);
798                 // We must begin a new paragraph if not already done
799                 if (! parent_context.atParagraphStart()) {
800                         parent_context.check_end_layout(os);
801                         parent_context.new_paragraph(os);
802                 }
803                 if (name == "flushleft" || name == "raggedright")
804                         parent_context.add_extra_stuff("\\align left\n");
805                 else if (name == "flushright" || name == "raggedleft")
806                         parent_context.add_extra_stuff("\\align right\n");
807                 else
808                         parent_context.add_extra_stuff("\\align center\n");
809                 parse_text(p, os, FLAG_END, outer, parent_context);
810                 // Just in case the environment is empty ..
811                 parent_context.extra_stuff.erase();
812                 // We must begin a new paragraph to reset the alignment
813                 parent_context.new_paragraph(os);
814                 p.skip_spaces();
815         }
816
817         // The single '=' is meant here.
818         else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
819                   newlayout->isEnvironment()) {
820                 eat_whitespace(p, os, parent_context, false);
821                 Context context(true, parent_context.textclass, newlayout,
822                                 parent_context.layout, parent_context.font);
823                 if (parent_context.deeper_paragraph) {
824                         // We are beginning a nested environment after a
825                         // deeper paragraph inside the outer list environment.
826                         // Therefore we don't need to output a "begin deeper".
827                         context.need_end_deeper = true;
828                 }
829                 parent_context.check_end_layout(os);
830                 switch (context.layout->latextype) {
831                 case  LATEX_LIST_ENVIRONMENT:
832                         context.extra_stuff = "\\labelwidthstring "
833                                 + p.verbatim_item() + '\n';
834                         p.skip_spaces();
835                         break;
836                 case  LATEX_BIB_ENVIRONMENT:
837                         p.verbatim_item(); // swallow next arg
838                         p.skip_spaces();
839                         break;
840                 default:
841                         break;
842                 }
843                 context.check_deeper(os);
844                 parse_text(p, os, FLAG_END, outer, context);
845                 context.check_end_layout(os);
846                 if (parent_context.deeper_paragraph) {
847                         // We must suppress the "end deeper" because we
848                         // suppressed the "begin deeper" above.
849                         context.need_end_deeper = false;
850                 }
851                 context.check_end_deeper(os);
852                 parent_context.new_paragraph(os);
853                 p.skip_spaces();
854         }
855
856         else if (name == "appendix") {
857                 // This is no good latex style, but it works and is used in some documents...
858                 eat_whitespace(p, os, parent_context, false);
859                 parent_context.check_end_layout(os);
860                 Context context(true, parent_context.textclass, parent_context.layout,
861                                 parent_context.layout, parent_context.font);
862                 context.check_layout(os);
863                 os << "\\start_of_appendix\n";
864                 parse_text(p, os, FLAG_END, outer, context);
865                 context.check_end_layout(os);
866                 p.skip_spaces();
867         }
868
869         else if (known_environments.find(name) != known_environments.end()) {
870                 vector<ArgumentType> arguments = known_environments[name];
871                 // The last "argument" denotes wether we may translate the
872                 // environment contents to LyX
873                 // The default required if no argument is given makes us
874                 // compatible with the reLyXre environment.
875                 ArgumentType contents = arguments.empty() ?
876                         required :
877                         arguments.back();
878                 if (!arguments.empty())
879                         arguments.pop_back();
880                 // See comment in parse_unknown_environment()
881                 bool const specialfont =
882                         (parent_context.font != parent_context.normalfont);
883                 bool const new_layout_allowed =
884                         parent_context.new_layout_allowed;
885                 if (specialfont)
886                         parent_context.new_layout_allowed = false;
887                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
888                                 outer, parent_context);
889                 if (contents == verbatim)
890                         handle_ert(os, p.verbatimEnvironment(name),
891                                    parent_context);
892                 else
893                         parse_text_snippet(p, os, FLAG_END, outer,
894                                            parent_context);
895                 handle_ert(os, "\\end{" + name + "}", parent_context);
896                 if (specialfont)
897                         parent_context.new_layout_allowed = new_layout_allowed;
898         }
899
900         else
901                 parse_unknown_environment(p, name, os, FLAG_END, outer,
902                                           parent_context);
903
904         active_environments.pop_back();
905 }
906
907
908 /// parses a comment and outputs it to \p os.
909 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
910 {
911         BOOST_ASSERT(t.cat() == catComment);
912         if (!t.cs().empty()) {
913                 context.check_layout(os);
914                 handle_comment(os, '%' + t.cs(), context);
915                 if (p.next_token().cat() == catNewline) {
916                         // A newline after a comment line starts a new
917                         // paragraph
918                         if (context.new_layout_allowed) {
919                                 if(!context.atParagraphStart())
920                                         // Only start a new paragraph if not already
921                                         // done (we might get called recursively)
922                                         context.new_paragraph(os);
923                         } else
924                                 handle_ert(os, "\n", context);
925                         eat_whitespace(p, os, context, true);
926                 }
927         } else {
928                 // "%\n" combination
929                 p.skip_spaces();
930         }
931 }
932
933
934 /*!
935  * Reads spaces and comments until the first non-space, non-comment token.
936  * New paragraphs (double newlines or \\par) are handled like simple spaces
937  * if \p eatParagraph is true.
938  * Spaces are skipped, but comments are written to \p os.
939  */
940 void eat_whitespace(Parser & p, ostream & os, Context & context,
941                     bool eatParagraph)
942 {
943         while (p.good()) {
944                 Token const & t = p.get_token();
945                 if (t.cat() == catComment)
946                         parse_comment(p, os, t, context);
947                 else if ((! eatParagraph && p.isParagraph()) ||
948                          (t.cat() != catSpace && t.cat() != catNewline)) {
949                         p.putback();
950                         return;
951                 }
952         }
953 }
954
955
956 /*!
957  * Set a font attribute, parse text and reset the font attribute.
958  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
959  * \param currentvalue Current value of the attribute. Is set to the new
960  * value during parsing.
961  * \param newvalue New value of the attribute
962  */
963 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
964                            Context & context, string const & attribute,
965                            string & currentvalue, string const & newvalue)
966 {
967         context.check_layout(os);
968         string const oldvalue = currentvalue;
969         currentvalue = newvalue;
970         os << '\n' << attribute << ' ' << newvalue << "\n";
971         parse_text_snippet(p, os, flags, outer, context);
972         context.check_layout(os);
973         os << '\n' << attribute << ' ' << oldvalue << "\n";
974         currentvalue = oldvalue;
975 }
976
977
978 /// get the arguments of a natbib or jurabib citation command
979 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
980 {
981         // We need to distinguish "" and "[]", so we can't use p.getOpt().
982
983         // text before the citation
984         string before;
985         // text after the citation
986         string after = p.getFullOpt();
987
988         if (!after.empty()) {
989                 before = p.getFullOpt();
990                 if (natbibOrder && !before.empty())
991                         std::swap(before, after);
992         }
993         return std::make_pair(before, after);
994 }
995
996
997 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
998 string const normalize_filename(string const & name)
999 {
1000         Parser p(trim(name, "\""));
1001         ostringstream os;
1002         while (p.good()) {
1003                 Token const & t = p.get_token();
1004                 if (t.cat() != catEscape)
1005                         os << t.asInput();
1006                 else if (t.cs() == "lyxdot") {
1007                         // This is used by LyX for simple dots in relative
1008                         // names
1009                         os << '.';
1010                         p.skip_spaces();
1011                 } else if (t.cs() == "space") {
1012                         os << ' ';
1013                         p.skip_spaces();
1014                 } else
1015                         os << t.asInput();
1016         }
1017         return os.str();
1018 }
1019
1020
1021 /// Convert \p name from TeX convention (relative to master file) to LyX
1022 /// convention (relative to .lyx file) if it is relative
1023 void fix_relative_filename(string & name)
1024 {
1025         if (lyx::support::absolutePath(name))
1026                 return;
1027         // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1028         // utf8)
1029         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1030                                    from_utf8(getParentFilePath())));
1031 }
1032
1033
1034 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1035 void parse_noweb(Parser & p, ostream & os, Context & context)
1036 {
1037         // assemble the rest of the keyword
1038         string name("<<");
1039         bool scrap = false;
1040         while (p.good()) {
1041                 Token const & t = p.get_token();
1042                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1043                         name += ">>";
1044                         p.get_token();
1045                         scrap = (p.good() && p.next_token().asInput() == "=");
1046                         if (scrap)
1047                                 name += p.get_token().asInput();
1048                         break;
1049                 }
1050                 name += t.asInput();
1051         }
1052
1053         if (!scrap || !context.new_layout_allowed ||
1054             !context.textclass.hasLayout("Scrap")) {
1055                 cerr << "Warning: Could not interpret '" << name
1056                      << "'. Ignoring it." << endl;
1057                 return;
1058         }
1059
1060         // We use new_paragraph instead of check_end_layout because the stuff
1061         // following the noweb chunk needs to start with a \begin_layout.
1062         // This may create a new paragraph even if there was none in the
1063         // noweb file, but the alternative is an invalid LyX file. Since
1064         // noweb code chunks are implemented with a layout style in LyX they
1065         // always must be in an own paragraph.
1066         context.new_paragraph(os);
1067         Context newcontext(true, context.textclass, context.textclass["Scrap"]);
1068         newcontext.check_layout(os);
1069         os << name;
1070         while (p.good()) {
1071                 Token const & t = p.get_token();
1072                 // We abuse the parser a bit, because this is no TeX syntax
1073                 // at all.
1074                 if (t.cat() == catEscape)
1075                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1076                 else
1077                         os << subst(t.asInput(), "\n", "\n\\newline\n");
1078                 // The scrap chunk is ended by an @ at the beginning of a line.
1079                 // After the @ the line may contain a comment and/or
1080                 // whitespace, but nothing else.
1081                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1082                     (p.next_token().cat() == catSpace ||
1083                      p.next_token().cat() == catNewline ||
1084                      p.next_token().cat() == catComment)) {
1085                         while (p.good() && p.next_token().cat() == catSpace)
1086                                 os << p.get_token().asInput();
1087                         if (p.next_token().cat() == catComment)
1088                                 // The comment includes a final '\n'
1089                                 os << p.get_token().asInput();
1090                         else {
1091                                 if (p.next_token().cat() == catNewline)
1092                                         p.get_token();
1093                                 os << '\n';
1094                         }
1095                         break;
1096                 }
1097         }
1098         newcontext.check_end_layout(os);
1099 }
1100
1101 } // anonymous namespace
1102
1103
1104 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1105                 Context & context)
1106 {
1107         Layout_ptr newlayout;
1108         // Store the latest bibliographystyle (needed for bibtex inset)
1109         string bibliographystyle;
1110         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1111         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1112         while (p.good()) {
1113                 Token const & t = p.get_token();
1114
1115 #ifdef FILEDEBUG
1116                 cerr << "t: " << t << " flags: " << flags << "\n";
1117 #endif
1118
1119                 if (flags & FLAG_ITEM) {
1120                         if (t.cat() == catSpace)
1121                                 continue;
1122
1123                         flags &= ~FLAG_ITEM;
1124                         if (t.cat() == catBegin) {
1125                                 // skip the brace and collect everything to the next matching
1126                                 // closing brace
1127                                 flags |= FLAG_BRACE_LAST;
1128                                 continue;
1129                         }
1130
1131                         // handle only this single token, leave the loop if done
1132                         flags |= FLAG_LEAVE;
1133                 }
1134
1135                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1136                         return;
1137
1138                 //
1139                 // cat codes
1140                 //
1141                 if (t.cat() == catMath) {
1142                         // we are inside some text mode thingy, so opening new math is allowed
1143                         context.check_layout(os);
1144                         begin_inset(os, "Formula ");
1145                         Token const & n = p.get_token();
1146                         if (n.cat() == catMath && outer) {
1147                                 // TeX's $$...$$ syntax for displayed math
1148                                 os << "\\[";
1149                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1150                                 os << "\\]";
1151                                 p.get_token(); // skip the second '$' token
1152                         } else {
1153                                 // simple $...$  stuff
1154                                 p.putback();
1155                                 os << '$';
1156                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1157                                 os << '$';
1158                         }
1159                         end_inset(os);
1160                 }
1161
1162                 else if (t.cat() == catSuper || t.cat() == catSub)
1163                         cerr << "catcode " << t << " illegal in text mode\n";
1164
1165                 // Basic support for english quotes. This should be
1166                 // extended to other quotes, but is not so easy (a
1167                 // left english quote is the same as a right german
1168                 // quote...)
1169                 else if (t.asInput() == "`"
1170                          && p.next_token().asInput() == "`") {
1171                         context.check_layout(os);
1172                         begin_inset(os, "Quotes ");
1173                         os << "eld";
1174                         end_inset(os);
1175                         p.get_token();
1176                         skip_braces(p);
1177                 }
1178                 else if (t.asInput() == "'"
1179                          && p.next_token().asInput() == "'") {
1180                         context.check_layout(os);
1181                         begin_inset(os, "Quotes ");
1182                         os << "erd";
1183                         end_inset(os);
1184                         p.get_token();
1185                         skip_braces(p);
1186                 }
1187
1188                 else if (t.asInput() == "<"
1189                          && p.next_token().asInput() == "<" && noweb_mode) {
1190                         p.get_token();
1191                         parse_noweb(p, os, context);
1192                 }
1193
1194                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1195                         check_space(p, os, context);
1196
1197                 else if (t.character() == '[' && noweb_mode &&
1198                          p.next_token().character() == '[') {
1199                         // These can contain underscores
1200                         p.putback();
1201                         string const s = p.getFullOpt() + ']';
1202                         if (p.next_token().character() == ']')
1203                                 p.get_token();
1204                         else
1205                                 cerr << "Warning: Inserting missing ']' in '"
1206                                      << s << "'." << endl;
1207                         handle_ert(os, s, context);
1208                 }
1209
1210                 else if (t.cat() == catLetter ||
1211                                t.cat() == catOther ||
1212                                t.cat() == catAlign ||
1213                                t.cat() == catParameter) {
1214                         // This translates "&" to "\\&" which may be wrong...
1215                         context.check_layout(os);
1216                         os << t.character();
1217                 }
1218
1219                 else if (p.isParagraph()) {
1220                         if (context.new_layout_allowed)
1221                                 context.new_paragraph(os);
1222                         else
1223                                 handle_ert(os, "\\par ", context);
1224                         eat_whitespace(p, os, context, true);
1225                 }
1226
1227                 else if (t.cat() == catActive) {
1228                         context.check_layout(os);
1229                         if (t.character() == '~') {
1230                                 if (context.layout->free_spacing)
1231                                         os << ' ';
1232                                 else
1233                                         os << "\\InsetSpace ~\n";
1234                         } else
1235                                 os << t.character();
1236                 }
1237
1238                 else if (t.cat() == catBegin &&
1239                          p.next_token().cat() == catEnd) {
1240                         // {}
1241                         Token const prev = p.prev_token();
1242                         p.get_token();
1243                         if (p.next_token().character() == '`' ||
1244                             (prev.character() == '-' &&
1245                              p.next_token().character() == '-'))
1246                                 ; // ignore it in {}`` or -{}-
1247                         else
1248                                 handle_ert(os, "{}", context);
1249
1250                 }
1251
1252                 else if (t.cat() == catBegin) {
1253                         context.check_layout(os);
1254                         // special handling of font attribute changes
1255                         Token const prev = p.prev_token();
1256                         Token const next = p.next_token();
1257                         TeXFont const oldFont = context.font;
1258                         if (next.character() == '[' ||
1259                             next.character() == ']' ||
1260                             next.character() == '*') {
1261                                 p.get_token();
1262                                 if (p.next_token().cat() == catEnd) {
1263                                         os << next.character();
1264                                         p.get_token();
1265                                 } else {
1266                                         p.putback();
1267                                         handle_ert(os, "{", context);
1268                                         parse_text_snippet(p, os,
1269                                                         FLAG_BRACE_LAST,
1270                                                         outer, context);
1271                                         handle_ert(os, "}", context);
1272                                 }
1273                         } else if (! context.new_layout_allowed) {
1274                                 handle_ert(os, "{", context);
1275                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1276                                                    outer, context);
1277                                 handle_ert(os, "}", context);
1278                         } else if (is_known(next.cs(), known_sizes)) {
1279                                 // next will change the size, so we must
1280                                 // reset it here
1281                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1282                                                    outer, context);
1283                                 if (!context.atParagraphStart())
1284                                         os << "\n\\size "
1285                                            << context.font.size << "\n";
1286                         } else if (is_known(next.cs(), known_font_families)) {
1287                                 // next will change the font family, so we
1288                                 // must reset it here
1289                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1290                                                    outer, context);
1291                                 if (!context.atParagraphStart())
1292                                         os << "\n\\family "
1293                                            << context.font.family << "\n";
1294                         } else if (is_known(next.cs(), known_font_series)) {
1295                                 // next will change the font series, so we
1296                                 // must reset it here
1297                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1298                                                    outer, context);
1299                                 if (!context.atParagraphStart())
1300                                         os << "\n\\series "
1301                                            << context.font.series << "\n";
1302                         } else if (is_known(next.cs(), known_font_shapes)) {
1303                                 // next will change the font shape, so we
1304                                 // must reset it here
1305                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1306                                                    outer, context);
1307                                 if (!context.atParagraphStart())
1308                                         os << "\n\\shape "
1309                                            << context.font.shape << "\n";
1310                         } else if (is_known(next.cs(), known_old_font_families) ||
1311                                    is_known(next.cs(), known_old_font_series) ||
1312                                    is_known(next.cs(), known_old_font_shapes)) {
1313                                 // next will change the font family, series
1314                                 // and shape, so we must reset it here
1315                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1316                                                    outer, context);
1317                                 if (!context.atParagraphStart())
1318                                         os <<  "\n\\family "
1319                                            << context.font.family
1320                                            << "\n\\series "
1321                                            << context.font.series
1322                                            << "\n\\shape "
1323                                            << context.font.shape << "\n";
1324                         } else {
1325                                 handle_ert(os, "{", context);
1326                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1327                                                    outer, context);
1328                                 handle_ert(os, "}", context);
1329                         }
1330                 }
1331
1332                 else if (t.cat() == catEnd) {
1333                         if (flags & FLAG_BRACE_LAST) {
1334                                 return;
1335                         }
1336                         cerr << "stray '}' in text\n";
1337                         handle_ert(os, "}", context);
1338                 }
1339
1340                 else if (t.cat() == catComment)
1341                         parse_comment(p, os, t, context);
1342
1343                 //
1344                 // control sequences
1345                 //
1346
1347                 else if (t.cs() == "(") {
1348                         context.check_layout(os);
1349                         begin_inset(os, "Formula");
1350                         os << " \\(";
1351                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1352                         os << "\\)";
1353                         end_inset(os);
1354                 }
1355
1356                 else if (t.cs() == "[") {
1357                         context.check_layout(os);
1358                         begin_inset(os, "Formula");
1359                         os << " \\[";
1360                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1361                         os << "\\]";
1362                         end_inset(os);
1363                 }
1364
1365                 else if (t.cs() == "begin")
1366                         parse_environment(p, os, outer, context);
1367
1368                 else if (t.cs() == "end") {
1369                         if (flags & FLAG_END) {
1370                                 // eat environment name
1371                                 string const name = p.getArg('{', '}');
1372                                 if (name != active_environment())
1373                                         cerr << "\\end{" + name + "} does not match \\begin{"
1374                                                 + active_environment() + "}\n";
1375                                 return;
1376                         }
1377                         p.error("found 'end' unexpectedly");
1378                 }
1379
1380                 else if (t.cs() == "item") {
1381                         p.skip_spaces();
1382                         string s;
1383                         bool optarg = false;
1384                         if (p.next_token().character() == '[') {
1385                                 p.get_token(); // eat '['
1386                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1387                                                        outer, context);
1388                                 optarg = true;
1389                         }
1390                         context.set_item();
1391                         context.check_layout(os);
1392                         if (context.has_item) {
1393                                 // An item in an unknown list-like environment
1394                                 // FIXME: Do this in check_layout()!
1395                                 context.has_item = false;
1396                                 if (optarg)
1397                                         handle_ert(os, "\\item", context);
1398                                 else
1399                                         handle_ert(os, "\\item ", context);
1400                         }
1401                         if (optarg) {
1402                                 if (context.layout->labeltype != LABEL_MANUAL) {
1403                                         // lyx does not support \item[\mybullet]
1404                                         // in itemize environments
1405                                         handle_ert(os, "[", context);
1406                                         os << s;
1407                                         handle_ert(os, "]", context);
1408                                 } else if (!s.empty()) {
1409                                         // The space is needed to separate the
1410                                         // item from the rest of the sentence.
1411                                         os << s << ' ';
1412                                         eat_whitespace(p, os, context, false);
1413                                 }
1414                         }
1415                 }
1416
1417                 else if (t.cs() == "bibitem") {
1418                         context.set_item();
1419                         context.check_layout(os);
1420                         os << "\\bibitem ";
1421                         os << p.getOpt();
1422                         os << '{' << p.verbatim_item() << '}' << "\n";
1423                 }
1424
1425                 else if (t.cs() == "def") {
1426                         context.check_layout(os);
1427                         eat_whitespace(p, os, context, false);
1428                         string name = p.get_token().cs();
1429                         eat_whitespace(p, os, context, false);
1430
1431                         // parameter text
1432                         bool simple = true;
1433                         string paramtext;
1434                         int arity = 0;
1435                         while (p.next_token().cat() != catBegin) {
1436                                 if (p.next_token().cat() == catParameter) {
1437                                         // # found
1438                                         p.get_token();
1439                                         paramtext += "#";
1440
1441                                         // followed by number?
1442                                         if (p.next_token().cat() == catOther) {
1443                                                 char c = p.getChar();
1444                                                 paramtext += c;
1445                                                 // number = current arity + 1?
1446                                                 if (c == arity + '0' + 1)
1447                                                         ++arity;
1448                                                 else
1449                                                         simple = false;
1450                                         } else
1451                                                 paramtext += p.get_token().asString();
1452                                 } else {
1453                                         paramtext += p.get_token().asString();
1454                                         simple = false;
1455                                 }
1456                         }
1457
1458                         // only output simple (i.e. compatible) macro as FormulaMacros
1459                         string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1460                         if (simple) {
1461                                 context.check_layout(os);
1462                                 begin_inset(os, "FormulaMacro");
1463                                 os << "\n" << ert;
1464                                 end_inset(os);
1465                         } else
1466                                 handle_ert(os, ert, context);
1467                 }
1468
1469                 else if (t.cs() == "noindent") {
1470                         p.skip_spaces();
1471                         context.add_extra_stuff("\\noindent\n");
1472                 }
1473
1474                 else if (t.cs() == "appendix") {
1475                         context.add_extra_stuff("\\start_of_appendix\n");
1476                         // We need to start a new paragraph. Otherwise the
1477                         // appendix in 'bla\appendix\chapter{' would start
1478                         // too late.
1479                         context.new_paragraph(os);
1480                         // We need to make sure that the paragraph is
1481                         // generated even if it is empty. Otherwise the
1482                         // appendix in '\par\appendix\par\chapter{' would
1483                         // start too late.
1484                         context.check_layout(os);
1485                         // FIXME: This is a hack to prevent paragraph
1486                         // deletion if it is empty. Handle this better!
1487                         handle_comment(os,
1488                                 "%dummy comment inserted by tex2lyx to "
1489                                 "ensure that this paragraph is not empty",
1490                                 context);
1491                         // Both measures above may generate an additional
1492                         // empty paragraph, but that does not hurt, because
1493                         // whitespace does not matter here.
1494                         eat_whitespace(p, os, context, true);
1495                 }
1496
1497                 // Must attempt to parse "Section*" before "Section".
1498                 else if ((p.next_token().asInput() == "*") &&
1499                          context.new_layout_allowed &&
1500                          // The single '=' is meant here.
1501                          (newlayout = findLayout(context.textclass,
1502                                                  t.cs() + '*')).get() &&
1503                          newlayout->isCommand()) {
1504                         p.get_token();
1505                         output_command_layout(os, p, outer, context, newlayout);
1506                         p.skip_spaces();
1507                 }
1508
1509                 // The single '=' is meant here.
1510                 else if (context.new_layout_allowed &&
1511                          (newlayout = findLayout(context.textclass, t.cs())).get() &&
1512                          newlayout->isCommand()) {
1513                         output_command_layout(os, p, outer, context, newlayout);
1514                         p.skip_spaces();
1515                 }
1516
1517                 // Special handling for \caption
1518                 // FIXME: remove this when InsetCaption is supported.
1519                 else if (context.new_layout_allowed &&
1520                          t.cs() == captionlayout->latexname()) {
1521                         output_command_layout(os, p, outer, context, 
1522                                               captionlayout);
1523                         p.skip_spaces();
1524                 }
1525
1526                 else if (t.cs() == "includegraphics") {
1527                         bool const clip = p.next_token().asInput() == "*";
1528                         if (clip)
1529                                 p.get_token();
1530                         map<string, string> opts = split_map(p.getArg('[', ']'));
1531                         if (clip)
1532                                 opts["clip"] = string();
1533                         string name = normalize_filename(p.verbatim_item());
1534
1535                         string const path = getMasterFilePath();
1536                         // We want to preserve relative / absolute filenames,
1537                         // therefore path is only used for testing
1538                         // FIXME UNICODE encoding of name and path may be
1539                         // wrong (makeAbsPath expects utf8)
1540                         if (!fs::exists(makeAbsPath(name, path).toFilesystemEncoding())) {
1541                                 // The file extension is probably missing.
1542                                 // Now try to find it out.
1543                                 string const dvips_name =
1544                                         find_file(name, path,
1545                                                   known_dvips_graphics_formats);
1546                                 string const pdftex_name =
1547                                         find_file(name, path,
1548                                                   known_pdftex_graphics_formats);
1549                                 if (!dvips_name.empty()) {
1550                                         if (!pdftex_name.empty()) {
1551                                                 cerr << "This file contains the "
1552                                                         "latex snippet\n"
1553                                                         "\"\\includegraphics{"
1554                                                      << name << "}\".\n"
1555                                                         "However, files\n\""
1556                                                      << dvips_name << "\" and\n\""
1557                                                      << pdftex_name << "\"\n"
1558                                                         "both exist, so I had to make a "
1559                                                         "choice and took the first one.\n"
1560                                                         "Please move the unwanted one "
1561                                                         "someplace else and try again\n"
1562                                                         "if my choice was wrong."
1563                                                      << endl;
1564                                         }
1565                                         name = dvips_name;
1566                                 } else if (!pdftex_name.empty())
1567                                         name = pdftex_name;
1568                         }
1569
1570                         // FIXME UNICODE encoding of name and path may be
1571                         // wrong (makeAbsPath expects utf8)
1572                         if (fs::exists(makeAbsPath(name, path).toFilesystemEncoding()))
1573                                 fix_relative_filename(name);
1574                         else
1575                                 cerr << "Warning: Could not find graphics file '"
1576                                      << name << "'." << endl;
1577
1578                         context.check_layout(os);
1579                         begin_inset(os, "Graphics ");
1580                         os << "\n\tfilename " << name << '\n';
1581                         if (opts.find("width") != opts.end())
1582                                 os << "\twidth "
1583                                    << translate_len(opts["width"]) << '\n';
1584                         if (opts.find("height") != opts.end())
1585                                 os << "\theight "
1586                                    << translate_len(opts["height"]) << '\n';
1587                         if (opts.find("scale") != opts.end()) {
1588                                 istringstream iss(opts["scale"]);
1589                                 double val;
1590                                 iss >> val;
1591                                 val = val*100;
1592                                 os << "\tscale " << val << '\n';
1593                         }
1594                         if (opts.find("angle") != opts.end())
1595                                 os << "\trotateAngle "
1596                                    << opts["angle"] << '\n';
1597                         if (opts.find("origin") != opts.end()) {
1598                                 ostringstream ss;
1599                                 string const opt = opts["origin"];
1600                                 if (opt.find('l') != string::npos) ss << "left";
1601                                 if (opt.find('r') != string::npos) ss << "right";
1602                                 if (opt.find('c') != string::npos) ss << "center";
1603                                 if (opt.find('t') != string::npos) ss << "Top";
1604                                 if (opt.find('b') != string::npos) ss << "Bottom";
1605                                 if (opt.find('B') != string::npos) ss << "Baseline";
1606                                 if (!ss.str().empty())
1607                                         os << "\trotateOrigin " << ss.str() << '\n';
1608                                 else
1609                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1610                         }
1611                         if (opts.find("keepaspectratio") != opts.end())
1612                                 os << "\tkeepAspectRatio\n";
1613                         if (opts.find("clip") != opts.end())
1614                                 os << "\tclip\n";
1615                         if (opts.find("draft") != opts.end())
1616                                 os << "\tdraft\n";
1617                         if (opts.find("bb") != opts.end())
1618                                 os << "\tBoundingBox "
1619                                    << opts["bb"] << '\n';
1620                         int numberOfbbOptions = 0;
1621                         if (opts.find("bbllx") != opts.end())
1622                                 numberOfbbOptions++;
1623                         if (opts.find("bblly") != opts.end())
1624                                 numberOfbbOptions++;
1625                         if (opts.find("bburx") != opts.end())
1626                                 numberOfbbOptions++;
1627                         if (opts.find("bbury") != opts.end())
1628                                 numberOfbbOptions++;
1629                         if (numberOfbbOptions == 4)
1630                                 os << "\tBoundingBox "
1631                                    << opts["bbllx"] << opts["bblly"]
1632                                    << opts["bburx"] << opts["bbury"] << '\n';
1633                         else if (numberOfbbOptions > 0)
1634                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1635                         numberOfbbOptions = 0;
1636                         if (opts.find("natwidth") != opts.end())
1637                                 numberOfbbOptions++;
1638                         if (opts.find("natheight") != opts.end())
1639                                 numberOfbbOptions++;
1640                         if (numberOfbbOptions == 2)
1641                                 os << "\tBoundingBox 0bp 0bp "
1642                                    << opts["natwidth"] << opts["natheight"] << '\n';
1643                         else if (numberOfbbOptions > 0)
1644                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1645                         ostringstream special;
1646                         if (opts.find("hiresbb") != opts.end())
1647                                 special << "hiresbb,";
1648                         if (opts.find("trim") != opts.end())
1649                                 special << "trim,";
1650                         if (opts.find("viewport") != opts.end())
1651                                 special << "viewport=" << opts["viewport"] << ',';
1652                         if (opts.find("totalheight") != opts.end())
1653                                 special << "totalheight=" << opts["totalheight"] << ',';
1654                         if (opts.find("type") != opts.end())
1655                                 special << "type=" << opts["type"] << ',';
1656                         if (opts.find("ext") != opts.end())
1657                                 special << "ext=" << opts["ext"] << ',';
1658                         if (opts.find("read") != opts.end())
1659                                 special << "read=" << opts["read"] << ',';
1660                         if (opts.find("command") != opts.end())
1661                                 special << "command=" << opts["command"] << ',';
1662                         string s_special = special.str();
1663                         if (!s_special.empty()) {
1664                                 // We had special arguments. Remove the trailing ','.
1665                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1666                         }
1667                         // TODO: Handle the unknown settings better.
1668                         // Warn about invalid options.
1669                         // Check whether some option was given twice.
1670                         end_inset(os);
1671                 }
1672
1673                 else if (t.cs() == "footnote" ||
1674                          (t.cs() == "thanks" && context.layout->intitle)) {
1675                         p.skip_spaces();
1676                         context.check_layout(os);
1677                         begin_inset(os, "Foot\n");
1678                         os << "status collapsed\n\n";
1679                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1680                         end_inset(os);
1681                 }
1682
1683                 else if (t.cs() == "marginpar") {
1684                         p.skip_spaces();
1685                         context.check_layout(os);
1686                         begin_inset(os, "Marginal\n");
1687                         os << "status collapsed\n\n";
1688                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1689                         end_inset(os);
1690                 }
1691
1692                 else if (t.cs() == "ensuremath") {
1693                         p.skip_spaces();
1694                         context.check_layout(os);
1695                         string const s = p.verbatim_item();
1696                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1697                                 os << s;
1698                         else
1699                                 handle_ert(os, "\\ensuremath{" + s + "}",
1700                                            context);
1701                 }
1702
1703                 else if (t.cs() == "hfill") {
1704                         context.check_layout(os);
1705                         os << "\n\\hfill\n";
1706                         skip_braces(p);
1707                         p.skip_spaces();
1708                 }
1709
1710                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1711                         // FIXME: Somehow prevent title layouts if
1712                         // "maketitle" was not found
1713                         p.skip_spaces();
1714                         skip_braces(p); // swallow this
1715                 }
1716
1717                 else if (t.cs() == "tableofcontents") {
1718                         p.skip_spaces();
1719                         context.check_layout(os);
1720                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1721                         end_inset(os);
1722                         skip_braces(p); // swallow this
1723                 }
1724
1725                 else if (t.cs() == "listoffigures") {
1726                         p.skip_spaces();
1727                         context.check_layout(os);
1728                         begin_inset(os, "FloatList figure\n");
1729                         end_inset(os);
1730                         skip_braces(p); // swallow this
1731                 }
1732
1733                 else if (t.cs() == "listoftables") {
1734                         p.skip_spaces();
1735                         context.check_layout(os);
1736                         begin_inset(os, "FloatList table\n");
1737                         end_inset(os);
1738                         skip_braces(p); // swallow this
1739                 }
1740
1741                 else if (t.cs() == "listof") {
1742                         p.skip_spaces(true);
1743                         string const name = p.get_token().asString();
1744                         if (context.textclass.floats().typeExist(name)) {
1745                                 context.check_layout(os);
1746                                 begin_inset(os, "FloatList ");
1747                                 os << name << "\n";
1748                                 end_inset(os);
1749                                 p.get_token(); // swallow second arg
1750                         } else
1751                                 handle_ert(os, "\\listof{" + name + "}", context);
1752                 }
1753
1754                 else if (t.cs() == "textrm")
1755                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1756                                               context, "\\family",
1757                                               context.font.family, "roman");
1758
1759                 else if (t.cs() == "textsf")
1760                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1761                                               context, "\\family",
1762                                               context.font.family, "sans");
1763
1764                 else if (t.cs() == "texttt")
1765                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1766                                               context, "\\family",
1767                                               context.font.family, "typewriter");
1768
1769                 else if (t.cs() == "textmd")
1770                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1771                                               context, "\\series",
1772                                               context.font.series, "medium");
1773
1774                 else if (t.cs() == "textbf")
1775                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1776                                               context, "\\series",
1777                                               context.font.series, "bold");
1778
1779                 else if (t.cs() == "textup")
1780                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1781                                               context, "\\shape",
1782                                               context.font.shape, "up");
1783
1784                 else if (t.cs() == "textit")
1785                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1786                                               context, "\\shape",
1787                                               context.font.shape, "italic");
1788
1789                 else if (t.cs() == "textsl")
1790                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1791                                               context, "\\shape",
1792                                               context.font.shape, "slanted");
1793
1794                 else if (t.cs() == "textsc")
1795                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1796                                               context, "\\shape",
1797                                               context.font.shape, "smallcaps");
1798
1799                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1800                         context.check_layout(os);
1801                         TeXFont oldFont = context.font;
1802                         context.font.init();
1803                         context.font.size = oldFont.size;
1804                         os << "\n\\family " << context.font.family << "\n";
1805                         os << "\n\\series " << context.font.series << "\n";
1806                         os << "\n\\shape " << context.font.shape << "\n";
1807                         if (t.cs() == "textnormal") {
1808                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1809                                 output_font_change(os, context.font, oldFont);
1810                                 context.font = oldFont;
1811                         } else
1812                                 eat_whitespace(p, os, context, false);
1813                 }
1814
1815                 else if (t.cs() == "underbar") {
1816                         // Do NOT handle \underline.
1817                         // \underbar cuts through y, g, q, p etc.,
1818                         // \underline does not.
1819                         context.check_layout(os);
1820                         os << "\n\\bar under\n";
1821                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1822                         context.check_layout(os);
1823                         os << "\n\\bar default\n";
1824                 }
1825
1826                 else if (t.cs() == "emph" || t.cs() == "noun") {
1827                         context.check_layout(os);
1828                         os << "\n\\" << t.cs() << " on\n";
1829                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1830                         context.check_layout(os);
1831                         os << "\n\\" << t.cs() << " default\n";
1832                 }
1833
1834                 else if (use_natbib &&
1835                          is_known(t.cs(), known_natbib_commands) &&
1836                          ((t.cs() != "citefullauthor" &&
1837                            t.cs() != "citeyear" &&
1838                            t.cs() != "citeyearpar") ||
1839                           p.next_token().asInput() != "*")) {
1840                         context.check_layout(os);
1841                         // tex                       lyx
1842                         // \citet[before][after]{a}  \citet[after][before]{a}
1843                         // \citet[before][]{a}       \citet[][before]{a}
1844                         // \citet[after]{a}          \citet[after]{a}
1845                         // \citet{a}                 \citet{a}
1846                         string command = '\\' + t.cs();
1847                         if (p.next_token().asInput() == "*") {
1848                                 command += '*';
1849                                 p.get_token();
1850                         }
1851                         if (command == "\\citefullauthor")
1852                                 // alternative name for "\\citeauthor*"
1853                                 command = "\\citeauthor*";
1854
1855                         // text before the citation
1856                         string before;
1857                         // text after the citation
1858                         string after;
1859
1860                         boost::tie(before, after) = getCiteArguments(p, true);
1861                         if (command == "\\cite") {
1862                                 // \cite without optional argument means
1863                                 // \citet, \cite with at least one optional
1864                                 // argument means \citep.
1865                                 if (before.empty() && after.empty())
1866                                         command = "\\citet";
1867                                 else
1868                                         command = "\\citep";
1869                         }
1870                         if (before.empty() && after == "[]")
1871                                 // avoid \citet[]{a}
1872                                 after.erase();
1873                         else if (before == "[]" && after == "[]") {
1874                                 // avoid \citet[][]{a}
1875                                 before.erase();
1876                                 after.erase();
1877                         }
1878                         begin_inset(os, "LatexCommand ");
1879                         os << command << after << before
1880                            << '{' << p.verbatim_item() << "}\n";
1881                         end_inset(os);
1882                 }
1883
1884                 else if (use_jurabib &&
1885                          is_known(t.cs(), known_jurabib_commands)) {
1886                         context.check_layout(os);
1887                         string const command = '\\' + t.cs();
1888                         char argumentOrder = '\0';
1889                         vector<string> const & options = used_packages["jurabib"];
1890                         if (std::find(options.begin(), options.end(),
1891                                       "natbiborder") != options.end())
1892                                 argumentOrder = 'n';
1893                         else if (std::find(options.begin(), options.end(),
1894                                            "jurabiborder") != options.end())
1895                                 argumentOrder = 'j';
1896
1897                         // text before the citation
1898                         string before;
1899                         // text after the citation
1900                         string after;
1901
1902                         boost::tie(before, after) =
1903                                 getCiteArguments(p, argumentOrder != 'j');
1904                         string const citation = p.verbatim_item();
1905                         if (!before.empty() && argumentOrder == '\0') {
1906                                 cerr << "Warning: Assuming argument order "
1907                                         "of jurabib version 0.6 for\n'"
1908                                      << command << before << after << '{'
1909                                      << citation << "}'.\n"
1910                                         "Add 'jurabiborder' to the jurabib "
1911                                         "package options if you used an\n"
1912                                         "earlier jurabib version." << endl;
1913                         }
1914                         begin_inset(os, "LatexCommand ");
1915                         os << command << after << before
1916                            << '{' << citation << "}\n";
1917                         end_inset(os);
1918                 }
1919
1920                 else if (is_known(t.cs(), known_latex_commands)) {
1921                         // This needs to be after the check for natbib and
1922                         // jurabib commands, because "cite" has different
1923                         // arguments with natbib and jurabib.
1924                         context.check_layout(os);
1925                         begin_inset(os, "LatexCommand ");
1926                         os << '\\' << t.cs();
1927                         // lyx cannot handle newlines in a latex command
1928                         // FIXME: Move the substitution into parser::getOpt()?
1929                         os << subst(p.getOpt(), "\n", " ");
1930                         os << subst(p.getOpt(), "\n", " ");
1931                         os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1932                         end_inset(os);
1933                 }
1934
1935                 else if (is_known(t.cs(), known_quotes)) {
1936                         char const * const * where = is_known(t.cs(), known_quotes);
1937                         context.check_layout(os);
1938                         begin_inset(os, "Quotes ");
1939                         os << known_coded_quotes[where - known_quotes];
1940                         end_inset(os);
1941                         // LyX adds {} after the quote, so we have to eat
1942                         // spaces here if there are any before a possible
1943                         // {} pair.
1944                         eat_whitespace(p, os, context, false);
1945                         skip_braces(p);
1946                 }
1947
1948                 else if (is_known(t.cs(), known_sizes) &&
1949                          context.new_layout_allowed) {
1950                         char const * const * where = is_known(t.cs(), known_sizes);
1951                         context.check_layout(os);
1952                         TeXFont const oldFont = context.font;
1953                         context.font.size = known_coded_sizes[where - known_sizes];
1954                         output_font_change(os, oldFont, context.font);
1955                         eat_whitespace(p, os, context, false);
1956                 }
1957
1958                 else if (is_known(t.cs(), known_font_families) &&
1959                          context.new_layout_allowed) {
1960                         char const * const * where =
1961                                 is_known(t.cs(), known_font_families);
1962                         context.check_layout(os);
1963                         TeXFont const oldFont = context.font;
1964                         context.font.family =
1965                                 known_coded_font_families[where - known_font_families];
1966                         output_font_change(os, oldFont, context.font);
1967                         eat_whitespace(p, os, context, false);
1968                 }
1969
1970                 else if (is_known(t.cs(), known_font_series) &&
1971                          context.new_layout_allowed) {
1972                         char const * const * where =
1973                                 is_known(t.cs(), known_font_series);
1974                         context.check_layout(os);
1975                         TeXFont const oldFont = context.font;
1976                         context.font.series =
1977                                 known_coded_font_series[where - known_font_series];
1978                         output_font_change(os, oldFont, context.font);
1979                         eat_whitespace(p, os, context, false);
1980                 }
1981
1982                 else if (is_known(t.cs(), known_font_shapes) &&
1983                          context.new_layout_allowed) {
1984                         char const * const * where =
1985                                 is_known(t.cs(), known_font_shapes);
1986                         context.check_layout(os);
1987                         TeXFont const oldFont = context.font;
1988                         context.font.shape =
1989                                 known_coded_font_shapes[where - known_font_shapes];
1990                         output_font_change(os, oldFont, context.font);
1991                         eat_whitespace(p, os, context, false);
1992                 }
1993                 else if (is_known(t.cs(), known_old_font_families) &&
1994                          context.new_layout_allowed) {
1995                         char const * const * where =
1996                                 is_known(t.cs(), known_old_font_families);
1997                         context.check_layout(os);
1998                         TeXFont const oldFont = context.font;
1999                         context.font.init();
2000                         context.font.size = oldFont.size;
2001                         context.font.family =
2002                                 known_coded_font_families[where - known_old_font_families];
2003                         output_font_change(os, oldFont, context.font);
2004                         eat_whitespace(p, os, context, false);
2005                 }
2006
2007                 else if (is_known(t.cs(), known_old_font_series) &&
2008                          context.new_layout_allowed) {
2009                         char const * const * where =
2010                                 is_known(t.cs(), known_old_font_series);
2011                         context.check_layout(os);
2012                         TeXFont const oldFont = context.font;
2013                         context.font.init();
2014                         context.font.size = oldFont.size;
2015                         context.font.series =
2016                                 known_coded_font_series[where - known_old_font_series];
2017                         output_font_change(os, oldFont, context.font);
2018                         eat_whitespace(p, os, context, false);
2019                 }
2020
2021                 else if (is_known(t.cs(), known_old_font_shapes) &&
2022                          context.new_layout_allowed) {
2023                         char const * const * where =
2024                                 is_known(t.cs(), known_old_font_shapes);
2025                         context.check_layout(os);
2026                         TeXFont const oldFont = context.font;
2027                         context.font.init();
2028                         context.font.size = oldFont.size;
2029                         context.font.shape =
2030                                 known_coded_font_shapes[where - known_old_font_shapes];
2031                         output_font_change(os, oldFont, context.font);
2032                         eat_whitespace(p, os, context, false);
2033                 }
2034
2035                 else if (t.cs() == "LyX" || t.cs() == "TeX"
2036                          || t.cs() == "LaTeX") {
2037                         context.check_layout(os);
2038                         os << t.cs();
2039                         skip_braces(p); // eat {}
2040                 }
2041
2042                 else if (t.cs() == "LaTeXe") {
2043                         context.check_layout(os);
2044                         os << "LaTeX2e";
2045                         skip_braces(p); // eat {}
2046                 }
2047
2048                 else if (t.cs() == "ldots") {
2049                         context.check_layout(os);
2050                         skip_braces(p);
2051                         os << "\\SpecialChar \\ldots{}\n";
2052                 }
2053
2054                 else if (t.cs() == "lyxarrow") {
2055                         context.check_layout(os);
2056                         os << "\\SpecialChar \\menuseparator\n";
2057                         skip_braces(p);
2058                 }
2059
2060                 else if (t.cs() == "textcompwordmark") {
2061                         context.check_layout(os);
2062                         os << "\\SpecialChar \\textcompwordmark{}\n";
2063                         skip_braces(p);
2064                 }
2065
2066                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2067                         context.check_layout(os);
2068                         os << "\\SpecialChar \\@.\n";
2069                         p.get_token();
2070                 }
2071
2072                 else if (t.cs() == "-") {
2073                         context.check_layout(os);
2074                         os << "\\SpecialChar \\-\n";
2075                 }
2076
2077                 else if (t.cs() == "textasciitilde") {
2078                         context.check_layout(os);
2079                         os << '~';
2080                         skip_braces(p);
2081                 }
2082
2083                 else if (t.cs() == "textasciicircum") {
2084                         context.check_layout(os);
2085                         os << '^';
2086                         skip_braces(p);
2087                 }
2088
2089                 else if (t.cs() == "textbackslash") {
2090                         context.check_layout(os);
2091                         os << "\n\\backslash\n";
2092                         skip_braces(p);
2093                 }
2094
2095                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2096                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2097                             || t.cs() == "%") {
2098                         context.check_layout(os);
2099                         os << t.cs();
2100                 }
2101
2102                 else if (t.cs() == "char") {
2103                         context.check_layout(os);
2104                         if (p.next_token().character() == '`') {
2105                                 p.get_token();
2106                                 if (p.next_token().cs() == "\"") {
2107                                         p.get_token();
2108                                         os << '"';
2109                                         skip_braces(p);
2110                                 } else {
2111                                         handle_ert(os, "\\char`", context);
2112                                 }
2113                         } else {
2114                                 handle_ert(os, "\\char", context);
2115                         }
2116                 }
2117
2118                 else if (t.cs() == "verb") {
2119                         context.check_layout(os);
2120                         char const delimiter = p.next_token().character();
2121                         string const arg = p.getArg(delimiter, delimiter);
2122                         ostringstream oss;
2123                         oss << "\\verb" << delimiter << arg << delimiter;
2124                         handle_ert(os, oss.str(), context);
2125                 }
2126
2127                 else if (t.cs() == "\"") {
2128                         context.check_layout(os);
2129                         string const name = p.verbatim_item();
2130                              if (name == "a") os << '\xe4';
2131                         else if (name == "o") os << '\xf6';
2132                         else if (name == "u") os << '\xfc';
2133                         else if (name == "A") os << '\xc4';
2134                         else if (name == "O") os << '\xd6';
2135                         else if (name == "U") os << '\xdc';
2136                         else handle_ert(os, "\"{" + name + "}", context);
2137                 }
2138
2139                 // Problem: \= creates a tabstop inside the tabbing environment
2140                 // and else an accent. In the latter case we really would want
2141                 // \={o} instead of \= o.
2142                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2143                         handle_ert(os, t.asInput(), context);
2144
2145                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2146                          || t.cs() == "'" || t.cs() == "`"
2147                          || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2148                         // we need the trim as the LyX parser chokes on such spaces
2149                         // The argument of InsetLatexAccent is parsed as a
2150                         // subset of LaTeX, so don't parse anything here,
2151                         // but use the raw argument.
2152                         // Otherwise we would convert \~{\i} wrongly.
2153                         // This will of course not translate \~{\ss} to \~{ß},
2154                         // but that does at least compile and does only look
2155                         // strange on screen.
2156                         context.check_layout(os);
2157                         os << "\\i \\" << t.cs() << "{"
2158                            << trim(p.verbatim_item(), " ")
2159                            << "}\n";
2160                 }
2161
2162                 else if (t.cs() == "ss") {
2163                         context.check_layout(os);
2164                         os << "\xdf";
2165                         skip_braces(p); // eat {}
2166                 }
2167
2168                 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2169                          t.cs() == "L") {
2170                         context.check_layout(os);
2171                         os << "\\i \\" << t.cs() << "{}\n";
2172                         skip_braces(p); // eat {}
2173                 }
2174
2175                 else if (t.cs() == "\\") {
2176                         context.check_layout(os);
2177                         string const next = p.next_token().asInput();
2178                         if (next == "[")
2179                                 handle_ert(os, "\\\\" + p.getOpt(), context);
2180                         else if (next == "*") {
2181                                 p.get_token();
2182                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
2183                         }
2184                         else {
2185                                 os << "\n\\newline\n";
2186                         }
2187                 }
2188
2189                 else if (t.cs() == "input" || t.cs() == "include"
2190                          || t.cs() == "verbatiminput") {
2191                         string name = '\\' + t.cs();
2192                         if (t.cs() == "verbatiminput"
2193                             && p.next_token().asInput() == "*")
2194                                 name += p.get_token().asInput();
2195                         context.check_layout(os);
2196                         begin_inset(os, "Include ");
2197                         string filename(normalize_filename(p.getArg('{', '}')));
2198                         string const path = getMasterFilePath();
2199                         // We want to preserve relative / absolute filenames,
2200                         // therefore path is only used for testing
2201                         // FIXME UNICODE encoding of filename and path may be
2202                         // wrong (makeAbsPath expects utf8)
2203                         if ((t.cs() == "include" || t.cs() == "input") &&
2204                             !fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2205                                 // The file extension is probably missing.
2206                                 // Now try to find it out.
2207                                 string const tex_name =
2208                                         find_file(filename, path,
2209                                                   known_tex_extensions);
2210                                 if (!tex_name.empty())
2211                                         filename = tex_name;
2212                         }
2213                         // FIXME UNICODE encoding of filename and path may be
2214                         // wrong (makeAbsPath expects utf8)
2215                         if (fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2216                                 string const abstexname =
2217                                         makeAbsPath(filename, path).absFilename();
2218                                 string const abslyxname =
2219                                         changeExtension(abstexname, ".lyx");
2220                                 fix_relative_filename(filename);
2221                                 string const lyxname =
2222                                         changeExtension(filename, ".lyx");
2223                                 if (t.cs() != "verbatiminput" &&
2224                                     tex2lyx(abstexname, FileName(abslyxname))) {
2225                                         os << name << '{' << lyxname << "}\n";
2226                                 } else {
2227                                         os << name << '{' << filename << "}\n";
2228                                 }
2229                         } else {
2230                                 cerr << "Warning: Could not find included file '"
2231                                      << filename << "'." << endl;
2232                                 os << name << '{' << filename << "}\n";
2233                         }
2234                         os << "preview false\n";
2235                         end_inset(os);
2236                 }
2237
2238                 else if (t.cs() == "bibliographystyle") {
2239                         // store new bibliographystyle
2240                         bibliographystyle = p.verbatim_item();
2241                         // output new bibliographystyle.
2242                         // This is only necessary if used in some other macro than \bibliography.
2243                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2244                 }
2245
2246                 else if (t.cs() == "bibliography") {
2247                         context.check_layout(os);
2248                         begin_inset(os, "LatexCommand ");
2249                         os << "\\bibtex";
2250                         // Do we have a bibliographystyle set?
2251                         if (!bibliographystyle.empty()) {
2252                                 os << '[' << bibliographystyle << ']';
2253                         }
2254                         os << '{' << p.verbatim_item() << "}\n";
2255                         end_inset(os);
2256                 }
2257
2258                 else if (t.cs() == "parbox")
2259                         parse_box(p, os, FLAG_ITEM, outer, context, true);
2260
2261                 else if (t.cs() == "smallskip" ||
2262                          t.cs() == "medskip" ||
2263                          t.cs() == "bigskip" ||
2264                          t.cs() == "vfill") {
2265                         context.check_layout(os);
2266                         begin_inset(os, "VSpace ");
2267                         os << t.cs();
2268                         end_inset(os);
2269                         skip_braces(p);
2270                 }
2271
2272                 else if (is_known(t.cs(), known_spaces)) {
2273                         char const * const * where = is_known(t.cs(), known_spaces);
2274                         context.check_layout(os);
2275                         begin_inset(os, "InsetSpace ");
2276                         os << '\\' << known_coded_spaces[where - known_spaces]
2277                            << '\n';
2278                         // LaTeX swallows whitespace after all spaces except
2279                         // "\\,". We have to do that here, too, because LyX
2280                         // adds "{}" which would make the spaces significant.
2281                         if (t.cs() !=  ",")
2282                                 eat_whitespace(p, os, context, false);
2283                         // LyX adds "{}" after all spaces except "\\ " and
2284                         // "\\,", so we have to remove "{}".
2285                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
2286                         // remove the braces after "\\,", too.
2287                         if (t.cs() != " ")
2288                                 skip_braces(p);
2289                 }
2290
2291                 else if (t.cs() == "newpage" ||
2292                          t.cs() == "clearpage" ||
2293                          t.cs() == "cleardoublepage") {
2294                         context.check_layout(os);
2295                         // FIXME: what about \\pagebreak?
2296                         os << "\n\\" << t.cs() << "\n";
2297                         skip_braces(p); // eat {}
2298                 }
2299
2300                 else if (t.cs() == "newcommand" ||
2301                          t.cs() == "providecommand" ||
2302                          t.cs() == "renewcommand") {
2303                         // these could be handled by parse_command(), but
2304                         // we need to call add_known_command() here.
2305                         string name = t.asInput();
2306                         if (p.next_token().asInput() == "*") {
2307                                 // Starred form. Eat '*'
2308                                 p.get_token();
2309                                 name += '*';
2310                         }
2311                         string const command = p.verbatim_item();
2312                         string const opt1 = p.getOpt();
2313                         string const opt2 = p.getFullOpt();
2314                         add_known_command(command, opt1, !opt2.empty());
2315                         string const ert = name + '{' + command + '}' +
2316                                            opt1 + opt2 +
2317                                            '{' + p.verbatim_item() + '}';
2318
2319                         if (opt2.empty()) {
2320                                 context.check_layout(os);
2321                                 begin_inset(os, "FormulaMacro");
2322                                 os << "\n" << ert;
2323                                 end_inset(os);
2324                         } else
2325                                 // we cannot handle optional argument, so only output ERT
2326                                 handle_ert(os, ert, context);
2327                 }
2328
2329                 else if (t.cs() == "vspace") {
2330                         bool starred = false;
2331                         if (p.next_token().asInput() == "*") {
2332                                 p.get_token();
2333                                 starred = true;
2334                         }
2335                         string const length = p.verbatim_item();
2336                         string unit;
2337                         string valstring;
2338                         bool valid = splitLatexLength(length, valstring, unit);
2339                         bool known_vspace = false;
2340                         bool known_unit = false;
2341                         double value;
2342                         if (valid) {
2343                                 istringstream iss(valstring);
2344                                 iss >> value;
2345                                 if (value == 1.0) {
2346                                         if (unit == "\\smallskipamount") {
2347                                                 unit = "smallskip";
2348                                                 known_vspace = true;
2349                                         } else if (unit == "\\medskipamount") {
2350                                                 unit = "medskip";
2351                                                 known_vspace = true;
2352                                         } else if (unit == "\\bigskipamount") {
2353                                                 unit = "bigskip";
2354                                                 known_vspace = true;
2355                                         } else if (unit == "\\fill") {
2356                                                 unit = "vfill";
2357                                                 known_vspace = true;
2358                                         }
2359                                 }
2360                                 if (!known_vspace) {
2361                                         switch (unitFromString(unit)) {
2362                                         case Length::SP:
2363                                         case Length::PT:
2364                                         case Length::BP:
2365                                         case Length::DD:
2366                                         case Length::MM:
2367                                         case Length::PC:
2368                                         case Length::CC:
2369                                         case Length::CM:
2370                                         case Length::IN:
2371                                         case Length::EX:
2372                                         case Length::EM:
2373                                         case Length::MU:
2374                                                 known_unit = true;
2375                                                 break;
2376                                         default:
2377                                                 break;
2378                                         }
2379                                 }
2380                         }
2381
2382                         if (known_unit || known_vspace) {
2383                                 // Literal length or known variable
2384                                 context.check_layout(os);
2385                                 begin_inset(os, "VSpace ");
2386                                 if (known_unit)
2387                                         os << value;
2388                                 os << unit;
2389                                 if (starred)
2390                                         os << '*';
2391                                 end_inset(os);
2392                         } else {
2393                                 // LyX can't handle other length variables in Inset VSpace
2394                                 string name = t.asInput();
2395                                 if (starred)
2396                                         name += '*';
2397                                 if (valid) {
2398                                         if (value == 1.0)
2399                                                 handle_ert(os, name + '{' + unit + '}', context);
2400                                         else if (value == -1.0)
2401                                                 handle_ert(os, name + "{-" + unit + '}', context);
2402                                         else
2403                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
2404                                 } else
2405                                         handle_ert(os, name + '{' + length + '}', context);
2406                         }
2407                 }
2408
2409                 else {
2410                         //cerr << "#: " << t << " mode: " << mode << endl;
2411                         // heuristic: read up to next non-nested space
2412                         /*
2413                         string s = t.asInput();
2414                         string z = p.verbatim_item();
2415                         while (p.good() && z != " " && z.size()) {
2416                                 //cerr << "read: " << z << endl;
2417                                 s += z;
2418                                 z = p.verbatim_item();
2419                         }
2420                         cerr << "found ERT: " << s << endl;
2421                         handle_ert(os, s + ' ', context);
2422                         */
2423                         string name = t.asInput();
2424                         if (p.next_token().asInput() == "*") {
2425                                 // Starred commands like \vspace*{}
2426                                 p.get_token();                          // Eat '*'
2427                                 name += '*';
2428                         }
2429                         if (! parse_command(name, p, os, outer, context))
2430                                 handle_ert(os, name, context);
2431                 }
2432
2433                 if (flags & FLAG_LEAVE) {
2434                         flags &= ~FLAG_LEAVE;
2435                         break;
2436                 }
2437         }
2438 }
2439
2440 // }])
2441
2442
2443 } // namespace lyx