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