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