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