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.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "support/lassert.h"
28 #include "support/convert.h"
29 #include "support/FileName.h"
30 #include "support/filetools.h"
31 #include "support/lstrings.h"
32 #include "support/lyxtime.h"
41 using namespace lyx::support;
46 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
47 Context const & context, InsetLayout const * layout)
49 bool const forcePlainLayout =
50 layout ? layout->forcePlainLayout() : false;
51 Context newcontext(true, context.textclass);
53 newcontext.layout = &context.textclass.plainLayout();
55 newcontext.font = context.font;
56 parse_text(p, os, flags, outer, newcontext);
57 newcontext.check_end_layout(os);
63 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
64 Context const & context, string const & name)
66 InsetLayout const * layout = 0;
67 DocumentClass::InsetLayouts::const_iterator it =
68 context.textclass.insetLayouts().find(from_ascii(name));
69 if (it != context.textclass.insetLayouts().end())
70 layout = &(it->second);
71 parse_text_in_inset(p, os, flags, outer, context, layout);
74 /// parses a paragraph snippet, useful for example for \\emph{...}
75 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
78 Context newcontext(context);
79 // Don't inherit the paragraph-level extra stuff
80 newcontext.par_extra_stuff.clear();
81 parse_text(p, os, flags, outer, newcontext);
82 // Make sure that we don't create invalid .lyx files
83 context.need_layout = newcontext.need_layout;
84 context.need_end_layout = newcontext.need_end_layout;
89 * Thin wrapper around parse_text_snippet() using a string.
91 * We completely ignore \c context.need_layout and \c context.need_end_layout,
92 * because our return value is not used directly (otherwise the stream version
93 * of parse_text_snippet() could be used). That means that the caller needs
94 * to do layout management manually.
95 * This is intended to parse text that does not create any layout changes.
97 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
100 Context newcontext(context);
101 newcontext.need_layout = false;
102 newcontext.need_end_layout = false;
103 newcontext.new_layout_allowed = false;
104 // Avoid warning by Context::~Context()
105 newcontext.par_extra_stuff.clear();
107 parse_text_snippet(p, os, flags, outer, newcontext);
112 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
113 "vpageref", "prettyref", "eqref", 0 };
115 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
116 "vpageref", "formatted", "eqref", 0 };
120 * The starred forms are also known except for "citefullauthor",
121 * "citeyear" and "citeyearpar".
123 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
124 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
125 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
129 * No starred form other than "cite*" known.
131 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
132 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
133 // jurabib commands not (yet) supported by LyX:
135 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
136 // "footciteauthor", "footciteyear", "footciteyearpar",
137 "citefield", "citetitle", 0 };
139 /// LaTeX names for quotes
140 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
141 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
142 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
143 "guilsinglleft", "frq", "guilsinglright", 0};
145 /// the same as known_quotes with .lyx names
146 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
147 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
148 "gld", "grd", "gls", "ers", "fls",
149 "fls", "frs", "frs", 0};
151 /// LaTeX names for font sizes
152 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
153 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
155 /// the same as known_sizes with .lyx names
156 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
157 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
159 /// LaTeX 2.09 names for font families
160 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
162 /// LaTeX names for font families
163 char const * const known_font_families[] = { "rmfamily", "sffamily",
166 /// LaTeX names for font family changing commands
167 char const * const known_text_font_families[] = { "textrm", "textsf",
170 /// The same as known_old_font_families, known_font_families and
171 /// known_text_font_families with .lyx names
172 char const * const known_coded_font_families[] = { "roman", "sans",
175 /// LaTeX 2.09 names for font series
176 char const * const known_old_font_series[] = { "bf", 0};
178 /// LaTeX names for font series
179 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
181 /// LaTeX names for font series changing commands
182 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
184 /// The same as known_old_font_series, known_font_series and
185 /// known_text_font_series with .lyx names
186 char const * const known_coded_font_series[] = { "bold", "medium", 0};
188 /// LaTeX 2.09 names for font shapes
189 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
191 /// LaTeX names for font shapes
192 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
195 /// LaTeX names for font shape changing commands
196 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
199 /// The same as known_old_font_shapes, known_font_shapes and
200 /// known_text_font_shapes with .lyx names
201 char const * const known_coded_font_shapes[] = { "italic", "slanted",
202 "smallcaps", "up", 0};
204 /// Known special characters which need skip_spaces_braces() afterwards
205 char const * const known_special_chars[] = {"ldots", "lyxarrow",
206 "textcompwordmark", "slash", 0};
208 /// the same as known_special_chars with .lyx names
209 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
210 "textcompwordmark{}", "slash{}", 0};
213 * Graphics file extensions known by the dvips driver of the graphics package.
214 * These extensions are used to complete the filename of an included
215 * graphics file if it does not contain an extension.
216 * The order must be the same that latex uses to find a file, because we
217 * will use the first extension that matches.
218 * This is only an approximation for the common cases. If we would want to
219 * do it right in all cases, we would need to know which graphics driver is
220 * used and know the extensions of every driver of the graphics package.
222 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
223 "ps.gz", "eps.Z", "ps.Z", 0};
226 * Graphics file extensions known by the pdftex driver of the graphics package.
227 * \sa known_dvips_graphics_formats
229 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
233 * Known file extensions for TeX files as used by \\include.
235 char const * const known_tex_extensions[] = {"tex", 0};
237 /// spaces known by InsetSpace
238 char const * const known_spaces[] = { " ", "space", ",",
239 "thinspace", "quad", "qquad", "enspace", "enskip",
240 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
241 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
242 "upbracefill", "downbracefill", 0};
244 /// the same as known_spaces with .lyx names
245 char const * const known_coded_spaces[] = { "space{}", "space{}",
246 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
247 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
248 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
249 "upbracefill{}", "downbracefill{}", 0};
251 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
252 /// them in ERT. "LaTeXe" must come before "LaTeX"!
253 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
254 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
255 int const known_phrase_lengths[] = {3, 5, 7, 0};
257 // string to store the float type to be able to determine the type of subfloats
258 string float_type = "";
261 /// splits "x=z, y=b" into a map and an ordered keyword vector
262 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
267 keys.resize(v.size());
268 for (size_t i = 0; i < v.size(); ++i) {
269 size_t const pos = v[i].find('=');
270 string const index = trimSpaceAndEol(v[i].substr(0, pos));
271 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
279 * Split a LaTeX length into value and unit.
280 * The latter can be a real unit like "pt", or a latex length variable
281 * like "\textwidth". The unit may contain additional stuff like glue
282 * lengths, but we don't care, because such lengths are ERT anyway.
283 * \returns true if \p value and \p unit are valid.
285 bool splitLatexLength(string const & len, string & value, string & unit)
289 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
290 //'4,5' is a valid LaTeX length number. Change it to '4.5'
291 string const length = subst(len, ',', '.');
292 if (i == string::npos)
295 if (len[0] == '\\') {
296 // We had something like \textwidth without a factor
302 value = trimSpaceAndEol(string(length, 0, i));
306 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
307 if (contains(len, '\\'))
308 unit = trimSpaceAndEol(string(len, i));
310 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
315 /// A simple function to translate a latex length to something LyX can
316 /// understand. Not perfect, but rather best-effort.
317 bool translate_len(string const & length, string & valstring, string & unit)
319 if (!splitLatexLength(length, valstring, unit))
321 // LyX uses percent values
323 istringstream iss(valstring);
328 string const percentval = oss.str();
330 if (unit.empty() || unit[0] != '\\')
332 string::size_type const i = unit.find(' ');
333 string const endlen = (i == string::npos) ? string() : string(unit, i);
334 if (unit == "\\textwidth") {
335 valstring = percentval;
336 unit = "text%" + endlen;
337 } else if (unit == "\\columnwidth") {
338 valstring = percentval;
339 unit = "col%" + endlen;
340 } else if (unit == "\\paperwidth") {
341 valstring = percentval;
342 unit = "page%" + endlen;
343 } else if (unit == "\\linewidth") {
344 valstring = percentval;
345 unit = "line%" + endlen;
346 } else if (unit == "\\paperheight") {
347 valstring = percentval;
348 unit = "pheight%" + endlen;
349 } else if (unit == "\\textheight") {
350 valstring = percentval;
351 unit = "theight%" + endlen;
359 string translate_len(string const & length)
363 if (translate_len(length, value, unit))
365 // If the input is invalid, return what we have.
373 * Translates a LaTeX length into \p value, \p unit and
374 * \p special parts suitable for a box inset.
375 * The difference from translate_len() is that a box inset knows about
376 * some special "units" that are stored in \p special.
378 void translate_box_len(string const & length, string & value, string & unit, string & special)
380 if (translate_len(length, value, unit)) {
381 if (unit == "\\height" || unit == "\\depth" ||
382 unit == "\\totalheight" || unit == "\\width") {
383 special = unit.substr(1);
384 // The unit is not used, but LyX requires a dummy setting
397 * Find a file with basename \p name in path \p path and an extension
400 string find_file(string const & name, string const & path,
401 char const * const * extensions)
403 for (char const * const * what = extensions; *what; ++what) {
404 string const trial = addExtension(name, *what);
405 if (makeAbsPath(trial, path).exists())
412 void begin_inset(ostream & os, string const & name)
414 os << "\n\\begin_inset " << name;
418 void begin_command_inset(ostream & os, string const & name,
419 string const & latexname)
421 begin_inset(os, "CommandInset ");
422 os << name << "\nLatexCommand " << latexname << '\n';
426 void end_inset(ostream & os)
428 os << "\n\\end_inset\n\n";
432 bool skip_braces(Parser & p)
434 if (p.next_token().cat() != catBegin)
437 if (p.next_token().cat() == catEnd) {
446 /// replace LaTeX commands in \p s from the unicodesymbols file with their
448 docstring convert_unicodesymbols(docstring s)
451 for (size_t i = 0; i < s.size();) {
458 docstring parsed = encodings.fromLaTeXCommand(s, rem,
459 Encodings::TEXT_CMD);
462 if (s.empty() || s[0] != '\\')
471 /// try to convert \p s to a valid InsetCommand argument
472 string convert_command_inset_arg(string s)
475 // since we don't know the input encoding we can't use from_utf8
476 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
477 // LyX cannot handle newlines in a latex command
478 return subst(s, "\n", " ");
482 void handle_backslash(ostream & os, string const & s)
484 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
486 os << "\n\\backslash\n";
493 void handle_ert(ostream & os, string const & s, Context & context)
495 // We must have a valid layout before outputting the ERT inset.
496 context.check_layout(os);
497 Context newcontext(true, context.textclass);
498 begin_inset(os, "ERT");
499 os << "\nstatus collapsed\n";
500 newcontext.check_layout(os);
501 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
503 os << "\n\\backslash\n";
504 else if (*it == '\n') {
505 newcontext.new_paragraph(os);
506 newcontext.check_layout(os);
510 newcontext.check_end_layout(os);
515 void handle_comment(ostream & os, string const & s, Context & context)
517 // TODO: Handle this better
518 Context newcontext(true, context.textclass);
519 begin_inset(os, "ERT");
520 os << "\nstatus collapsed\n";
521 newcontext.check_layout(os);
522 handle_backslash(os, s);
523 // make sure that our comment is the last thing on the line
524 newcontext.new_paragraph(os);
525 newcontext.check_layout(os);
526 newcontext.check_end_layout(os);
531 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
533 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
536 if (checkModule(name, command))
537 return findLayoutWithoutModule(textclass, name, command);
542 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
544 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
547 if (checkModule(name, command))
548 return findInsetLayoutWithoutModule(textclass, name, command);
553 void eat_whitespace(Parser &, ostream &, Context &, bool);
557 * Skips whitespace and braces.
558 * This should be called after a command has been parsed that is not put into
559 * ERT, and where LyX adds "{}" if needed.
561 void skip_spaces_braces(Parser & p, bool keepws = false)
563 /* The following four examples produce the same typeset output and
564 should be handled by this function:
572 // Unfortunately we need to skip comments, too.
573 // We can't use eat_whitespace since writing them after the {}
574 // results in different output in some cases.
575 bool const skipped_spaces = p.skip_spaces(true);
576 bool const skipped_braces = skip_braces(p);
577 if (keepws && skipped_spaces && !skipped_braces)
578 // put back the space (it is better handled by check_space)
579 p.unskip_spaces(true);
583 void output_command_layout(ostream & os, Parser & p, bool outer,
584 Context & parent_context,
585 Layout const * newlayout)
587 TeXFont const oldFont = parent_context.font;
588 // save the current font size
589 string const size = oldFont.size;
590 // reset the font size to default, because the font size switches
591 // don't affect section headings and the like
592 parent_context.font.size = Context::normalfont.size;
593 // we only need to write the font change if we have an open layout
594 if (!parent_context.atParagraphStart())
595 output_font_change(os, oldFont, parent_context.font);
596 parent_context.check_end_layout(os);
597 Context context(true, parent_context.textclass, newlayout,
598 parent_context.layout, parent_context.font);
599 if (parent_context.deeper_paragraph) {
600 // We are beginning a nested environment after a
601 // deeper paragraph inside the outer list environment.
602 // Therefore we don't need to output a "begin deeper".
603 context.need_end_deeper = true;
605 context.check_deeper(os);
606 context.check_layout(os);
607 unsigned int optargs = 0;
608 while (optargs < context.layout->optargs) {
609 eat_whitespace(p, os, context, false);
610 if (p.next_token().cat() == catEscape ||
611 p.next_token().character() != '[')
613 p.get_token(); // eat '['
614 begin_inset(os, "Argument\n");
615 os << "status collapsed\n\n";
616 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
618 eat_whitespace(p, os, context, false);
621 unsigned int reqargs = 0;
622 while (reqargs < context.layout->reqargs) {
623 eat_whitespace(p, os, context, false);
624 if (p.next_token().cat() != catBegin)
626 p.get_token(); // eat '{'
627 begin_inset(os, "Argument\n");
628 os << "status collapsed\n\n";
629 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
631 eat_whitespace(p, os, context, false);
634 parse_text(p, os, FLAG_ITEM, outer, context);
635 context.check_end_layout(os);
636 if (parent_context.deeper_paragraph) {
637 // We must suppress the "end deeper" because we
638 // suppressed the "begin deeper" above.
639 context.need_end_deeper = false;
641 context.check_end_deeper(os);
642 // We don't need really a new paragraph, but
643 // we must make sure that the next item gets a \begin_layout.
644 parent_context.new_paragraph(os);
645 // Set the font size to the original value. No need to output it here
646 // (Context::begin_layout() will do that if needed)
647 parent_context.font.size = size;
652 * Output a space if necessary.
653 * This function gets called for every whitespace token.
655 * We have three cases here:
656 * 1. A space must be suppressed. Example: The lyxcode case below
657 * 2. A space may be suppressed. Example: Spaces before "\par"
658 * 3. A space must not be suppressed. Example: A space between two words
660 * We currently handle only 1. and 3 and from 2. only the case of
661 * spaces before newlines as a side effect.
663 * 2. could be used to suppress as many spaces as possible. This has two effects:
664 * - Reimporting LyX generated LaTeX files changes almost no whitespace
665 * - Superflous whitespace from non LyX generated LaTeX files is removed.
666 * The drawback is that the logic inside the function becomes
667 * complicated, and that is the reason why it is not implemented.
669 void check_space(Parser & p, ostream & os, Context & context)
671 Token const next = p.next_token();
672 Token const curr = p.curr_token();
673 // A space before a single newline and vice versa must be ignored
674 // LyX emits a newline before \end{lyxcode}.
675 // This newline must be ignored,
676 // otherwise LyX will add an additional protected space.
677 if (next.cat() == catSpace ||
678 next.cat() == catNewline ||
679 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
682 context.check_layout(os);
688 * Parse all arguments of \p command
690 void parse_arguments(string const & command,
691 vector<ArgumentType> const & template_arguments,
692 Parser & p, ostream & os, bool outer, Context & context)
694 string ert = command;
695 size_t no_arguments = template_arguments.size();
696 for (size_t i = 0; i < no_arguments; ++i) {
697 switch (template_arguments[i]) {
700 // This argument contains regular LaTeX
701 handle_ert(os, ert + '{', context);
702 eat_whitespace(p, os, context, false);
703 if (template_arguments[i] == required)
704 parse_text(p, os, FLAG_ITEM, outer, context);
706 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
710 // This argument consists only of a single item.
711 // The presence of '{' or not must be preserved.
713 if (p.next_token().cat() == catBegin)
714 ert += '{' + p.verbatim_item() + '}';
716 ert += p.verbatim_item();
720 // This argument may contain special characters
721 ert += '{' + p.verbatim_item() + '}';
725 // true because we must not eat whitespace
726 // if an optional arg follows we must not strip the
727 // brackets from this one
728 if (i < no_arguments - 1 &&
729 template_arguments[i+1] == optional)
730 ert += p.getFullOpt(true);
732 ert += p.getOpt(true);
736 handle_ert(os, ert, context);
741 * Check whether \p command is a known command. If yes,
742 * handle the command with all arguments.
743 * \return true if the command was parsed, false otherwise.
745 bool parse_command(string const & command, Parser & p, ostream & os,
746 bool outer, Context & context)
748 if (known_commands.find(command) != known_commands.end()) {
749 parse_arguments(command, known_commands[command], p, os,
757 /// Parses a minipage or parbox
758 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
759 unsigned inner_flags, bool outer, Context & parent_context,
760 string const & outer_type, string const & special,
761 string const & inner_type)
765 string hor_pos = "c";
766 // We need to set the height to the LaTeX default of 1\\totalheight
767 // for the case when no height argument is given
768 string height_value = "1";
769 string height_unit = "in";
770 string height_special = "totalheight";
775 string width_special = "none";
776 if (!inner_type.empty() && p.hasOpt()) {
777 if (inner_type != "makebox")
778 position = p.getArg('[', ']');
780 latex_width = p.getArg('[', ']');
781 translate_box_len(latex_width, width_value, width_unit, width_special);
784 if (position != "t" && position != "c" && position != "b") {
785 cerr << "invalid position " << position << " for "
786 << inner_type << endl;
790 if (inner_type != "makebox") {
791 latex_height = p.getArg('[', ']');
792 translate_box_len(latex_height, height_value, height_unit, height_special);
794 hor_pos = p.getArg('[', ']');
797 inner_pos = p.getArg('[', ']');
798 if (inner_pos != "c" && inner_pos != "t" &&
799 inner_pos != "b" && inner_pos != "s") {
800 cerr << "invalid inner_pos "
801 << inner_pos << " for "
802 << inner_type << endl;
803 inner_pos = position;
808 if (inner_type.empty()) {
809 if (special.empty() && outer_type != "framebox")
810 latex_width = "1\\columnwidth";
813 latex_width = p2.getArg('[', ']');
814 string const opt = p2.getArg('[', ']');
817 if (hor_pos != "l" && hor_pos != "c" &&
819 cerr << "invalid hor_pos " << hor_pos
820 << " for " << outer_type << endl;
825 } else if (inner_type != "makebox")
826 latex_width = p.verbatim_item();
827 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
828 // as this is LyX's standard for such cases (except for makebox)
829 // \framebox is more special and handled below
830 if (latex_width.empty() && inner_type != "makebox"
831 && outer_type != "framebox")
832 latex_width = "1\\columnwidth";
834 translate_len(latex_width, width_value, width_unit);
836 bool shadedparbox = false;
837 if (inner_type == "shaded") {
838 eat_whitespace(p, os, parent_context, false);
839 if (outer_type == "parbox") {
841 if (p.next_token().cat() == catBegin)
843 eat_whitespace(p, os, parent_context, false);
849 // If we already read the inner box we have to push the inner env
850 if (!outer_type.empty() && !inner_type.empty() &&
851 (inner_flags & FLAG_END))
852 active_environments.push_back(inner_type);
853 // LyX can't handle length variables
854 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
855 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
856 // Look whether there is some content after the end of the
857 // inner box, but before the end of the outer box.
858 // If yes, we need to output ERT.
860 if (inner_flags & FLAG_END)
861 p.verbatimEnvironment(inner_type);
865 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
866 if ((outer_env && p.next_token().asInput() != "\\end") ||
867 (!outer_env && p.next_token().cat() != catEnd)) {
868 // something is between the end of the inner box and
869 // the end of the outer box, so we need to use ERT.
874 // if only \makebox{content} was used we can set its width to 1\width
875 // because this identic and also identic to \mbox
876 // this doesn't work for \framebox{content}, thus we have to use ERT for this
877 if (latex_width.empty() && inner_type == "makebox") {
880 width_special = "width";
881 } else if (latex_width.empty() && outer_type == "framebox") {
886 if (!outer_type.empty()) {
887 if (outer_flags & FLAG_END)
888 ss << "\\begin{" << outer_type << '}';
890 ss << '\\' << outer_type << '{';
891 if (!special.empty())
895 if (!inner_type.empty()) {
896 if (inner_type != "shaded") {
897 if (inner_flags & FLAG_END)
898 ss << "\\begin{" << inner_type << '}';
900 ss << '\\' << inner_type;
902 if (!position.empty())
903 ss << '[' << position << ']';
904 if (!latex_height.empty())
905 ss << '[' << latex_height << ']';
906 if (!inner_pos.empty())
907 ss << '[' << inner_pos << ']';
908 ss << '{' << latex_width << '}';
909 if (!(inner_flags & FLAG_END))
912 if (inner_type == "shaded")
913 ss << "\\begin{shaded}";
914 handle_ert(os, ss.str(), parent_context);
915 if (!inner_type.empty()) {
916 parse_text(p, os, inner_flags, outer, parent_context);
917 if (inner_flags & FLAG_END)
918 handle_ert(os, "\\end{" + inner_type + '}',
921 handle_ert(os, "}", parent_context);
923 if (!outer_type.empty()) {
924 // If we already read the inner box we have to pop
926 if (!inner_type.empty() && (inner_flags & FLAG_END))
927 active_environments.pop_back();
929 // Ensure that the end of the outer box is parsed correctly:
930 // The opening brace has been eaten by parse_outer_box()
931 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
932 outer_flags &= ~FLAG_ITEM;
933 outer_flags |= FLAG_BRACE_LAST;
935 parse_text(p, os, outer_flags, outer, parent_context);
936 if (outer_flags & FLAG_END)
937 handle_ert(os, "\\end{" + outer_type + '}',
939 else if (inner_type.empty() && outer_type == "framebox")
940 // in this case it is already closed later
943 handle_ert(os, "}", parent_context);
946 // LyX does not like empty positions, so we have
947 // to set them to the LaTeX default values here.
948 if (position.empty())
950 if (inner_pos.empty())
951 inner_pos = position;
952 parent_context.check_layout(os);
953 begin_inset(os, "Box ");
954 if (outer_type == "framed")
956 else if (outer_type == "framebox")
958 else if (outer_type == "shadowbox")
960 else if ((outer_type == "shaded" && inner_type.empty()) ||
961 (outer_type == "minipage" && inner_type == "shaded") ||
962 (outer_type == "parbox" && inner_type == "shaded")) {
964 preamble.registerAutomaticallyLoadedPackage("color");
965 } else if (outer_type == "doublebox")
967 else if (outer_type.empty())
970 os << outer_type << '\n';
971 os << "position \"" << position << "\"\n";
972 os << "hor_pos \"" << hor_pos << "\"\n";
973 os << "has_inner_box " << !inner_type.empty() << "\n";
974 os << "inner_pos \"" << inner_pos << "\"\n";
975 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
977 os << "use_makebox " << (inner_type == "makebox") << '\n';
978 os << "width \"" << width_value << width_unit << "\"\n";
979 os << "special \"" << width_special << "\"\n";
980 os << "height \"" << height_value << height_unit << "\"\n";
981 os << "height_special \"" << height_special << "\"\n";
982 os << "status open\n\n";
984 // Unfortunately we can't use parse_text_in_inset:
985 // InsetBox::forcePlainLayout() is hard coded and does not
986 // use the inset layout. Apart from that do we call parse_text
987 // up to two times, but need only one check_end_layout.
988 bool const forcePlainLayout =
989 (!inner_type.empty() || inner_type == "makebox") &&
990 outer_type != "shaded" && outer_type != "framed";
991 Context context(true, parent_context.textclass);
992 if (forcePlainLayout)
993 context.layout = &context.textclass.plainLayout();
995 context.font = parent_context.font;
997 // If we have no inner box the contents will be read with the outer box
998 if (!inner_type.empty())
999 parse_text(p, os, inner_flags, outer, context);
1001 // Ensure that the end of the outer box is parsed correctly:
1002 // The opening brace has been eaten by parse_outer_box()
1003 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1004 outer_flags &= ~FLAG_ITEM;
1005 outer_flags |= FLAG_BRACE_LAST;
1008 // Find end of outer box, output contents if inner_type is
1009 // empty and output possible comments
1010 if (!outer_type.empty()) {
1011 // If we already read the inner box we have to pop
1013 if (!inner_type.empty() && (inner_flags & FLAG_END))
1014 active_environments.pop_back();
1015 // This does not output anything but comments if
1016 // inner_type is not empty (see use_ert)
1017 parse_text(p, os, outer_flags, outer, context);
1020 context.check_end_layout(os);
1022 #ifdef PRESERVE_LAYOUT
1023 // LyX puts a % after the end of the minipage
1024 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1026 //handle_comment(os, "%dummy", parent_context);
1029 parent_context.new_paragraph(os);
1031 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1032 //handle_comment(os, "%dummy", parent_context);
1035 // We add a protected space if something real follows
1036 if (p.good() && p.next_token().cat() != catComment) {
1037 begin_inset(os, "space ~\n");
1046 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1047 Context & parent_context, string const & outer_type,
1048 string const & special)
1050 eat_whitespace(p, os, parent_context, false);
1051 if (flags & FLAG_ITEM) {
1053 if (p.next_token().cat() == catBegin)
1056 cerr << "Warning: Ignoring missing '{' after \\"
1057 << outer_type << '.' << endl;
1058 eat_whitespace(p, os, parent_context, false);
1061 unsigned int inner_flags = 0;
1063 if (outer_type == "minipage" || outer_type == "parbox") {
1064 p.skip_spaces(true);
1065 while (p.hasOpt()) {
1067 p.skip_spaces(true);
1070 p.skip_spaces(true);
1071 if (outer_type == "parbox") {
1073 if (p.next_token().cat() == catBegin)
1075 p.skip_spaces(true);
1078 if (outer_type == "shaded") {
1079 // These boxes never have an inner box
1081 } else if (p.next_token().asInput() == "\\parbox") {
1082 inner = p.get_token().cs();
1083 inner_flags = FLAG_ITEM;
1084 } else if (p.next_token().asInput() == "\\begin") {
1085 // Is this a minipage or shaded box?
1088 inner = p.getArg('{', '}');
1090 if (inner == "minipage" || inner == "shaded")
1091 inner_flags = FLAG_END;
1096 if (inner_flags == FLAG_END) {
1097 if (inner != "shaded")
1101 eat_whitespace(p, os, parent_context, false);
1103 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1104 outer_type, special, inner);
1106 if (inner_flags == FLAG_ITEM) {
1108 eat_whitespace(p, os, parent_context, false);
1110 parse_box(p, os, flags, inner_flags, outer, parent_context,
1111 outer_type, special, inner);
1116 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1118 parent_context.check_layout(os);
1119 begin_inset(os, "listings\n");
1120 os << "inline false\n"
1121 << "status collapsed\n";
1122 Context context(true, parent_context.textclass);
1123 context.layout = &parent_context.textclass.plainLayout();
1124 context.check_layout(os);
1125 string const s = p.verbatimEnvironment("lstlisting");
1126 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1128 os << "\n\\backslash\n";
1129 else if (*it == '\n') {
1130 // avoid adding an empty paragraph at the end
1132 context.new_paragraph(os);
1133 context.check_layout(os);
1138 context.check_end_layout(os);
1143 /// parse an unknown environment
1144 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1145 unsigned flags, bool outer,
1146 Context & parent_context)
1148 if (name == "tabbing")
1149 // We need to remember that we have to handle '\=' specially
1150 flags |= FLAG_TABBING;
1152 // We need to translate font changes and paragraphs inside the
1153 // environment to ERT if we have a non standard font.
1154 // Otherwise things like
1155 // \large\begin{foo}\huge bar\end{foo}
1157 bool const specialfont =
1158 (parent_context.font != parent_context.normalfont);
1159 bool const new_layout_allowed = parent_context.new_layout_allowed;
1161 parent_context.new_layout_allowed = false;
1162 handle_ert(os, "\\begin{" + name + "}", parent_context);
1163 parse_text_snippet(p, os, flags, outer, parent_context);
1164 handle_ert(os, "\\end{" + name + "}", parent_context);
1166 parent_context.new_layout_allowed = new_layout_allowed;
1170 void parse_environment(Parser & p, ostream & os, bool outer,
1171 string & last_env, bool & title_layout_found,
1172 Context & parent_context)
1174 Layout const * newlayout;
1175 InsetLayout const * newinsetlayout = 0;
1176 string const name = p.getArg('{', '}');
1177 const bool is_starred = suffixIs(name, '*');
1178 string const unstarred_name = rtrim(name, "*");
1179 active_environments.push_back(name);
1181 if (is_math_env(name)) {
1182 parent_context.check_layout(os);
1183 begin_inset(os, "Formula ");
1184 os << "\\begin{" << name << "}";
1185 parse_math(p, os, FLAG_END, MATH_MODE);
1186 os << "\\end{" << name << "}";
1188 if (is_display_math_env(name)) {
1189 // Prevent the conversion of a line break to a space
1190 // (bug 7668). This does not change the output, but
1191 // looks ugly in LyX.
1192 eat_whitespace(p, os, parent_context, false);
1196 else if (unstarred_name == "tabular" || name == "longtable") {
1197 eat_whitespace(p, os, parent_context, false);
1198 string width = "0pt";
1199 if (name == "tabular*") {
1200 width = lyx::translate_len(p.getArg('{', '}'));
1201 eat_whitespace(p, os, parent_context, false);
1203 parent_context.check_layout(os);
1204 begin_inset(os, "Tabular ");
1205 handle_tabular(p, os, name, width, parent_context);
1210 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1211 eat_whitespace(p, os, parent_context, false);
1212 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1213 eat_whitespace(p, os, parent_context, false);
1214 parent_context.check_layout(os);
1215 begin_inset(os, "Float " + unstarred_name + "\n");
1216 // store the float type for subfloats
1217 // subfloats only work with figures and tables
1218 if (unstarred_name == "figure")
1219 float_type = unstarred_name;
1220 else if (unstarred_name == "table")
1221 float_type = unstarred_name;
1225 os << "placement " << opt << '\n';
1226 if (contains(opt, "H"))
1227 preamble.registerAutomaticallyLoadedPackage("float");
1229 Floating const & fl = parent_context.textclass.floats()
1230 .getType(unstarred_name);
1231 if (!fl.floattype().empty() && fl.usesFloatPkg())
1232 preamble.registerAutomaticallyLoadedPackage("float");
1235 os << "wide " << convert<string>(is_starred)
1236 << "\nsideways false"
1237 << "\nstatus open\n\n";
1238 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1240 // We don't need really a new paragraph, but
1241 // we must make sure that the next item gets a \begin_layout.
1242 parent_context.new_paragraph(os);
1244 // the float is parsed thus delete the type
1248 else if (unstarred_name == "sidewaysfigure"
1249 || unstarred_name == "sidewaystable") {
1250 eat_whitespace(p, os, parent_context, false);
1251 parent_context.check_layout(os);
1252 if (unstarred_name == "sidewaysfigure")
1253 begin_inset(os, "Float figure\n");
1255 begin_inset(os, "Float table\n");
1256 os << "wide " << convert<string>(is_starred)
1257 << "\nsideways true"
1258 << "\nstatus open\n\n";
1259 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1261 // We don't need really a new paragraph, but
1262 // we must make sure that the next item gets a \begin_layout.
1263 parent_context.new_paragraph(os);
1267 else if (name == "wrapfigure" || name == "wraptable") {
1268 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1269 eat_whitespace(p, os, parent_context, false);
1270 parent_context.check_layout(os);
1273 string overhang = "0col%";
1276 lines = p.getArg('[', ']');
1277 string const placement = p.getArg('{', '}');
1279 overhang = p.getArg('[', ']');
1280 string const width = p.getArg('{', '}');
1282 if (name == "wrapfigure")
1283 begin_inset(os, "Wrap figure\n");
1285 begin_inset(os, "Wrap table\n");
1286 os << "lines " << lines
1287 << "\nplacement " << placement
1288 << "\noverhang " << lyx::translate_len(overhang)
1289 << "\nwidth " << lyx::translate_len(width)
1290 << "\nstatus open\n\n";
1291 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1293 // We don't need really a new paragraph, but
1294 // we must make sure that the next item gets a \begin_layout.
1295 parent_context.new_paragraph(os);
1299 else if (name == "minipage") {
1300 eat_whitespace(p, os, parent_context, false);
1301 // Test whether this is an outer box of a shaded box
1303 // swallow arguments
1304 while (p.hasOpt()) {
1306 p.skip_spaces(true);
1309 p.skip_spaces(true);
1310 Token t = p.get_token();
1311 bool shaded = false;
1312 if (t.asInput() == "\\begin") {
1313 p.skip_spaces(true);
1314 if (p.getArg('{', '}') == "shaded")
1319 parse_outer_box(p, os, FLAG_END, outer,
1320 parent_context, name, "shaded");
1322 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1327 else if (name == "comment") {
1328 eat_whitespace(p, os, parent_context, false);
1329 parent_context.check_layout(os);
1330 begin_inset(os, "Note Comment\n");
1331 os << "status open\n";
1332 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1335 skip_braces(p); // eat {} that might by set by LyX behind comments
1338 else if (name == "lyxgreyedout") {
1339 eat_whitespace(p, os, parent_context, false);
1340 parent_context.check_layout(os);
1341 begin_inset(os, "Note Greyedout\n");
1342 os << "status open\n";
1343 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1346 if (!preamble.notefontcolor().empty())
1347 preamble.registerAutomaticallyLoadedPackage("color");
1350 else if (name == "framed" || name == "shaded") {
1351 eat_whitespace(p, os, parent_context, false);
1352 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1356 else if (name == "lstlisting") {
1357 eat_whitespace(p, os, parent_context, false);
1358 // FIXME handle listings with parameters
1359 // If this is added, don't forgot to handle the
1360 // automatic color package loading
1362 parse_unknown_environment(p, name, os, FLAG_END,
1363 outer, parent_context);
1365 parse_listings(p, os, parent_context);
1369 else if (!parent_context.new_layout_allowed)
1370 parse_unknown_environment(p, name, os, FLAG_END, outer,
1373 // Alignment and spacing settings
1374 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1375 // therefore are totally broken!
1376 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1377 // they are commands not environments. They are furthermore switches that
1378 // can be ended by another switches, but also by commands like \footnote or
1379 // \parbox. So the only safe way is to leave them untouched.
1380 else if (name == "center" || name == "centering" ||
1381 name == "flushleft" || name == "flushright" ||
1382 name == "singlespace" || name == "onehalfspace" ||
1383 name == "doublespace" || name == "spacing") {
1384 eat_whitespace(p, os, parent_context, false);
1385 // We must begin a new paragraph if not already done
1386 if (! parent_context.atParagraphStart()) {
1387 parent_context.check_end_layout(os);
1388 parent_context.new_paragraph(os);
1390 if (name == "flushleft")
1391 parent_context.add_extra_stuff("\\align left\n");
1392 else if (name == "flushright")
1393 parent_context.add_extra_stuff("\\align right\n");
1394 else if (name == "center" || name == "centering")
1395 parent_context.add_extra_stuff("\\align center\n");
1396 else if (name == "singlespace")
1397 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1398 else if (name == "onehalfspace") {
1399 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1400 preamble.registerAutomaticallyLoadedPackage("setspace");
1401 } else if (name == "doublespace") {
1402 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1403 preamble.registerAutomaticallyLoadedPackage("setspace");
1404 } else if (name == "spacing") {
1405 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1406 preamble.registerAutomaticallyLoadedPackage("setspace");
1408 parse_text(p, os, FLAG_END, outer, parent_context);
1409 // Just in case the environment is empty
1410 parent_context.extra_stuff.erase();
1411 // We must begin a new paragraph to reset the alignment
1412 parent_context.new_paragraph(os);
1416 // The single '=' is meant here.
1417 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1418 eat_whitespace(p, os, parent_context, false);
1419 Context context(true, parent_context.textclass, newlayout,
1420 parent_context.layout, parent_context.font);
1421 if (parent_context.deeper_paragraph) {
1422 // We are beginning a nested environment after a
1423 // deeper paragraph inside the outer list environment.
1424 // Therefore we don't need to output a "begin deeper".
1425 context.need_end_deeper = true;
1427 parent_context.check_end_layout(os);
1428 if (last_env == name) {
1429 // we need to output a separator since LyX would export
1430 // the two environments as one otherwise (bug 5716)
1431 docstring const sep = from_ascii("--Separator--");
1432 TeX2LyXDocClass const & textclass(parent_context.textclass);
1433 if (textclass.hasLayout(sep)) {
1434 Context newcontext(parent_context);
1435 newcontext.layout = &(textclass[sep]);
1436 newcontext.check_layout(os);
1437 newcontext.check_end_layout(os);
1439 parent_context.check_layout(os);
1440 begin_inset(os, "Note Note\n");
1441 os << "status closed\n";
1442 Context newcontext(true, textclass,
1443 &(textclass.defaultLayout()));
1444 newcontext.check_layout(os);
1445 newcontext.check_end_layout(os);
1447 parent_context.check_end_layout(os);
1450 switch (context.layout->latextype) {
1451 case LATEX_LIST_ENVIRONMENT:
1452 context.add_par_extra_stuff("\\labelwidthstring "
1453 + p.verbatim_item() + '\n');
1456 case LATEX_BIB_ENVIRONMENT:
1457 p.verbatim_item(); // swallow next arg
1463 context.check_deeper(os);
1464 // handle known optional and required arguments
1465 // layouts require all optional arguments before the required ones
1466 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1467 // It is impossible to place anything after the environment name,
1468 // but before the first \\item.
1469 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1470 bool need_layout = true;
1471 unsigned int optargs = 0;
1472 while (optargs < context.layout->optargs) {
1473 eat_whitespace(p, os, context, false);
1474 if (p.next_token().cat() == catEscape ||
1475 p.next_token().character() != '[')
1477 p.get_token(); // eat '['
1479 context.check_layout(os);
1480 need_layout = false;
1482 begin_inset(os, "Argument\n");
1483 os << "status collapsed\n\n";
1484 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1486 eat_whitespace(p, os, context, false);
1489 unsigned int reqargs = 0;
1490 while (reqargs < context.layout->reqargs) {
1491 eat_whitespace(p, os, context, false);
1492 if (p.next_token().cat() != catBegin)
1494 p.get_token(); // eat '{'
1496 context.check_layout(os);
1497 need_layout = false;
1499 begin_inset(os, "Argument\n");
1500 os << "status collapsed\n\n";
1501 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1503 eat_whitespace(p, os, context, false);
1507 parse_text(p, os, FLAG_END, outer, context);
1508 context.check_end_layout(os);
1509 if (parent_context.deeper_paragraph) {
1510 // We must suppress the "end deeper" because we
1511 // suppressed the "begin deeper" above.
1512 context.need_end_deeper = false;
1514 context.check_end_deeper(os);
1515 parent_context.new_paragraph(os);
1517 if (!title_layout_found)
1518 title_layout_found = newlayout->intitle;
1519 set<string> const & req = newlayout->requires();
1520 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
1521 preamble.registerAutomaticallyLoadedPackage(*it);
1524 // The single '=' is meant here.
1525 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1526 eat_whitespace(p, os, parent_context, false);
1527 parent_context.check_layout(os);
1528 begin_inset(os, "Flex ");
1529 os << to_utf8(newinsetlayout->name()) << '\n'
1530 << "status collapsed\n";
1531 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1535 else if (name == "appendix") {
1536 // This is no good latex style, but it works and is used in some documents...
1537 eat_whitespace(p, os, parent_context, false);
1538 parent_context.check_end_layout(os);
1539 Context context(true, parent_context.textclass, parent_context.layout,
1540 parent_context.layout, parent_context.font);
1541 context.check_layout(os);
1542 os << "\\start_of_appendix\n";
1543 parse_text(p, os, FLAG_END, outer, context);
1544 context.check_end_layout(os);
1548 else if (known_environments.find(name) != known_environments.end()) {
1549 vector<ArgumentType> arguments = known_environments[name];
1550 // The last "argument" denotes wether we may translate the
1551 // environment contents to LyX
1552 // The default required if no argument is given makes us
1553 // compatible with the reLyXre environment.
1554 ArgumentType contents = arguments.empty() ?
1557 if (!arguments.empty())
1558 arguments.pop_back();
1559 // See comment in parse_unknown_environment()
1560 bool const specialfont =
1561 (parent_context.font != parent_context.normalfont);
1562 bool const new_layout_allowed =
1563 parent_context.new_layout_allowed;
1565 parent_context.new_layout_allowed = false;
1566 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1567 outer, parent_context);
1568 if (contents == verbatim)
1569 handle_ert(os, p.verbatimEnvironment(name),
1572 parse_text_snippet(p, os, FLAG_END, outer,
1574 handle_ert(os, "\\end{" + name + "}", parent_context);
1576 parent_context.new_layout_allowed = new_layout_allowed;
1580 parse_unknown_environment(p, name, os, FLAG_END, outer,
1584 active_environments.pop_back();
1588 /// parses a comment and outputs it to \p os.
1589 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1591 LASSERT(t.cat() == catComment, return);
1592 if (!t.cs().empty()) {
1593 context.check_layout(os);
1594 handle_comment(os, '%' + t.cs(), context);
1595 if (p.next_token().cat() == catNewline) {
1596 // A newline after a comment line starts a new
1598 if (context.new_layout_allowed) {
1599 if(!context.atParagraphStart())
1600 // Only start a new paragraph if not already
1601 // done (we might get called recursively)
1602 context.new_paragraph(os);
1604 handle_ert(os, "\n", context);
1605 eat_whitespace(p, os, context, true);
1608 // "%\n" combination
1615 * Reads spaces and comments until the first non-space, non-comment token.
1616 * New paragraphs (double newlines or \\par) are handled like simple spaces
1617 * if \p eatParagraph is true.
1618 * Spaces are skipped, but comments are written to \p os.
1620 void eat_whitespace(Parser & p, ostream & os, Context & context,
1624 Token const & t = p.get_token();
1625 if (t.cat() == catComment)
1626 parse_comment(p, os, t, context);
1627 else if ((! eatParagraph && p.isParagraph()) ||
1628 (t.cat() != catSpace && t.cat() != catNewline)) {
1637 * Set a font attribute, parse text and reset the font attribute.
1638 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1639 * \param currentvalue Current value of the attribute. Is set to the new
1640 * value during parsing.
1641 * \param newvalue New value of the attribute
1643 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1644 Context & context, string const & attribute,
1645 string & currentvalue, string const & newvalue)
1647 context.check_layout(os);
1648 string const oldvalue = currentvalue;
1649 currentvalue = newvalue;
1650 os << '\n' << attribute << ' ' << newvalue << "\n";
1651 parse_text_snippet(p, os, flags, outer, context);
1652 context.check_layout(os);
1653 os << '\n' << attribute << ' ' << oldvalue << "\n";
1654 currentvalue = oldvalue;
1658 /// get the arguments of a natbib or jurabib citation command
1659 void get_cite_arguments(Parser & p, bool natbibOrder,
1660 string & before, string & after)
1662 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1664 // text before the citation
1666 // text after the citation
1667 after = p.getFullOpt();
1669 if (!after.empty()) {
1670 before = p.getFullOpt();
1671 if (natbibOrder && !before.empty())
1672 swap(before, after);
1677 /// Convert filenames with TeX macros and/or quotes to something LyX
1679 string const normalize_filename(string const & name)
1681 Parser p(trim(name, "\""));
1684 Token const & t = p.get_token();
1685 if (t.cat() != catEscape)
1687 else if (t.cs() == "lyxdot") {
1688 // This is used by LyX for simple dots in relative
1692 } else if (t.cs() == "space") {
1702 /// Convert \p name from TeX convention (relative to master file) to LyX
1703 /// convention (relative to .lyx file) if it is relative
1704 void fix_relative_filename(string & name)
1706 if (FileName::isAbsolute(name))
1709 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1710 from_utf8(getParentFilePath())));
1714 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1715 void parse_noweb(Parser & p, ostream & os, Context & context)
1717 // assemble the rest of the keyword
1721 Token const & t = p.get_token();
1722 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1725 scrap = (p.good() && p.next_token().asInput() == "=");
1727 name += p.get_token().asInput();
1730 name += t.asInput();
1733 if (!scrap || !context.new_layout_allowed ||
1734 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1735 cerr << "Warning: Could not interpret '" << name
1736 << "'. Ignoring it." << endl;
1740 // We use new_paragraph instead of check_end_layout because the stuff
1741 // following the noweb chunk needs to start with a \begin_layout.
1742 // This may create a new paragraph even if there was none in the
1743 // noweb file, but the alternative is an invalid LyX file. Since
1744 // noweb code chunks are implemented with a layout style in LyX they
1745 // always must be in an own paragraph.
1746 context.new_paragraph(os);
1747 Context newcontext(true, context.textclass,
1748 &context.textclass[from_ascii("Scrap")]);
1749 newcontext.check_layout(os);
1752 Token const & t = p.get_token();
1753 // We abuse the parser a bit, because this is no TeX syntax
1755 if (t.cat() == catEscape)
1756 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1759 Context tmp(false, context.textclass,
1760 &context.textclass[from_ascii("Scrap")]);
1761 tmp.need_end_layout = true;
1762 tmp.check_layout(oss);
1763 os << subst(t.asInput(), "\n", oss.str());
1765 // The scrap chunk is ended by an @ at the beginning of a line.
1766 // After the @ the line may contain a comment and/or
1767 // whitespace, but nothing else.
1768 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1769 (p.next_token().cat() == catSpace ||
1770 p.next_token().cat() == catNewline ||
1771 p.next_token().cat() == catComment)) {
1772 while (p.good() && p.next_token().cat() == catSpace)
1773 os << p.get_token().asInput();
1774 if (p.next_token().cat() == catComment)
1775 // The comment includes a final '\n'
1776 os << p.get_token().asInput();
1778 if (p.next_token().cat() == catNewline)
1785 newcontext.check_end_layout(os);
1789 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1790 bool is_macro(Parser & p)
1792 Token first = p.curr_token();
1793 if (first.cat() != catEscape || !p.good())
1795 if (first.cs() == "def")
1797 if (first.cs() != "global" && first.cs() != "long")
1799 Token second = p.get_token();
1801 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1802 second.cat() == catNewline || second.cat() == catComment)) {
1803 second = p.get_token();
1806 bool secondvalid = second.cat() == catEscape;
1808 bool thirdvalid = false;
1809 if (p.good() && first.cs() == "global" && secondvalid &&
1810 second.cs() == "long") {
1811 third = p.get_token();
1813 while (p.good() && !p.isParagraph() &&
1814 (third.cat() == catSpace ||
1815 third.cat() == catNewline ||
1816 third.cat() == catComment)) {
1817 third = p.get_token();
1820 thirdvalid = third.cat() == catEscape;
1822 for (int i = 0; i < pos; ++i)
1827 return (first.cs() == "global" || first.cs() == "long") &&
1828 second.cs() == "def";
1829 return first.cs() == "global" && second.cs() == "long" &&
1830 third.cs() == "def";
1834 /// Parse a macro definition (assumes that is_macro() returned true)
1835 void parse_macro(Parser & p, ostream & os, Context & context)
1837 context.check_layout(os);
1838 Token first = p.curr_token();
1841 string command = first.asInput();
1842 if (first.cs() != "def") {
1844 eat_whitespace(p, os, context, false);
1845 second = p.curr_token();
1846 command += second.asInput();
1847 if (second.cs() != "def") {
1849 eat_whitespace(p, os, context, false);
1850 third = p.curr_token();
1851 command += third.asInput();
1854 eat_whitespace(p, os, context, false);
1855 string const name = p.get_token().cs();
1856 eat_whitespace(p, os, context, false);
1862 while (p.next_token().cat() != catBegin) {
1863 if (p.next_token().cat() == catParameter) {
1868 // followed by number?
1869 if (p.next_token().cat() == catOther) {
1870 char c = p.getChar();
1872 // number = current arity + 1?
1873 if (c == arity + '0' + 1)
1878 paramtext += p.get_token().cs();
1880 paramtext += p.get_token().cs();
1885 // only output simple (i.e. compatible) macro as FormulaMacros
1886 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1888 context.check_layout(os);
1889 begin_inset(os, "FormulaMacro");
1890 os << "\n\\def" << ert;
1893 handle_ert(os, command + ert, context);
1896 } // anonymous namespace
1899 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1902 Layout const * newlayout = 0;
1903 InsetLayout const * newinsetlayout = 0;
1904 char const * const * where = 0;
1905 // Store the latest bibliographystyle and nocite{*} option
1906 // (needed for bibtex inset)
1908 string bibliographystyle;
1909 bool const use_natbib = preamble.isPackageUsed("natbib");
1910 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1912 bool title_layout_found = false;
1914 Token const & t = p.get_token();
1917 debugToken(cerr, t, flags);
1920 if (flags & FLAG_ITEM) {
1921 if (t.cat() == catSpace)
1924 flags &= ~FLAG_ITEM;
1925 if (t.cat() == catBegin) {
1926 // skip the brace and collect everything to the next matching
1928 flags |= FLAG_BRACE_LAST;
1932 // handle only this single token, leave the loop if done
1933 flags |= FLAG_LEAVE;
1936 if (t.cat() != catEscape && t.character() == ']' &&
1937 (flags & FLAG_BRACK_LAST))
1939 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1942 // If there is anything between \end{env} and \begin{env} we
1943 // don't need to output a separator.
1944 if (t.cat() != catSpace && t.cat() != catNewline &&
1945 t.asInput() != "\\begin")
1951 if (t.cat() == catMath) {
1952 // we are inside some text mode thingy, so opening new math is allowed
1953 context.check_layout(os);
1954 begin_inset(os, "Formula ");
1955 Token const & n = p.get_token();
1956 bool const display(n.cat() == catMath && outer);
1958 // TeX's $$...$$ syntax for displayed math
1960 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1962 p.get_token(); // skip the second '$' token
1964 // simple $...$ stuff
1967 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1972 // Prevent the conversion of a line break to a
1973 // space (bug 7668). This does not change the
1974 // output, but looks ugly in LyX.
1975 eat_whitespace(p, os, context, false);
1979 else if (t.cat() == catSuper || t.cat() == catSub)
1980 cerr << "catcode " << t << " illegal in text mode\n";
1982 // Basic support for english quotes. This should be
1983 // extended to other quotes, but is not so easy (a
1984 // left english quote is the same as a right german
1986 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1987 context.check_layout(os);
1988 begin_inset(os, "Quotes ");
1994 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1995 context.check_layout(os);
1996 begin_inset(os, "Quotes ");
2003 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2004 context.check_layout(os);
2005 begin_inset(os, "Quotes ");
2012 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2013 context.check_layout(os);
2014 begin_inset(os, "Quotes ");
2021 else if (t.asInput() == "<"
2022 && p.next_token().asInput() == "<" && noweb_mode) {
2024 parse_noweb(p, os, context);
2027 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2028 check_space(p, os, context);
2030 else if (t.character() == '[' && noweb_mode &&
2031 p.next_token().character() == '[') {
2032 // These can contain underscores
2034 string const s = p.getFullOpt() + ']';
2035 if (p.next_token().character() == ']')
2038 cerr << "Warning: Inserting missing ']' in '"
2039 << s << "'." << endl;
2040 handle_ert(os, s, context);
2043 else if (t.cat() == catLetter) {
2044 context.check_layout(os);
2045 // Workaround for bug 4752.
2046 // FIXME: This whole code block needs to be removed
2047 // when the bug is fixed and tex2lyx produces
2048 // the updated file format.
2049 // The replacement algorithm in LyX is so stupid that
2050 // it even translates a phrase if it is part of a word.
2051 bool handled = false;
2052 for (int const * l = known_phrase_lengths; *l; ++l) {
2053 string phrase = t.cs();
2054 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2055 phrase += p.get_token().cs();
2056 if (is_known(phrase, known_coded_phrases)) {
2057 handle_ert(os, phrase, context);
2061 for (size_t i = 1; i < phrase.length(); ++i)
2069 else if (t.cat() == catOther ||
2070 t.cat() == catAlign ||
2071 t.cat() == catParameter) {
2072 // This translates "&" to "\\&" which may be wrong...
2073 context.check_layout(os);
2077 else if (p.isParagraph()) {
2078 if (context.new_layout_allowed)
2079 context.new_paragraph(os);
2081 handle_ert(os, "\\par ", context);
2082 eat_whitespace(p, os, context, true);
2085 else if (t.cat() == catActive) {
2086 context.check_layout(os);
2087 if (t.character() == '~') {
2088 if (context.layout->free_spacing)
2091 begin_inset(os, "space ~\n");
2098 else if (t.cat() == catBegin) {
2099 Token const next = p.next_token();
2100 Token const end = p.next_next_token();
2101 if (next.cat() == catEnd) {
2103 Token const prev = p.prev_token();
2105 if (p.next_token().character() == '`' ||
2106 (prev.character() == '-' &&
2107 p.next_token().character() == '-'))
2108 ; // ignore it in {}`` or -{}-
2110 handle_ert(os, "{}", context);
2111 } else if (next.cat() == catEscape &&
2112 is_known(next.cs(), known_quotes) &&
2113 end.cat() == catEnd) {
2114 // Something like {\textquoteright} (e.g.
2115 // from writer2latex). LyX writes
2116 // \textquoteright{}, so we may skip the
2117 // braces here for better readability.
2118 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2121 context.check_layout(os);
2122 // special handling of font attribute changes
2123 Token const prev = p.prev_token();
2124 TeXFont const oldFont = context.font;
2125 if (next.character() == '[' ||
2126 next.character() == ']' ||
2127 next.character() == '*') {
2129 if (p.next_token().cat() == catEnd) {
2134 handle_ert(os, "{", context);
2135 parse_text_snippet(p, os,
2138 handle_ert(os, "}", context);
2140 } else if (! context.new_layout_allowed) {
2141 handle_ert(os, "{", context);
2142 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2144 handle_ert(os, "}", context);
2145 } else if (is_known(next.cs(), known_sizes)) {
2146 // next will change the size, so we must
2148 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2150 if (!context.atParagraphStart())
2152 << context.font.size << "\n";
2153 } else if (is_known(next.cs(), known_font_families)) {
2154 // next will change the font family, so we
2155 // must reset it here
2156 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2158 if (!context.atParagraphStart())
2160 << context.font.family << "\n";
2161 } else if (is_known(next.cs(), known_font_series)) {
2162 // next will change the font series, so we
2163 // must reset it here
2164 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2166 if (!context.atParagraphStart())
2168 << context.font.series << "\n";
2169 } else if (is_known(next.cs(), known_font_shapes)) {
2170 // next will change the font shape, so we
2171 // must reset it here
2172 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2174 if (!context.atParagraphStart())
2176 << context.font.shape << "\n";
2177 } else if (is_known(next.cs(), known_old_font_families) ||
2178 is_known(next.cs(), known_old_font_series) ||
2179 is_known(next.cs(), known_old_font_shapes)) {
2180 // next will change the font family, series
2181 // and shape, so we must reset it here
2182 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2184 if (!context.atParagraphStart())
2186 << context.font.family
2188 << context.font.series
2190 << context.font.shape << "\n";
2192 handle_ert(os, "{", context);
2193 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2195 handle_ert(os, "}", context);
2200 else if (t.cat() == catEnd) {
2201 if (flags & FLAG_BRACE_LAST) {
2204 cerr << "stray '}' in text\n";
2205 handle_ert(os, "}", context);
2208 else if (t.cat() == catComment)
2209 parse_comment(p, os, t, context);
2212 // control sequences
2215 else if (t.cs() == "(") {
2216 context.check_layout(os);
2217 begin_inset(os, "Formula");
2219 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2224 else if (t.cs() == "[") {
2225 context.check_layout(os);
2226 begin_inset(os, "Formula");
2228 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2231 // Prevent the conversion of a line break to a space
2232 // (bug 7668). This does not change the output, but
2233 // looks ugly in LyX.
2234 eat_whitespace(p, os, context, false);
2237 else if (t.cs() == "begin")
2238 parse_environment(p, os, outer, last_env,
2239 title_layout_found, context);
2241 else if (t.cs() == "end") {
2242 if (flags & FLAG_END) {
2243 // eat environment name
2244 string const name = p.getArg('{', '}');
2245 if (name != active_environment())
2246 cerr << "\\end{" + name + "} does not match \\begin{"
2247 + active_environment() + "}\n";
2250 p.error("found 'end' unexpectedly");
2253 else if (t.cs() == "item") {
2255 bool const optarg = p.hasOpt();
2257 // FIXME: This swallows comments, but we cannot use
2258 // eat_whitespace() since we must not output
2259 // anything before the item.
2260 p.skip_spaces(true);
2261 s = p.verbatimOption();
2263 p.skip_spaces(false);
2265 context.check_layout(os);
2266 if (context.has_item) {
2267 // An item in an unknown list-like environment
2268 // FIXME: Do this in check_layout()!
2269 context.has_item = false;
2271 handle_ert(os, "\\item", context);
2273 handle_ert(os, "\\item ", context);
2276 if (context.layout->labeltype != LABEL_MANUAL) {
2277 // LyX does not support \item[\mybullet]
2278 // in itemize environments
2280 os << parse_text_snippet(p2,
2281 FLAG_BRACK_LAST, outer, context);
2282 } else if (!s.empty()) {
2283 // LyX adds braces around the argument,
2284 // so we need to remove them here.
2285 if (s.size() > 2 && s[0] == '{' &&
2286 s[s.size()-1] == '}')
2287 s = s.substr(1, s.size()-2);
2288 // If the argument contains a space we
2289 // must put it into ERT: Otherwise LyX
2290 // would misinterpret the space as
2291 // item delimiter (bug 7663)
2292 if (contains(s, ' ')) {
2293 handle_ert(os, s, context);
2296 os << parse_text_snippet(p2,
2300 // The space is needed to separate the
2301 // item from the rest of the sentence.
2303 eat_whitespace(p, os, context, false);
2308 else if (t.cs() == "bibitem") {
2310 context.check_layout(os);
2311 eat_whitespace(p, os, context, false);
2312 string label = convert_command_inset_arg(p.verbatimOption());
2313 string key = convert_command_inset_arg(p.verbatim_item());
2314 if (contains(label, '\\') || contains(key, '\\')) {
2315 // LyX can't handle LaTeX commands in labels or keys
2316 handle_ert(os, t.asInput() + '[' + label +
2317 "]{" + p.verbatim_item() + '}',
2320 begin_command_inset(os, "bibitem", "bibitem");
2321 os << "label \"" << label << "\"\n"
2322 "key \"" << key << "\"\n";
2327 else if (is_macro(p)) {
2328 // catch the case of \def\inputGnumericTable
2330 if (t.cs() == "def") {
2331 Token second = p.next_token();
2332 if (second.cs() == "inputGnumericTable") {
2336 Token third = p.get_token();
2338 if (third.cs() == "input") {
2342 string name = normalize_filename(p.verbatim_item());
2343 string const path = getMasterFilePath();
2344 // We want to preserve relative / absolute filenames,
2345 // therefore path is only used for testing
2346 if (!makeAbsPath(name, path).exists()) {
2347 // The file extension is probably missing.
2348 // Now try to find it out.
2349 char const * const Gnumeric_formats[] = {"gnumeric"
2351 string const Gnumeric_name =
2352 find_file(name, path, Gnumeric_formats);
2353 if (!Gnumeric_name.empty())
2354 name = Gnumeric_name;
2356 if (makeAbsPath(name, path).exists())
2357 fix_relative_filename(name);
2359 cerr << "Warning: Could not find file '"
2360 << name << "'." << endl;
2361 context.check_layout(os);
2362 begin_inset(os, "External\n\ttemplate ");
2363 os << "GnumericSpreadsheet\n\tfilename "
2366 context.check_layout(os);
2372 parse_macro(p, os, context);
2375 else if (t.cs() == "noindent") {
2377 context.add_par_extra_stuff("\\noindent\n");
2380 else if (t.cs() == "appendix") {
2381 context.add_par_extra_stuff("\\start_of_appendix\n");
2382 // We need to start a new paragraph. Otherwise the
2383 // appendix in 'bla\appendix\chapter{' would start
2385 context.new_paragraph(os);
2386 // We need to make sure that the paragraph is
2387 // generated even if it is empty. Otherwise the
2388 // appendix in '\par\appendix\par\chapter{' would
2390 context.check_layout(os);
2391 // FIXME: This is a hack to prevent paragraph
2392 // deletion if it is empty. Handle this better!
2394 "%dummy comment inserted by tex2lyx to "
2395 "ensure that this paragraph is not empty",
2397 // Both measures above may generate an additional
2398 // empty paragraph, but that does not hurt, because
2399 // whitespace does not matter here.
2400 eat_whitespace(p, os, context, true);
2403 // Must catch empty dates before findLayout is called below
2404 else if (t.cs() == "date") {
2405 string const date = p.verbatim_item();
2407 preamble.suppressDate(true);
2409 preamble.suppressDate(false);
2410 if (context.new_layout_allowed &&
2411 (newlayout = findLayout(context.textclass,
2414 output_command_layout(os, p, outer,
2415 context, newlayout);
2417 if (!title_layout_found)
2418 title_layout_found = newlayout->intitle;
2419 set<string> const & req = newlayout->requires();
2420 for (set<string>::const_iterator it = req.begin();
2421 it != req.end(); it++)
2422 preamble.registerAutomaticallyLoadedPackage(*it);
2424 handle_ert(os, "\\date{" + date + '}',
2429 // Starred section headings
2430 // Must attempt to parse "Section*" before "Section".
2431 else if ((p.next_token().asInput() == "*") &&
2432 context.new_layout_allowed &&
2433 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2436 output_command_layout(os, p, outer, context, newlayout);
2438 if (!title_layout_found)
2439 title_layout_found = newlayout->intitle;
2440 set<string> const & req = newlayout->requires();
2441 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2442 preamble.registerAutomaticallyLoadedPackage(*it);
2445 // Section headings and the like
2446 else if (context.new_layout_allowed &&
2447 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2449 output_command_layout(os, p, outer, context, newlayout);
2451 if (!title_layout_found)
2452 title_layout_found = newlayout->intitle;
2453 set<string> const & req = newlayout->requires();
2454 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2455 preamble.registerAutomaticallyLoadedPackage(*it);
2458 else if (t.cs() == "caption") {
2460 context.check_layout(os);
2462 begin_inset(os, "Caption\n");
2463 Context newcontext(true, context.textclass);
2464 newcontext.font = context.font;
2465 newcontext.check_layout(os);
2466 if (p.next_token().cat() != catEscape &&
2467 p.next_token().character() == '[') {
2468 p.get_token(); // eat '['
2469 begin_inset(os, "Argument\n");
2470 os << "status collapsed\n";
2471 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2473 eat_whitespace(p, os, context, false);
2475 parse_text(p, os, FLAG_ITEM, outer, context);
2476 context.check_end_layout(os);
2477 // We don't need really a new paragraph, but
2478 // we must make sure that the next item gets a \begin_layout.
2479 context.new_paragraph(os);
2482 newcontext.check_end_layout(os);
2485 else if (t.cs() == "subfloat") {
2486 // the syntax is \subfloat[caption]{content}
2487 // if it is a table of figure depends on the surrounding float
2488 bool has_caption = false;
2490 // do nothing if there is no outer float
2491 if (!float_type.empty()) {
2492 context.check_layout(os);
2494 begin_inset(os, "Float " + float_type + "\n");
2496 << "\nsideways false"
2497 << "\nstatus collapsed\n\n";
2500 if (p.next_token().cat() != catEscape &&
2501 p.next_token().character() == '[') {
2502 p.get_token(); // eat '['
2503 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2507 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2508 // the caption comes always as the last
2510 // we must make sure that the caption gets a \begin_layout
2511 os << "\n\\begin_layout Plain Layout";
2513 begin_inset(os, "Caption\n");
2514 Context newcontext(true, context.textclass);
2515 newcontext.font = context.font;
2516 newcontext.check_layout(os);
2517 os << caption << "\n";
2518 newcontext.check_end_layout(os);
2519 // We don't need really a new paragraph, but
2520 // we must make sure that the next item gets a \begin_layout.
2521 //newcontext.new_paragraph(os);
2525 // We don't need really a new paragraph, but
2526 // we must make sure that the next item gets a \begin_layout.
2528 context.new_paragraph(os);
2531 context.check_end_layout(os);
2532 // close the layout we opened
2534 os << "\n\\end_layout\n";
2536 // if the float type is not supported or there is no surrounding float
2539 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2540 handle_ert(os, t.asInput() + '[' + opt_arg +
2541 "]{" + p.verbatim_item() + '}', context);
2543 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2547 else if (t.cs() == "includegraphics") {
2548 bool const clip = p.next_token().asInput() == "*";
2551 string const arg = p.getArg('[', ']');
2552 map<string, string> opts;
2553 vector<string> keys;
2554 split_map(arg, opts, keys);
2556 opts["clip"] = string();
2557 string name = normalize_filename(p.verbatim_item());
2559 string const path = getMasterFilePath();
2560 // We want to preserve relative / absolute filenames,
2561 // therefore path is only used for testing
2562 if (!makeAbsPath(name, path).exists()) {
2563 // The file extension is probably missing.
2564 // Now try to find it out.
2565 string const dvips_name =
2566 find_file(name, path,
2567 known_dvips_graphics_formats);
2568 string const pdftex_name =
2569 find_file(name, path,
2570 known_pdftex_graphics_formats);
2571 if (!dvips_name.empty()) {
2572 if (!pdftex_name.empty()) {
2573 cerr << "This file contains the "
2575 "\"\\includegraphics{"
2577 "However, files\n\""
2578 << dvips_name << "\" and\n\""
2579 << pdftex_name << "\"\n"
2580 "both exist, so I had to make a "
2581 "choice and took the first one.\n"
2582 "Please move the unwanted one "
2583 "someplace else and try again\n"
2584 "if my choice was wrong."
2588 } else if (!pdftex_name.empty()) {
2594 if (makeAbsPath(name, path).exists())
2595 fix_relative_filename(name);
2597 cerr << "Warning: Could not find graphics file '"
2598 << name << "'." << endl;
2600 context.check_layout(os);
2601 begin_inset(os, "Graphics ");
2602 os << "\n\tfilename " << name << '\n';
2603 if (opts.find("width") != opts.end())
2605 << translate_len(opts["width"]) << '\n';
2606 if (opts.find("height") != opts.end())
2608 << translate_len(opts["height"]) << '\n';
2609 if (opts.find("scale") != opts.end()) {
2610 istringstream iss(opts["scale"]);
2614 os << "\tscale " << val << '\n';
2616 if (opts.find("angle") != opts.end()) {
2617 os << "\trotateAngle "
2618 << opts["angle"] << '\n';
2619 vector<string>::const_iterator a =
2620 find(keys.begin(), keys.end(), "angle");
2621 vector<string>::const_iterator s =
2622 find(keys.begin(), keys.end(), "width");
2623 if (s == keys.end())
2624 s = find(keys.begin(), keys.end(), "height");
2625 if (s == keys.end())
2626 s = find(keys.begin(), keys.end(), "scale");
2627 if (s != keys.end() && distance(s, a) > 0)
2628 os << "\tscaleBeforeRotation\n";
2630 if (opts.find("origin") != opts.end()) {
2632 string const opt = opts["origin"];
2633 if (opt.find('l') != string::npos) ss << "left";
2634 if (opt.find('r') != string::npos) ss << "right";
2635 if (opt.find('c') != string::npos) ss << "center";
2636 if (opt.find('t') != string::npos) ss << "Top";
2637 if (opt.find('b') != string::npos) ss << "Bottom";
2638 if (opt.find('B') != string::npos) ss << "Baseline";
2639 if (!ss.str().empty())
2640 os << "\trotateOrigin " << ss.str() << '\n';
2642 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2644 if (opts.find("keepaspectratio") != opts.end())
2645 os << "\tkeepAspectRatio\n";
2646 if (opts.find("clip") != opts.end())
2648 if (opts.find("draft") != opts.end())
2650 if (opts.find("bb") != opts.end())
2651 os << "\tBoundingBox "
2652 << opts["bb"] << '\n';
2653 int numberOfbbOptions = 0;
2654 if (opts.find("bbllx") != opts.end())
2655 numberOfbbOptions++;
2656 if (opts.find("bblly") != opts.end())
2657 numberOfbbOptions++;
2658 if (opts.find("bburx") != opts.end())
2659 numberOfbbOptions++;
2660 if (opts.find("bbury") != opts.end())
2661 numberOfbbOptions++;
2662 if (numberOfbbOptions == 4)
2663 os << "\tBoundingBox "
2664 << opts["bbllx"] << " " << opts["bblly"] << " "
2665 << opts["bburx"] << " " << opts["bbury"] << '\n';
2666 else if (numberOfbbOptions > 0)
2667 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2668 numberOfbbOptions = 0;
2669 if (opts.find("natwidth") != opts.end())
2670 numberOfbbOptions++;
2671 if (opts.find("natheight") != opts.end())
2672 numberOfbbOptions++;
2673 if (numberOfbbOptions == 2)
2674 os << "\tBoundingBox 0bp 0bp "
2675 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2676 else if (numberOfbbOptions > 0)
2677 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2678 ostringstream special;
2679 if (opts.find("hiresbb") != opts.end())
2680 special << "hiresbb,";
2681 if (opts.find("trim") != opts.end())
2683 if (opts.find("viewport") != opts.end())
2684 special << "viewport=" << opts["viewport"] << ',';
2685 if (opts.find("totalheight") != opts.end())
2686 special << "totalheight=" << opts["totalheight"] << ',';
2687 if (opts.find("type") != opts.end())
2688 special << "type=" << opts["type"] << ',';
2689 if (opts.find("ext") != opts.end())
2690 special << "ext=" << opts["ext"] << ',';
2691 if (opts.find("read") != opts.end())
2692 special << "read=" << opts["read"] << ',';
2693 if (opts.find("command") != opts.end())
2694 special << "command=" << opts["command"] << ',';
2695 string s_special = special.str();
2696 if (!s_special.empty()) {
2697 // We had special arguments. Remove the trailing ','.
2698 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2700 // TODO: Handle the unknown settings better.
2701 // Warn about invalid options.
2702 // Check whether some option was given twice.
2706 else if (t.cs() == "footnote" ||
2707 (t.cs() == "thanks" && context.layout->intitle)) {
2709 context.check_layout(os);
2710 begin_inset(os, "Foot\n");
2711 os << "status collapsed\n\n";
2712 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2716 else if (t.cs() == "marginpar") {
2718 context.check_layout(os);
2719 begin_inset(os, "Marginal\n");
2720 os << "status collapsed\n\n";
2721 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2725 else if (t.cs() == "ensuremath") {
2727 context.check_layout(os);
2728 string const s = p.verbatim_item();
2729 //FIXME: this never triggers in UTF8
2730 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2733 handle_ert(os, "\\ensuremath{" + s + "}",
2737 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2738 if (title_layout_found) {
2740 skip_spaces_braces(p);
2742 handle_ert(os, t.asInput(), context);
2745 else if (t.cs() == "tableofcontents") {
2746 context.check_layout(os);
2747 begin_command_inset(os, "toc", "tableofcontents");
2749 skip_spaces_braces(p);
2752 else if (t.cs() == "listoffigures") {
2753 context.check_layout(os);
2754 begin_inset(os, "FloatList figure\n");
2756 skip_spaces_braces(p);
2759 else if (t.cs() == "listoftables") {
2760 context.check_layout(os);
2761 begin_inset(os, "FloatList table\n");
2763 skip_spaces_braces(p);
2766 else if (t.cs() == "listof") {
2767 p.skip_spaces(true);
2768 string const name = p.get_token().cs();
2769 if (context.textclass.floats().typeExist(name)) {
2770 context.check_layout(os);
2771 begin_inset(os, "FloatList ");
2774 p.get_token(); // swallow second arg
2776 handle_ert(os, "\\listof{" + name + "}", context);
2779 else if ((where = is_known(t.cs(), known_text_font_families)))
2780 parse_text_attributes(p, os, FLAG_ITEM, outer,
2781 context, "\\family", context.font.family,
2782 known_coded_font_families[where - known_text_font_families]);
2784 else if ((where = is_known(t.cs(), known_text_font_series)))
2785 parse_text_attributes(p, os, FLAG_ITEM, outer,
2786 context, "\\series", context.font.series,
2787 known_coded_font_series[where - known_text_font_series]);
2789 else if ((where = is_known(t.cs(), known_text_font_shapes)))
2790 parse_text_attributes(p, os, FLAG_ITEM, outer,
2791 context, "\\shape", context.font.shape,
2792 known_coded_font_shapes[where - known_text_font_shapes]);
2794 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2795 context.check_layout(os);
2796 TeXFont oldFont = context.font;
2797 context.font.init();
2798 context.font.size = oldFont.size;
2799 os << "\n\\family " << context.font.family << "\n";
2800 os << "\n\\series " << context.font.series << "\n";
2801 os << "\n\\shape " << context.font.shape << "\n";
2802 if (t.cs() == "textnormal") {
2803 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2804 output_font_change(os, context.font, oldFont);
2805 context.font = oldFont;
2807 eat_whitespace(p, os, context, false);
2810 else if (t.cs() == "textcolor") {
2811 // scheme is \textcolor{color name}{text}
2812 string const color = p.verbatim_item();
2813 // we only support the predefined colors of the color package
2814 if (color == "black" || color == "blue" || color == "cyan"
2815 || color == "green" || color == "magenta" || color == "red"
2816 || color == "white" || color == "yellow") {
2817 context.check_layout(os);
2818 os << "\n\\color " << color << "\n";
2819 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2820 context.check_layout(os);
2821 os << "\n\\color inherit\n";
2822 preamble.registerAutomaticallyLoadedPackage("color");
2824 // for custom defined colors
2825 handle_ert(os, t.asInput() + "{" + color + "}", context);
2828 else if (t.cs() == "underbar" || t.cs() == "uline") {
2829 // \underbar is not 100% correct (LyX outputs \uline
2830 // of ulem.sty). The difference is that \ulem allows
2831 // line breaks, and \underbar does not.
2832 // Do NOT handle \underline.
2833 // \underbar cuts through y, g, q, p etc.,
2834 // \underline does not.
2835 context.check_layout(os);
2836 os << "\n\\bar under\n";
2837 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2838 context.check_layout(os);
2839 os << "\n\\bar default\n";
2840 preamble.registerAutomaticallyLoadedPackage("ulem");
2843 else if (t.cs() == "sout") {
2844 context.check_layout(os);
2845 os << "\n\\strikeout on\n";
2846 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2847 context.check_layout(os);
2848 os << "\n\\strikeout default\n";
2849 preamble.registerAutomaticallyLoadedPackage("ulem");
2852 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2853 t.cs() == "emph" || t.cs() == "noun") {
2854 context.check_layout(os);
2855 os << "\n\\" << t.cs() << " on\n";
2856 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2857 context.check_layout(os);
2858 os << "\n\\" << t.cs() << " default\n";
2859 if (t.cs() == "uuline" || t.cs() == "uwave")
2860 preamble.registerAutomaticallyLoadedPackage("ulem");
2863 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2864 context.check_layout(os);
2865 string name = p.getArg('{', '}');
2866 string localtime = p.getArg('{', '}');
2867 preamble.registerAuthor(name);
2868 Author const & author = preamble.getAuthor(name);
2869 // from_ctime() will fail if LyX decides to output the
2870 // time in the text language. It might also use a wrong
2871 // time zone (if the original LyX document was exported
2872 // with a different time zone).
2873 time_t ptime = from_ctime(localtime);
2874 if (ptime == static_cast<time_t>(-1)) {
2875 cerr << "Warning: Could not parse time `" << localtime
2876 << "´ for change tracking, using current time instead.\n";
2877 ptime = current_time();
2879 if (t.cs() == "lyxadded")
2880 os << "\n\\change_inserted ";
2882 os << "\n\\change_deleted ";
2883 os << author.bufferId() << ' ' << ptime << '\n';
2884 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2885 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2886 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2887 LaTeXPackages::isAvailable("xcolor");
2888 // No need to test for luatex, since luatex comes in
2889 // two flavours (dvi and pdf), like latex, and those
2890 // are detected by pdflatex.
2891 if (pdflatex || xetex) {
2893 preamble.registerAutomaticallyLoadedPackage("ulem");
2894 preamble.registerAutomaticallyLoadedPackage("xcolor");
2895 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2899 preamble.registerAutomaticallyLoadedPackage("dvipost");
2900 } else if (xcolorulem) {
2901 preamble.registerAutomaticallyLoadedPackage("ulem");
2902 preamble.registerAutomaticallyLoadedPackage("xcolor");
2907 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2908 t.cs() == "vphantom") {
2909 context.check_layout(os);
2910 if (t.cs() == "phantom")
2911 begin_inset(os, "Phantom Phantom\n");
2912 if (t.cs() == "hphantom")
2913 begin_inset(os, "Phantom HPhantom\n");
2914 if (t.cs() == "vphantom")
2915 begin_inset(os, "Phantom VPhantom\n");
2916 os << "status open\n";
2917 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2922 else if (t.cs() == "href") {
2923 context.check_layout(os);
2924 string target = p.getArg('{', '}');
2925 string name = p.getArg('{', '}');
2927 size_t i = target.find(':');
2928 if (i != string::npos) {
2929 type = target.substr(0, i + 1);
2930 if (type == "mailto:" || type == "file:")
2931 target = target.substr(i + 1);
2932 // handle the case that name is equal to target, except of "http://"
2933 else if (target.substr(i + 3) == name && type == "http:")
2936 begin_command_inset(os, "href", "href");
2938 os << "name \"" << name << "\"\n";
2939 os << "target \"" << target << "\"\n";
2940 if (type == "mailto:" || type == "file:")
2941 os << "type \"" << type << "\"\n";
2943 skip_spaces_braces(p);
2946 else if (t.cs() == "lyxline") {
2947 // swallow size argument (it is not used anyway)
2949 if (!context.atParagraphStart()) {
2950 // so our line is in the middle of a paragraph
2951 // we need to add a new line, lest this line
2952 // follow the other content on that line and
2953 // run off the side of the page
2954 // FIXME: This may create an empty paragraph,
2955 // but without that it would not be
2956 // possible to set noindent below.
2957 // Fortunately LaTeX does not care
2958 // about the empty paragraph.
2959 context.new_paragraph(os);
2961 if (preamble.indentParagraphs()) {
2962 // we need to unindent, lest the line be too long
2963 context.add_par_extra_stuff("\\noindent\n");
2965 context.check_layout(os);
2966 begin_command_inset(os, "line", "rule");
2967 os << "offset \"0.5ex\"\n"
2968 "width \"100line%\"\n"
2973 else if (t.cs() == "rule") {
2974 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2975 string const width = p.getArg('{', '}');
2976 string const thickness = p.getArg('{', '}');
2977 context.check_layout(os);
2978 begin_command_inset(os, "line", "rule");
2979 if (!offset.empty())
2980 os << "offset \"" << translate_len(offset) << "\"\n";
2981 os << "width \"" << translate_len(width) << "\"\n"
2982 "height \"" << translate_len(thickness) << "\"\n";
2986 else if (is_known(t.cs(), known_phrases) ||
2987 (t.cs() == "protect" &&
2988 p.next_token().cat() == catEscape &&
2989 is_known(p.next_token().cs(), known_phrases))) {
2990 // LyX sometimes puts a \protect in front, so we have to ignore it
2991 // FIXME: This needs to be changed when bug 4752 is fixed.
2993 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2995 context.check_layout(os);
2996 os << known_coded_phrases[where - known_phrases];
2997 skip_spaces_braces(p);
3000 else if ((where = is_known(t.cs(), known_ref_commands))) {
3001 string const opt = p.getOpt();
3003 context.check_layout(os);
3004 begin_command_inset(os, "ref",
3005 known_coded_ref_commands[where - known_ref_commands]);
3006 os << "reference \""
3007 << convert_command_inset_arg(p.verbatim_item())
3011 // LyX does not support optional arguments of ref commands
3012 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3013 p.verbatim_item() + "}", context);
3017 else if (use_natbib &&
3018 is_known(t.cs(), known_natbib_commands) &&
3019 ((t.cs() != "citefullauthor" &&
3020 t.cs() != "citeyear" &&
3021 t.cs() != "citeyearpar") ||
3022 p.next_token().asInput() != "*")) {
3023 context.check_layout(os);
3024 string command = t.cs();
3025 if (p.next_token().asInput() == "*") {
3029 if (command == "citefullauthor")
3030 // alternative name for "\\citeauthor*"
3031 command = "citeauthor*";
3033 // text before the citation
3035 // text after the citation
3037 get_cite_arguments(p, true, before, after);
3039 if (command == "cite") {
3040 // \cite without optional argument means
3041 // \citet, \cite with at least one optional
3042 // argument means \citep.
3043 if (before.empty() && after.empty())
3048 if (before.empty() && after == "[]")
3049 // avoid \citet[]{a}
3051 else if (before == "[]" && after == "[]") {
3052 // avoid \citet[][]{a}
3056 // remove the brackets around after and before
3057 if (!after.empty()) {
3059 after.erase(after.length() - 1, 1);
3060 after = convert_command_inset_arg(after);
3062 if (!before.empty()) {
3064 before.erase(before.length() - 1, 1);
3065 before = convert_command_inset_arg(before);
3067 begin_command_inset(os, "citation", command);
3068 os << "after " << '"' << after << '"' << "\n";
3069 os << "before " << '"' << before << '"' << "\n";
3071 << convert_command_inset_arg(p.verbatim_item())
3076 else if (use_jurabib &&
3077 is_known(t.cs(), known_jurabib_commands) &&
3078 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3079 context.check_layout(os);
3080 string command = t.cs();
3081 if (p.next_token().asInput() == "*") {
3085 char argumentOrder = '\0';
3086 vector<string> const options =
3087 preamble.getPackageOptions("jurabib");
3088 if (find(options.begin(), options.end(),
3089 "natbiborder") != options.end())
3090 argumentOrder = 'n';
3091 else if (find(options.begin(), options.end(),
3092 "jurabiborder") != options.end())
3093 argumentOrder = 'j';
3095 // text before the citation
3097 // text after the citation
3099 get_cite_arguments(p, argumentOrder != 'j', before, after);
3101 string const citation = p.verbatim_item();
3102 if (!before.empty() && argumentOrder == '\0') {
3103 cerr << "Warning: Assuming argument order "
3104 "of jurabib version 0.6 for\n'"
3105 << command << before << after << '{'
3106 << citation << "}'.\n"
3107 "Add 'jurabiborder' to the jurabib "
3108 "package options if you used an\n"
3109 "earlier jurabib version." << endl;
3111 if (!after.empty()) {
3113 after.erase(after.length() - 1, 1);
3115 if (!before.empty()) {
3117 before.erase(before.length() - 1, 1);
3119 begin_command_inset(os, "citation", command);
3120 os << "after " << '"' << after << '"' << "\n";
3121 os << "before " << '"' << before << '"' << "\n";
3122 os << "key " << '"' << citation << '"' << "\n";
3126 else if (t.cs() == "cite"
3127 || t.cs() == "nocite") {
3128 context.check_layout(os);
3129 string after = convert_command_inset_arg(p.getArg('[', ']'));
3130 string key = convert_command_inset_arg(p.verbatim_item());
3131 // store the case that it is "\nocite{*}" to use it later for
3134 begin_command_inset(os, "citation", t.cs());
3135 os << "after " << '"' << after << '"' << "\n";
3136 os << "key " << '"' << key << '"' << "\n";
3138 } else if (t.cs() == "nocite")
3142 else if (t.cs() == "index") {
3143 context.check_layout(os);
3144 begin_inset(os, "Index idx\n");
3145 os << "status collapsed\n";
3146 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3150 else if (t.cs() == "nomenclature") {
3151 context.check_layout(os);
3152 begin_command_inset(os, "nomenclature", "nomenclature");
3153 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3154 if (!prefix.empty())
3155 os << "prefix " << '"' << prefix << '"' << "\n";
3156 os << "symbol " << '"'
3157 << convert_command_inset_arg(p.verbatim_item());
3158 os << "\"\ndescription \""
3159 << convert_command_inset_arg(p.verbatim_item())
3162 preamble.registerAutomaticallyLoadedPackage("nomencl");
3165 else if (t.cs() == "label") {
3166 context.check_layout(os);
3167 begin_command_inset(os, "label", "label");
3169 << convert_command_inset_arg(p.verbatim_item())
3174 else if (t.cs() == "printindex") {
3175 context.check_layout(os);
3176 begin_command_inset(os, "index_print", "printindex");
3177 os << "type \"idx\"\n";
3179 skip_spaces_braces(p);
3180 preamble.registerAutomaticallyLoadedPackage("makeidx");
3181 if (preamble.use_indices() == "true")
3182 preamble.registerAutomaticallyLoadedPackage("splitidx");
3185 else if (t.cs() == "printnomenclature") {
3187 string width_type = "";
3188 context.check_layout(os);
3189 begin_command_inset(os, "nomencl_print", "printnomenclature");
3190 // case of a custom width
3192 width = p.getArg('[', ']');
3193 width = translate_len(width);
3194 width_type = "custom";
3196 // case of no custom width
3197 // the case of no custom width but the width set
3198 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3199 // because the user could have set anything, not only the width
3200 // of the longest label (which would be width_type = "auto")
3201 string label = convert_command_inset_arg(p.getArg('{', '}'));
3202 if (label.empty() && width_type.empty())
3203 width_type = "none";
3204 os << "set_width \"" << width_type << "\"\n";
3205 if (width_type == "custom")
3206 os << "width \"" << width << '\"';
3208 skip_spaces_braces(p);
3209 preamble.registerAutomaticallyLoadedPackage("nomencl");
3212 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3213 context.check_layout(os);
3214 begin_inset(os, "script ");
3215 os << t.cs().substr(4) << '\n';
3216 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3218 if (t.cs() == "textsubscript")
3219 preamble.registerAutomaticallyLoadedPackage("subscript");
3222 else if ((where = is_known(t.cs(), known_quotes))) {
3223 context.check_layout(os);
3224 begin_inset(os, "Quotes ");
3225 os << known_coded_quotes[where - known_quotes];
3227 // LyX adds {} after the quote, so we have to eat
3228 // spaces here if there are any before a possible
3230 eat_whitespace(p, os, context, false);
3234 else if ((where = is_known(t.cs(), known_sizes)) &&
3235 context.new_layout_allowed) {
3236 context.check_layout(os);
3237 TeXFont const oldFont = context.font;
3238 context.font.size = known_coded_sizes[where - known_sizes];
3239 output_font_change(os, oldFont, context.font);
3240 eat_whitespace(p, os, context, false);
3243 else if ((where = is_known(t.cs(), known_font_families)) &&
3244 context.new_layout_allowed) {
3245 context.check_layout(os);
3246 TeXFont const oldFont = context.font;
3247 context.font.family =
3248 known_coded_font_families[where - known_font_families];
3249 output_font_change(os, oldFont, context.font);
3250 eat_whitespace(p, os, context, false);
3253 else if ((where = is_known(t.cs(), known_font_series)) &&
3254 context.new_layout_allowed) {
3255 context.check_layout(os);
3256 TeXFont const oldFont = context.font;
3257 context.font.series =
3258 known_coded_font_series[where - known_font_series];
3259 output_font_change(os, oldFont, context.font);
3260 eat_whitespace(p, os, context, false);
3263 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3264 context.new_layout_allowed) {
3265 context.check_layout(os);
3266 TeXFont const oldFont = context.font;
3267 context.font.shape =
3268 known_coded_font_shapes[where - known_font_shapes];
3269 output_font_change(os, oldFont, context.font);
3270 eat_whitespace(p, os, context, false);
3272 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3273 context.new_layout_allowed) {
3274 context.check_layout(os);
3275 TeXFont const oldFont = context.font;
3276 context.font.init();
3277 context.font.size = oldFont.size;
3278 context.font.family =
3279 known_coded_font_families[where - known_old_font_families];
3280 output_font_change(os, oldFont, context.font);
3281 eat_whitespace(p, os, context, false);
3284 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3285 context.new_layout_allowed) {
3286 context.check_layout(os);
3287 TeXFont const oldFont = context.font;
3288 context.font.init();
3289 context.font.size = oldFont.size;
3290 context.font.series =
3291 known_coded_font_series[where - known_old_font_series];
3292 output_font_change(os, oldFont, context.font);
3293 eat_whitespace(p, os, context, false);
3296 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3297 context.new_layout_allowed) {
3298 context.check_layout(os);
3299 TeXFont const oldFont = context.font;
3300 context.font.init();
3301 context.font.size = oldFont.size;
3302 context.font.shape =
3303 known_coded_font_shapes[where - known_old_font_shapes];
3304 output_font_change(os, oldFont, context.font);
3305 eat_whitespace(p, os, context, false);
3308 else if (t.cs() == "selectlanguage") {
3309 context.check_layout(os);
3310 // save the language for the case that a
3311 // \foreignlanguage is used
3313 context.font.language = babel2lyx(p.verbatim_item());
3314 os << "\n\\lang " << context.font.language << "\n";
3317 else if (t.cs() == "foreignlanguage") {
3318 string const lang = babel2lyx(p.verbatim_item());
3319 parse_text_attributes(p, os, FLAG_ITEM, outer,
3321 context.font.language, lang);
3324 else if (t.cs() == "inputencoding") {
3325 // nothing to write here
3326 string const enc = subst(p.verbatim_item(), "\n", " ");
3330 else if ((where = is_known(t.cs(), known_special_chars))) {
3331 context.check_layout(os);
3332 os << "\\SpecialChar \\"
3333 << known_coded_special_chars[where - known_special_chars]
3335 skip_spaces_braces(p);
3338 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3339 context.check_layout(os);
3340 os << "\\SpecialChar \\nobreakdash-\n";
3344 else if (t.cs() == "textquotedbl") {
3345 context.check_layout(os);
3350 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3351 context.check_layout(os);
3352 os << "\\SpecialChar \\@.\n";
3356 else if (t.cs() == "-") {
3357 context.check_layout(os);
3358 os << "\\SpecialChar \\-\n";
3361 else if (t.cs() == "textasciitilde") {
3362 context.check_layout(os);
3364 skip_spaces_braces(p);
3367 else if (t.cs() == "textasciicircum") {
3368 context.check_layout(os);
3370 skip_spaces_braces(p);
3373 else if (t.cs() == "textbackslash") {
3374 context.check_layout(os);
3375 os << "\n\\backslash\n";
3376 skip_spaces_braces(p);
3379 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3380 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3382 context.check_layout(os);
3386 else if (t.cs() == "char") {
3387 context.check_layout(os);
3388 if (p.next_token().character() == '`') {
3390 if (p.next_token().cs() == "\"") {
3395 handle_ert(os, "\\char`", context);
3398 handle_ert(os, "\\char", context);
3402 else if (t.cs() == "verb") {
3403 context.check_layout(os);
3404 char const delimiter = p.next_token().character();
3405 string const arg = p.getArg(delimiter, delimiter);
3407 oss << "\\verb" << delimiter << arg << delimiter;
3408 handle_ert(os, oss.str(), context);
3411 // Problem: \= creates a tabstop inside the tabbing environment
3412 // and else an accent. In the latter case we really would want
3413 // \={o} instead of \= o.
3414 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3415 handle_ert(os, t.asInput(), context);
3417 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3418 else if (t.cs().size() == 1
3419 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3420 context.check_layout(os);
3421 // try to see whether the string is in unicodesymbols
3423 string command = t.asInput() + "{"
3424 + trimSpaceAndEol(p.verbatim_item())
3426 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3429 cerr << "When parsing " << command
3430 << ", result is " << to_utf8(s)
3431 << "+" << to_utf8(rem) << endl;
3434 // we did not find a non-ert version
3435 handle_ert(os, command, context);
3438 else if (t.cs() == "\\") {
3439 context.check_layout(os);
3441 handle_ert(os, "\\\\" + p.getOpt(), context);
3442 else if (p.next_token().asInput() == "*") {
3444 // getOpt() eats the following space if there
3445 // is no optional argument, but that is OK
3446 // here since it has no effect in the output.
3447 handle_ert(os, "\\\\*" + p.getOpt(), context);
3450 begin_inset(os, "Newline newline");
3455 else if (t.cs() == "newline" ||
3456 (t.cs() == "linebreak" && !p.hasOpt())) {
3457 context.check_layout(os);
3458 begin_inset(os, "Newline ");
3461 skip_spaces_braces(p);
3464 else if (t.cs() == "input" || t.cs() == "include"
3465 || t.cs() == "verbatiminput") {
3466 string name = t.cs();
3467 if (t.cs() == "verbatiminput"
3468 && p.next_token().asInput() == "*")
3469 name += p.get_token().asInput();
3470 context.check_layout(os);
3471 string filename(normalize_filename(p.getArg('{', '}')));
3472 string const path = getMasterFilePath();
3473 // We want to preserve relative / absolute filenames,
3474 // therefore path is only used for testing
3475 if ((t.cs() == "include" || t.cs() == "input") &&
3476 !makeAbsPath(filename, path).exists()) {
3477 // The file extension is probably missing.
3478 // Now try to find it out.
3479 string const tex_name =
3480 find_file(filename, path,
3481 known_tex_extensions);
3482 if (!tex_name.empty())
3483 filename = tex_name;
3485 bool external = false;
3487 if (makeAbsPath(filename, path).exists()) {
3488 string const abstexname =
3489 makeAbsPath(filename, path).absFileName();
3490 string const abslyxname =
3491 changeExtension(abstexname, ".lyx");
3492 string const absfigname =
3493 changeExtension(abstexname, ".fig");
3494 fix_relative_filename(filename);
3495 string const lyxname =
3496 changeExtension(filename, ".lyx");
3498 external = FileName(absfigname).exists();
3499 if (t.cs() == "input") {
3500 string const ext = getExtension(abstexname);
3502 // Combined PS/LaTeX:
3503 // x.eps, x.pstex_t (old xfig)
3504 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3505 FileName const absepsname(
3506 changeExtension(abstexname, ".eps"));
3507 FileName const abspstexname(
3508 changeExtension(abstexname, ".pstex"));
3509 bool const xfigeps =
3510 (absepsname.exists() ||
3511 abspstexname.exists()) &&
3514 // Combined PDF/LaTeX:
3515 // x.pdf, x.pdftex_t (old xfig)
3516 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3517 FileName const abspdfname(
3518 changeExtension(abstexname, ".pdf"));
3519 bool const xfigpdf =
3520 abspdfname.exists() &&
3521 (ext == "pdftex_t" || ext == "pdf_t");
3525 // Combined PS/PDF/LaTeX:
3526 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3527 string const absbase2(
3528 removeExtension(abstexname) + "_pspdftex");
3529 FileName const abseps2name(
3530 addExtension(absbase2, ".eps"));
3531 FileName const abspdf2name(
3532 addExtension(absbase2, ".pdf"));
3533 bool const xfigboth =
3534 abspdf2name.exists() &&
3535 abseps2name.exists() && ext == "pspdftex";
3537 xfig = xfigpdf || xfigeps || xfigboth;
3538 external = external && xfig;
3541 outname = changeExtension(filename, ".fig");
3543 // Don't try to convert, the result
3544 // would be full of ERT.
3546 } else if (t.cs() != "verbatiminput" &&
3547 tex2lyx(abstexname, FileName(abslyxname),
3554 cerr << "Warning: Could not find included file '"
3555 << filename << "'." << endl;
3559 begin_inset(os, "External\n");
3560 os << "\ttemplate XFig\n"
3561 << "\tfilename " << outname << '\n';
3563 begin_command_inset(os, "include", name);
3564 os << "preview false\n"
3565 "filename \"" << outname << "\"\n";
3570 else if (t.cs() == "bibliographystyle") {
3571 // store new bibliographystyle
3572 bibliographystyle = p.verbatim_item();
3573 // If any other command than \bibliography and
3574 // \nocite{*} follows, we need to output the style
3575 // (because it might be used by that command).
3576 // Otherwise, it will automatically be output by LyX.
3579 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3580 if (t2.cat() == catBegin)
3582 if (t2.cat() != catEscape)
3584 if (t2.cs() == "nocite") {
3585 if (p.getArg('{', '}') == "*")
3587 } else if (t2.cs() == "bibliography")
3594 "\\bibliographystyle{" + bibliographystyle + '}',
3599 else if (t.cs() == "bibliography") {
3600 context.check_layout(os);
3601 begin_command_inset(os, "bibtex", "bibtex");
3602 if (!btprint.empty()) {
3603 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3604 // clear the string because the next BibTeX inset can be without the
3605 // \nocite{*} option
3608 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3609 // Do we have a bibliographystyle set?
3610 if (!bibliographystyle.empty())
3611 os << "options " << '"' << bibliographystyle << '"' << "\n";
3615 else if (t.cs() == "parbox") {
3616 // Test whether this is an outer box of a shaded box
3618 // swallow arguments
3619 while (p.hasOpt()) {
3621 p.skip_spaces(true);
3624 p.skip_spaces(true);
3626 if (p.next_token().cat() == catBegin)
3628 p.skip_spaces(true);
3629 Token to = p.get_token();
3630 bool shaded = false;
3631 if (to.asInput() == "\\begin") {
3632 p.skip_spaces(true);
3633 if (p.getArg('{', '}') == "shaded")
3638 parse_outer_box(p, os, FLAG_ITEM, outer,
3639 context, "parbox", "shaded");
3641 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3645 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3646 t.cs() == "shadowbox" || t.cs() == "doublebox")
3647 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3649 else if (t.cs() == "framebox") {
3650 if (p.next_token().character() == '(') {
3651 //the syntax is: \framebox(x,y)[position]{content}
3652 string arg = t.asInput();
3653 arg += p.getFullParentheseArg();
3654 arg += p.getFullOpt();
3655 eat_whitespace(p, os, context, false);
3656 handle_ert(os, arg + '{', context);
3657 eat_whitespace(p, os, context, false);
3658 parse_text(p, os, FLAG_ITEM, outer, context);
3659 handle_ert(os, "}", context);
3661 string special = p.getFullOpt();
3662 special += p.getOpt();
3663 parse_outer_box(p, os, FLAG_ITEM, outer,
3664 context, t.cs(), special);
3668 //\makebox() is part of the picture environment and different from \makebox{}
3669 //\makebox{} will be parsed by parse_box
3670 else if (t.cs() == "makebox") {
3671 if (p.next_token().character() == '(') {
3672 //the syntax is: \makebox(x,y)[position]{content}
3673 string arg = t.asInput();
3674 arg += p.getFullParentheseArg();
3675 arg += p.getFullOpt();
3676 eat_whitespace(p, os, context, false);
3677 handle_ert(os, arg + '{', context);
3678 eat_whitespace(p, os, context, false);
3679 parse_text(p, os, FLAG_ITEM, outer, context);
3680 handle_ert(os, "}", context);
3682 //the syntax is: \makebox[width][position]{content}
3683 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3687 else if (t.cs() == "smallskip" ||
3688 t.cs() == "medskip" ||
3689 t.cs() == "bigskip" ||
3690 t.cs() == "vfill") {
3691 context.check_layout(os);
3692 begin_inset(os, "VSpace ");
3695 skip_spaces_braces(p);
3698 else if ((where = is_known(t.cs(), known_spaces))) {
3699 context.check_layout(os);
3700 begin_inset(os, "space ");
3701 os << '\\' << known_coded_spaces[where - known_spaces]
3704 // LaTeX swallows whitespace after all spaces except
3705 // "\\,". We have to do that here, too, because LyX
3706 // adds "{}" which would make the spaces significant.
3708 eat_whitespace(p, os, context, false);
3709 // LyX adds "{}" after all spaces except "\\ " and
3710 // "\\,", so we have to remove "{}".
3711 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3712 // remove the braces after "\\,", too.
3717 else if (t.cs() == "newpage" ||
3718 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3719 t.cs() == "clearpage" ||
3720 t.cs() == "cleardoublepage") {
3721 context.check_layout(os);
3722 begin_inset(os, "Newpage ");
3725 skip_spaces_braces(p);
3728 else if (t.cs() == "DeclareRobustCommand" ||
3729 t.cs() == "DeclareRobustCommandx" ||
3730 t.cs() == "newcommand" ||
3731 t.cs() == "newcommandx" ||
3732 t.cs() == "providecommand" ||
3733 t.cs() == "providecommandx" ||
3734 t.cs() == "renewcommand" ||
3735 t.cs() == "renewcommandx") {
3736 // DeclareRobustCommand, DeclareRobustCommandx,
3737 // providecommand and providecommandx could be handled
3738 // by parse_command(), but we need to call
3739 // add_known_command() here.
3740 string name = t.asInput();
3741 if (p.next_token().asInput() == "*") {
3742 // Starred form. Eat '*'
3746 string const command = p.verbatim_item();
3747 string const opt1 = p.getFullOpt();
3748 string const opt2 = p.getFullOpt();
3749 add_known_command(command, opt1, !opt2.empty());
3750 string const ert = name + '{' + command + '}' +
3752 '{' + p.verbatim_item() + '}';
3754 if (t.cs() == "DeclareRobustCommand" ||
3755 t.cs() == "DeclareRobustCommandx" ||
3756 t.cs() == "providecommand" ||
3757 t.cs() == "providecommandx" ||
3758 name[name.length()-1] == '*')
3759 handle_ert(os, ert, context);
3761 context.check_layout(os);
3762 begin_inset(os, "FormulaMacro");
3768 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3769 // let could be handled by parse_command(),
3770 // but we need to call add_known_command() here.
3771 string ert = t.asInput();
3774 if (p.next_token().cat() == catBegin) {
3775 name = p.verbatim_item();
3776 ert += '{' + name + '}';
3778 name = p.verbatim_item();
3783 if (p.next_token().cat() == catBegin) {
3784 command = p.verbatim_item();
3785 ert += '{' + command + '}';
3787 command = p.verbatim_item();
3790 // If command is known, make name known too, to parse
3791 // its arguments correctly. For this reason we also
3792 // have commands in syntax.default that are hardcoded.
3793 CommandMap::iterator it = known_commands.find(command);
3794 if (it != known_commands.end())
3795 known_commands[t.asInput()] = it->second;
3796 handle_ert(os, ert, context);
3799 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3800 bool starred = false;
3801 if (p.next_token().asInput() == "*") {
3805 string name = t.asInput();
3806 string const length = p.verbatim_item();
3809 bool valid = splitLatexLength(length, valstring, unit);
3810 bool known_hspace = false;
3811 bool known_vspace = false;
3812 bool known_unit = false;
3815 istringstream iss(valstring);
3818 if (t.cs()[0] == 'h') {
3819 if (unit == "\\fill") {
3824 known_hspace = true;
3827 if (unit == "\\smallskipamount") {
3829 known_vspace = true;
3830 } else if (unit == "\\medskipamount") {
3832 known_vspace = true;
3833 } else if (unit == "\\bigskipamount") {
3835 known_vspace = true;
3836 } else if (unit == "\\fill") {
3838 known_vspace = true;
3842 if (!known_hspace && !known_vspace) {
3843 switch (unitFromString(unit)) {
3864 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3865 // Literal horizontal length or known variable
3866 context.check_layout(os);
3867 begin_inset(os, "space ");
3875 if (known_unit && !known_hspace)
3877 << translate_len(length);
3879 } else if (known_unit || known_vspace) {
3880 // Literal vertical length or known variable
3881 context.check_layout(os);
3882 begin_inset(os, "VSpace ");
3890 // LyX can't handle other length variables in Inset VSpace/space
3895 handle_ert(os, name + '{' + unit + '}', context);
3896 else if (value == -1.0)
3897 handle_ert(os, name + "{-" + unit + '}', context);
3899 handle_ert(os, name + '{' + valstring + unit + '}', context);
3901 handle_ert(os, name + '{' + length + '}', context);
3905 // The single '=' is meant here.
3906 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3908 context.check_layout(os);
3909 begin_inset(os, "Flex ");
3910 os << to_utf8(newinsetlayout->name()) << '\n'
3911 << "status collapsed\n";
3912 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3916 else if (t.cs() == "includepdf") {
3918 string const arg = p.getArg('[', ']');
3919 map<string, string> opts;
3920 vector<string> keys;
3921 split_map(arg, opts, keys);
3922 string name = normalize_filename(p.verbatim_item());
3923 string const path = getMasterFilePath();
3924 // We want to preserve relative / absolute filenames,
3925 // therefore path is only used for testing
3926 if (!makeAbsPath(name, path).exists()) {
3927 // The file extension is probably missing.
3928 // Now try to find it out.
3929 char const * const pdfpages_format[] = {"pdf", 0};
3930 string const pdftex_name =
3931 find_file(name, path, pdfpages_format);
3932 if (!pdftex_name.empty()) {
3937 if (makeAbsPath(name, path).exists())
3938 fix_relative_filename(name);
3940 cerr << "Warning: Could not find file '"
3941 << name << "'." << endl;
3943 context.check_layout(os);
3944 begin_inset(os, "External\n\ttemplate ");
3945 os << "PDFPages\n\tfilename "
3947 // parse the options
3948 if (opts.find("pages") != opts.end())
3949 os << "\textra LaTeX \"pages="
3950 << opts["pages"] << "\"\n";
3951 if (opts.find("angle") != opts.end())
3952 os << "\trotateAngle "
3953 << opts["angle"] << '\n';
3954 if (opts.find("origin") != opts.end()) {
3956 string const opt = opts["origin"];
3957 if (opt == "tl") ss << "topleft";
3958 if (opt == "bl") ss << "bottomleft";
3959 if (opt == "Bl") ss << "baselineleft";
3960 if (opt == "c") ss << "center";
3961 if (opt == "tc") ss << "topcenter";
3962 if (opt == "bc") ss << "bottomcenter";
3963 if (opt == "Bc") ss << "baselinecenter";
3964 if (opt == "tr") ss << "topright";
3965 if (opt == "br") ss << "bottomright";
3966 if (opt == "Br") ss << "baselineright";
3967 if (!ss.str().empty())
3968 os << "\trotateOrigin " << ss.str() << '\n';
3970 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3972 if (opts.find("width") != opts.end())
3974 << translate_len(opts["width"]) << '\n';
3975 if (opts.find("height") != opts.end())
3977 << translate_len(opts["height"]) << '\n';
3978 if (opts.find("keepaspectratio") != opts.end())
3979 os << "\tkeepAspectRatio\n";
3981 context.check_layout(os);
3984 else if (t.cs() == "loadgame") {
3986 string name = normalize_filename(p.verbatim_item());
3987 string const path = getMasterFilePath();
3988 // We want to preserve relative / absolute filenames,
3989 // therefore path is only used for testing
3990 if (!makeAbsPath(name, path).exists()) {
3991 // The file extension is probably missing.
3992 // Now try to find it out.
3993 char const * const lyxskak_format[] = {"fen", 0};
3994 string const lyxskak_name =
3995 find_file(name, path, lyxskak_format);
3996 if (!lyxskak_name.empty())
3997 name = lyxskak_name;
3999 if (makeAbsPath(name, path).exists())
4000 fix_relative_filename(name);
4002 cerr << "Warning: Could not find file '"
4003 << name << "'." << endl;
4004 context.check_layout(os);
4005 begin_inset(os, "External\n\ttemplate ");
4006 os << "ChessDiagram\n\tfilename "
4009 context.check_layout(os);
4010 // after a \loadgame follows a \showboard
4011 if (p.get_token().asInput() == "showboard")
4016 // try to see whether the string is in unicodesymbols
4017 // Only use text mode commands, since we are in text mode here,
4018 // and math commands may be invalid (bug 6797)
4020 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4021 rem, Encodings::TEXT_CMD);
4024 cerr << "When parsing " << t.cs()
4025 << ", result is " << to_utf8(s)
4026 << "+" << to_utf8(rem) << endl;
4027 context.check_layout(os);
4029 skip_spaces_braces(p);
4031 //cerr << "#: " << t << " mode: " << mode << endl;
4032 // heuristic: read up to next non-nested space
4034 string s = t.asInput();
4035 string z = p.verbatim_item();
4036 while (p.good() && z != " " && z.size()) {
4037 //cerr << "read: " << z << endl;
4039 z = p.verbatim_item();
4041 cerr << "found ERT: " << s << endl;
4042 handle_ert(os, s + ' ', context);
4045 string name = t.asInput();
4046 if (p.next_token().asInput() == "*") {
4047 // Starred commands like \vspace*{}
4048 p.get_token(); // Eat '*'
4051 if (!parse_command(name, p, os, outer, context))
4052 handle_ert(os, name, context);
4056 if (flags & FLAG_LEAVE) {
4057 flags &= ~FLAG_LEAVE;