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"
25 #include "support/lassert.h"
26 #include "support/convert.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
38 using namespace lyx::support;
43 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
44 Context const & context, InsetLayout const * layout)
46 bool const forcePlainLayout =
47 layout ? layout->forcePlainLayout() : false;
48 Context newcontext(true, context.textclass);
50 newcontext.layout = &context.textclass.plainLayout();
52 newcontext.font = context.font;
53 parse_text(p, os, flags, outer, newcontext);
54 newcontext.check_end_layout(os);
60 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
61 Context const & context, string const & name)
63 InsetLayout const * layout = 0;
64 DocumentClass::InsetLayouts::const_iterator it =
65 context.textclass.insetLayouts().find(from_ascii(name));
66 if (it != context.textclass.insetLayouts().end())
67 layout = &(it->second);
68 parse_text_in_inset(p, os, flags, outer, context, layout);
71 /// parses a paragraph snippet, useful for example for \\emph{...}
72 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
75 Context newcontext(context);
76 // Don't inherit the paragraph-level extra stuff
77 newcontext.par_extra_stuff.clear();
78 parse_text(p, os, flags, outer, newcontext);
79 // Make sure that we don't create invalid .lyx files
80 context.need_layout = newcontext.need_layout;
81 context.need_end_layout = newcontext.need_end_layout;
86 * Thin wrapper around parse_text_snippet() using a string.
88 * We completely ignore \c context.need_layout and \c context.need_end_layout,
89 * because our return value is not used directly (otherwise the stream version
90 * of parse_text_snippet() could be used). That means that the caller needs
91 * to do layout management manually.
92 * This is intended to parse text that does not create any layout changes.
94 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
97 Context newcontext(context);
98 newcontext.need_layout = false;
99 newcontext.need_end_layout = false;
100 newcontext.new_layout_allowed = false;
101 // Avoid warning by Context::~Context()
102 newcontext.par_extra_stuff.clear();
104 parse_text_snippet(p, os, flags, outer, newcontext);
109 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
110 "vpageref", "prettyref", "eqref", 0 };
112 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
113 "vpageref", "formatted", "eqref", 0 };
117 * The starred forms are also known except for "citefullauthor",
118 * "citeyear" and "citeyearpar".
120 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
121 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
122 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
126 * No starred form other than "cite*" known.
128 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
129 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
130 // jurabib commands not (yet) supported by LyX:
132 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
133 // "footciteauthor", "footciteyear", "footciteyearpar",
134 "citefield", "citetitle", 0 };
136 /// LaTeX names for quotes
137 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
138 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
139 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
140 "guilsinglleft", "frq", "guilsinglright", 0};
142 /// the same as known_quotes with .lyx names
143 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
144 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
145 "gld", "grd", "gls", "ers", "fls",
146 "fls", "frs", "frs", 0};
148 /// LaTeX names for font sizes
149 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
150 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
152 /// the same as known_sizes with .lyx names
153 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
154 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
156 /// LaTeX 2.09 names for font families
157 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
159 /// LaTeX names for font families
160 char const * const known_font_families[] = { "rmfamily", "sffamily",
163 /// the same as known_old_font_families and known_font_families with .lyx names
164 char const * const known_coded_font_families[] = { "roman", "sans",
167 /// LaTeX 2.09 names for font series
168 char const * const known_old_font_series[] = { "bf", 0};
170 /// LaTeX names for font series
171 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
173 /// the same as known_old_font_series and known_font_series with .lyx names
174 char const * const known_coded_font_series[] = { "bold", "medium", 0};
176 /// LaTeX 2.09 names for font shapes
177 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
179 /// LaTeX names for font shapes
180 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
183 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
184 char const * const known_coded_font_shapes[] = { "italic", "slanted",
185 "smallcaps", "up", 0};
188 * Graphics file extensions known by the dvips driver of the graphics package.
189 * These extensions are used to complete the filename of an included
190 * graphics file if it does not contain an extension.
191 * The order must be the same that latex uses to find a file, because we
192 * will use the first extension that matches.
193 * This is only an approximation for the common cases. If we would want to
194 * do it right in all cases, we would need to know which graphics driver is
195 * used and know the extensions of every driver of the graphics package.
197 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
198 "ps.gz", "eps.Z", "ps.Z", 0};
201 * Graphics file extensions known by the pdftex driver of the graphics package.
202 * \sa known_dvips_graphics_formats
204 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
208 * Known file extensions for TeX files as used by \\include.
210 char const * const known_tex_extensions[] = {"tex", 0};
212 /// spaces known by InsetSpace
213 char const * const known_spaces[] = { " ", "space", ",",
214 "thinspace", "quad", "qquad", "enspace", "enskip",
215 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
216 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
217 "upbracefill", "downbracefill", 0};
219 /// the same as known_spaces with .lyx names
220 char const * const known_coded_spaces[] = { "space{}", "space{}",
221 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
222 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
223 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
224 "upbracefill{}", "downbracefill{}", 0};
226 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
227 /// them in ERT. "LaTeXe" must come before "LaTeX"!
228 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
229 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
230 int const known_phrase_lengths[] = {3, 5, 7, 0};
233 /// splits "x=z, y=b" into a map and an ordered keyword vector
234 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
239 keys.resize(v.size());
240 for (size_t i = 0; i < v.size(); ++i) {
241 size_t const pos = v[i].find('=');
242 string const index = trimSpaceAndEol(v[i].substr(0, pos));
243 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
251 * Split a LaTeX length into value and unit.
252 * The latter can be a real unit like "pt", or a latex length variable
253 * like "\textwidth". The unit may contain additional stuff like glue
254 * lengths, but we don't care, because such lengths are ERT anyway.
255 * \returns true if \p value and \p unit are valid.
257 bool splitLatexLength(string const & len, string & value, string & unit)
261 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
262 //'4,5' is a valid LaTeX length number. Change it to '4.5'
263 string const length = subst(len, ',', '.');
264 if (i == string::npos)
267 if (len[0] == '\\') {
268 // We had something like \textwidth without a factor
274 value = trimSpaceAndEol(string(length, 0, i));
278 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
279 if (contains(len, '\\'))
280 unit = trimSpaceAndEol(string(len, i));
282 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
287 /// A simple function to translate a latex length to something LyX can
288 /// understand. Not perfect, but rather best-effort.
289 bool translate_len(string const & length, string & valstring, string & unit)
291 if (!splitLatexLength(length, valstring, unit))
293 // LyX uses percent values
295 istringstream iss(valstring);
300 string const percentval = oss.str();
302 if (unit.empty() || unit[0] != '\\')
304 string::size_type const i = unit.find(' ');
305 string const endlen = (i == string::npos) ? string() : string(unit, i);
306 if (unit == "\\textwidth") {
307 valstring = percentval;
308 unit = "text%" + endlen;
309 } else if (unit == "\\columnwidth") {
310 valstring = percentval;
311 unit = "col%" + endlen;
312 } else if (unit == "\\paperwidth") {
313 valstring = percentval;
314 unit = "page%" + endlen;
315 } else if (unit == "\\linewidth") {
316 valstring = percentval;
317 unit = "line%" + endlen;
318 } else if (unit == "\\paperheight") {
319 valstring = percentval;
320 unit = "pheight%" + endlen;
321 } else if (unit == "\\textheight") {
322 valstring = percentval;
323 unit = "theight%" + endlen;
331 string translate_len(string const & length)
335 if (translate_len(length, value, unit))
337 // If the input is invalid, return what we have.
345 * Translates a LaTeX length into \p value, \p unit and
346 * \p special parts suitable for a box inset.
347 * The difference from translate_len() is that a box inset knows about
348 * some special "units" that are stored in \p special.
350 void translate_box_len(string const & length, string & value, string & unit, string & special)
352 if (translate_len(length, value, unit)) {
353 if (unit == "\\height" || unit == "\\depth" ||
354 unit == "\\totalheight" || unit == "\\width") {
355 special = unit.substr(1);
356 // The unit is not used, but LyX requires a dummy setting
369 * Find a file with basename \p name in path \p path and an extension
372 string find_file(string const & name, string const & path,
373 char const * const * extensions)
375 for (char const * const * what = extensions; *what; ++what) {
376 string const trial = addExtension(name, *what);
377 if (makeAbsPath(trial, path).exists())
384 void begin_inset(ostream & os, string const & name)
386 os << "\n\\begin_inset " << name;
390 void begin_command_inset(ostream & os, string const & name,
391 string const & latexname)
393 begin_inset(os, "CommandInset ");
394 os << name << "\nLatexCommand " << latexname << '\n';
398 void end_inset(ostream & os)
400 os << "\n\\end_inset\n\n";
404 bool skip_braces(Parser & p)
406 if (p.next_token().cat() != catBegin)
409 if (p.next_token().cat() == catEnd) {
418 /// replace LaTeX commands in \p s from the unicodesymbols file with their
420 docstring convert_unicodesymbols(docstring s)
423 for (size_t i = 0; i < s.size();) {
430 docstring parsed = encodings.fromLaTeXCommand(s, rem,
431 Encodings::TEXT_CMD);
434 if (s.empty() || s[0] != '\\')
443 /// try to convert \p s to a valid InsetCommand argument
444 string convert_command_inset_arg(string s)
447 // since we don't know the input encoding we can't use from_utf8
448 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
449 // LyX cannot handle newlines in a latex command
450 return subst(s, "\n", " ");
454 void handle_backslash(ostream & os, string const & s)
456 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
458 os << "\n\\backslash\n";
465 void handle_ert(ostream & os, string const & s, Context & context)
467 // We must have a valid layout before outputting the ERT inset.
468 context.check_layout(os);
469 Context newcontext(true, context.textclass);
470 begin_inset(os, "ERT");
471 os << "\nstatus collapsed\n";
472 newcontext.check_layout(os);
473 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
475 os << "\n\\backslash\n";
476 else if (*it == '\n') {
477 newcontext.new_paragraph(os);
478 newcontext.check_layout(os);
482 newcontext.check_end_layout(os);
487 void handle_comment(ostream & os, string const & s, Context & context)
489 // TODO: Handle this better
490 Context newcontext(true, context.textclass);
491 begin_inset(os, "ERT");
492 os << "\nstatus collapsed\n";
493 newcontext.check_layout(os);
494 handle_backslash(os, s);
495 // make sure that our comment is the last thing on the line
496 newcontext.new_paragraph(os);
497 newcontext.check_layout(os);
498 newcontext.check_end_layout(os);
503 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
505 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
508 if (checkModule(name, command))
509 return findLayoutWithoutModule(textclass, name, command);
514 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
516 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
519 if (checkModule(name, command))
520 return findInsetLayoutWithoutModule(textclass, name, command);
525 void eat_whitespace(Parser &, ostream &, Context &, bool);
529 * Skips whitespace and braces.
530 * This should be called after a command has been parsed that is not put into
531 * ERT, and where LyX adds "{}" if needed.
533 void skip_spaces_braces(Parser & p, bool keepws = false)
535 /* The following four examples produce the same typeset output and
536 should be handled by this function:
544 // Unfortunately we need to skip comments, too.
545 // We can't use eat_whitespace since writing them after the {}
546 // results in different output in some cases.
547 bool const skipped_spaces = p.skip_spaces(true);
548 bool const skipped_braces = skip_braces(p);
549 if (keepws && skipped_spaces && !skipped_braces)
550 // put back the space (it is better handled by check_space)
551 p.unskip_spaces(true);
555 void output_command_layout(ostream & os, Parser & p, bool outer,
556 Context & parent_context,
557 Layout const * newlayout)
559 TeXFont const oldFont = parent_context.font;
560 // save the current font size
561 string const size = oldFont.size;
562 // reset the font size to default, because the font size switches
563 // don't affect section headings and the like
564 parent_context.font.size = Context::normalfont.size;
565 // we only need to write the font change if we have an open layout
566 if (!parent_context.atParagraphStart())
567 output_font_change(os, oldFont, parent_context.font);
568 parent_context.check_end_layout(os);
569 Context context(true, parent_context.textclass, newlayout,
570 parent_context.layout, parent_context.font);
571 if (parent_context.deeper_paragraph) {
572 // We are beginning a nested environment after a
573 // deeper paragraph inside the outer list environment.
574 // Therefore we don't need to output a "begin deeper".
575 context.need_end_deeper = true;
577 context.check_deeper(os);
578 context.check_layout(os);
579 unsigned int optargs = 0;
580 while (optargs < context.layout->optargs) {
581 eat_whitespace(p, os, context, false);
582 if (p.next_token().cat() == catEscape ||
583 p.next_token().character() != '[')
585 p.get_token(); // eat '['
586 begin_inset(os, "Argument\n");
587 os << "status collapsed\n\n";
588 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
590 eat_whitespace(p, os, context, false);
593 unsigned int reqargs = 0;
594 while (reqargs < context.layout->reqargs) {
595 eat_whitespace(p, os, context, false);
596 if (p.next_token().cat() != catBegin)
598 p.get_token(); // eat '{'
599 begin_inset(os, "Argument\n");
600 os << "status collapsed\n\n";
601 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
603 eat_whitespace(p, os, context, false);
606 parse_text(p, os, FLAG_ITEM, outer, context);
607 context.check_end_layout(os);
608 if (parent_context.deeper_paragraph) {
609 // We must suppress the "end deeper" because we
610 // suppressed the "begin deeper" above.
611 context.need_end_deeper = false;
613 context.check_end_deeper(os);
614 // We don't need really a new paragraph, but
615 // we must make sure that the next item gets a \begin_layout.
616 parent_context.new_paragraph(os);
617 // Set the font size to the original value. No need to output it here
618 // (Context::begin_layout() will do that if needed)
619 parent_context.font.size = size;
624 * Output a space if necessary.
625 * This function gets called for every whitespace token.
627 * We have three cases here:
628 * 1. A space must be suppressed. Example: The lyxcode case below
629 * 2. A space may be suppressed. Example: Spaces before "\par"
630 * 3. A space must not be suppressed. Example: A space between two words
632 * We currently handle only 1. and 3 and from 2. only the case of
633 * spaces before newlines as a side effect.
635 * 2. could be used to suppress as many spaces as possible. This has two effects:
636 * - Reimporting LyX generated LaTeX files changes almost no whitespace
637 * - Superflous whitespace from non LyX generated LaTeX files is removed.
638 * The drawback is that the logic inside the function becomes
639 * complicated, and that is the reason why it is not implemented.
641 void check_space(Parser & p, ostream & os, Context & context)
643 Token const next = p.next_token();
644 Token const curr = p.curr_token();
645 // A space before a single newline and vice versa must be ignored
646 // LyX emits a newline before \end{lyxcode}.
647 // This newline must be ignored,
648 // otherwise LyX will add an additional protected space.
649 if (next.cat() == catSpace ||
650 next.cat() == catNewline ||
651 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
654 context.check_layout(os);
660 * Parse all arguments of \p command
662 void parse_arguments(string const & command,
663 vector<ArgumentType> const & template_arguments,
664 Parser & p, ostream & os, bool outer, Context & context)
666 string ert = command;
667 size_t no_arguments = template_arguments.size();
668 for (size_t i = 0; i < no_arguments; ++i) {
669 switch (template_arguments[i]) {
671 // This argument contains regular LaTeX
672 handle_ert(os, ert + '{', context);
673 eat_whitespace(p, os, context, false);
674 parse_text(p, os, FLAG_ITEM, outer, context);
678 // This argument consists only of a single item.
679 // The presence of '{' or not must be preserved.
681 if (p.next_token().cat() == catBegin)
682 ert += '{' + p.verbatim_item() + '}';
684 ert += p.verbatim_item();
687 // This argument may contain special characters
688 ert += '{' + p.verbatim_item() + '}';
691 // true because we must not eat whitespace
692 // if an optional arg follows we must not strip the
693 // brackets from this one
694 if (i < no_arguments - 1 &&
695 template_arguments[i+1] == optional)
696 ert += p.getFullOpt(true);
698 ert += p.getOpt(true);
702 handle_ert(os, ert, context);
707 * Check whether \p command is a known command. If yes,
708 * handle the command with all arguments.
709 * \return true if the command was parsed, false otherwise.
711 bool parse_command(string const & command, Parser & p, ostream & os,
712 bool outer, Context & context)
714 if (known_commands.find(command) != known_commands.end()) {
715 parse_arguments(command, known_commands[command], p, os,
723 /// Parses a minipage or parbox
724 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
725 unsigned inner_flags, bool outer, Context & parent_context,
726 string const & outer_type, string const & special,
727 string const & inner_type)
731 string hor_pos = "c";
732 // We need to set the height to the LaTeX default of 1\\totalheight
733 // for the case when no height argument is given
734 string height_value = "1";
735 string height_unit = "in";
736 string height_special = "totalheight";
738 if (!inner_type.empty() && p.hasOpt()) {
739 position = p.getArg('[', ']');
740 if (position != "t" && position != "c" && position != "b") {
741 cerr << "invalid position " << position << " for "
742 << inner_type << endl;
746 latex_height = p.getArg('[', ']');
747 translate_box_len(latex_height, height_value, height_unit, height_special);
750 inner_pos = p.getArg('[', ']');
751 if (inner_pos != "c" && inner_pos != "t" &&
752 inner_pos != "b" && inner_pos != "s") {
753 cerr << "invalid inner_pos "
754 << inner_pos << " for "
755 << inner_type << endl;
756 inner_pos = position;
764 if (inner_type.empty()) {
766 latex_width = "\\columnwidth";
769 latex_width = p2.getArg('[', ']');
770 string const opt = p2.getArg('[', ']');
773 if (hor_pos != "l" && hor_pos != "c" &&
775 cerr << "invalid hor_pos " << hor_pos
776 << " for " << outer_type << endl;
782 latex_width = p.verbatim_item();
783 translate_len(latex_width, width_value, width_unit);
784 // LyX can't handle length variables
785 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
786 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
787 // Look whether there is some content after the end of the
788 // inner box, but before the end of the outer box.
789 // If yes, we need to output ERT.
791 if (inner_flags & FLAG_END)
792 p.verbatimEnvironment(inner_type);
796 if ((outer_type == "framed" && p.next_token().asInput() != "\\end") ||
797 (outer_type != "framed" && p.next_token().cat() != catEnd)) {
798 // something is between the end of the inner box and
799 // the end of the outer box, so we need to use ERT.
806 if (!outer_type.empty()) {
807 if (outer_flags & FLAG_END)
808 ss << "\\begin{" << outer_type << '}';
810 ss << '\\' << outer_type << '{';
811 if (!special.empty())
815 if (!inner_type.empty()) {
816 if (inner_flags & FLAG_END)
817 ss << "\\begin{" << inner_type << '}';
819 ss << '\\' << inner_type;
820 if (!position.empty())
821 ss << '[' << position << ']';
822 if (!latex_height.empty())
823 ss << '[' << latex_height << ']';
824 if (!inner_pos.empty())
825 ss << '[' << inner_pos << ']';
826 ss << '{' << latex_width << '}';
827 if (!(inner_flags & FLAG_END))
830 handle_ert(os, ss.str(), parent_context);
831 if (!inner_type.empty()) {
832 parse_text(p, os, inner_flags, outer, parent_context);
833 if (inner_flags & FLAG_END)
834 handle_ert(os, "\\end{" + inner_type + '}',
837 handle_ert(os, "}", parent_context);
839 if (!outer_type.empty()) {
840 parse_text(p, os, outer_flags, outer, parent_context);
841 if (outer_flags & FLAG_END)
842 handle_ert(os, "\\end{" + outer_type + '}',
845 handle_ert(os, "}", parent_context);
848 // LyX does not like empty positions, so we have
849 // to set them to the LaTeX default values here.
850 if (position.empty())
852 if (inner_pos.empty())
853 inner_pos = position;
854 parent_context.check_layout(os);
855 begin_inset(os, "Box ");
856 if (outer_type == "framed")
858 else if (outer_type == "framebox")
860 else if (outer_type == "shadowbox")
862 else if (outer_type == "shaded")
864 else if (outer_type == "doublebox")
866 else if (outer_type.empty())
869 os << outer_type << '\n';
870 os << "position \"" << position << "\"\n";
871 os << "hor_pos \"" << hor_pos << "\"\n";
872 os << "has_inner_box " << !inner_type.empty() << "\n";
873 os << "inner_pos \"" << inner_pos << "\"\n";
874 os << "use_parbox " << (inner_type == "parbox") << '\n';
875 os << "use_makebox 0\n";
876 os << "width \"" << width_value << width_unit << "\"\n";
877 os << "special \"none\"\n";
878 os << "height \"" << height_value << height_unit << "\"\n";
879 os << "height_special \"" << height_special << "\"\n";
880 os << "status open\n\n";
881 Context context(true, parent_context.textclass);
882 context.font = parent_context.font;
884 // FIXME, the inset layout should be plain, not standard, see bug #7846
886 // If we have no inner box the contens will be read with the outer box
887 if (!inner_type.empty())
888 parse_text(p, os, inner_flags, outer, context);
890 // Ensure that the end of the outer box is parsed correctly:
891 // The opening brace has been eaten by parse_outer_box()
892 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
893 outer_flags &= ~FLAG_ITEM;
894 outer_flags |= FLAG_BRACE_LAST;
897 // Find end of outer box, output contents if inner_type is
898 // empty and output possible comments
899 if (!outer_type.empty()) {
900 // This does not output anything but comments if
901 // inner_type is not empty (see use_ert)
902 parse_text(p, os, outer_flags, outer, context);
905 context.check_end_layout(os);
907 #ifdef PRESERVE_LAYOUT
908 // LyX puts a % after the end of the minipage
909 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
911 //handle_comment(os, "%dummy", parent_context);
914 parent_context.new_paragraph(os);
916 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
917 //handle_comment(os, "%dummy", parent_context);
920 // We add a protected space if something real follows
921 if (p.good() && p.next_token().cat() != catComment) {
922 begin_inset(os, "space ~\n");
931 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
932 Context & parent_context, string const & outer_type,
933 string const & special)
935 eat_whitespace(p, os, parent_context, false);
936 if (flags & FLAG_ITEM) {
938 if (p.next_token().cat() == catBegin)
941 cerr << "Warning: Ignoring missing '{' after \\"
942 << outer_type << '.' << endl;
943 eat_whitespace(p, os, parent_context, false);
946 unsigned int inner_flags = 0;
947 if (outer_type == "shaded") {
948 // These boxes never have an inner box
950 } else if (p.next_token().asInput() == "\\parbox") {
951 inner = p.get_token().cs();
952 inner_flags = FLAG_ITEM;
953 } else if (p.next_token().asInput() == "\\begin") {
954 // Is this a minipage?
957 inner = p.getArg('{', '}');
959 if (inner == "minipage") {
962 eat_whitespace(p, os, parent_context, false);
963 inner_flags = FLAG_END;
967 if (inner_flags == FLAG_END) {
968 active_environments.push_back(inner);
969 parse_box(p, os, flags, FLAG_END, outer, parent_context,
970 outer_type, special, inner);
971 active_environments.pop_back();
973 parse_box(p, os, flags, inner_flags, outer, parent_context,
974 outer_type, special, inner);
979 void parse_listings(Parser & p, ostream & os, Context & parent_context)
981 parent_context.check_layout(os);
982 begin_inset(os, "listings\n");
983 os << "inline false\n"
984 << "status collapsed\n";
985 Context context(true, parent_context.textclass);
986 context.layout = &parent_context.textclass.plainLayout();
987 context.check_layout(os);
988 string const s = p.verbatimEnvironment("lstlisting");
989 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
991 os << "\n\\backslash\n";
992 else if (*it == '\n') {
993 // avoid adding an empty paragraph at the end
995 context.new_paragraph(os);
996 context.check_layout(os);
1001 context.check_end_layout(os);
1006 /// parse an unknown environment
1007 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1008 unsigned flags, bool outer,
1009 Context & parent_context)
1011 if (name == "tabbing")
1012 // We need to remember that we have to handle '\=' specially
1013 flags |= FLAG_TABBING;
1015 // We need to translate font changes and paragraphs inside the
1016 // environment to ERT if we have a non standard font.
1017 // Otherwise things like
1018 // \large\begin{foo}\huge bar\end{foo}
1020 bool const specialfont =
1021 (parent_context.font != parent_context.normalfont);
1022 bool const new_layout_allowed = parent_context.new_layout_allowed;
1024 parent_context.new_layout_allowed = false;
1025 handle_ert(os, "\\begin{" + name + "}", parent_context);
1026 parse_text_snippet(p, os, flags, outer, parent_context);
1027 handle_ert(os, "\\end{" + name + "}", parent_context);
1029 parent_context.new_layout_allowed = new_layout_allowed;
1033 void parse_environment(Parser & p, ostream & os, bool outer,
1034 string & last_env, Context & parent_context)
1036 Layout const * newlayout;
1037 InsetLayout const * newinsetlayout = 0;
1038 string const name = p.getArg('{', '}');
1039 const bool is_starred = suffixIs(name, '*');
1040 string const unstarred_name = rtrim(name, "*");
1041 active_environments.push_back(name);
1043 if (is_math_env(name)) {
1044 parent_context.check_layout(os);
1045 begin_inset(os, "Formula ");
1046 os << "\\begin{" << name << "}";
1047 parse_math(p, os, FLAG_END, MATH_MODE);
1048 os << "\\end{" << name << "}";
1052 else if (name == "tabular" || name == "longtable") {
1053 eat_whitespace(p, os, parent_context, false);
1054 parent_context.check_layout(os);
1055 begin_inset(os, "Tabular ");
1056 handle_tabular(p, os, name == "longtable", parent_context);
1061 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1062 eat_whitespace(p, os, parent_context, false);
1063 parent_context.check_layout(os);
1064 begin_inset(os, "Float " + unstarred_name + "\n");
1066 os << "placement " << p.getArg('[', ']') << '\n';
1067 os << "wide " << convert<string>(is_starred)
1068 << "\nsideways false"
1069 << "\nstatus open\n\n";
1070 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1072 // We don't need really a new paragraph, but
1073 // we must make sure that the next item gets a \begin_layout.
1074 parent_context.new_paragraph(os);
1078 else if (unstarred_name == "sidewaysfigure"
1079 || unstarred_name == "sidewaystable") {
1080 eat_whitespace(p, os, parent_context, false);
1081 parent_context.check_layout(os);
1082 if (unstarred_name == "sidewaysfigure")
1083 begin_inset(os, "Float figure\n");
1085 begin_inset(os, "Float table\n");
1086 os << "wide " << convert<string>(is_starred)
1087 << "\nsideways true"
1088 << "\nstatus open\n\n";
1089 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1091 // We don't need really a new paragraph, but
1092 // we must make sure that the next item gets a \begin_layout.
1093 parent_context.new_paragraph(os);
1097 else if (name == "minipage") {
1098 eat_whitespace(p, os, parent_context, false);
1099 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1103 else if (name == "comment") {
1104 eat_whitespace(p, os, parent_context, false);
1105 parent_context.check_layout(os);
1106 begin_inset(os, "Note Comment\n");
1107 os << "status open\n";
1108 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1111 skip_braces(p); // eat {} that might by set by LyX behind comments
1114 else if (name == "lyxgreyedout") {
1115 eat_whitespace(p, os, parent_context, false);
1116 parent_context.check_layout(os);
1117 begin_inset(os, "Note Greyedout\n");
1118 os << "status open\n";
1119 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1124 else if (name == "framed" || name == "shaded") {
1125 eat_whitespace(p, os, parent_context, false);
1126 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1130 else if (name == "lstlisting") {
1131 eat_whitespace(p, os, parent_context, false);
1132 // FIXME handle listings with parameters
1134 parse_unknown_environment(p, name, os, FLAG_END,
1135 outer, parent_context);
1137 parse_listings(p, os, parent_context);
1141 else if (!parent_context.new_layout_allowed)
1142 parse_unknown_environment(p, name, os, FLAG_END, outer,
1145 // Alignment and spacing settings
1146 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1147 // therefore are totally broken!
1148 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1149 // they are commands not environments. They are furthermore switches that
1150 // can be ended by another switches, but also by commands like \footnote or
1151 // \parbox. So the only safe way is to leave them untouched.
1152 else if (name == "center" || name == "centering" ||
1153 name == "flushleft" || name == "flushright" ||
1154 name == "singlespace" || name == "onehalfspace" ||
1155 name == "doublespace" || name == "spacing") {
1156 eat_whitespace(p, os, parent_context, false);
1157 // We must begin a new paragraph if not already done
1158 if (! parent_context.atParagraphStart()) {
1159 parent_context.check_end_layout(os);
1160 parent_context.new_paragraph(os);
1162 if (name == "flushleft")
1163 parent_context.add_extra_stuff("\\align left\n");
1164 else if (name == "flushright")
1165 parent_context.add_extra_stuff("\\align right\n");
1166 else if (name == "center" || name == "centering")
1167 parent_context.add_extra_stuff("\\align center\n");
1168 else if (name == "singlespace")
1169 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1170 else if (name == "onehalfspace")
1171 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1172 else if (name == "doublespace")
1173 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1174 else if (name == "spacing")
1175 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1176 parse_text(p, os, FLAG_END, outer, parent_context);
1177 // Just in case the environment is empty
1178 parent_context.extra_stuff.erase();
1179 // We must begin a new paragraph to reset the alignment
1180 parent_context.new_paragraph(os);
1184 // The single '=' is meant here.
1185 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1186 eat_whitespace(p, os, parent_context, false);
1187 Context context(true, parent_context.textclass, newlayout,
1188 parent_context.layout, parent_context.font);
1189 if (parent_context.deeper_paragraph) {
1190 // We are beginning a nested environment after a
1191 // deeper paragraph inside the outer list environment.
1192 // Therefore we don't need to output a "begin deeper".
1193 context.need_end_deeper = true;
1195 parent_context.check_end_layout(os);
1196 if (last_env == name) {
1197 // we need to output a separator since LyX would export
1198 // the two environments as one otherwise (bug 5716)
1199 docstring const sep = from_ascii("--Separator--");
1200 TeX2LyXDocClass const & textclass(parent_context.textclass);
1201 if (textclass.hasLayout(sep)) {
1202 Context newcontext(parent_context);
1203 newcontext.layout = &(textclass[sep]);
1204 newcontext.check_layout(os);
1205 newcontext.check_end_layout(os);
1207 parent_context.check_layout(os);
1208 begin_inset(os, "Note Note\n");
1209 os << "status closed\n";
1210 Context newcontext(true, textclass,
1211 &(textclass.defaultLayout()));
1212 newcontext.check_layout(os);
1213 newcontext.check_end_layout(os);
1215 parent_context.check_end_layout(os);
1218 switch (context.layout->latextype) {
1219 case LATEX_LIST_ENVIRONMENT:
1220 context.add_par_extra_stuff("\\labelwidthstring "
1221 + p.verbatim_item() + '\n');
1224 case LATEX_BIB_ENVIRONMENT:
1225 p.verbatim_item(); // swallow next arg
1231 context.check_deeper(os);
1232 // handle known optional and required arguments
1233 // layouts require all optional arguments before the required ones
1234 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1235 // It is impossible to place anything after the environment name,
1236 // but before the first \\item.
1237 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1238 bool need_layout = true;
1239 unsigned int optargs = 0;
1240 while (optargs < context.layout->optargs) {
1241 eat_whitespace(p, os, context, false);
1242 if (p.next_token().cat() == catEscape ||
1243 p.next_token().character() != '[')
1245 p.get_token(); // eat '['
1247 context.check_layout(os);
1248 need_layout = false;
1250 begin_inset(os, "Argument\n");
1251 os << "status collapsed\n\n";
1252 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1254 eat_whitespace(p, os, context, false);
1257 unsigned int reqargs = 0;
1258 while (reqargs < context.layout->reqargs) {
1259 eat_whitespace(p, os, context, false);
1260 if (p.next_token().cat() != catBegin)
1262 p.get_token(); // eat '{'
1264 context.check_layout(os);
1265 need_layout = false;
1267 begin_inset(os, "Argument\n");
1268 os << "status collapsed\n\n";
1269 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1271 eat_whitespace(p, os, context, false);
1275 parse_text(p, os, FLAG_END, outer, context);
1276 context.check_end_layout(os);
1277 if (parent_context.deeper_paragraph) {
1278 // We must suppress the "end deeper" because we
1279 // suppressed the "begin deeper" above.
1280 context.need_end_deeper = false;
1282 context.check_end_deeper(os);
1283 parent_context.new_paragraph(os);
1287 // The single '=' is meant here.
1288 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1289 eat_whitespace(p, os, parent_context, false);
1290 parent_context.check_layout(os);
1291 begin_inset(os, "Flex ");
1292 os << to_utf8(newinsetlayout->name()) << '\n'
1293 << "status collapsed\n";
1294 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1298 else if (name == "appendix") {
1299 // This is no good latex style, but it works and is used in some documents...
1300 eat_whitespace(p, os, parent_context, false);
1301 parent_context.check_end_layout(os);
1302 Context context(true, parent_context.textclass, parent_context.layout,
1303 parent_context.layout, parent_context.font);
1304 context.check_layout(os);
1305 os << "\\start_of_appendix\n";
1306 parse_text(p, os, FLAG_END, outer, context);
1307 context.check_end_layout(os);
1311 else if (known_environments.find(name) != known_environments.end()) {
1312 vector<ArgumentType> arguments = known_environments[name];
1313 // The last "argument" denotes wether we may translate the
1314 // environment contents to LyX
1315 // The default required if no argument is given makes us
1316 // compatible with the reLyXre environment.
1317 ArgumentType contents = arguments.empty() ?
1320 if (!arguments.empty())
1321 arguments.pop_back();
1322 // See comment in parse_unknown_environment()
1323 bool const specialfont =
1324 (parent_context.font != parent_context.normalfont);
1325 bool const new_layout_allowed =
1326 parent_context.new_layout_allowed;
1328 parent_context.new_layout_allowed = false;
1329 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1330 outer, parent_context);
1331 if (contents == verbatim)
1332 handle_ert(os, p.verbatimEnvironment(name),
1335 parse_text_snippet(p, os, FLAG_END, outer,
1337 handle_ert(os, "\\end{" + name + "}", parent_context);
1339 parent_context.new_layout_allowed = new_layout_allowed;
1343 parse_unknown_environment(p, name, os, FLAG_END, outer,
1347 active_environments.pop_back();
1351 /// parses a comment and outputs it to \p os.
1352 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1354 LASSERT(t.cat() == catComment, return);
1355 if (!t.cs().empty()) {
1356 context.check_layout(os);
1357 handle_comment(os, '%' + t.cs(), context);
1358 if (p.next_token().cat() == catNewline) {
1359 // A newline after a comment line starts a new
1361 if (context.new_layout_allowed) {
1362 if(!context.atParagraphStart())
1363 // Only start a new paragraph if not already
1364 // done (we might get called recursively)
1365 context.new_paragraph(os);
1367 handle_ert(os, "\n", context);
1368 eat_whitespace(p, os, context, true);
1371 // "%\n" combination
1378 * Reads spaces and comments until the first non-space, non-comment token.
1379 * New paragraphs (double newlines or \\par) are handled like simple spaces
1380 * if \p eatParagraph is true.
1381 * Spaces are skipped, but comments are written to \p os.
1383 void eat_whitespace(Parser & p, ostream & os, Context & context,
1387 Token const & t = p.get_token();
1388 if (t.cat() == catComment)
1389 parse_comment(p, os, t, context);
1390 else if ((! eatParagraph && p.isParagraph()) ||
1391 (t.cat() != catSpace && t.cat() != catNewline)) {
1400 * Set a font attribute, parse text and reset the font attribute.
1401 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1402 * \param currentvalue Current value of the attribute. Is set to the new
1403 * value during parsing.
1404 * \param newvalue New value of the attribute
1406 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1407 Context & context, string const & attribute,
1408 string & currentvalue, string const & newvalue)
1410 context.check_layout(os);
1411 string const oldvalue = currentvalue;
1412 currentvalue = newvalue;
1413 os << '\n' << attribute << ' ' << newvalue << "\n";
1414 parse_text_snippet(p, os, flags, outer, context);
1415 context.check_layout(os);
1416 os << '\n' << attribute << ' ' << oldvalue << "\n";
1417 currentvalue = oldvalue;
1421 /// get the arguments of a natbib or jurabib citation command
1422 void get_cite_arguments(Parser & p, bool natbibOrder,
1423 string & before, string & after)
1425 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1427 // text before the citation
1429 // text after the citation
1430 after = p.getFullOpt();
1432 if (!after.empty()) {
1433 before = p.getFullOpt();
1434 if (natbibOrder && !before.empty())
1435 swap(before, after);
1440 /// Convert filenames with TeX macros and/or quotes to something LyX
1442 string const normalize_filename(string const & name)
1444 Parser p(trim(name, "\""));
1447 Token const & t = p.get_token();
1448 if (t.cat() != catEscape)
1450 else if (t.cs() == "lyxdot") {
1451 // This is used by LyX for simple dots in relative
1455 } else if (t.cs() == "space") {
1465 /// Convert \p name from TeX convention (relative to master file) to LyX
1466 /// convention (relative to .lyx file) if it is relative
1467 void fix_relative_filename(string & name)
1469 if (FileName::isAbsolute(name))
1472 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1473 from_utf8(getParentFilePath())));
1477 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1478 void parse_noweb(Parser & p, ostream & os, Context & context)
1480 // assemble the rest of the keyword
1484 Token const & t = p.get_token();
1485 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1488 scrap = (p.good() && p.next_token().asInput() == "=");
1490 name += p.get_token().asInput();
1493 name += t.asInput();
1496 if (!scrap || !context.new_layout_allowed ||
1497 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1498 cerr << "Warning: Could not interpret '" << name
1499 << "'. Ignoring it." << endl;
1503 // We use new_paragraph instead of check_end_layout because the stuff
1504 // following the noweb chunk needs to start with a \begin_layout.
1505 // This may create a new paragraph even if there was none in the
1506 // noweb file, but the alternative is an invalid LyX file. Since
1507 // noweb code chunks are implemented with a layout style in LyX they
1508 // always must be in an own paragraph.
1509 context.new_paragraph(os);
1510 Context newcontext(true, context.textclass,
1511 &context.textclass[from_ascii("Scrap")]);
1512 newcontext.check_layout(os);
1515 Token const & t = p.get_token();
1516 // We abuse the parser a bit, because this is no TeX syntax
1518 if (t.cat() == catEscape)
1519 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1522 Context tmp(false, context.textclass,
1523 &context.textclass[from_ascii("Scrap")]);
1524 tmp.need_end_layout = true;
1525 tmp.check_layout(oss);
1526 os << subst(t.asInput(), "\n", oss.str());
1528 // The scrap chunk is ended by an @ at the beginning of a line.
1529 // After the @ the line may contain a comment and/or
1530 // whitespace, but nothing else.
1531 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1532 (p.next_token().cat() == catSpace ||
1533 p.next_token().cat() == catNewline ||
1534 p.next_token().cat() == catComment)) {
1535 while (p.good() && p.next_token().cat() == catSpace)
1536 os << p.get_token().asInput();
1537 if (p.next_token().cat() == catComment)
1538 // The comment includes a final '\n'
1539 os << p.get_token().asInput();
1541 if (p.next_token().cat() == catNewline)
1548 newcontext.check_end_layout(os);
1552 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1553 bool is_macro(Parser & p)
1555 Token first = p.curr_token();
1556 if (first.cat() != catEscape || !p.good())
1558 if (first.cs() == "def")
1560 if (first.cs() != "global" && first.cs() != "long")
1562 Token second = p.get_token();
1564 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1565 second.cat() == catNewline || second.cat() == catComment)) {
1566 second = p.get_token();
1569 bool secondvalid = second.cat() == catEscape;
1571 bool thirdvalid = false;
1572 if (p.good() && first.cs() == "global" && secondvalid &&
1573 second.cs() == "long") {
1574 third = p.get_token();
1576 while (p.good() && !p.isParagraph() &&
1577 (third.cat() == catSpace ||
1578 third.cat() == catNewline ||
1579 third.cat() == catComment)) {
1580 third = p.get_token();
1583 thirdvalid = third.cat() == catEscape;
1585 for (int i = 0; i < pos; ++i)
1590 return (first.cs() == "global" || first.cs() == "long") &&
1591 second.cs() == "def";
1592 return first.cs() == "global" && second.cs() == "long" &&
1593 third.cs() == "def";
1597 /// Parse a macro definition (assumes that is_macro() returned true)
1598 void parse_macro(Parser & p, ostream & os, Context & context)
1600 context.check_layout(os);
1601 Token first = p.curr_token();
1604 string command = first.asInput();
1605 if (first.cs() != "def") {
1607 eat_whitespace(p, os, context, false);
1608 second = p.curr_token();
1609 command += second.asInput();
1610 if (second.cs() != "def") {
1612 eat_whitespace(p, os, context, false);
1613 third = p.curr_token();
1614 command += third.asInput();
1617 eat_whitespace(p, os, context, false);
1618 string const name = p.get_token().cs();
1619 eat_whitespace(p, os, context, false);
1625 while (p.next_token().cat() != catBegin) {
1626 if (p.next_token().cat() == catParameter) {
1631 // followed by number?
1632 if (p.next_token().cat() == catOther) {
1633 char c = p.getChar();
1635 // number = current arity + 1?
1636 if (c == arity + '0' + 1)
1641 paramtext += p.get_token().cs();
1643 paramtext += p.get_token().cs();
1648 // only output simple (i.e. compatible) macro as FormulaMacros
1649 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1651 context.check_layout(os);
1652 begin_inset(os, "FormulaMacro");
1653 os << "\n\\def" << ert;
1656 handle_ert(os, command + ert, context);
1659 } // anonymous namespace
1662 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1665 Layout const * newlayout = 0;
1666 InsetLayout const * newinsetlayout = 0;
1667 // Store the latest bibliographystyle and nocite{*} option
1668 // (needed for bibtex inset)
1670 string bibliographystyle;
1671 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1672 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1675 Token const & t = p.get_token();
1678 debugToken(cerr, t, flags);
1681 if (flags & FLAG_ITEM) {
1682 if (t.cat() == catSpace)
1685 flags &= ~FLAG_ITEM;
1686 if (t.cat() == catBegin) {
1687 // skip the brace and collect everything to the next matching
1689 flags |= FLAG_BRACE_LAST;
1693 // handle only this single token, leave the loop if done
1694 flags |= FLAG_LEAVE;
1697 if (t.cat() != catEscape && t.character() == ']' &&
1698 (flags & FLAG_BRACK_LAST))
1700 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1703 // If there is anything between \end{env} and \begin{env} we
1704 // don't need to output a separator.
1705 if (t.cat() != catSpace && t.cat() != catNewline &&
1706 t.asInput() != "\\begin")
1712 if (t.cat() == catMath) {
1713 // we are inside some text mode thingy, so opening new math is allowed
1714 context.check_layout(os);
1715 begin_inset(os, "Formula ");
1716 Token const & n = p.get_token();
1717 if (n.cat() == catMath && outer) {
1718 // TeX's $$...$$ syntax for displayed math
1720 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1722 p.get_token(); // skip the second '$' token
1724 // simple $...$ stuff
1727 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1733 else if (t.cat() == catSuper || t.cat() == catSub)
1734 cerr << "catcode " << t << " illegal in text mode\n";
1736 // Basic support for english quotes. This should be
1737 // extended to other quotes, but is not so easy (a
1738 // left english quote is the same as a right german
1740 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1741 context.check_layout(os);
1742 begin_inset(os, "Quotes ");
1748 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1749 context.check_layout(os);
1750 begin_inset(os, "Quotes ");
1757 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1758 context.check_layout(os);
1759 begin_inset(os, "Quotes ");
1766 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1767 context.check_layout(os);
1768 begin_inset(os, "Quotes ");
1775 else if (t.asInput() == "<"
1776 && p.next_token().asInput() == "<" && noweb_mode) {
1778 parse_noweb(p, os, context);
1781 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1782 check_space(p, os, context);
1784 else if (t.character() == '[' && noweb_mode &&
1785 p.next_token().character() == '[') {
1786 // These can contain underscores
1788 string const s = p.getFullOpt() + ']';
1789 if (p.next_token().character() == ']')
1792 cerr << "Warning: Inserting missing ']' in '"
1793 << s << "'." << endl;
1794 handle_ert(os, s, context);
1797 else if (t.cat() == catLetter) {
1798 context.check_layout(os);
1799 // Workaround for bug 4752.
1800 // FIXME: This whole code block needs to be removed
1801 // when the bug is fixed and tex2lyx produces
1802 // the updated file format.
1803 // The replacement algorithm in LyX is so stupid that
1804 // it even translates a phrase if it is part of a word.
1805 bool handled = false;
1806 for (int const * l = known_phrase_lengths; *l; ++l) {
1807 string phrase = t.cs();
1808 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1809 phrase += p.get_token().cs();
1810 if (is_known(phrase, known_coded_phrases)) {
1811 handle_ert(os, phrase, context);
1815 for (size_t i = 1; i < phrase.length(); ++i)
1823 else if (t.cat() == catOther ||
1824 t.cat() == catAlign ||
1825 t.cat() == catParameter) {
1826 // This translates "&" to "\\&" which may be wrong...
1827 context.check_layout(os);
1831 else if (p.isParagraph()) {
1832 if (context.new_layout_allowed)
1833 context.new_paragraph(os);
1835 handle_ert(os, "\\par ", context);
1836 eat_whitespace(p, os, context, true);
1839 else if (t.cat() == catActive) {
1840 context.check_layout(os);
1841 if (t.character() == '~') {
1842 if (context.layout->free_spacing)
1845 begin_inset(os, "space ~\n");
1852 else if (t.cat() == catBegin &&
1853 p.next_token().cat() == catEnd) {
1855 Token const prev = p.prev_token();
1857 if (p.next_token().character() == '`' ||
1858 (prev.character() == '-' &&
1859 p.next_token().character() == '-'))
1860 ; // ignore it in {}`` or -{}-
1862 handle_ert(os, "{}", context);
1866 else if (t.cat() == catBegin) {
1867 context.check_layout(os);
1868 // special handling of font attribute changes
1869 Token const prev = p.prev_token();
1870 Token const next = p.next_token();
1871 TeXFont const oldFont = context.font;
1872 if (next.character() == '[' ||
1873 next.character() == ']' ||
1874 next.character() == '*') {
1876 if (p.next_token().cat() == catEnd) {
1881 handle_ert(os, "{", context);
1882 parse_text_snippet(p, os,
1885 handle_ert(os, "}", context);
1887 } else if (! context.new_layout_allowed) {
1888 handle_ert(os, "{", context);
1889 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1891 handle_ert(os, "}", context);
1892 } else if (is_known(next.cs(), known_sizes)) {
1893 // next will change the size, so we must
1895 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1897 if (!context.atParagraphStart())
1899 << context.font.size << "\n";
1900 } else if (is_known(next.cs(), known_font_families)) {
1901 // next will change the font family, so we
1902 // must reset it here
1903 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1905 if (!context.atParagraphStart())
1907 << context.font.family << "\n";
1908 } else if (is_known(next.cs(), known_font_series)) {
1909 // next will change the font series, so we
1910 // must reset it here
1911 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1913 if (!context.atParagraphStart())
1915 << context.font.series << "\n";
1916 } else if (is_known(next.cs(), known_font_shapes)) {
1917 // next will change the font shape, so we
1918 // must reset it here
1919 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1921 if (!context.atParagraphStart())
1923 << context.font.shape << "\n";
1924 } else if (is_known(next.cs(), known_old_font_families) ||
1925 is_known(next.cs(), known_old_font_series) ||
1926 is_known(next.cs(), known_old_font_shapes)) {
1927 // next will change the font family, series
1928 // and shape, so we must reset it here
1929 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1931 if (!context.atParagraphStart())
1933 << context.font.family
1935 << context.font.series
1937 << context.font.shape << "\n";
1939 handle_ert(os, "{", context);
1940 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1942 handle_ert(os, "}", context);
1946 else if (t.cat() == catEnd) {
1947 if (flags & FLAG_BRACE_LAST) {
1950 cerr << "stray '}' in text\n";
1951 handle_ert(os, "}", context);
1954 else if (t.cat() == catComment)
1955 parse_comment(p, os, t, context);
1958 // control sequences
1961 else if (t.cs() == "(") {
1962 context.check_layout(os);
1963 begin_inset(os, "Formula");
1965 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1970 else if (t.cs() == "[") {
1971 context.check_layout(os);
1972 begin_inset(os, "Formula");
1974 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1979 else if (t.cs() == "begin")
1980 parse_environment(p, os, outer, last_env, context);
1982 else if (t.cs() == "end") {
1983 if (flags & FLAG_END) {
1984 // eat environment name
1985 string const name = p.getArg('{', '}');
1986 if (name != active_environment())
1987 cerr << "\\end{" + name + "} does not match \\begin{"
1988 + active_environment() + "}\n";
1991 p.error("found 'end' unexpectedly");
1994 else if (t.cs() == "item") {
1997 bool optarg = false;
1998 if (p.next_token().cat() != catEscape &&
1999 p.next_token().character() == '[') {
2000 p.get_token(); // eat '['
2001 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2006 context.check_layout(os);
2007 if (context.has_item) {
2008 // An item in an unknown list-like environment
2009 // FIXME: Do this in check_layout()!
2010 context.has_item = false;
2012 handle_ert(os, "\\item", context);
2014 handle_ert(os, "\\item ", context);
2017 if (context.layout->labeltype != LABEL_MANUAL) {
2018 // LyX does not support \item[\mybullet]
2019 // in itemize environments
2020 handle_ert(os, "[", context);
2022 handle_ert(os, "]", context);
2023 } else if (!s.empty()) {
2024 // The space is needed to separate the
2025 // item from the rest of the sentence.
2027 eat_whitespace(p, os, context, false);
2032 else if (t.cs() == "bibitem") {
2034 context.check_layout(os);
2035 string label = convert_command_inset_arg(p.getArg('[', ']'));
2036 string key = convert_command_inset_arg(p.verbatim_item());
2037 if (contains(label, '\\') || contains(key, '\\')) {
2038 // LyX can't handle LaTeX commands in labels or keys
2039 handle_ert(os, t.asInput() + '[' + label +
2040 "]{" + p.verbatim_item() + '}',
2043 begin_command_inset(os, "bibitem", "bibitem");
2044 os << "label \"" << label << "\"\n"
2045 "key \"" << key << "\"\n";
2050 else if (is_macro(p))
2051 parse_macro(p, os, context);
2053 else if (t.cs() == "noindent") {
2055 context.add_par_extra_stuff("\\noindent\n");
2058 else if (t.cs() == "appendix") {
2059 context.add_par_extra_stuff("\\start_of_appendix\n");
2060 // We need to start a new paragraph. Otherwise the
2061 // appendix in 'bla\appendix\chapter{' would start
2063 context.new_paragraph(os);
2064 // We need to make sure that the paragraph is
2065 // generated even if it is empty. Otherwise the
2066 // appendix in '\par\appendix\par\chapter{' would
2068 context.check_layout(os);
2069 // FIXME: This is a hack to prevent paragraph
2070 // deletion if it is empty. Handle this better!
2072 "%dummy comment inserted by tex2lyx to "
2073 "ensure that this paragraph is not empty",
2075 // Both measures above may generate an additional
2076 // empty paragraph, but that does not hurt, because
2077 // whitespace does not matter here.
2078 eat_whitespace(p, os, context, true);
2081 // Starred section headings
2082 // Must attempt to parse "Section*" before "Section".
2083 else if ((p.next_token().asInput() == "*") &&
2084 context.new_layout_allowed &&
2085 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2088 output_command_layout(os, p, outer, context, newlayout);
2092 // Section headings and the like
2093 else if (context.new_layout_allowed &&
2094 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2096 output_command_layout(os, p, outer, context, newlayout);
2100 else if (t.cs() == "caption") {
2102 context.check_layout(os);
2104 begin_inset(os, "Caption\n\n");
2105 Context newcontext(true, context.textclass);
2106 newcontext.font = context.font;
2107 newcontext.check_layout(os);
2108 if (p.next_token().cat() != catEscape &&
2109 p.next_token().character() == '[') {
2110 p.get_token(); // eat '['
2111 begin_inset(os, "Argument\n");
2112 os << "status collapsed\n";
2113 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2115 eat_whitespace(p, os, context, false);
2117 parse_text(p, os, FLAG_ITEM, outer, context);
2118 context.check_end_layout(os);
2119 // We don't need really a new paragraph, but
2120 // we must make sure that the next item gets a \begin_layout.
2121 context.new_paragraph(os);
2124 newcontext.check_end_layout(os);
2127 else if (t.cs() == "includegraphics") {
2128 bool const clip = p.next_token().asInput() == "*";
2131 string const arg = p.getArg('[', ']');
2132 map<string, string> opts;
2133 vector<string> keys;
2134 split_map(arg, opts, keys);
2136 opts["clip"] = string();
2137 string name = normalize_filename(p.verbatim_item());
2139 string const path = getMasterFilePath();
2140 // We want to preserve relative / absolute filenames,
2141 // therefore path is only used for testing
2142 if (!makeAbsPath(name, path).exists()) {
2143 // The file extension is probably missing.
2144 // Now try to find it out.
2145 string const dvips_name =
2146 find_file(name, path,
2147 known_dvips_graphics_formats);
2148 string const pdftex_name =
2149 find_file(name, path,
2150 known_pdftex_graphics_formats);
2151 if (!dvips_name.empty()) {
2152 if (!pdftex_name.empty()) {
2153 cerr << "This file contains the "
2155 "\"\\includegraphics{"
2157 "However, files\n\""
2158 << dvips_name << "\" and\n\""
2159 << pdftex_name << "\"\n"
2160 "both exist, so I had to make a "
2161 "choice and took the first one.\n"
2162 "Please move the unwanted one "
2163 "someplace else and try again\n"
2164 "if my choice was wrong."
2168 } else if (!pdftex_name.empty()) {
2174 if (makeAbsPath(name, path).exists())
2175 fix_relative_filename(name);
2177 cerr << "Warning: Could not find graphics file '"
2178 << name << "'." << endl;
2180 context.check_layout(os);
2181 begin_inset(os, "Graphics ");
2182 os << "\n\tfilename " << name << '\n';
2183 if (opts.find("width") != opts.end())
2185 << translate_len(opts["width"]) << '\n';
2186 if (opts.find("height") != opts.end())
2188 << translate_len(opts["height"]) << '\n';
2189 if (opts.find("scale") != opts.end()) {
2190 istringstream iss(opts["scale"]);
2194 os << "\tscale " << val << '\n';
2196 if (opts.find("angle") != opts.end()) {
2197 os << "\trotateAngle "
2198 << opts["angle"] << '\n';
2199 vector<string>::const_iterator a =
2200 find(keys.begin(), keys.end(), "angle");
2201 vector<string>::const_iterator s =
2202 find(keys.begin(), keys.end(), "width");
2203 if (s == keys.end())
2204 s = find(keys.begin(), keys.end(), "height");
2205 if (s == keys.end())
2206 s = find(keys.begin(), keys.end(), "scale");
2207 if (s != keys.end() && distance(s, a) > 0)
2208 os << "\tscaleBeforeRotation\n";
2210 if (opts.find("origin") != opts.end()) {
2212 string const opt = opts["origin"];
2213 if (opt.find('l') != string::npos) ss << "left";
2214 if (opt.find('r') != string::npos) ss << "right";
2215 if (opt.find('c') != string::npos) ss << "center";
2216 if (opt.find('t') != string::npos) ss << "Top";
2217 if (opt.find('b') != string::npos) ss << "Bottom";
2218 if (opt.find('B') != string::npos) ss << "Baseline";
2219 if (!ss.str().empty())
2220 os << "\trotateOrigin " << ss.str() << '\n';
2222 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2224 if (opts.find("keepaspectratio") != opts.end())
2225 os << "\tkeepAspectRatio\n";
2226 if (opts.find("clip") != opts.end())
2228 if (opts.find("draft") != opts.end())
2230 if (opts.find("bb") != opts.end())
2231 os << "\tBoundingBox "
2232 << opts["bb"] << '\n';
2233 int numberOfbbOptions = 0;
2234 if (opts.find("bbllx") != opts.end())
2235 numberOfbbOptions++;
2236 if (opts.find("bblly") != opts.end())
2237 numberOfbbOptions++;
2238 if (opts.find("bburx") != opts.end())
2239 numberOfbbOptions++;
2240 if (opts.find("bbury") != opts.end())
2241 numberOfbbOptions++;
2242 if (numberOfbbOptions == 4)
2243 os << "\tBoundingBox "
2244 << opts["bbllx"] << " " << opts["bblly"] << " "
2245 << opts["bburx"] << " " << opts["bbury"] << '\n';
2246 else if (numberOfbbOptions > 0)
2247 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2248 numberOfbbOptions = 0;
2249 if (opts.find("natwidth") != opts.end())
2250 numberOfbbOptions++;
2251 if (opts.find("natheight") != opts.end())
2252 numberOfbbOptions++;
2253 if (numberOfbbOptions == 2)
2254 os << "\tBoundingBox 0bp 0bp "
2255 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2256 else if (numberOfbbOptions > 0)
2257 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2258 ostringstream special;
2259 if (opts.find("hiresbb") != opts.end())
2260 special << "hiresbb,";
2261 if (opts.find("trim") != opts.end())
2263 if (opts.find("viewport") != opts.end())
2264 special << "viewport=" << opts["viewport"] << ',';
2265 if (opts.find("totalheight") != opts.end())
2266 special << "totalheight=" << opts["totalheight"] << ',';
2267 if (opts.find("type") != opts.end())
2268 special << "type=" << opts["type"] << ',';
2269 if (opts.find("ext") != opts.end())
2270 special << "ext=" << opts["ext"] << ',';
2271 if (opts.find("read") != opts.end())
2272 special << "read=" << opts["read"] << ',';
2273 if (opts.find("command") != opts.end())
2274 special << "command=" << opts["command"] << ',';
2275 string s_special = special.str();
2276 if (!s_special.empty()) {
2277 // We had special arguments. Remove the trailing ','.
2278 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2280 // TODO: Handle the unknown settings better.
2281 // Warn about invalid options.
2282 // Check whether some option was given twice.
2286 else if (t.cs() == "footnote" ||
2287 (t.cs() == "thanks" && context.layout->intitle)) {
2289 context.check_layout(os);
2290 begin_inset(os, "Foot\n");
2291 os << "status collapsed\n\n";
2292 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2296 else if (t.cs() == "marginpar") {
2298 context.check_layout(os);
2299 begin_inset(os, "Marginal\n");
2300 os << "status collapsed\n\n";
2301 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2305 else if (t.cs() == "ensuremath") {
2307 context.check_layout(os);
2308 string const s = p.verbatim_item();
2309 //FIXME: this never triggers in UTF8
2310 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2313 handle_ert(os, "\\ensuremath{" + s + "}",
2317 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2318 // FIXME: Somehow prevent title layouts if
2319 // "maketitle" was not found
2321 skip_spaces_braces(p);
2324 else if (t.cs() == "tableofcontents") {
2325 context.check_layout(os);
2326 begin_command_inset(os, "toc", "tableofcontents");
2328 skip_spaces_braces(p);
2331 else if (t.cs() == "listoffigures") {
2332 context.check_layout(os);
2333 begin_inset(os, "FloatList figure\n");
2335 skip_spaces_braces(p);
2338 else if (t.cs() == "listoftables") {
2339 context.check_layout(os);
2340 begin_inset(os, "FloatList table\n");
2342 skip_spaces_braces(p);
2345 else if (t.cs() == "listof") {
2346 p.skip_spaces(true);
2347 string const name = p.get_token().cs();
2348 if (context.textclass.floats().typeExist(name)) {
2349 context.check_layout(os);
2350 begin_inset(os, "FloatList ");
2353 p.get_token(); // swallow second arg
2355 handle_ert(os, "\\listof{" + name + "}", context);
2358 else if (t.cs() == "textrm")
2359 parse_text_attributes(p, os, FLAG_ITEM, outer,
2360 context, "\\family",
2361 context.font.family, "roman");
2363 else if (t.cs() == "textsf")
2364 parse_text_attributes(p, os, FLAG_ITEM, outer,
2365 context, "\\family",
2366 context.font.family, "sans");
2368 else if (t.cs() == "texttt")
2369 parse_text_attributes(p, os, FLAG_ITEM, outer,
2370 context, "\\family",
2371 context.font.family, "typewriter");
2373 else if (t.cs() == "textmd")
2374 parse_text_attributes(p, os, FLAG_ITEM, outer,
2375 context, "\\series",
2376 context.font.series, "medium");
2378 else if (t.cs() == "textbf")
2379 parse_text_attributes(p, os, FLAG_ITEM, outer,
2380 context, "\\series",
2381 context.font.series, "bold");
2383 else if (t.cs() == "textup")
2384 parse_text_attributes(p, os, FLAG_ITEM, outer,
2386 context.font.shape, "up");
2388 else if (t.cs() == "textit")
2389 parse_text_attributes(p, os, FLAG_ITEM, outer,
2391 context.font.shape, "italic");
2393 else if (t.cs() == "textsl")
2394 parse_text_attributes(p, os, FLAG_ITEM, outer,
2396 context.font.shape, "slanted");
2398 else if (t.cs() == "textsc")
2399 parse_text_attributes(p, os, FLAG_ITEM, outer,
2401 context.font.shape, "smallcaps");
2403 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2404 context.check_layout(os);
2405 TeXFont oldFont = context.font;
2406 context.font.init();
2407 context.font.size = oldFont.size;
2408 os << "\n\\family " << context.font.family << "\n";
2409 os << "\n\\series " << context.font.series << "\n";
2410 os << "\n\\shape " << context.font.shape << "\n";
2411 if (t.cs() == "textnormal") {
2412 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2413 output_font_change(os, context.font, oldFont);
2414 context.font = oldFont;
2416 eat_whitespace(p, os, context, false);
2419 else if (t.cs() == "textcolor") {
2420 // scheme is \textcolor{color name}{text}
2421 string const color = p.verbatim_item();
2422 // we only support the predefined colors of the color package
2423 if (color == "black" || color == "blue" || color == "cyan"
2424 || color == "green" || color == "magenta" || color == "red"
2425 || color == "white" || color == "yellow") {
2426 context.check_layout(os);
2427 os << "\n\\color " << color << "\n";
2428 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2429 context.check_layout(os);
2430 os << "\n\\color inherit\n";
2432 // for custom defined colors
2433 handle_ert(os, t.asInput() + "{" + color + "}", context);
2436 else if (t.cs() == "underbar" || t.cs() == "uline") {
2437 // \underbar is not 100% correct (LyX outputs \uline
2438 // of ulem.sty). The difference is that \ulem allows
2439 // line breaks, and \underbar does not.
2440 // Do NOT handle \underline.
2441 // \underbar cuts through y, g, q, p etc.,
2442 // \underline does not.
2443 context.check_layout(os);
2444 os << "\n\\bar under\n";
2445 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2446 context.check_layout(os);
2447 os << "\n\\bar default\n";
2450 else if (t.cs() == "sout") {
2451 context.check_layout(os);
2452 os << "\n\\strikeout on\n";
2453 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2454 context.check_layout(os);
2455 os << "\n\\strikeout default\n";
2458 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2459 t.cs() == "emph" || t.cs() == "noun") {
2460 context.check_layout(os);
2461 os << "\n\\" << t.cs() << " on\n";
2462 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2463 context.check_layout(os);
2464 os << "\n\\" << t.cs() << " default\n";
2467 // FIXME, the inset layout should be plain, not standard, see bug #7846
2468 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2469 t.cs() == "vphantom") {
2470 context.check_layout(os);
2471 if (t.cs() == "phantom")
2472 begin_inset(os, "Phantom Phantom\n");
2473 if (t.cs() == "hphantom")
2474 begin_inset(os, "Phantom HPhantom\n");
2475 if (t.cs() == "vphantom")
2476 begin_inset(os, "Phantom VPhantom\n");
2477 os << "status open\n";
2478 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2482 else if (t.cs() == "href") {
2483 context.check_layout(os);
2484 string target = p.getArg('{', '}');
2485 string name = p.getArg('{', '}');
2487 size_t i = target.find(':');
2488 if (i != string::npos) {
2489 type = target.substr(0, i + 1);
2490 if (type == "mailto:" || type == "file:")
2491 target = target.substr(i + 1);
2492 // handle the case that name is equal to target, except of "http://"
2493 else if (target.substr(i + 3) == name && type == "http:")
2496 begin_command_inset(os, "href", "href");
2498 os << "name \"" << name << "\"\n";
2499 os << "target \"" << target << "\"\n";
2500 if (type == "mailto:" || type == "file:")
2501 os << "type \"" << type << "\"\n";
2503 skip_spaces_braces(p);
2506 else if (t.cs() == "lyxline") {
2507 // swallow size argument (it is not used anyway)
2509 if (!context.atParagraphStart()) {
2510 // so our line is in the middle of a paragraph
2511 // we need to add a new line, lest this line
2512 // follow the other content on that line and
2513 // run off the side of the page
2514 // FIXME: This may create an empty paragraph,
2515 // but without that it would not be
2516 // possible to set noindent below.
2517 // Fortunately LaTeX does not care
2518 // about the empty paragraph.
2519 context.new_paragraph(os);
2521 if (h_paragraph_separation == "indent") {
2522 // we need to unindent, lest the line be too long
2523 context.add_par_extra_stuff("\\noindent\n");
2525 context.check_layout(os);
2526 begin_command_inset(os, "line", "rule");
2527 os << "offset \"0.5ex\"\n"
2528 "width \"100line%\"\n"
2533 else if (t.cs() == "rule") {
2534 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2535 string const width = p.getArg('{', '}');
2536 string const thickness = p.getArg('{', '}');
2538 context.check_layout(os);
2539 begin_command_inset(os, "line", "rule");
2540 if (!offset.empty())
2541 os << "offset \"" << translate_len(offset) << "\"\n";
2542 os << "width \"" << translate_len(width) << "\"\n"
2543 "height \"" << translate_len(thickness) << "\"\n";
2547 else if (is_known(t.cs(), known_phrases) ||
2548 (t.cs() == "protect" &&
2549 p.next_token().cat() == catEscape &&
2550 is_known(p.next_token().cs(), known_phrases))) {
2551 // LyX sometimes puts a \protect in front, so we have to ignore it
2552 // FIXME: This needs to be changed when bug 4752 is fixed.
2553 char const * const * where = is_known(
2554 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2556 context.check_layout(os);
2557 os << known_coded_phrases[where - known_phrases];
2558 skip_spaces_braces(p);
2561 else if (is_known(t.cs(), known_ref_commands)) {
2562 string const opt = p.getOpt();
2564 context.check_layout(os);
2565 char const * const * where = is_known(t.cs(),
2566 known_ref_commands);
2567 begin_command_inset(os, "ref",
2568 known_coded_ref_commands[where - known_ref_commands]);
2569 os << "reference \""
2570 << convert_command_inset_arg(p.verbatim_item())
2574 // LyX does not support optional arguments of ref commands
2575 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2576 p.verbatim_item() + "}", context);
2580 else if (use_natbib &&
2581 is_known(t.cs(), known_natbib_commands) &&
2582 ((t.cs() != "citefullauthor" &&
2583 t.cs() != "citeyear" &&
2584 t.cs() != "citeyearpar") ||
2585 p.next_token().asInput() != "*")) {
2586 context.check_layout(os);
2587 string command = t.cs();
2588 if (p.next_token().asInput() == "*") {
2592 if (command == "citefullauthor")
2593 // alternative name for "\\citeauthor*"
2594 command = "citeauthor*";
2596 // text before the citation
2598 // text after the citation
2600 get_cite_arguments(p, true, before, after);
2602 if (command == "cite") {
2603 // \cite without optional argument means
2604 // \citet, \cite with at least one optional
2605 // argument means \citep.
2606 if (before.empty() && after.empty())
2611 if (before.empty() && after == "[]")
2612 // avoid \citet[]{a}
2614 else if (before == "[]" && after == "[]") {
2615 // avoid \citet[][]{a}
2619 // remove the brackets around after and before
2620 if (!after.empty()) {
2622 after.erase(after.length() - 1, 1);
2623 after = convert_command_inset_arg(after);
2625 if (!before.empty()) {
2627 before.erase(before.length() - 1, 1);
2628 before = convert_command_inset_arg(before);
2630 begin_command_inset(os, "citation", command);
2631 os << "after " << '"' << after << '"' << "\n";
2632 os << "before " << '"' << before << '"' << "\n";
2634 << convert_command_inset_arg(p.verbatim_item())
2639 else if (use_jurabib &&
2640 is_known(t.cs(), known_jurabib_commands) &&
2641 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2642 context.check_layout(os);
2643 string command = t.cs();
2644 if (p.next_token().asInput() == "*") {
2648 char argumentOrder = '\0';
2649 vector<string> const & options = used_packages["jurabib"];
2650 if (find(options.begin(), options.end(),
2651 "natbiborder") != options.end())
2652 argumentOrder = 'n';
2653 else if (find(options.begin(), options.end(),
2654 "jurabiborder") != options.end())
2655 argumentOrder = 'j';
2657 // text before the citation
2659 // text after the citation
2661 get_cite_arguments(p, argumentOrder != 'j', before, after);
2663 string const citation = p.verbatim_item();
2664 if (!before.empty() && argumentOrder == '\0') {
2665 cerr << "Warning: Assuming argument order "
2666 "of jurabib version 0.6 for\n'"
2667 << command << before << after << '{'
2668 << citation << "}'.\n"
2669 "Add 'jurabiborder' to the jurabib "
2670 "package options if you used an\n"
2671 "earlier jurabib version." << endl;
2673 if (!after.empty()) {
2675 after.erase(after.length() - 1, 1);
2677 if (!before.empty()) {
2679 before.erase(before.length() - 1, 1);
2681 begin_command_inset(os, "citation", command);
2682 os << "after " << '"' << after << '"' << "\n";
2683 os << "before " << '"' << before << '"' << "\n";
2684 os << "key " << '"' << citation << '"' << "\n";
2688 else if (t.cs() == "cite"
2689 || t.cs() == "nocite") {
2690 context.check_layout(os);
2691 string after = convert_command_inset_arg(p.getArg('[', ']'));
2692 string key = convert_command_inset_arg(p.verbatim_item());
2693 // store the case that it is "\nocite{*}" to use it later for
2696 begin_command_inset(os, "citation", t.cs());
2697 os << "after " << '"' << after << '"' << "\n";
2698 os << "key " << '"' << key << '"' << "\n";
2700 } else if (t.cs() == "nocite")
2704 else if (t.cs() == "index") {
2705 context.check_layout(os);
2706 begin_inset(os, "Index idx\n");
2707 os << "status collapsed\n";
2708 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2712 else if (t.cs() == "nomenclature") {
2713 context.check_layout(os);
2714 begin_command_inset(os, "nomenclature", "nomenclature");
2715 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2716 if (!prefix.empty())
2717 os << "prefix " << '"' << prefix << '"' << "\n";
2718 os << "symbol " << '"'
2719 << convert_command_inset_arg(p.verbatim_item());
2720 os << "\"\ndescription \""
2721 << convert_command_inset_arg(p.verbatim_item())
2726 else if (t.cs() == "label") {
2727 context.check_layout(os);
2728 begin_command_inset(os, "label", "label");
2730 << convert_command_inset_arg(p.verbatim_item())
2735 else if (t.cs() == "printindex") {
2736 context.check_layout(os);
2737 begin_command_inset(os, "index_print", "printindex");
2738 os << "type \"idx\"\n";
2740 skip_spaces_braces(p);
2743 else if (t.cs() == "printnomenclature") {
2745 string width_type = "";
2746 context.check_layout(os);
2747 begin_command_inset(os, "nomencl_print", "printnomenclature");
2748 // case of a custom width
2750 width = p.getArg('[', ']');
2751 width = translate_len(width);
2752 width_type = "custom";
2754 // case of no custom width
2755 // the case of no custom width but the width set
2756 // via \settowidth{\nomlabelwidth}{***} cannot be supported
2757 // because the user could have set anything, not only the width
2758 // of the longest label (which would be width_type = "auto")
2759 string label = convert_command_inset_arg(p.getArg('{', '}'));
2760 if (label.empty() && width_type.empty())
2761 width_type = "none";
2762 os << "set_width \"" << width_type << "\"\n";
2763 if (width_type == "custom")
2764 os << "width \"" << width << '\"';
2766 skip_spaces_braces(p);
2769 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2770 context.check_layout(os);
2771 begin_inset(os, "script ");
2772 os << t.cs().substr(4) << '\n';
2773 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2777 else if (is_known(t.cs(), known_quotes)) {
2778 char const * const * where = is_known(t.cs(), known_quotes);
2779 context.check_layout(os);
2780 begin_inset(os, "Quotes ");
2781 os << known_coded_quotes[where - known_quotes];
2783 // LyX adds {} after the quote, so we have to eat
2784 // spaces here if there are any before a possible
2786 eat_whitespace(p, os, context, false);
2790 else if (is_known(t.cs(), known_sizes) &&
2791 context.new_layout_allowed) {
2792 char const * const * where = is_known(t.cs(), known_sizes);
2793 context.check_layout(os);
2794 TeXFont const oldFont = context.font;
2795 context.font.size = known_coded_sizes[where - known_sizes];
2796 output_font_change(os, oldFont, context.font);
2797 eat_whitespace(p, os, context, false);
2800 else if (is_known(t.cs(), known_font_families) &&
2801 context.new_layout_allowed) {
2802 char const * const * where =
2803 is_known(t.cs(), known_font_families);
2804 context.check_layout(os);
2805 TeXFont const oldFont = context.font;
2806 context.font.family =
2807 known_coded_font_families[where - known_font_families];
2808 output_font_change(os, oldFont, context.font);
2809 eat_whitespace(p, os, context, false);
2812 else if (is_known(t.cs(), known_font_series) &&
2813 context.new_layout_allowed) {
2814 char const * const * where =
2815 is_known(t.cs(), known_font_series);
2816 context.check_layout(os);
2817 TeXFont const oldFont = context.font;
2818 context.font.series =
2819 known_coded_font_series[where - known_font_series];
2820 output_font_change(os, oldFont, context.font);
2821 eat_whitespace(p, os, context, false);
2824 else if (is_known(t.cs(), known_font_shapes) &&
2825 context.new_layout_allowed) {
2826 char const * const * where =
2827 is_known(t.cs(), known_font_shapes);
2828 context.check_layout(os);
2829 TeXFont const oldFont = context.font;
2830 context.font.shape =
2831 known_coded_font_shapes[where - known_font_shapes];
2832 output_font_change(os, oldFont, context.font);
2833 eat_whitespace(p, os, context, false);
2835 else if (is_known(t.cs(), known_old_font_families) &&
2836 context.new_layout_allowed) {
2837 char const * const * where =
2838 is_known(t.cs(), known_old_font_families);
2839 context.check_layout(os);
2840 TeXFont const oldFont = context.font;
2841 context.font.init();
2842 context.font.size = oldFont.size;
2843 context.font.family =
2844 known_coded_font_families[where - known_old_font_families];
2845 output_font_change(os, oldFont, context.font);
2846 eat_whitespace(p, os, context, false);
2849 else if (is_known(t.cs(), known_old_font_series) &&
2850 context.new_layout_allowed) {
2851 char const * const * where =
2852 is_known(t.cs(), known_old_font_series);
2853 context.check_layout(os);
2854 TeXFont const oldFont = context.font;
2855 context.font.init();
2856 context.font.size = oldFont.size;
2857 context.font.series =
2858 known_coded_font_series[where - known_old_font_series];
2859 output_font_change(os, oldFont, context.font);
2860 eat_whitespace(p, os, context, false);
2863 else if (is_known(t.cs(), known_old_font_shapes) &&
2864 context.new_layout_allowed) {
2865 char const * const * where =
2866 is_known(t.cs(), known_old_font_shapes);
2867 context.check_layout(os);
2868 TeXFont const oldFont = context.font;
2869 context.font.init();
2870 context.font.size = oldFont.size;
2871 context.font.shape =
2872 known_coded_font_shapes[where - known_old_font_shapes];
2873 output_font_change(os, oldFont, context.font);
2874 eat_whitespace(p, os, context, false);
2877 else if (t.cs() == "selectlanguage") {
2878 context.check_layout(os);
2879 // save the language for the case that a
2880 // \foreignlanguage is used
2882 context.font.language = babel2lyx(p.verbatim_item());
2883 os << "\n\\lang " << context.font.language << "\n";
2886 else if (t.cs() == "foreignlanguage") {
2887 string const lang = babel2lyx(p.verbatim_item());
2888 parse_text_attributes(p, os, FLAG_ITEM, outer,
2890 context.font.language, lang);
2893 else if (t.cs() == "inputencoding") {
2894 // nothing to write here
2895 string const enc = subst(p.verbatim_item(), "\n", " ");
2899 else if (t.cs() == "ldots") {
2900 context.check_layout(os);
2901 os << "\\SpecialChar \\ldots{}\n";
2902 skip_spaces_braces(p);
2905 else if (t.cs() == "lyxarrow") {
2906 context.check_layout(os);
2907 os << "\\SpecialChar \\menuseparator\n";
2908 skip_spaces_braces(p);
2911 else if (t.cs() == "textcompwordmark") {
2912 context.check_layout(os);
2913 os << "\\SpecialChar \\textcompwordmark{}\n";
2914 skip_spaces_braces(p);
2917 else if (t.cs() == "slash") {
2918 context.check_layout(os);
2919 os << "\\SpecialChar \\slash{}\n";
2920 skip_spaces_braces(p);
2923 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2924 context.check_layout(os);
2925 os << "\\SpecialChar \\nobreakdash-\n";
2929 else if (t.cs() == "textquotedbl") {
2930 context.check_layout(os);
2935 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2936 context.check_layout(os);
2937 os << "\\SpecialChar \\@.\n";
2941 else if (t.cs() == "-") {
2942 context.check_layout(os);
2943 os << "\\SpecialChar \\-\n";
2946 else if (t.cs() == "textasciitilde") {
2947 context.check_layout(os);
2949 skip_spaces_braces(p);
2952 else if (t.cs() == "textasciicircum") {
2953 context.check_layout(os);
2955 skip_spaces_braces(p);
2958 else if (t.cs() == "textbackslash") {
2959 context.check_layout(os);
2960 os << "\n\\backslash\n";
2961 skip_spaces_braces(p);
2964 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2965 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2967 context.check_layout(os);
2971 else if (t.cs() == "char") {
2972 context.check_layout(os);
2973 if (p.next_token().character() == '`') {
2975 if (p.next_token().cs() == "\"") {
2980 handle_ert(os, "\\char`", context);
2983 handle_ert(os, "\\char", context);
2987 else if (t.cs() == "verb") {
2988 context.check_layout(os);
2989 char const delimiter = p.next_token().character();
2990 string const arg = p.getArg(delimiter, delimiter);
2992 oss << "\\verb" << delimiter << arg << delimiter;
2993 handle_ert(os, oss.str(), context);
2996 // Problem: \= creates a tabstop inside the tabbing environment
2997 // and else an accent. In the latter case we really would want
2998 // \={o} instead of \= o.
2999 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3000 handle_ert(os, t.asInput(), context);
3002 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3003 else if (t.cs().size() == 1
3004 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3005 context.check_layout(os);
3006 // try to see whether the string is in unicodesymbols
3008 string command = t.asInput() + "{"
3009 + trimSpaceAndEol(p.verbatim_item())
3011 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3014 cerr << "When parsing " << command
3015 << ", result is " << to_utf8(s)
3016 << "+" << to_utf8(rem) << endl;
3019 // we did not find a non-ert version
3020 handle_ert(os, command, context);
3023 else if (t.cs() == "\\") {
3024 context.check_layout(os);
3026 handle_ert(os, "\\\\" + p.getOpt(), context);
3027 else if (p.next_token().asInput() == "*") {
3029 // getOpt() eats the following space if there
3030 // is no optional argument, but that is OK
3031 // here since it has no effect in the output.
3032 handle_ert(os, "\\\\*" + p.getOpt(), context);
3035 begin_inset(os, "Newline newline");
3040 else if (t.cs() == "newline" ||
3041 (t.cs() == "linebreak" && !p.hasOpt())) {
3042 context.check_layout(os);
3043 begin_inset(os, "Newline ");
3046 skip_spaces_braces(p);
3049 else if (t.cs() == "input" || t.cs() == "include"
3050 || t.cs() == "verbatiminput") {
3051 string name = t.cs();
3052 if (t.cs() == "verbatiminput"
3053 && p.next_token().asInput() == "*")
3054 name += p.get_token().asInput();
3055 context.check_layout(os);
3056 string filename(normalize_filename(p.getArg('{', '}')));
3057 string const path = getMasterFilePath();
3058 // We want to preserve relative / absolute filenames,
3059 // therefore path is only used for testing
3060 if ((t.cs() == "include" || t.cs() == "input") &&
3061 !makeAbsPath(filename, path).exists()) {
3062 // The file extension is probably missing.
3063 // Now try to find it out.
3064 string const tex_name =
3065 find_file(filename, path,
3066 known_tex_extensions);
3067 if (!tex_name.empty())
3068 filename = tex_name;
3070 bool external = false;
3072 if (makeAbsPath(filename, path).exists()) {
3073 string const abstexname =
3074 makeAbsPath(filename, path).absFileName();
3075 string const abslyxname =
3076 changeExtension(abstexname, ".lyx");
3077 string const absfigname =
3078 changeExtension(abstexname, ".fig");
3079 fix_relative_filename(filename);
3080 string const lyxname =
3081 changeExtension(filename, ".lyx");
3083 external = FileName(absfigname).exists();
3084 if (t.cs() == "input") {
3085 string const ext = getExtension(abstexname);
3087 // Combined PS/LaTeX:
3088 // x.eps, x.pstex_t (old xfig)
3089 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3090 FileName const absepsname(
3091 changeExtension(abstexname, ".eps"));
3092 FileName const abspstexname(
3093 changeExtension(abstexname, ".pstex"));
3094 bool const xfigeps =
3095 (absepsname.exists() ||
3096 abspstexname.exists()) &&
3099 // Combined PDF/LaTeX:
3100 // x.pdf, x.pdftex_t (old xfig)
3101 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3102 FileName const abspdfname(
3103 changeExtension(abstexname, ".pdf"));
3104 bool const xfigpdf =
3105 abspdfname.exists() &&
3106 (ext == "pdftex_t" || ext == "pdf_t");
3110 // Combined PS/PDF/LaTeX:
3111 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3112 string const absbase2(
3113 removeExtension(abstexname) + "_pspdftex");
3114 FileName const abseps2name(
3115 addExtension(absbase2, ".eps"));
3116 FileName const abspdf2name(
3117 addExtension(absbase2, ".pdf"));
3118 bool const xfigboth =
3119 abspdf2name.exists() &&
3120 abseps2name.exists() && ext == "pspdftex";
3122 xfig = xfigpdf || xfigeps || xfigboth;
3123 external = external && xfig;
3126 outname = changeExtension(filename, ".fig");
3128 // Don't try to convert, the result
3129 // would be full of ERT.
3131 } else if (t.cs() != "verbatiminput" &&
3132 tex2lyx(abstexname, FileName(abslyxname),
3139 cerr << "Warning: Could not find included file '"
3140 << filename << "'." << endl;
3144 begin_inset(os, "External\n");
3145 os << "\ttemplate XFig\n"
3146 << "\tfilename " << outname << '\n';
3148 begin_command_inset(os, "include", name);
3149 os << "preview false\n"
3150 "filename \"" << outname << "\"\n";
3155 else if (t.cs() == "bibliographystyle") {
3156 // store new bibliographystyle
3157 bibliographystyle = p.verbatim_item();
3158 // If any other command than \bibliography and
3159 // \nocite{*} follows, we need to output the style
3160 // (because it might be used by that command).
3161 // Otherwise, it will automatically be output by LyX.
3164 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3165 if (t2.cat() == catBegin)
3167 if (t2.cat() != catEscape)
3169 if (t2.cs() == "nocite") {
3170 if (p.getArg('{', '}') == "*")
3172 } else if (t2.cs() == "bibliography")
3179 "\\bibliographystyle{" + bibliographystyle + '}',
3184 else if (t.cs() == "bibliography") {
3185 context.check_layout(os);
3186 begin_command_inset(os, "bibtex", "bibtex");
3187 if (!btprint.empty()) {
3188 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3189 // clear the string because the next BibTeX inset can be without the
3190 // \nocite{*} option
3193 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3194 // Do we have a bibliographystyle set?
3195 if (!bibliographystyle.empty())
3196 os << "options " << '"' << bibliographystyle << '"' << "\n";
3200 else if (t.cs() == "parbox")
3201 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3203 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3204 t.cs() == "shadowbox" || t.cs() == "doublebox")
3205 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3207 else if (t.cs() == "framebox") {
3208 string special = p.getFullOpt();
3209 special += p.getOpt();
3210 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3213 //\makebox() is part of the picture environment and different from \makebox{}
3214 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3215 else if (t.cs() == "makebox") {
3216 string arg = t.asInput();
3217 if (p.next_token().character() == '(')
3218 //the syntax is: \makebox(x,y)[position]{content}
3219 arg += p.getFullParentheseArg();
3221 //the syntax is: \makebox[width][position]{content}
3222 arg += p.getFullOpt();
3223 handle_ert(os, arg + p.getFullOpt(), context);
3226 else if (t.cs() == "smallskip" ||
3227 t.cs() == "medskip" ||
3228 t.cs() == "bigskip" ||
3229 t.cs() == "vfill") {
3230 context.check_layout(os);
3231 begin_inset(os, "VSpace ");
3234 skip_spaces_braces(p);
3237 else if (is_known(t.cs(), known_spaces)) {
3238 char const * const * where = is_known(t.cs(), known_spaces);
3239 context.check_layout(os);
3240 begin_inset(os, "space ");
3241 os << '\\' << known_coded_spaces[where - known_spaces]
3244 // LaTeX swallows whitespace after all spaces except
3245 // "\\,". We have to do that here, too, because LyX
3246 // adds "{}" which would make the spaces significant.
3248 eat_whitespace(p, os, context, false);
3249 // LyX adds "{}" after all spaces except "\\ " and
3250 // "\\,", so we have to remove "{}".
3251 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3252 // remove the braces after "\\,", too.
3257 else if (t.cs() == "newpage" ||
3258 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3259 t.cs() == "clearpage" ||
3260 t.cs() == "cleardoublepage") {
3261 context.check_layout(os);
3262 begin_inset(os, "Newpage ");
3265 skip_spaces_braces(p);
3268 else if (t.cs() == "DeclareRobustCommand" ||
3269 t.cs() == "DeclareRobustCommandx" ||
3270 t.cs() == "newcommand" ||
3271 t.cs() == "newcommandx" ||
3272 t.cs() == "providecommand" ||
3273 t.cs() == "providecommandx" ||
3274 t.cs() == "renewcommand" ||
3275 t.cs() == "renewcommandx") {
3276 // DeclareRobustCommand, DeclareRobustCommandx,
3277 // providecommand and providecommandx could be handled
3278 // by parse_command(), but we need to call
3279 // add_known_command() here.
3280 string name = t.asInput();
3281 if (p.next_token().asInput() == "*") {
3282 // Starred form. Eat '*'
3286 string const command = p.verbatim_item();
3287 string const opt1 = p.getFullOpt();
3288 string const opt2 = p.getFullOpt();
3289 add_known_command(command, opt1, !opt2.empty());
3290 string const ert = name + '{' + command + '}' +
3292 '{' + p.verbatim_item() + '}';
3294 if (t.cs() == "DeclareRobustCommand" ||
3295 t.cs() == "DeclareRobustCommandx" ||
3296 t.cs() == "providecommand" ||
3297 t.cs() == "providecommandx" ||
3298 name[name.length()-1] == '*')
3299 handle_ert(os, ert, context);
3301 context.check_layout(os);
3302 begin_inset(os, "FormulaMacro");
3308 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3309 // let could be handled by parse_command(),
3310 // but we need to call add_known_command() here.
3311 string ert = t.asInput();
3314 if (p.next_token().cat() == catBegin) {
3315 name = p.verbatim_item();
3316 ert += '{' + name + '}';
3318 name = p.verbatim_item();
3323 if (p.next_token().cat() == catBegin) {
3324 command = p.verbatim_item();
3325 ert += '{' + command + '}';
3327 command = p.verbatim_item();
3330 // If command is known, make name known too, to parse
3331 // its arguments correctly. For this reason we also
3332 // have commands in syntax.default that are hardcoded.
3333 CommandMap::iterator it = known_commands.find(command);
3334 if (it != known_commands.end())
3335 known_commands[t.asInput()] = it->second;
3336 handle_ert(os, ert, context);
3339 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3340 bool starred = false;
3341 if (p.next_token().asInput() == "*") {
3345 string name = t.asInput();
3346 string const length = p.verbatim_item();
3349 bool valid = splitLatexLength(length, valstring, unit);
3350 bool known_hspace = false;
3351 bool known_vspace = false;
3352 bool known_unit = false;
3355 istringstream iss(valstring);
3358 if (t.cs()[0] == 'h') {
3359 if (unit == "\\fill") {
3364 known_hspace = true;
3367 if (unit == "\\smallskipamount") {
3369 known_vspace = true;
3370 } else if (unit == "\\medskipamount") {
3372 known_vspace = true;
3373 } else if (unit == "\\bigskipamount") {
3375 known_vspace = true;
3376 } else if (unit == "\\fill") {
3378 known_vspace = true;
3382 if (!known_hspace && !known_vspace) {
3383 switch (unitFromString(unit)) {
3404 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3405 // Literal horizontal length or known variable
3406 context.check_layout(os);
3407 begin_inset(os, "space ");
3415 if (known_unit && !known_hspace)
3417 << translate_len(length);
3419 } else if (known_unit || known_vspace) {
3420 // Literal vertical length or known variable
3421 context.check_layout(os);
3422 begin_inset(os, "VSpace ");
3430 // LyX can't handle other length variables in Inset VSpace/space
3435 handle_ert(os, name + '{' + unit + '}', context);
3436 else if (value == -1.0)
3437 handle_ert(os, name + "{-" + unit + '}', context);
3439 handle_ert(os, name + '{' + valstring + unit + '}', context);
3441 handle_ert(os, name + '{' + length + '}', context);
3445 // The single '=' is meant here.
3446 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3448 context.check_layout(os);
3449 begin_inset(os, "Flex ");
3450 os << to_utf8(newinsetlayout->name()) << '\n'
3451 << "status collapsed\n";
3452 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3457 // try to see whether the string is in unicodesymbols
3458 // Only use text mode commands, since we are in text mode here,
3459 // and math commands may be invalid (bug 6797)
3461 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3462 rem, Encodings::TEXT_CMD);
3465 cerr << "When parsing " << t.cs()
3466 << ", result is " << to_utf8(s)
3467 << "+" << to_utf8(rem) << endl;
3468 context.check_layout(os);
3470 skip_spaces_braces(p);
3472 //cerr << "#: " << t << " mode: " << mode << endl;
3473 // heuristic: read up to next non-nested space
3475 string s = t.asInput();
3476 string z = p.verbatim_item();
3477 while (p.good() && z != " " && z.size()) {
3478 //cerr << "read: " << z << endl;
3480 z = p.verbatim_item();
3482 cerr << "found ERT: " << s << endl;
3483 handle_ert(os, s + ' ', context);
3486 string name = t.asInput();
3487 if (p.next_token().asInput() == "*") {
3488 // Starred commands like \vspace*{}
3489 p.get_token(); // Eat '*'
3492 if (!parse_command(name, p, os, outer, context))
3493 handle_ert(os, name, context);
3497 if (flags & FLAG_LEAVE) {
3498 flags &= ~FLAG_LEAVE;