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