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.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
20 #include "FloatList.h"
24 #include "support/lstrings.h"
25 #include "support/convert.h"
26 #include "support/filetools.h"
28 #include <boost/tuple/tuple.hpp>
40 using std::ostringstream;
41 using std::istringstream;
47 using support::addExtension;
48 using support::changeExtension;
49 using support::FileName;
50 using support::makeAbsPath;
51 using support::makeRelPath;
53 using support::suffixIs;
54 using support::contains;
58 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
59 Context const & context)
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);
70 /// parses a paragraph snippet, useful for example for \\emph{...}
71 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
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;
85 * Thin wrapper around parse_text_snippet() using a string.
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.
93 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
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();
103 parse_text_snippet(p, os, flags, outer, newcontext);
108 char const * const known_latex_commands[] = { "ref", "cite", "label",
109 "index", "pageref", "url", "vref", "vpageref", "prettyref",
114 * We can't put these into known_latex_commands because the argument order
115 * is reversed in lyx if there are 2 arguments.
116 * The starred forms are also known.
118 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
119 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
120 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
124 * We can't put these into known_latex_commands because the argument order
125 * is reversed in lyx if there are 2 arguments.
126 * No starred form other than "cite*" known.
128 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
129 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
130 // jurabib commands not (yet) supported by LyX:
132 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
133 // "footciteauthor", "footciteyear", "footciteyearpar",
134 "citefield", "citetitle", "cite*", 0 };
136 /// LaTeX names for quotes
137 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
138 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
140 /// the same as known_quotes with .lyx names
141 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
142 "grd", "gls", "fls", "frs", 0};
144 /// LaTeX names for font sizes
145 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
146 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
148 /// the same as known_sizes with .lyx names
149 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
150 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
152 /// LaTeX 2.09 names for font families
153 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
155 /// LaTeX names for font families
156 char const * const known_font_families[] = { "rmfamily", "sffamily",
159 /// the same as known_old_font_families and known_font_families with .lyx names
160 char const * const known_coded_font_families[] = { "roman", "sans",
163 /// LaTeX 2.09 names for font series
164 char const * const known_old_font_series[] = { "bf", 0};
166 /// LaTeX names for font series
167 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
169 /// the same as known_old_font_series and known_font_series with .lyx names
170 char const * const known_coded_font_series[] = { "bold", "medium", 0};
172 /// LaTeX 2.09 names for font shapes
173 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
175 /// LaTeX names for font shapes
176 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
179 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
180 char const * const known_coded_font_shapes[] = { "italic", "slanted",
181 "smallcaps", "up", 0};
184 * Graphics file extensions known by the dvips driver of the graphics package.
185 * These extensions are used to complete the filename of an included
186 * graphics file if it does not contain an extension.
187 * The order must be the same that latex uses to find a file, because we
188 * will use the first extension that matches.
189 * This is only an approximation for the common cases. If we would want to
190 * do it right in all cases, we would need to know which graphics driver is
191 * used and know the extensions of every driver of the graphics package.
193 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
194 "ps.gz", "eps.Z", "ps.Z", 0};
197 * Graphics file extensions known by the pdftex driver of the graphics package.
198 * \sa known_dvips_graphics_formats
200 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
204 * Known file extensions for TeX files as used by \\include.
206 char const * const known_tex_extensions[] = {"tex", 0};
208 /// spaces known by InsetSpace
209 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
210 "qquad", "enspace", "enskip", "negthinspace", 0};
212 /// the same as known_spaces with .lyx names
213 char const * const known_coded_spaces[] = { "space{}", "space{}",
214 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
215 "negthinspace{}", 0};
218 /// splits "x=z, y=b" into a map
219 map<string, string> split_map(string const & s)
221 map<string, string> res;
224 for (size_t i = 0; i < v.size(); ++i) {
225 size_t const pos = v[i].find('=');
226 string const index = v[i].substr(0, pos);
227 string const value = v[i].substr(pos + 1, string::npos);
228 res[trim(index)] = trim(value);
235 * Split a LaTeX length into value and unit.
236 * The latter can be a real unit like "pt", or a latex length variable
237 * like "\textwidth". The unit may contain additional stuff like glue
238 * lengths, but we don't care, because such lengths are ERT anyway.
239 * \returns true if \p value and \p unit are valid.
241 bool splitLatexLength(string const & len, string & value, string & unit)
245 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
246 //'4,5' is a valid LaTeX length number. Change it to '4.5'
247 string const length = subst(len, ',', '.');
248 if (i == string::npos)
251 if (len[0] == '\\') {
252 // We had something like \textwidth without a factor
258 value = trim(string(length, 0, i));
262 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
263 if (contains(len, '\\'))
264 unit = trim(string(len, i));
266 unit = support::ascii_lowercase(trim(string(len, i)));
271 /// A simple function to translate a latex length to something lyx can
272 /// understand. Not perfect, but rather best-effort.
273 bool translate_len(string const & length, string & valstring, string & unit)
275 if (!splitLatexLength(length, valstring, unit))
277 // LyX uses percent values
279 istringstream iss(valstring);
284 string const percentval = oss.str();
286 if (unit.empty() || unit[0] != '\\')
288 string::size_type const i = unit.find(' ');
289 string const endlen = (i == string::npos) ? string() : string(unit, i);
290 if (unit == "\\textwidth") {
291 valstring = percentval;
292 unit = "text%" + endlen;
293 } else if (unit == "\\columnwidth") {
294 valstring = percentval;
295 unit = "col%" + endlen;
296 } else if (unit == "\\paperwidth") {
297 valstring = percentval;
298 unit = "page%" + endlen;
299 } else if (unit == "\\linewidth") {
300 valstring = percentval;
301 unit = "line%" + endlen;
302 } else if (unit == "\\paperheight") {
303 valstring = percentval;
304 unit = "pheight%" + endlen;
305 } else if (unit == "\\textheight") {
306 valstring = percentval;
307 unit = "theight%" + endlen;
315 string translate_len(string const & length)
319 if (translate_len(length, value, unit))
321 // If the input is invalid, return what we have.
329 * Translates a LaTeX length into \p value, \p unit and
330 * \p special parts suitable for a box inset.
331 * The difference from translate_len() is that a box inset knows about
332 * some special "units" that are stored in \p special.
334 void translate_box_len(string const & length, string & value, string & unit, string & special)
336 if (translate_len(length, value, unit)) {
337 if (unit == "\\height" || unit == "\\depth" ||
338 unit == "\\totalheight" || unit == "\\width") {
339 special = unit.substr(1);
340 // The unit is not used, but LyX requires a dummy setting
353 * Find a file with basename \p name in path \p path and an extension
356 string find_file(string const & name, string const & path,
357 char const * const * extensions)
359 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
361 for (char const * const * what = extensions; *what; ++what) {
362 string const trial = addExtension(name, *what);
363 if (makeAbsPath(trial, path).exists())
370 void begin_inset(ostream & os, string const & name)
372 os << "\n\\begin_inset " << name;
376 void end_inset(ostream & os)
378 os << "\n\\end_inset\n\n";
382 void skip_braces(Parser & p)
384 if (p.next_token().cat() != catBegin)
387 if (p.next_token().cat() == catEnd) {
395 void handle_ert(ostream & os, string const & s, Context & context)
397 // We must have a valid layout before outputting the ERT inset.
398 context.check_layout(os);
399 Context newcontext(true, context.textclass);
400 begin_inset(os, "ERT");
401 os << "\nstatus collapsed\n";
402 newcontext.check_layout(os);
403 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
405 os << "\n\\backslash\n";
406 else if (*it == '\n') {
407 newcontext.new_paragraph(os);
408 newcontext.check_layout(os);
412 newcontext.check_end_layout(os);
417 void handle_comment(ostream & os, string const & s, Context & context)
419 // TODO: Handle this better
420 Context newcontext(true, context.textclass);
421 begin_inset(os, "ERT");
422 os << "\nstatus collapsed\n";
423 newcontext.check_layout(os);
424 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
426 os << "\n\\backslash\n";
430 // make sure that our comment is the last thing on the line
431 newcontext.new_paragraph(os);
432 newcontext.check_layout(os);
433 newcontext.check_end_layout(os);
438 class isLayout : public std::unary_function<LayoutPtr, bool> {
440 isLayout(string const name) : name_(name) {}
441 bool operator()(LayoutPtr const & ptr) const {
442 return ptr->latexname() == name_;
449 LayoutPtr findLayout(TextClass const & textclass,
452 TextClass::const_iterator beg = textclass.begin();
453 TextClass::const_iterator end = textclass.end();
455 TextClass::const_iterator
456 it = std::find_if(beg, end, isLayout(name));
458 return (it == end) ? LayoutPtr() : *it;
462 void eat_whitespace(Parser &, ostream &, Context &, bool);
465 void output_command_layout(ostream & os, Parser & p, bool outer,
466 Context & parent_context,
469 parent_context.check_end_layout(os);
470 Context context(true, parent_context.textclass, newlayout,
471 parent_context.layout, parent_context.font);
472 if (parent_context.deeper_paragraph) {
473 // We are beginning a nested environment after a
474 // deeper paragraph inside the outer list environment.
475 // Therefore we don't need to output a "begin deeper".
476 context.need_end_deeper = true;
478 context.check_deeper(os);
479 context.check_layout(os);
480 if (context.layout->optionalargs > 0) {
481 eat_whitespace(p, os, context, false);
482 if (p.next_token().character() == '[') {
483 p.get_token(); // eat '['
484 begin_inset(os, "OptArg\n");
485 os << "status collapsed\n\n";
486 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
488 eat_whitespace(p, os, context, false);
491 parse_text(p, os, FLAG_ITEM, outer, context);
492 context.check_end_layout(os);
493 if (parent_context.deeper_paragraph) {
494 // We must suppress the "end deeper" because we
495 // suppressed the "begin deeper" above.
496 context.need_end_deeper = false;
498 context.check_end_deeper(os);
499 // We don't need really a new paragraph, but
500 // we must make sure that the next item gets a \begin_layout.
501 parent_context.new_paragraph(os);
506 * Output a space if necessary.
507 * This function gets called for every whitespace token.
509 * We have three cases here:
510 * 1. A space must be suppressed. Example: The lyxcode case below
511 * 2. A space may be suppressed. Example: Spaces before "\par"
512 * 3. A space must not be suppressed. Example: A space between two words
514 * We currently handle only 1. and 3 and from 2. only the case of
515 * spaces before newlines as a side effect.
517 * 2. could be used to suppress as many spaces as possible. This has two effects:
518 * - Reimporting LyX generated LaTeX files changes almost no whitespace
519 * - Superflous whitespace from non LyX generated LaTeX files is removed.
520 * The drawback is that the logic inside the function becomes
521 * complicated, and that is the reason why it is not implemented.
523 void check_space(Parser const & p, ostream & os, Context & context)
525 Token const next = p.next_token();
526 Token const curr = p.curr_token();
527 // A space before a single newline and vice versa must be ignored
528 // LyX emits a newline before \end{lyxcode}.
529 // This newline must be ignored,
530 // otherwise LyX will add an additional protected space.
531 if (next.cat() == catSpace ||
532 next.cat() == catNewline ||
533 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
536 context.check_layout(os);
542 * Parse all arguments of \p command
544 void parse_arguments(string const & command,
545 vector<ArgumentType> const & template_arguments,
546 Parser & p, ostream & os, bool outer, Context & context)
548 string ert = command;
549 size_t no_arguments = template_arguments.size();
550 for (size_t i = 0; i < no_arguments; ++i) {
551 switch (template_arguments[i]) {
553 // This argument contains regular LaTeX
554 handle_ert(os, ert + '{', context);
555 eat_whitespace(p, os, context, false);
556 parse_text(p, os, FLAG_ITEM, outer, context);
560 // This argument may contain special characters
561 ert += '{' + p.verbatim_item() + '}';
568 handle_ert(os, ert, context);
573 * Check whether \p command is a known command. If yes,
574 * handle the command with all arguments.
575 * \return true if the command was parsed, false otherwise.
577 bool parse_command(string const & command, Parser & p, ostream & os,
578 bool outer, Context & context)
580 if (known_commands.find(command) != known_commands.end()) {
581 parse_arguments(command, known_commands[command], p, os,
589 /// Parses a minipage or parbox
590 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
591 Context & parent_context, bool use_parbox)
595 // We need to set the height to the LaTeX default of 1\\totalheight
596 // for the case when no height argument is given
597 string height_value = "1";
598 string height_unit = "in";
599 string height_special = "totalheight";
601 if (p.next_token().asInput() == "[") {
602 position = p.getArg('[', ']');
603 if (position != "t" && position != "c" && position != "b") {
605 cerr << "invalid position for minipage/parbox" << endl;
607 if (p.next_token().asInput() == "[") {
608 latex_height = p.getArg('[', ']');
609 translate_box_len(latex_height, height_value, height_unit, height_special);
611 if (p.next_token().asInput() == "[") {
612 inner_pos = p.getArg('[', ']');
613 if (inner_pos != "c" && inner_pos != "t" &&
614 inner_pos != "b" && inner_pos != "s") {
615 inner_pos = position;
616 cerr << "invalid inner_pos for minipage/parbox"
624 string const latex_width = p.verbatim_item();
625 translate_len(latex_width, width_value, width_unit);
626 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
627 // LyX can't handle length variables
632 ss << "\\begin{minipage}";
633 if (!position.empty())
634 ss << '[' << position << ']';
635 if (!latex_height.empty())
636 ss << '[' << latex_height << ']';
637 if (!inner_pos.empty())
638 ss << '[' << inner_pos << ']';
639 ss << "{" << latex_width << "}";
642 handle_ert(os, ss.str(), parent_context);
643 parent_context.new_paragraph(os);
644 parse_text_in_inset(p, os, flags, outer, parent_context);
646 handle_ert(os, "}", parent_context);
648 handle_ert(os, "\\end{minipage}", parent_context);
650 // LyX does not like empty positions, so we have
651 // to set them to the LaTeX default values here.
652 if (position.empty())
654 if (inner_pos.empty())
655 inner_pos = position;
656 parent_context.check_layout(os);
657 begin_inset(os, "Box Frameless\n");
658 os << "position \"" << position << "\"\n";
659 os << "hor_pos \"c\"\n";
660 os << "has_inner_box 1\n";
661 os << "inner_pos \"" << inner_pos << "\"\n";
662 os << "use_parbox " << use_parbox << "\n";
663 os << "width \"" << width_value << width_unit << "\"\n";
664 os << "special \"none\"\n";
665 os << "height \"" << height_value << height_unit << "\"\n";
666 os << "height_special \"" << height_special << "\"\n";
667 os << "status open\n\n";
668 parse_text_in_inset(p, os, flags, outer, parent_context);
670 #ifdef PRESERVE_LAYOUT
671 // lyx puts a % after the end of the minipage
672 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
674 //handle_comment(os, "%dummy", parent_context);
677 parent_context.new_paragraph(os);
679 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
680 //handle_comment(os, "%dummy", parent_context);
683 // We add a protected space if something real follows
684 if (p.good() && p.next_token().cat() != catComment) {
685 os << "\\InsetSpace ~\n";
693 /// parse an unknown environment
694 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
695 unsigned flags, bool outer,
696 Context & parent_context)
698 if (name == "tabbing")
699 // We need to remember that we have to handle '\=' specially
700 flags |= FLAG_TABBING;
702 // We need to translate font changes and paragraphs inside the
703 // environment to ERT if we have a non standard font.
704 // Otherwise things like
705 // \large\begin{foo}\huge bar\end{foo}
707 bool const specialfont =
708 (parent_context.font != parent_context.normalfont);
709 bool const new_layout_allowed = parent_context.new_layout_allowed;
711 parent_context.new_layout_allowed = false;
712 handle_ert(os, "\\begin{" + name + "}", parent_context);
713 parse_text_snippet(p, os, flags, outer, parent_context);
714 handle_ert(os, "\\end{" + name + "}", parent_context);
716 parent_context.new_layout_allowed = new_layout_allowed;
720 void parse_environment(Parser & p, ostream & os, bool outer,
721 Context & parent_context)
724 string const name = p.getArg('{', '}');
725 const bool is_starred = suffixIs(name, '*');
726 string const unstarred_name = rtrim(name, "*");
727 active_environments.push_back(name);
729 if (is_math_env(name)) {
730 parent_context.check_layout(os);
731 begin_inset(os, "Formula ");
732 os << "\\begin{" << name << "}";
733 parse_math(p, os, FLAG_END, MATH_MODE);
734 os << "\\end{" << name << "}";
738 else if (name == "tabular" || name == "longtable") {
739 eat_whitespace(p, os, parent_context, false);
740 parent_context.check_layout(os);
741 begin_inset(os, "Tabular ");
742 handle_tabular(p, os, name == "longtable", parent_context);
747 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
748 eat_whitespace(p, os, parent_context, false);
749 parent_context.check_layout(os);
750 begin_inset(os, "Float " + unstarred_name + "\n");
751 if (p.next_token().asInput() == "[") {
752 os << "placement " << p.getArg('[', ']') << '\n';
754 os << "wide " << convert<string>(is_starred)
755 << "\nsideways false"
756 << "\nstatus open\n\n";
757 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
759 // We don't need really a new paragraph, but
760 // we must make sure that the next item gets a \begin_layout.
761 parent_context.new_paragraph(os);
765 else if (name == "minipage") {
766 eat_whitespace(p, os, parent_context, false);
767 parse_box(p, os, FLAG_END, outer, parent_context, false);
771 else if (name == "comment") {
772 eat_whitespace(p, os, parent_context, false);
773 parent_context.check_layout(os);
774 begin_inset(os, "Note Comment\n");
775 os << "status open\n";
776 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
779 // FIXME the comment note inset has a trailing "{}" pair
783 else if (name == "lyxgreyedout") {
784 eat_whitespace(p, os, parent_context, false);
785 parent_context.check_layout(os);
786 begin_inset(os, "Note Greyedout\n");
787 os << "status open\n";
788 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
793 else if (name == "framed") {
794 eat_whitespace(p, os, parent_context, false);
795 parent_context.check_layout(os);
796 begin_inset(os, "Note Framed\n");
797 os << "status open\n";
798 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
803 else if (name == "shaded") {
804 eat_whitespace(p, os, parent_context, false);
805 parent_context.check_layout(os);
806 begin_inset(os, "Note Shaded\n");
807 os << "status open\n";
808 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
813 else if (!parent_context.new_layout_allowed)
814 parse_unknown_environment(p, name, os, FLAG_END, outer,
817 // Alignment settings
818 else if (name == "center" || name == "flushleft" || name == "flushright" ||
819 name == "centering" || name == "raggedright" || name == "raggedleft") {
820 eat_whitespace(p, os, parent_context, false);
821 // We must begin a new paragraph if not already done
822 if (! parent_context.atParagraphStart()) {
823 parent_context.check_end_layout(os);
824 parent_context.new_paragraph(os);
826 if (name == "flushleft" || name == "raggedright")
827 parent_context.add_extra_stuff("\\align left\n");
828 else if (name == "flushright" || name == "raggedleft")
829 parent_context.add_extra_stuff("\\align right\n");
831 parent_context.add_extra_stuff("\\align center\n");
832 parse_text(p, os, FLAG_END, outer, parent_context);
833 // Just in case the environment is empty ..
834 parent_context.extra_stuff.erase();
835 // We must begin a new paragraph to reset the alignment
836 parent_context.new_paragraph(os);
840 // The single '=' is meant here.
841 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
842 newlayout->isEnvironment()) {
843 eat_whitespace(p, os, parent_context, false);
844 Context context(true, parent_context.textclass, newlayout,
845 parent_context.layout, parent_context.font);
846 if (parent_context.deeper_paragraph) {
847 // We are beginning a nested environment after a
848 // deeper paragraph inside the outer list environment.
849 // Therefore we don't need to output a "begin deeper".
850 context.need_end_deeper = true;
852 parent_context.check_end_layout(os);
853 switch (context.layout->latextype) {
854 case LATEX_LIST_ENVIRONMENT:
855 context.extra_stuff = "\\labelwidthstring "
856 + p.verbatim_item() + '\n';
859 case LATEX_BIB_ENVIRONMENT:
860 p.verbatim_item(); // swallow next arg
866 context.check_deeper(os);
867 parse_text(p, os, FLAG_END, outer, context);
868 context.check_end_layout(os);
869 if (parent_context.deeper_paragraph) {
870 // We must suppress the "end deeper" because we
871 // suppressed the "begin deeper" above.
872 context.need_end_deeper = false;
874 context.check_end_deeper(os);
875 parent_context.new_paragraph(os);
879 else if (name == "appendix") {
880 // This is no good latex style, but it works and is used in some documents...
881 eat_whitespace(p, os, parent_context, false);
882 parent_context.check_end_layout(os);
883 Context context(true, parent_context.textclass, parent_context.layout,
884 parent_context.layout, parent_context.font);
885 context.check_layout(os);
886 os << "\\start_of_appendix\n";
887 parse_text(p, os, FLAG_END, outer, context);
888 context.check_end_layout(os);
892 else if (known_environments.find(name) != known_environments.end()) {
893 vector<ArgumentType> arguments = known_environments[name];
894 // The last "argument" denotes wether we may translate the
895 // environment contents to LyX
896 // The default required if no argument is given makes us
897 // compatible with the reLyXre environment.
898 ArgumentType contents = arguments.empty() ?
901 if (!arguments.empty())
902 arguments.pop_back();
903 // See comment in parse_unknown_environment()
904 bool const specialfont =
905 (parent_context.font != parent_context.normalfont);
906 bool const new_layout_allowed =
907 parent_context.new_layout_allowed;
909 parent_context.new_layout_allowed = false;
910 parse_arguments("\\begin{" + name + "}", arguments, p, os,
911 outer, parent_context);
912 if (contents == verbatim)
913 handle_ert(os, p.verbatimEnvironment(name),
916 parse_text_snippet(p, os, FLAG_END, outer,
918 handle_ert(os, "\\end{" + name + "}", parent_context);
920 parent_context.new_layout_allowed = new_layout_allowed;
924 parse_unknown_environment(p, name, os, FLAG_END, outer,
927 active_environments.pop_back();
931 /// parses a comment and outputs it to \p os.
932 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
934 BOOST_ASSERT(t.cat() == catComment);
935 if (!t.cs().empty()) {
936 context.check_layout(os);
937 handle_comment(os, '%' + t.cs(), context);
938 if (p.next_token().cat() == catNewline) {
939 // A newline after a comment line starts a new
941 if (context.new_layout_allowed) {
942 if(!context.atParagraphStart())
943 // Only start a new paragraph if not already
944 // done (we might get called recursively)
945 context.new_paragraph(os);
947 handle_ert(os, "\n", context);
948 eat_whitespace(p, os, context, true);
958 * Reads spaces and comments until the first non-space, non-comment token.
959 * New paragraphs (double newlines or \\par) are handled like simple spaces
960 * if \p eatParagraph is true.
961 * Spaces are skipped, but comments are written to \p os.
963 void eat_whitespace(Parser & p, ostream & os, Context & context,
967 Token const & t = p.get_token();
968 if (t.cat() == catComment)
969 parse_comment(p, os, t, context);
970 else if ((! eatParagraph && p.isParagraph()) ||
971 (t.cat() != catSpace && t.cat() != catNewline)) {
980 * Set a font attribute, parse text and reset the font attribute.
981 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
982 * \param currentvalue Current value of the attribute. Is set to the new
983 * value during parsing.
984 * \param newvalue New value of the attribute
986 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
987 Context & context, string const & attribute,
988 string & currentvalue, string const & newvalue)
990 context.check_layout(os);
991 string const oldvalue = currentvalue;
992 currentvalue = newvalue;
993 os << '\n' << attribute << ' ' << newvalue << "\n";
994 parse_text_snippet(p, os, flags, outer, context);
995 context.check_layout(os);
996 os << '\n' << attribute << ' ' << oldvalue << "\n";
997 currentvalue = oldvalue;
1001 /// get the arguments of a natbib or jurabib citation command
1002 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
1004 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1006 // text before the citation
1008 // text after the citation
1009 string after = p.getFullOpt();
1011 if (!after.empty()) {
1012 before = p.getFullOpt();
1013 if (natbibOrder && !before.empty())
1014 std::swap(before, after);
1016 return std::make_pair(before, after);
1020 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
1021 string const normalize_filename(string const & name)
1023 Parser p(trim(name, "\""));
1026 Token const & t = p.get_token();
1027 if (t.cat() != catEscape)
1029 else if (t.cs() == "lyxdot") {
1030 // This is used by LyX for simple dots in relative
1034 } else if (t.cs() == "space") {
1044 /// Convert \p name from TeX convention (relative to master file) to LyX
1045 /// convention (relative to .lyx file) if it is relative
1046 void fix_relative_filename(string & name)
1048 if (lyx::support::absolutePath(name))
1050 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1052 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1053 from_utf8(getParentFilePath())));
1057 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1058 void parse_noweb(Parser & p, ostream & os, Context & context)
1060 // assemble the rest of the keyword
1064 Token const & t = p.get_token();
1065 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1068 scrap = (p.good() && p.next_token().asInput() == "=");
1070 name += p.get_token().asInput();
1073 name += t.asInput();
1076 if (!scrap || !context.new_layout_allowed ||
1077 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1078 cerr << "Warning: Could not interpret '" << name
1079 << "'. Ignoring it." << endl;
1083 // We use new_paragraph instead of check_end_layout because the stuff
1084 // following the noweb chunk needs to start with a \begin_layout.
1085 // This may create a new paragraph even if there was none in the
1086 // noweb file, but the alternative is an invalid LyX file. Since
1087 // noweb code chunks are implemented with a layout style in LyX they
1088 // always must be in an own paragraph.
1089 context.new_paragraph(os);
1090 Context newcontext(true, context.textclass,
1091 context.textclass[from_ascii("Scrap")]);
1092 newcontext.check_layout(os);
1095 Token const & t = p.get_token();
1096 // We abuse the parser a bit, because this is no TeX syntax
1098 if (t.cat() == catEscape)
1099 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1101 os << subst(t.asInput(), "\n", "\n\\newline\n");
1102 // The scrap chunk is ended by an @ at the beginning of a line.
1103 // After the @ the line may contain a comment and/or
1104 // whitespace, but nothing else.
1105 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1106 (p.next_token().cat() == catSpace ||
1107 p.next_token().cat() == catNewline ||
1108 p.next_token().cat() == catComment)) {
1109 while (p.good() && p.next_token().cat() == catSpace)
1110 os << p.get_token().asInput();
1111 if (p.next_token().cat() == catComment)
1112 // The comment includes a final '\n'
1113 os << p.get_token().asInput();
1115 if (p.next_token().cat() == catNewline)
1122 newcontext.check_end_layout(os);
1125 } // anonymous namespace
1128 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1131 LayoutPtr newlayout;
1132 // store the current selectlanguage to be used after \foreignlanguage
1134 // Store the latest bibliographystyle (needed for bibtex inset)
1135 string bibliographystyle;
1136 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1137 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1139 Token const & t = p.get_token();
1142 cerr << "t: " << t << " flags: " << flags << "\n";
1145 if (flags & FLAG_ITEM) {
1146 if (t.cat() == catSpace)
1149 flags &= ~FLAG_ITEM;
1150 if (t.cat() == catBegin) {
1151 // skip the brace and collect everything to the next matching
1153 flags |= FLAG_BRACE_LAST;
1157 // handle only this single token, leave the loop if done
1158 flags |= FLAG_LEAVE;
1161 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1167 if (t.cat() == catMath) {
1168 // we are inside some text mode thingy, so opening new math is allowed
1169 context.check_layout(os);
1170 begin_inset(os, "Formula ");
1171 Token const & n = p.get_token();
1172 if (n.cat() == catMath && outer) {
1173 // TeX's $$...$$ syntax for displayed math
1175 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1177 p.get_token(); // skip the second '$' token
1179 // simple $...$ stuff
1182 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1188 else if (t.cat() == catSuper || t.cat() == catSub)
1189 cerr << "catcode " << t << " illegal in text mode\n";
1191 // Basic support for english quotes. This should be
1192 // extended to other quotes, but is not so easy (a
1193 // left english quote is the same as a right german
1195 else if (t.asInput() == "`"
1196 && p.next_token().asInput() == "`") {
1197 context.check_layout(os);
1198 begin_inset(os, "Quotes ");
1204 else if (t.asInput() == "'"
1205 && p.next_token().asInput() == "'") {
1206 context.check_layout(os);
1207 begin_inset(os, "Quotes ");
1214 else if (t.asInput() == "<"
1215 && p.next_token().asInput() == "<" && noweb_mode) {
1217 parse_noweb(p, os, context);
1220 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1221 check_space(p, os, context);
1223 else if (t.character() == '[' && noweb_mode &&
1224 p.next_token().character() == '[') {
1225 // These can contain underscores
1227 string const s = p.getFullOpt() + ']';
1228 if (p.next_token().character() == ']')
1231 cerr << "Warning: Inserting missing ']' in '"
1232 << s << "'." << endl;
1233 handle_ert(os, s, context);
1236 else if (t.cat() == catLetter ||
1237 t.cat() == catOther ||
1238 t.cat() == catAlign ||
1239 t.cat() == catParameter) {
1240 // This translates "&" to "\\&" which may be wrong...
1241 context.check_layout(os);
1242 os << t.character();
1245 else if (p.isParagraph()) {
1246 if (context.new_layout_allowed)
1247 context.new_paragraph(os);
1249 handle_ert(os, "\\par ", context);
1250 eat_whitespace(p, os, context, true);
1253 else if (t.cat() == catActive) {
1254 context.check_layout(os);
1255 if (t.character() == '~') {
1256 if (context.layout->free_spacing)
1259 os << "\\InsetSpace ~\n";
1261 os << t.character();
1264 else if (t.cat() == catBegin &&
1265 p.next_token().cat() == catEnd) {
1267 Token const prev = p.prev_token();
1269 if (p.next_token().character() == '`' ||
1270 (prev.character() == '-' &&
1271 p.next_token().character() == '-'))
1272 ; // ignore it in {}`` or -{}-
1274 handle_ert(os, "{}", context);
1278 else if (t.cat() == catBegin) {
1279 context.check_layout(os);
1280 // special handling of font attribute changes
1281 Token const prev = p.prev_token();
1282 Token const next = p.next_token();
1283 TeXFont const oldFont = context.font;
1284 if (next.character() == '[' ||
1285 next.character() == ']' ||
1286 next.character() == '*') {
1288 if (p.next_token().cat() == catEnd) {
1289 os << next.character();
1293 handle_ert(os, "{", context);
1294 parse_text_snippet(p, os,
1297 handle_ert(os, "}", context);
1299 } else if (! context.new_layout_allowed) {
1300 handle_ert(os, "{", context);
1301 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1303 handle_ert(os, "}", context);
1304 } else if (is_known(next.cs(), known_sizes)) {
1305 // next will change the size, so we must
1307 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1309 if (!context.atParagraphStart())
1311 << context.font.size << "\n";
1312 } else if (is_known(next.cs(), known_font_families)) {
1313 // next will change the font family, so we
1314 // must reset it here
1315 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1317 if (!context.atParagraphStart())
1319 << context.font.family << "\n";
1320 } else if (is_known(next.cs(), known_font_series)) {
1321 // next will change the font series, so we
1322 // must reset it here
1323 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1325 if (!context.atParagraphStart())
1327 << context.font.series << "\n";
1328 } else if (is_known(next.cs(), known_font_shapes)) {
1329 // next will change the font shape, so we
1330 // must reset it here
1331 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1333 if (!context.atParagraphStart())
1335 << context.font.shape << "\n";
1336 } else if (is_known(next.cs(), known_old_font_families) ||
1337 is_known(next.cs(), known_old_font_series) ||
1338 is_known(next.cs(), known_old_font_shapes)) {
1339 // next will change the font family, series
1340 // and shape, so we must reset it here
1341 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1343 if (!context.atParagraphStart())
1345 << context.font.family
1347 << context.font.series
1349 << context.font.shape << "\n";
1351 handle_ert(os, "{", context);
1352 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1354 handle_ert(os, "}", context);
1358 else if (t.cat() == catEnd) {
1359 if (flags & FLAG_BRACE_LAST) {
1362 cerr << "stray '}' in text\n";
1363 handle_ert(os, "}", context);
1366 else if (t.cat() == catComment)
1367 parse_comment(p, os, t, context);
1370 // control sequences
1373 else if (t.cs() == "(") {
1374 context.check_layout(os);
1375 begin_inset(os, "Formula");
1377 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1382 else if (t.cs() == "[") {
1383 context.check_layout(os);
1384 begin_inset(os, "Formula");
1386 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1391 else if (t.cs() == "begin")
1392 parse_environment(p, os, outer, context);
1394 else if (t.cs() == "end") {
1395 if (flags & FLAG_END) {
1396 // eat environment name
1397 string const name = p.getArg('{', '}');
1398 if (name != active_environment())
1399 cerr << "\\end{" + name + "} does not match \\begin{"
1400 + active_environment() + "}\n";
1403 p.error("found 'end' unexpectedly");
1406 else if (t.cs() == "item") {
1409 bool optarg = false;
1410 if (p.next_token().character() == '[') {
1411 p.get_token(); // eat '['
1412 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1417 context.check_layout(os);
1418 if (context.has_item) {
1419 // An item in an unknown list-like environment
1420 // FIXME: Do this in check_layout()!
1421 context.has_item = false;
1423 handle_ert(os, "\\item", context);
1425 handle_ert(os, "\\item ", context);
1428 if (context.layout->labeltype != LABEL_MANUAL) {
1429 // lyx does not support \item[\mybullet]
1430 // in itemize environments
1431 handle_ert(os, "[", context);
1433 handle_ert(os, "]", context);
1434 } else if (!s.empty()) {
1435 // The space is needed to separate the
1436 // item from the rest of the sentence.
1438 eat_whitespace(p, os, context, false);
1443 else if (t.cs() == "bibitem") {
1445 context.check_layout(os);
1448 os << '{' << p.verbatim_item() << '}' << "\n";
1451 else if (t.cs() == "def") {
1452 context.check_layout(os);
1453 eat_whitespace(p, os, context, false);
1454 string name = p.get_token().cs();
1455 eat_whitespace(p, os, context, false);
1461 while (p.next_token().cat() != catBegin) {
1462 if (p.next_token().cat() == catParameter) {
1467 // followed by number?
1468 if (p.next_token().cat() == catOther) {
1469 char c = p.getChar();
1471 // number = current arity + 1?
1472 if (c == arity + '0' + 1)
1477 paramtext += p.get_token().asString();
1479 paramtext += p.get_token().asString();
1484 // only output simple (i.e. compatible) macro as FormulaMacros
1485 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1487 context.check_layout(os);
1488 begin_inset(os, "FormulaMacro");
1492 handle_ert(os, ert, context);
1495 else if (t.cs() == "noindent") {
1497 context.add_extra_stuff("\\noindent\n");
1500 else if (t.cs() == "appendix") {
1501 context.add_extra_stuff("\\start_of_appendix\n");
1502 // We need to start a new paragraph. Otherwise the
1503 // appendix in 'bla\appendix\chapter{' would start
1505 context.new_paragraph(os);
1506 // We need to make sure that the paragraph is
1507 // generated even if it is empty. Otherwise the
1508 // appendix in '\par\appendix\par\chapter{' would
1510 context.check_layout(os);
1511 // FIXME: This is a hack to prevent paragraph
1512 // deletion if it is empty. Handle this better!
1514 "%dummy comment inserted by tex2lyx to "
1515 "ensure that this paragraph is not empty",
1517 // Both measures above may generate an additional
1518 // empty paragraph, but that does not hurt, because
1519 // whitespace does not matter here.
1520 eat_whitespace(p, os, context, true);
1523 // Must attempt to parse "Section*" before "Section".
1524 else if ((p.next_token().asInput() == "*") &&
1525 context.new_layout_allowed &&
1526 // The single '=' is meant here.
1527 (newlayout = findLayout(context.textclass,
1528 t.cs() + '*')).get() &&
1529 newlayout->isCommand()) {
1531 output_command_layout(os, p, outer, context, newlayout);
1535 // The single '=' is meant here.
1536 else if (context.new_layout_allowed &&
1537 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1538 newlayout->isCommand()) {
1539 output_command_layout(os, p, outer, context, newlayout);
1543 // Special handling for \caption
1544 // FIXME: remove this when InsetCaption is supported.
1545 else if (context.new_layout_allowed &&
1546 t.cs() == captionlayout->latexname()) {
1547 output_command_layout(os, p, outer, context,
1552 else if (t.cs() == "includegraphics") {
1553 bool const clip = p.next_token().asInput() == "*";
1556 map<string, string> opts = split_map(p.getArg('[', ']'));
1558 opts["clip"] = string();
1559 string name = normalize_filename(p.verbatim_item());
1561 string const path = getMasterFilePath();
1562 // We want to preserve relative / absolute filenames,
1563 // therefore path is only used for testing
1564 // FIXME UNICODE encoding of name and path may be
1565 // wrong (makeAbsPath expects utf8)
1566 if (!makeAbsPath(name, path).exists()) {
1567 // The file extension is probably missing.
1568 // Now try to find it out.
1569 string const dvips_name =
1570 find_file(name, path,
1571 known_dvips_graphics_formats);
1572 string const pdftex_name =
1573 find_file(name, path,
1574 known_pdftex_graphics_formats);
1575 if (!dvips_name.empty()) {
1576 if (!pdftex_name.empty()) {
1577 cerr << "This file contains the "
1579 "\"\\includegraphics{"
1581 "However, files\n\""
1582 << dvips_name << "\" and\n\""
1583 << pdftex_name << "\"\n"
1584 "both exist, so I had to make a "
1585 "choice and took the first one.\n"
1586 "Please move the unwanted one "
1587 "someplace else and try again\n"
1588 "if my choice was wrong."
1592 } else if (!pdftex_name.empty())
1596 // FIXME UNICODE encoding of name and path may be
1597 // wrong (makeAbsPath expects utf8)
1598 if (makeAbsPath(name, path).exists())
1599 fix_relative_filename(name);
1601 cerr << "Warning: Could not find graphics file '"
1602 << name << "'." << endl;
1604 context.check_layout(os);
1605 begin_inset(os, "Graphics ");
1606 os << "\n\tfilename " << name << '\n';
1607 if (opts.find("width") != opts.end())
1609 << translate_len(opts["width"]) << '\n';
1610 if (opts.find("height") != opts.end())
1612 << translate_len(opts["height"]) << '\n';
1613 if (opts.find("scale") != opts.end()) {
1614 istringstream iss(opts["scale"]);
1618 os << "\tscale " << val << '\n';
1620 if (opts.find("angle") != opts.end())
1621 os << "\trotateAngle "
1622 << opts["angle"] << '\n';
1623 if (opts.find("origin") != opts.end()) {
1625 string const opt = opts["origin"];
1626 if (opt.find('l') != string::npos) ss << "left";
1627 if (opt.find('r') != string::npos) ss << "right";
1628 if (opt.find('c') != string::npos) ss << "center";
1629 if (opt.find('t') != string::npos) ss << "Top";
1630 if (opt.find('b') != string::npos) ss << "Bottom";
1631 if (opt.find('B') != string::npos) ss << "Baseline";
1632 if (!ss.str().empty())
1633 os << "\trotateOrigin " << ss.str() << '\n';
1635 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1637 if (opts.find("keepaspectratio") != opts.end())
1638 os << "\tkeepAspectRatio\n";
1639 if (opts.find("clip") != opts.end())
1641 if (opts.find("draft") != opts.end())
1643 if (opts.find("bb") != opts.end())
1644 os << "\tBoundingBox "
1645 << opts["bb"] << '\n';
1646 int numberOfbbOptions = 0;
1647 if (opts.find("bbllx") != opts.end())
1648 numberOfbbOptions++;
1649 if (opts.find("bblly") != opts.end())
1650 numberOfbbOptions++;
1651 if (opts.find("bburx") != opts.end())
1652 numberOfbbOptions++;
1653 if (opts.find("bbury") != opts.end())
1654 numberOfbbOptions++;
1655 if (numberOfbbOptions == 4)
1656 os << "\tBoundingBox "
1657 << opts["bbllx"] << opts["bblly"]
1658 << opts["bburx"] << opts["bbury"] << '\n';
1659 else if (numberOfbbOptions > 0)
1660 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1661 numberOfbbOptions = 0;
1662 if (opts.find("natwidth") != opts.end())
1663 numberOfbbOptions++;
1664 if (opts.find("natheight") != opts.end())
1665 numberOfbbOptions++;
1666 if (numberOfbbOptions == 2)
1667 os << "\tBoundingBox 0bp 0bp "
1668 << opts["natwidth"] << opts["natheight"] << '\n';
1669 else if (numberOfbbOptions > 0)
1670 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1671 ostringstream special;
1672 if (opts.find("hiresbb") != opts.end())
1673 special << "hiresbb,";
1674 if (opts.find("trim") != opts.end())
1676 if (opts.find("viewport") != opts.end())
1677 special << "viewport=" << opts["viewport"] << ',';
1678 if (opts.find("totalheight") != opts.end())
1679 special << "totalheight=" << opts["totalheight"] << ',';
1680 if (opts.find("type") != opts.end())
1681 special << "type=" << opts["type"] << ',';
1682 if (opts.find("ext") != opts.end())
1683 special << "ext=" << opts["ext"] << ',';
1684 if (opts.find("read") != opts.end())
1685 special << "read=" << opts["read"] << ',';
1686 if (opts.find("command") != opts.end())
1687 special << "command=" << opts["command"] << ',';
1688 string s_special = special.str();
1689 if (!s_special.empty()) {
1690 // We had special arguments. Remove the trailing ','.
1691 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1693 // TODO: Handle the unknown settings better.
1694 // Warn about invalid options.
1695 // Check whether some option was given twice.
1699 else if (t.cs() == "footnote" ||
1700 (t.cs() == "thanks" && context.layout->intitle)) {
1702 context.check_layout(os);
1703 begin_inset(os, "Foot\n");
1704 os << "status collapsed\n\n";
1705 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1709 else if (t.cs() == "marginpar") {
1711 context.check_layout(os);
1712 begin_inset(os, "Marginal\n");
1713 os << "status collapsed\n\n";
1714 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1718 else if (t.cs() == "ensuremath") {
1720 context.check_layout(os);
1721 string const s = p.verbatim_item();
1722 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1725 handle_ert(os, "\\ensuremath{" + s + "}",
1729 else if (t.cs() == "hfill") {
1730 context.check_layout(os);
1731 os << "\n\\hfill\n";
1736 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1737 // FIXME: Somehow prevent title layouts if
1738 // "maketitle" was not found
1740 skip_braces(p); // swallow this
1743 else if (t.cs() == "tableofcontents") {
1745 context.check_layout(os);
1746 begin_inset(os, "CommandInset toc\n");
1747 os << "LatexCommand tableofcontents\n";
1749 skip_braces(p); // swallow this
1752 else if (t.cs() == "listoffigures") {
1754 context.check_layout(os);
1755 begin_inset(os, "FloatList figure\n");
1757 skip_braces(p); // swallow this
1760 else if (t.cs() == "listoftables") {
1762 context.check_layout(os);
1763 begin_inset(os, "FloatList table\n");
1765 skip_braces(p); // swallow this
1768 else if (t.cs() == "listof") {
1769 p.skip_spaces(true);
1770 string const name = p.verbatim_item();
1771 string const name2 = subst(p.verbatim_item(), "\n", " ");
1772 if (context.textclass.floats().typeExist(name)) {
1773 context.check_layout(os);
1774 begin_inset(os, "FloatList ");
1777 // the second argument is not needed
1779 handle_ert(os, "\\listof{" + name + "}{" + name2 + "}", context);
1782 else if (t.cs() == "textrm")
1783 parse_text_attributes(p, os, FLAG_ITEM, outer,
1784 context, "\\family",
1785 context.font.family, "roman");
1787 else if (t.cs() == "textsf")
1788 parse_text_attributes(p, os, FLAG_ITEM, outer,
1789 context, "\\family",
1790 context.font.family, "sans");
1792 else if (t.cs() == "texttt")
1793 parse_text_attributes(p, os, FLAG_ITEM, outer,
1794 context, "\\family",
1795 context.font.family, "typewriter");
1797 else if (t.cs() == "textmd")
1798 parse_text_attributes(p, os, FLAG_ITEM, outer,
1799 context, "\\series",
1800 context.font.series, "medium");
1802 else if (t.cs() == "textbf")
1803 parse_text_attributes(p, os, FLAG_ITEM, outer,
1804 context, "\\series",
1805 context.font.series, "bold");
1807 else if (t.cs() == "textup")
1808 parse_text_attributes(p, os, FLAG_ITEM, outer,
1810 context.font.shape, "up");
1812 else if (t.cs() == "textit")
1813 parse_text_attributes(p, os, FLAG_ITEM, outer,
1815 context.font.shape, "italic");
1817 else if (t.cs() == "textsl")
1818 parse_text_attributes(p, os, FLAG_ITEM, outer,
1820 context.font.shape, "slanted");
1822 else if (t.cs() == "textsc")
1823 parse_text_attributes(p, os, FLAG_ITEM, outer,
1825 context.font.shape, "smallcaps");
1827 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1828 context.check_layout(os);
1829 TeXFont oldFont = context.font;
1830 context.font.init();
1831 context.font.size = oldFont.size;
1832 os << "\n\\family " << context.font.family << "\n";
1833 os << "\n\\series " << context.font.series << "\n";
1834 os << "\n\\shape " << context.font.shape << "\n";
1835 if (t.cs() == "textnormal") {
1836 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1837 output_font_change(os, context.font, oldFont);
1838 context.font = oldFont;
1840 eat_whitespace(p, os, context, false);
1843 else if (t.cs() == "underbar") {
1844 // Do NOT handle \underline.
1845 // \underbar cuts through y, g, q, p etc.,
1846 // \underline does not.
1847 context.check_layout(os);
1848 os << "\n\\bar under\n";
1849 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1850 context.check_layout(os);
1851 os << "\n\\bar default\n";
1854 else if (t.cs() == "emph" || t.cs() == "noun") {
1855 context.check_layout(os);
1856 os << "\n\\" << t.cs() << " on\n";
1857 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1858 context.check_layout(os);
1859 os << "\n\\" << t.cs() << " default\n";
1862 else if (use_natbib &&
1863 is_known(t.cs(), known_natbib_commands) &&
1864 ((t.cs() != "citefullauthor" &&
1865 t.cs() != "citeyear" &&
1866 t.cs() != "citeyearpar") ||
1867 p.next_token().asInput() != "*")) {
1868 context.check_layout(os);
1870 // \citet[before][after]{a} \citet[after][before]{a}
1871 // \citet[before][]{a} \citet[][before]{a}
1872 // \citet[after]{a} \citet[after]{a}
1873 // \citet{a} \citet{a}
1874 string command = '\\' + t.cs();
1875 if (p.next_token().asInput() == "*") {
1879 if (command == "\\citefullauthor")
1880 // alternative name for "\\citeauthor*"
1881 command = "\\citeauthor*";
1883 // text before the citation
1885 // text after the citation
1888 boost::tie(before, after) = getCiteArguments(p, true);
1889 if (command == "\\cite") {
1890 // \cite without optional argument means
1891 // \citet, \cite with at least one optional
1892 // argument means \citep.
1893 if (before.empty() && after.empty())
1894 command = "\\citet";
1896 command = "\\citep";
1898 if (before.empty() && after == "[]")
1899 // avoid \citet[]{a}
1901 else if (before == "[]" && after == "[]") {
1902 // avoid \citet[][]{a}
1906 begin_inset(os, "LatexCommand ");
1907 os << command << after << before
1908 << '{' << p.verbatim_item() << "}\n";
1912 else if (use_jurabib &&
1913 is_known(t.cs(), known_jurabib_commands)) {
1914 context.check_layout(os);
1915 string const command = '\\' + t.cs();
1916 char argumentOrder = '\0';
1917 vector<string> const & options = used_packages["jurabib"];
1918 if (std::find(options.begin(), options.end(),
1919 "natbiborder") != options.end())
1920 argumentOrder = 'n';
1921 else if (std::find(options.begin(), options.end(),
1922 "jurabiborder") != options.end())
1923 argumentOrder = 'j';
1925 // text before the citation
1927 // text after the citation
1930 boost::tie(before, after) =
1931 getCiteArguments(p, argumentOrder != 'j');
1932 string const citation = p.verbatim_item();
1933 if (!before.empty() && argumentOrder == '\0') {
1934 cerr << "Warning: Assuming argument order "
1935 "of jurabib version 0.6 for\n'"
1936 << command << before << after << '{'
1937 << citation << "}'.\n"
1938 "Add 'jurabiborder' to the jurabib "
1939 "package options if you used an\n"
1940 "earlier jurabib version." << endl;
1942 begin_inset(os, "LatexCommand ");
1943 os << command << after << before
1944 << '{' << citation << "}\n";
1948 else if (is_known(t.cs(), known_latex_commands)) {
1949 // This needs to be after the check for natbib and
1950 // jurabib commands, because "cite" has different
1951 // arguments with natbib and jurabib.
1952 context.check_layout(os);
1953 begin_inset(os, "LatexCommand ");
1954 os << '\\' << t.cs();
1955 // lyx cannot handle newlines in a latex command
1956 // FIXME: Move the substitution into parser::getOpt()?
1957 os << subst(p.getOpt(), "\n", " ");
1958 os << subst(p.getOpt(), "\n", " ");
1959 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1963 else if (is_known(t.cs(), known_quotes)) {
1964 char const * const * where = is_known(t.cs(), known_quotes);
1965 context.check_layout(os);
1966 begin_inset(os, "Quotes ");
1967 os << known_coded_quotes[where - known_quotes];
1969 // LyX adds {} after the quote, so we have to eat
1970 // spaces here if there are any before a possible
1972 eat_whitespace(p, os, context, false);
1976 else if (is_known(t.cs(), known_sizes) &&
1977 context.new_layout_allowed) {
1978 char const * const * where = is_known(t.cs(), known_sizes);
1979 context.check_layout(os);
1980 TeXFont const oldFont = context.font;
1981 context.font.size = known_coded_sizes[where - known_sizes];
1982 output_font_change(os, oldFont, context.font);
1983 eat_whitespace(p, os, context, false);
1986 else if (is_known(t.cs(), known_font_families) &&
1987 context.new_layout_allowed) {
1988 char const * const * where =
1989 is_known(t.cs(), known_font_families);
1990 context.check_layout(os);
1991 TeXFont const oldFont = context.font;
1992 context.font.family =
1993 known_coded_font_families[where - known_font_families];
1994 output_font_change(os, oldFont, context.font);
1995 eat_whitespace(p, os, context, false);
1998 else if (is_known(t.cs(), known_font_series) &&
1999 context.new_layout_allowed) {
2000 char const * const * where =
2001 is_known(t.cs(), known_font_series);
2002 context.check_layout(os);
2003 TeXFont const oldFont = context.font;
2004 context.font.series =
2005 known_coded_font_series[where - known_font_series];
2006 output_font_change(os, oldFont, context.font);
2007 eat_whitespace(p, os, context, false);
2010 else if (is_known(t.cs(), known_font_shapes) &&
2011 context.new_layout_allowed) {
2012 char const * const * where =
2013 is_known(t.cs(), known_font_shapes);
2014 context.check_layout(os);
2015 TeXFont const oldFont = context.font;
2016 context.font.shape =
2017 known_coded_font_shapes[where - known_font_shapes];
2018 output_font_change(os, oldFont, context.font);
2019 eat_whitespace(p, os, context, false);
2021 else if (is_known(t.cs(), known_old_font_families) &&
2022 context.new_layout_allowed) {
2023 char const * const * where =
2024 is_known(t.cs(), known_old_font_families);
2025 context.check_layout(os);
2026 TeXFont const oldFont = context.font;
2027 context.font.init();
2028 context.font.size = oldFont.size;
2029 context.font.family =
2030 known_coded_font_families[where - known_old_font_families];
2031 output_font_change(os, oldFont, context.font);
2032 eat_whitespace(p, os, context, false);
2035 else if (is_known(t.cs(), known_old_font_series) &&
2036 context.new_layout_allowed) {
2037 char const * const * where =
2038 is_known(t.cs(), known_old_font_series);
2039 context.check_layout(os);
2040 TeXFont const oldFont = context.font;
2041 context.font.init();
2042 context.font.size = oldFont.size;
2043 context.font.series =
2044 known_coded_font_series[where - known_old_font_series];
2045 output_font_change(os, oldFont, context.font);
2046 eat_whitespace(p, os, context, false);
2049 else if (is_known(t.cs(), known_old_font_shapes) &&
2050 context.new_layout_allowed) {
2051 char const * const * where =
2052 is_known(t.cs(), known_old_font_shapes);
2053 context.check_layout(os);
2054 TeXFont const oldFont = context.font;
2055 context.font.init();
2056 context.font.size = oldFont.size;
2057 context.font.shape =
2058 known_coded_font_shapes[where - known_old_font_shapes];
2059 output_font_change(os, oldFont, context.font);
2060 eat_whitespace(p, os, context, false);
2063 else if (t.cs() == "selectlanguage") {
2064 context.check_layout(os);
2065 // save the language for the case that a \foreignlanguage is used
2066 selectlang = subst(p.verbatim_item(), "\n", " ");
2067 os << "\\lang " << selectlang << "\n";
2071 else if (t.cs() == "foreignlanguage") {
2072 context.check_layout(os);
2073 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2074 os << subst(p.verbatim_item(), "\n", " ");
2075 // set back to last selectlanguage
2076 os << "\n\\lang " << selectlang << "\n";
2079 else if (t.cs() == "inputencoding")
2080 // write nothing because this is done by LyX using the "\lang"
2081 // information given by selectlanguage and foreignlanguage
2082 subst(p.verbatim_item(), "\n", " ");
2084 else if (t.cs() == "LyX" || t.cs() == "TeX"
2085 || t.cs() == "LaTeX") {
2086 context.check_layout(os);
2088 skip_braces(p); // eat {}
2091 else if (t.cs() == "LaTeXe") {
2092 context.check_layout(os);
2094 skip_braces(p); // eat {}
2097 else if (t.cs() == "ldots") {
2098 context.check_layout(os);
2100 os << "\\SpecialChar \\ldots{}\n";
2103 else if (t.cs() == "lyxarrow") {
2104 context.check_layout(os);
2105 os << "\\SpecialChar \\menuseparator\n";
2109 else if (t.cs() == "lyxline") {
2110 context.check_layout(os);
2111 // the argument can be omitted, is handled by LyX
2112 subst(p.verbatim_item(), "\n", " ");
2113 os << "\\lyxline\n ";
2117 else if (t.cs() == "textcompwordmark") {
2118 context.check_layout(os);
2119 os << "\\SpecialChar \\textcompwordmark{}\n";
2123 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2124 context.check_layout(os);
2125 os << "\\SpecialChar \\@.\n";
2129 else if (t.cs() == "-") {
2130 context.check_layout(os);
2131 os << "\\SpecialChar \\-\n";
2134 else if (t.cs() == "textasciitilde") {
2135 context.check_layout(os);
2140 else if (t.cs() == "textasciicircum") {
2141 context.check_layout(os);
2146 else if (t.cs() == "textbackslash") {
2147 context.check_layout(os);
2148 os << "\n\\backslash\n";
2152 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2153 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2155 context.check_layout(os);
2159 else if (t.cs() == "char") {
2160 context.check_layout(os);
2161 if (p.next_token().character() == '`') {
2163 if (p.next_token().cs() == "\"") {
2168 handle_ert(os, "\\char`", context);
2171 handle_ert(os, "\\char", context);
2175 else if (t.cs() == "verb") {
2176 context.check_layout(os);
2177 char const delimiter = p.next_token().character();
2178 string const arg = p.getArg(delimiter, delimiter);
2180 oss << "\\verb" << delimiter << arg << delimiter;
2181 handle_ert(os, oss.str(), context);
2184 else if (t.cs() == "\"") {
2185 context.check_layout(os);
2186 string const name = p.verbatim_item();
2187 if (name == "a") os << '\xe4';
2188 else if (name == "o") os << '\xf6';
2189 else if (name == "u") os << '\xfc';
2190 else if (name == "A") os << '\xc4';
2191 else if (name == "O") os << '\xd6';
2192 else if (name == "U") os << '\xdc';
2193 else handle_ert(os, "\"{" + name + "}", context);
2196 // Problem: \= creates a tabstop inside the tabbing environment
2197 // and else an accent. In the latter case we really would want
2198 // \={o} instead of \= o.
2199 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2200 handle_ert(os, t.asInput(), context);
2202 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2203 || t.cs() == "'" || t.cs() == "`"
2204 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2205 // we need the trim as the LyX parser chokes on such spaces
2206 // The argument of InsetLatexAccent is parsed as a
2207 // subset of LaTeX, so don't parse anything here,
2208 // but use the raw argument.
2209 // Otherwise we would convert \~{\i} wrongly.
2210 // This will of course not translate \~{\ss} to \~{ß},
2211 // but that does at least compile and does only look
2212 // strange on screen.
2213 context.check_layout(os);
2214 os << "\\i \\" << t.cs() << "{"
2215 << trim(p.verbatim_item(), " ")
2219 else if (t.cs() == "ss") {
2220 context.check_layout(os);
2222 skip_braces(p); // eat {}
2225 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2227 context.check_layout(os);
2228 os << "\\i \\" << t.cs() << "{}\n";
2229 skip_braces(p); // eat {}
2232 else if (t.cs() == "\\") {
2233 context.check_layout(os);
2234 string const next = p.next_token().asInput();
2236 handle_ert(os, "\\\\" + p.getOpt(), context);
2237 else if (next == "*") {
2239 handle_ert(os, "\\\\*" + p.getOpt(), context);
2242 os << "\n\\newline\n";
2246 else if (t.cs() == "newline" ||
2247 t.cs() == "linebreak") {
2248 context.check_layout(os);
2249 os << "\n\\" << t.cs() << "\n";
2250 skip_braces(p); // eat {}
2253 else if (t.cs() == "href") {
2254 context.check_layout(os);
2255 begin_inset(os, "CommandInset ");
2256 os << t.cs() << "\n";
2257 os << "LatexCommand " << t.cs() << "\n";
2260 // the first argument is "type:target", "type:" is optional
2261 // the second argument the name
2262 string href_target = subst(p.verbatim_item(), "\n", " ");
2263 string href_name = subst(p.verbatim_item(), "\n", " ");
2265 // serach for the ":" to divide type from target
2266 if ((pos = href_target.find(":", 0)) != string::npos){
2267 href_type = href_target;
2268 href_type.erase(pos + 1, href_type.length());
2269 href_target.erase(0, pos + 1);
2272 os << "name " << '"' << href_name << '"' << "\n";
2273 os << "target " << '"' << href_target << '"' << "\n";
2275 os << "type " << '"' << href_type << '"' << "\n";
2279 else if (t.cs() == "input" || t.cs() == "include"
2280 || t.cs() == "verbatiminput") {
2281 string name = '\\' + t.cs();
2282 if (t.cs() == "verbatiminput"
2283 && p.next_token().asInput() == "*")
2284 name += p.get_token().asInput();
2285 context.check_layout(os);
2286 begin_inset(os, "Include ");
2287 string filename(normalize_filename(p.getArg('{', '}')));
2288 string const path = getMasterFilePath();
2289 // We want to preserve relative / absolute filenames,
2290 // therefore path is only used for testing
2291 // FIXME UNICODE encoding of filename and path may be
2292 // wrong (makeAbsPath expects utf8)
2293 if ((t.cs() == "include" || t.cs() == "input") &&
2294 !makeAbsPath(filename, path).exists()) {
2295 // The file extension is probably missing.
2296 // Now try to find it out.
2297 string const tex_name =
2298 find_file(filename, path,
2299 known_tex_extensions);
2300 if (!tex_name.empty())
2301 filename = tex_name;
2303 // FIXME UNICODE encoding of filename and path may be
2304 // wrong (makeAbsPath expects utf8)
2305 if (makeAbsPath(filename, path).exists()) {
2306 string const abstexname =
2307 makeAbsPath(filename, path).absFilename();
2308 string const abslyxname =
2309 changeExtension(abstexname, ".lyx");
2310 fix_relative_filename(filename);
2311 string const lyxname =
2312 changeExtension(filename, ".lyx");
2313 if (t.cs() != "verbatiminput" &&
2314 tex2lyx(abstexname, FileName(abslyxname))) {
2315 os << name << '{' << lyxname << "}\n";
2317 os << name << '{' << filename << "}\n";
2320 cerr << "Warning: Could not find included file '"
2321 << filename << "'." << endl;
2322 os << name << '{' << filename << "}\n";
2324 os << "preview false\n";
2328 else if (t.cs() == "bibliographystyle") {
2329 // store new bibliographystyle
2330 bibliographystyle = p.verbatim_item();
2331 // output new bibliographystyle.
2332 // This is only necessary if used in some other macro than \bibliography.
2333 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2336 else if (t.cs() == "bibliography") {
2337 context.check_layout(os);
2338 begin_inset(os, "CommandInset bibtex");
2339 os << "\nLatexCommand bibtex";
2340 // Do we have a bibliographystyle set?
2341 if (!bibliographystyle.empty())
2342 os << "\noptions " << '"' << bibliographystyle << '"';
2343 os << "\nbibfiles " << '"' << p.verbatim_item() << '"';
2347 else if (t.cs() == "printindex") {
2348 context.check_layout(os);
2349 begin_inset(os, "CommandInset index_print\n");
2350 os << "LatexCommand printindex";
2355 else if (t.cs() == "printnomenclature") {
2356 context.check_layout(os);
2357 begin_inset(os, "CommandInset nomencl_print\n");
2358 os << "LatexCommand printnomenclature";
2363 else if (t.cs() == "parbox")
2364 parse_box(p, os, FLAG_ITEM, outer, context, true);
2366 else if (t.cs() == "smallskip" ||
2367 t.cs() == "medskip" ||
2368 t.cs() == "bigskip" ||
2369 t.cs() == "vfill") {
2370 context.check_layout(os);
2371 begin_inset(os, "VSpace ");
2377 else if (is_known(t.cs(), known_spaces)) {
2378 char const * const * where = is_known(t.cs(), known_spaces);
2379 context.check_layout(os);
2380 begin_inset(os, "InsetSpace ");
2381 os << '\\' << known_coded_spaces[where - known_spaces]
2383 // LaTeX swallows whitespace after all spaces except
2384 // "\\,". We have to do that here, too, because LyX
2385 // adds "{}" which would make the spaces significant.
2387 eat_whitespace(p, os, context, false);
2388 // LyX adds "{}" after all spaces except "\\ " and
2389 // "\\,", so we have to remove "{}".
2390 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2391 // remove the braces after "\\,", too.
2396 else if (t.cs() == "newpage" ||
2397 t.cs() == "pagebreak" ||
2398 t.cs() == "clearpage" ||
2399 t.cs() == "cleardoublepage") {
2400 context.check_layout(os);
2401 os << "\n\\" << t.cs() << "\n";
2402 skip_braces(p); // eat {}
2405 else if (t.cs() == "newcommand" ||
2406 t.cs() == "providecommand" ||
2407 t.cs() == "renewcommand") {
2408 // these could be handled by parse_command(), but
2409 // we need to call add_known_command() here.
2410 string name = t.asInput();
2411 if (p.next_token().asInput() == "*") {
2412 // Starred form. Eat '*'
2416 string const command = p.verbatim_item();
2417 string const opt1 = p.getOpt();
2418 string const opt2 = p.getFullOpt();
2419 add_known_command(command, opt1, !opt2.empty());
2420 string const ert = name + '{' + command + '}' +
2422 '{' + p.verbatim_item() + '}';
2424 context.check_layout(os);
2425 begin_inset(os, "FormulaMacro");
2430 else if (t.cs() == "vspace") {
2431 bool starred = false;
2432 if (p.next_token().asInput() == "*") {
2436 string const length = p.verbatim_item();
2439 bool valid = splitLatexLength(length, valstring, unit);
2440 bool known_vspace = false;
2441 bool known_unit = false;
2444 istringstream iss(valstring);
2447 if (unit == "\\smallskipamount") {
2449 known_vspace = true;
2450 } else if (unit == "\\medskipamount") {
2452 known_vspace = true;
2453 } else if (unit == "\\bigskipamount") {
2455 known_vspace = true;
2456 } else if (unit == "\\fill") {
2458 known_vspace = true;
2461 if (!known_vspace) {
2462 switch (unitFromString(unit)) {
2483 if (known_unit || known_vspace) {
2484 // Literal length or known variable
2485 context.check_layout(os);
2486 begin_inset(os, "VSpace ");
2494 // LyX can't handle other length variables in Inset VSpace
2495 string name = t.asInput();
2500 handle_ert(os, name + '{' + unit + '}', context);
2501 else if (value == -1.0)
2502 handle_ert(os, name + "{-" + unit + '}', context);
2504 handle_ert(os, name + '{' + valstring + unit + '}', context);
2506 handle_ert(os, name + '{' + length + '}', context);
2511 //cerr << "#: " << t << " mode: " << mode << endl;
2512 // heuristic: read up to next non-nested space
2514 string s = t.asInput();
2515 string z = p.verbatim_item();
2516 while (p.good() && z != " " && z.size()) {
2517 //cerr << "read: " << z << endl;
2519 z = p.verbatim_item();
2521 cerr << "found ERT: " << s << endl;
2522 handle_ert(os, s + ' ', context);
2524 string name = t.asInput();
2525 if (p.next_token().asInput() == "*") {
2526 // Starred commands like \vspace*{}
2527 p.get_token(); // Eat '*'
2530 if (! parse_command(name, p, os, outer, context))
2531 handle_ert(os, name, context);
2534 if (flags & FLAG_LEAVE) {
2535 flags &= ~FLAG_LEAVE;