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"
26 #include "support/lassert.h"
27 #include "support/convert.h"
28 #include "support/FileName.h"
29 #include "support/filetools.h"
30 #include "support/lstrings.h"
39 using namespace lyx::support;
44 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
45 Context const & context, InsetLayout const * layout)
47 bool const forcePlainLayout =
48 layout ? layout->forcePlainLayout() : false;
49 Context newcontext(true, context.textclass);
51 newcontext.layout = &context.textclass.plainLayout();
53 newcontext.font = context.font;
54 parse_text(p, os, flags, outer, newcontext);
55 newcontext.check_end_layout(os);
61 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
62 Context const & context, string const & name)
64 InsetLayout const * layout = 0;
65 DocumentClass::InsetLayouts::const_iterator it =
66 context.textclass.insetLayouts().find(from_ascii(name));
67 if (it != context.textclass.insetLayouts().end())
68 layout = &(it->second);
69 parse_text_in_inset(p, os, flags, outer, context, layout);
72 /// parses a paragraph snippet, useful for example for \\emph{...}
73 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
76 Context newcontext(context);
77 // Don't inherit the paragraph-level extra stuff
78 newcontext.par_extra_stuff.clear();
79 parse_text(p, os, flags, outer, newcontext);
80 // Make sure that we don't create invalid .lyx files
81 context.need_layout = newcontext.need_layout;
82 context.need_end_layout = newcontext.need_end_layout;
87 * Thin wrapper around parse_text_snippet() using a string.
89 * We completely ignore \c context.need_layout and \c context.need_end_layout,
90 * because our return value is not used directly (otherwise the stream version
91 * of parse_text_snippet() could be used). That means that the caller needs
92 * to do layout management manually.
93 * This is intended to parse text that does not create any layout changes.
95 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
98 Context newcontext(context);
99 newcontext.need_layout = false;
100 newcontext.need_end_layout = false;
101 newcontext.new_layout_allowed = false;
102 // Avoid warning by Context::~Context()
103 newcontext.par_extra_stuff.clear();
105 parse_text_snippet(p, os, flags, outer, newcontext);
110 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
111 "vpageref", "prettyref", "eqref", 0 };
113 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
114 "vpageref", "formatted", "eqref", 0 };
118 * The starred forms are also known except for "citefullauthor",
119 * "citeyear" and "citeyearpar".
121 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
122 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
123 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
127 * No starred form other than "cite*" known.
129 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
130 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
131 // jurabib commands not (yet) supported by LyX:
133 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
134 // "footciteauthor", "footciteyear", "footciteyearpar",
135 "citefield", "citetitle", 0 };
137 /// LaTeX names for quotes
138 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
139 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
140 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
141 "guilsinglleft", "frq", "guilsinglright", 0};
143 /// the same as known_quotes with .lyx names
144 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
145 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
146 "gld", "grd", "gls", "ers", "fls",
147 "fls", "frs", "frs", 0};
149 /// LaTeX names for font sizes
150 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
151 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
153 /// the same as known_sizes with .lyx names
154 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
155 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
157 /// LaTeX 2.09 names for font families
158 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
160 /// LaTeX names for font families
161 char const * const known_font_families[] = { "rmfamily", "sffamily",
164 /// the same as known_old_font_families and known_font_families with .lyx names
165 char const * const known_coded_font_families[] = { "roman", "sans",
168 /// LaTeX 2.09 names for font series
169 char const * const known_old_font_series[] = { "bf", 0};
171 /// LaTeX names for font series
172 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
174 /// the same as known_old_font_series and known_font_series with .lyx names
175 char const * const known_coded_font_series[] = { "bold", "medium", 0};
177 /// LaTeX 2.09 names for font shapes
178 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
180 /// LaTeX names for font shapes
181 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
184 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
185 char const * const known_coded_font_shapes[] = { "italic", "slanted",
186 "smallcaps", "up", 0};
189 * Graphics file extensions known by the dvips driver of the graphics package.
190 * These extensions are used to complete the filename of an included
191 * graphics file if it does not contain an extension.
192 * The order must be the same that latex uses to find a file, because we
193 * will use the first extension that matches.
194 * This is only an approximation for the common cases. If we would want to
195 * do it right in all cases, we would need to know which graphics driver is
196 * used and know the extensions of every driver of the graphics package.
198 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
199 "ps.gz", "eps.Z", "ps.Z", 0};
202 * Graphics file extensions known by the pdftex driver of the graphics package.
203 * \sa known_dvips_graphics_formats
205 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
209 * Known file extensions for TeX files as used by \\include.
211 char const * const known_tex_extensions[] = {"tex", 0};
213 /// spaces known by InsetSpace
214 char const * const known_spaces[] = { " ", "space", ",",
215 "thinspace", "quad", "qquad", "enspace", "enskip",
216 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
217 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
218 "upbracefill", "downbracefill", 0};
220 /// the same as known_spaces with .lyx names
221 char const * const known_coded_spaces[] = { "space{}", "space{}",
222 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
223 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
224 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
225 "upbracefill{}", "downbracefill{}", 0};
227 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
228 /// them in ERT. "LaTeXe" must come before "LaTeX"!
229 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
230 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
231 int const known_phrase_lengths[] = {3, 5, 7, 0};
233 // string to store the float type to be able to determine the type of subfloats
234 string float_type = "";
237 /// splits "x=z, y=b" into a map and an ordered keyword vector
238 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
243 keys.resize(v.size());
244 for (size_t i = 0; i < v.size(); ++i) {
245 size_t const pos = v[i].find('=');
246 string const index = trimSpaceAndEol(v[i].substr(0, pos));
247 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
255 * Split a LaTeX length into value and unit.
256 * The latter can be a real unit like "pt", or a latex length variable
257 * like "\textwidth". The unit may contain additional stuff like glue
258 * lengths, but we don't care, because such lengths are ERT anyway.
259 * \returns true if \p value and \p unit are valid.
261 bool splitLatexLength(string const & len, string & value, string & unit)
265 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
266 //'4,5' is a valid LaTeX length number. Change it to '4.5'
267 string const length = subst(len, ',', '.');
268 if (i == string::npos)
271 if (len[0] == '\\') {
272 // We had something like \textwidth without a factor
278 value = trimSpaceAndEol(string(length, 0, i));
282 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
283 if (contains(len, '\\'))
284 unit = trimSpaceAndEol(string(len, i));
286 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
291 /// A simple function to translate a latex length to something LyX can
292 /// understand. Not perfect, but rather best-effort.
293 bool translate_len(string const & length, string & valstring, string & unit)
295 if (!splitLatexLength(length, valstring, unit))
297 // LyX uses percent values
299 istringstream iss(valstring);
304 string const percentval = oss.str();
306 if (unit.empty() || unit[0] != '\\')
308 string::size_type const i = unit.find(' ');
309 string const endlen = (i == string::npos) ? string() : string(unit, i);
310 if (unit == "\\textwidth") {
311 valstring = percentval;
312 unit = "text%" + endlen;
313 } else if (unit == "\\columnwidth") {
314 valstring = percentval;
315 unit = "col%" + endlen;
316 } else if (unit == "\\paperwidth") {
317 valstring = percentval;
318 unit = "page%" + endlen;
319 } else if (unit == "\\linewidth") {
320 valstring = percentval;
321 unit = "line%" + endlen;
322 } else if (unit == "\\paperheight") {
323 valstring = percentval;
324 unit = "pheight%" + endlen;
325 } else if (unit == "\\textheight") {
326 valstring = percentval;
327 unit = "theight%" + endlen;
335 string translate_len(string const & length)
339 if (translate_len(length, value, unit))
341 // If the input is invalid, return what we have.
349 * Translates a LaTeX length into \p value, \p unit and
350 * \p special parts suitable for a box inset.
351 * The difference from translate_len() is that a box inset knows about
352 * some special "units" that are stored in \p special.
354 void translate_box_len(string const & length, string & value, string & unit, string & special)
356 if (translate_len(length, value, unit)) {
357 if (unit == "\\height" || unit == "\\depth" ||
358 unit == "\\totalheight" || unit == "\\width") {
359 special = unit.substr(1);
360 // The unit is not used, but LyX requires a dummy setting
373 * Find a file with basename \p name in path \p path and an extension
376 string find_file(string const & name, string const & path,
377 char const * const * extensions)
379 for (char const * const * what = extensions; *what; ++what) {
380 string const trial = addExtension(name, *what);
381 if (makeAbsPath(trial, path).exists())
388 void begin_inset(ostream & os, string const & name)
390 os << "\n\\begin_inset " << name;
394 void begin_command_inset(ostream & os, string const & name,
395 string const & latexname)
397 begin_inset(os, "CommandInset ");
398 os << name << "\nLatexCommand " << latexname << '\n';
402 void end_inset(ostream & os)
404 os << "\n\\end_inset\n\n";
408 bool skip_braces(Parser & p)
410 if (p.next_token().cat() != catBegin)
413 if (p.next_token().cat() == catEnd) {
422 /// replace LaTeX commands in \p s from the unicodesymbols file with their
424 docstring convert_unicodesymbols(docstring s)
427 for (size_t i = 0; i < s.size();) {
434 docstring parsed = encodings.fromLaTeXCommand(s, rem,
435 Encodings::TEXT_CMD);
438 if (s.empty() || s[0] != '\\')
447 /// try to convert \p s to a valid InsetCommand argument
448 string convert_command_inset_arg(string s)
451 // since we don't know the input encoding we can't use from_utf8
452 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
453 // LyX cannot handle newlines in a latex command
454 return subst(s, "\n", " ");
458 void handle_backslash(ostream & os, string const & s)
460 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
462 os << "\n\\backslash\n";
469 void handle_ert(ostream & os, string const & s, Context & context)
471 // We must have a valid layout before outputting the ERT inset.
472 context.check_layout(os);
473 Context newcontext(true, context.textclass);
474 begin_inset(os, "ERT");
475 os << "\nstatus collapsed\n";
476 newcontext.check_layout(os);
477 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
479 os << "\n\\backslash\n";
480 else if (*it == '\n') {
481 newcontext.new_paragraph(os);
482 newcontext.check_layout(os);
486 newcontext.check_end_layout(os);
491 void handle_comment(ostream & os, string const & s, Context & context)
493 // TODO: Handle this better
494 Context newcontext(true, context.textclass);
495 begin_inset(os, "ERT");
496 os << "\nstatus collapsed\n";
497 newcontext.check_layout(os);
498 handle_backslash(os, s);
499 // make sure that our comment is the last thing on the line
500 newcontext.new_paragraph(os);
501 newcontext.check_layout(os);
502 newcontext.check_end_layout(os);
507 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
509 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
512 if (checkModule(name, command))
513 return findLayoutWithoutModule(textclass, name, command);
518 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
520 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
523 if (checkModule(name, command))
524 return findInsetLayoutWithoutModule(textclass, name, command);
529 void eat_whitespace(Parser &, ostream &, Context &, bool);
533 * Skips whitespace and braces.
534 * This should be called after a command has been parsed that is not put into
535 * ERT, and where LyX adds "{}" if needed.
537 void skip_spaces_braces(Parser & p, bool keepws = false)
539 /* The following four examples produce the same typeset output and
540 should be handled by this function:
548 // Unfortunately we need to skip comments, too.
549 // We can't use eat_whitespace since writing them after the {}
550 // results in different output in some cases.
551 bool const skipped_spaces = p.skip_spaces(true);
552 bool const skipped_braces = skip_braces(p);
553 if (keepws && skipped_spaces && !skipped_braces)
554 // put back the space (it is better handled by check_space)
555 p.unskip_spaces(true);
559 void output_command_layout(ostream & os, Parser & p, bool outer,
560 Context & parent_context,
561 Layout const * newlayout)
563 TeXFont const oldFont = parent_context.font;
564 // save the current font size
565 string const size = oldFont.size;
566 // reset the font size to default, because the font size switches
567 // don't affect section headings and the like
568 parent_context.font.size = Context::normalfont.size;
569 // we only need to write the font change if we have an open layout
570 if (!parent_context.atParagraphStart())
571 output_font_change(os, oldFont, parent_context.font);
572 parent_context.check_end_layout(os);
573 Context context(true, parent_context.textclass, newlayout,
574 parent_context.layout, parent_context.font);
575 if (parent_context.deeper_paragraph) {
576 // We are beginning a nested environment after a
577 // deeper paragraph inside the outer list environment.
578 // Therefore we don't need to output a "begin deeper".
579 context.need_end_deeper = true;
581 context.check_deeper(os);
582 context.check_layout(os);
583 unsigned int optargs = 0;
584 while (optargs < context.layout->optargs) {
585 eat_whitespace(p, os, context, false);
586 if (p.next_token().cat() == catEscape ||
587 p.next_token().character() != '[')
589 p.get_token(); // eat '['
590 begin_inset(os, "Argument\n");
591 os << "status collapsed\n\n";
592 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
594 eat_whitespace(p, os, context, false);
597 unsigned int reqargs = 0;
598 while (reqargs < context.layout->reqargs) {
599 eat_whitespace(p, os, context, false);
600 if (p.next_token().cat() != catBegin)
602 p.get_token(); // eat '{'
603 begin_inset(os, "Argument\n");
604 os << "status collapsed\n\n";
605 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
607 eat_whitespace(p, os, context, false);
610 parse_text(p, os, FLAG_ITEM, outer, context);
611 context.check_end_layout(os);
612 if (parent_context.deeper_paragraph) {
613 // We must suppress the "end deeper" because we
614 // suppressed the "begin deeper" above.
615 context.need_end_deeper = false;
617 context.check_end_deeper(os);
618 // We don't need really a new paragraph, but
619 // we must make sure that the next item gets a \begin_layout.
620 parent_context.new_paragraph(os);
621 // Set the font size to the original value. No need to output it here
622 // (Context::begin_layout() will do that if needed)
623 parent_context.font.size = size;
628 * Output a space if necessary.
629 * This function gets called for every whitespace token.
631 * We have three cases here:
632 * 1. A space must be suppressed. Example: The lyxcode case below
633 * 2. A space may be suppressed. Example: Spaces before "\par"
634 * 3. A space must not be suppressed. Example: A space between two words
636 * We currently handle only 1. and 3 and from 2. only the case of
637 * spaces before newlines as a side effect.
639 * 2. could be used to suppress as many spaces as possible. This has two effects:
640 * - Reimporting LyX generated LaTeX files changes almost no whitespace
641 * - Superflous whitespace from non LyX generated LaTeX files is removed.
642 * The drawback is that the logic inside the function becomes
643 * complicated, and that is the reason why it is not implemented.
645 void check_space(Parser & p, ostream & os, Context & context)
647 Token const next = p.next_token();
648 Token const curr = p.curr_token();
649 // A space before a single newline and vice versa must be ignored
650 // LyX emits a newline before \end{lyxcode}.
651 // This newline must be ignored,
652 // otherwise LyX will add an additional protected space.
653 if (next.cat() == catSpace ||
654 next.cat() == catNewline ||
655 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
658 context.check_layout(os);
664 * Parse all arguments of \p command
666 void parse_arguments(string const & command,
667 vector<ArgumentType> const & template_arguments,
668 Parser & p, ostream & os, bool outer, Context & context)
670 string ert = command;
671 size_t no_arguments = template_arguments.size();
672 for (size_t i = 0; i < no_arguments; ++i) {
673 switch (template_arguments[i]) {
675 // This argument contains regular LaTeX
676 handle_ert(os, ert + '{', context);
677 eat_whitespace(p, os, context, false);
678 parse_text(p, os, FLAG_ITEM, outer, context);
682 // This argument consists only of a single item.
683 // The presence of '{' or not must be preserved.
685 if (p.next_token().cat() == catBegin)
686 ert += '{' + p.verbatim_item() + '}';
688 ert += p.verbatim_item();
691 // This argument may contain special characters
692 ert += '{' + p.verbatim_item() + '}';
695 // true because we must not eat whitespace
696 // if an optional arg follows we must not strip the
697 // brackets from this one
698 if (i < no_arguments - 1 &&
699 template_arguments[i+1] == optional)
700 ert += p.getFullOpt(true);
702 ert += p.getOpt(true);
706 handle_ert(os, ert, context);
711 * Check whether \p command is a known command. If yes,
712 * handle the command with all arguments.
713 * \return true if the command was parsed, false otherwise.
715 bool parse_command(string const & command, Parser & p, ostream & os,
716 bool outer, Context & context)
718 if (known_commands.find(command) != known_commands.end()) {
719 parse_arguments(command, known_commands[command], p, os,
727 /// Parses a minipage or parbox
728 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
729 unsigned inner_flags, bool outer, Context & parent_context,
730 string const & outer_type, string const & special,
731 string const & inner_type)
735 string hor_pos = "c";
736 // We need to set the height to the LaTeX default of 1\\totalheight
737 // for the case when no height argument is given
738 string height_value = "1";
739 string height_unit = "in";
740 string height_special = "totalheight";
742 if (!inner_type.empty() && p.hasOpt()) {
743 position = p.getArg('[', ']');
744 if (position != "t" && position != "c" && position != "b") {
745 cerr << "invalid position " << position << " for "
746 << inner_type << endl;
750 latex_height = p.getArg('[', ']');
751 translate_box_len(latex_height, height_value, height_unit, height_special);
754 inner_pos = p.getArg('[', ']');
755 if (inner_pos != "c" && inner_pos != "t" &&
756 inner_pos != "b" && inner_pos != "s") {
757 cerr << "invalid inner_pos "
758 << inner_pos << " for "
759 << inner_type << endl;
760 inner_pos = position;
768 if (inner_type.empty()) {
770 latex_width = "\\columnwidth";
773 latex_width = p2.getArg('[', ']');
774 string const opt = p2.getArg('[', ']');
777 if (hor_pos != "l" && hor_pos != "c" &&
779 cerr << "invalid hor_pos " << hor_pos
780 << " for " << outer_type << endl;
786 latex_width = p.verbatim_item();
787 translate_len(latex_width, width_value, width_unit);
788 // LyX can't handle length variables
789 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
790 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
791 // Look whether there is some content after the end of the
792 // inner box, but before the end of the outer box.
793 // If yes, we need to output ERT.
795 if (inner_flags & FLAG_END)
796 p.verbatimEnvironment(inner_type);
800 if ((outer_type == "framed" && p.next_token().asInput() != "\\end") ||
801 (outer_type != "framed" && p.next_token().cat() != catEnd)) {
802 // something is between the end of the inner box and
803 // the end of the outer box, so we need to use ERT.
810 if (!outer_type.empty()) {
811 if (outer_flags & FLAG_END)
812 ss << "\\begin{" << outer_type << '}';
814 ss << '\\' << outer_type << '{';
815 if (!special.empty())
819 if (!inner_type.empty()) {
820 if (inner_flags & FLAG_END)
821 ss << "\\begin{" << inner_type << '}';
823 ss << '\\' << inner_type;
824 if (!position.empty())
825 ss << '[' << position << ']';
826 if (!latex_height.empty())
827 ss << '[' << latex_height << ']';
828 if (!inner_pos.empty())
829 ss << '[' << inner_pos << ']';
830 ss << '{' << latex_width << '}';
831 if (!(inner_flags & FLAG_END))
834 handle_ert(os, ss.str(), parent_context);
835 if (!inner_type.empty()) {
836 parse_text(p, os, inner_flags, outer, parent_context);
837 if (inner_flags & FLAG_END)
838 handle_ert(os, "\\end{" + inner_type + '}',
841 handle_ert(os, "}", parent_context);
843 if (!outer_type.empty()) {
844 parse_text(p, os, outer_flags, outer, parent_context);
845 if (outer_flags & FLAG_END)
846 handle_ert(os, "\\end{" + outer_type + '}',
849 handle_ert(os, "}", parent_context);
852 // LyX does not like empty positions, so we have
853 // to set them to the LaTeX default values here.
854 if (position.empty())
856 if (inner_pos.empty())
857 inner_pos = position;
858 parent_context.check_layout(os);
859 begin_inset(os, "Box ");
860 if (outer_type == "framed")
862 else if (outer_type == "framebox")
864 else if (outer_type == "shadowbox")
866 else if (outer_type == "shaded")
868 else if (outer_type == "doublebox")
870 else if (outer_type.empty())
873 os << outer_type << '\n';
874 os << "position \"" << position << "\"\n";
875 os << "hor_pos \"" << hor_pos << "\"\n";
876 os << "has_inner_box " << !inner_type.empty() << "\n";
877 os << "inner_pos \"" << inner_pos << "\"\n";
878 os << "use_parbox " << (inner_type == "parbox") << '\n';
879 os << "use_makebox 0\n";
880 os << "width \"" << width_value << width_unit << "\"\n";
881 os << "special \"none\"\n";
882 os << "height \"" << height_value << height_unit << "\"\n";
883 os << "height_special \"" << height_special << "\"\n";
884 os << "status open\n\n";
885 Context context(true, parent_context.textclass);
886 context.font = parent_context.font;
888 // FIXME, the inset layout should be plain, not standard, see bug #7846
890 // If we have no inner box the contens will be read with the outer box
891 if (!inner_type.empty())
892 parse_text(p, os, inner_flags, outer, context);
894 // Ensure that the end of the outer box is parsed correctly:
895 // The opening brace has been eaten by parse_outer_box()
896 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
897 outer_flags &= ~FLAG_ITEM;
898 outer_flags |= FLAG_BRACE_LAST;
901 // Find end of outer box, output contents if inner_type is
902 // empty and output possible comments
903 if (!outer_type.empty()) {
904 // This does not output anything but comments if
905 // inner_type is not empty (see use_ert)
906 parse_text(p, os, outer_flags, outer, context);
909 context.check_end_layout(os);
911 #ifdef PRESERVE_LAYOUT
912 // LyX puts a % after the end of the minipage
913 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
915 //handle_comment(os, "%dummy", parent_context);
918 parent_context.new_paragraph(os);
920 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
921 //handle_comment(os, "%dummy", parent_context);
924 // We add a protected space if something real follows
925 if (p.good() && p.next_token().cat() != catComment) {
926 begin_inset(os, "space ~\n");
935 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
936 Context & parent_context, string const & outer_type,
937 string const & special)
939 eat_whitespace(p, os, parent_context, false);
940 if (flags & FLAG_ITEM) {
942 if (p.next_token().cat() == catBegin)
945 cerr << "Warning: Ignoring missing '{' after \\"
946 << outer_type << '.' << endl;
947 eat_whitespace(p, os, parent_context, false);
950 unsigned int inner_flags = 0;
951 if (outer_type == "shaded") {
952 // These boxes never have an inner box
954 } else if (p.next_token().asInput() == "\\parbox") {
955 inner = p.get_token().cs();
956 inner_flags = FLAG_ITEM;
957 } else if (p.next_token().asInput() == "\\begin") {
958 // Is this a minipage?
961 inner = p.getArg('{', '}');
963 if (inner == "minipage") {
966 eat_whitespace(p, os, parent_context, false);
967 inner_flags = FLAG_END;
971 if (inner_flags == FLAG_END) {
972 active_environments.push_back(inner);
973 parse_box(p, os, flags, FLAG_END, outer, parent_context,
974 outer_type, special, inner);
975 active_environments.pop_back();
977 parse_box(p, os, flags, inner_flags, outer, parent_context,
978 outer_type, special, inner);
983 void parse_listings(Parser & p, ostream & os, Context & parent_context)
985 parent_context.check_layout(os);
986 begin_inset(os, "listings\n");
987 os << "inline false\n"
988 << "status collapsed\n";
989 Context context(true, parent_context.textclass);
990 context.layout = &parent_context.textclass.plainLayout();
991 context.check_layout(os);
992 string const s = p.verbatimEnvironment("lstlisting");
993 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
995 os << "\n\\backslash\n";
996 else if (*it == '\n') {
997 // avoid adding an empty paragraph at the end
999 context.new_paragraph(os);
1000 context.check_layout(os);
1005 context.check_end_layout(os);
1010 /// parse an unknown environment
1011 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1012 unsigned flags, bool outer,
1013 Context & parent_context)
1015 if (name == "tabbing")
1016 // We need to remember that we have to handle '\=' specially
1017 flags |= FLAG_TABBING;
1019 // We need to translate font changes and paragraphs inside the
1020 // environment to ERT if we have a non standard font.
1021 // Otherwise things like
1022 // \large\begin{foo}\huge bar\end{foo}
1024 bool const specialfont =
1025 (parent_context.font != parent_context.normalfont);
1026 bool const new_layout_allowed = parent_context.new_layout_allowed;
1028 parent_context.new_layout_allowed = false;
1029 handle_ert(os, "\\begin{" + name + "}", parent_context);
1030 parse_text_snippet(p, os, flags, outer, parent_context);
1031 handle_ert(os, "\\end{" + name + "}", parent_context);
1033 parent_context.new_layout_allowed = new_layout_allowed;
1037 void parse_environment(Parser & p, ostream & os, bool outer,
1038 string & last_env, bool & title_layout_found,
1039 Context & parent_context)
1041 Layout const * newlayout;
1042 InsetLayout const * newinsetlayout = 0;
1043 string const name = p.getArg('{', '}');
1044 const bool is_starred = suffixIs(name, '*');
1045 string const unstarred_name = rtrim(name, "*");
1046 active_environments.push_back(name);
1048 if (is_math_env(name)) {
1049 parent_context.check_layout(os);
1050 begin_inset(os, "Formula ");
1051 os << "\\begin{" << name << "}";
1052 parse_math(p, os, FLAG_END, MATH_MODE);
1053 os << "\\end{" << name << "}";
1057 else if (name == "tabular" || name == "longtable") {
1058 eat_whitespace(p, os, parent_context, false);
1059 parent_context.check_layout(os);
1060 begin_inset(os, "Tabular ");
1061 handle_tabular(p, os, name == "longtable", parent_context);
1066 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1067 eat_whitespace(p, os, parent_context, false);
1068 parent_context.check_layout(os);
1069 begin_inset(os, "Float " + unstarred_name + "\n");
1070 // store the float type for subfloats
1071 // subfloats only work with figures and tables
1072 if (unstarred_name == "figure")
1073 float_type = unstarred_name;
1074 else if (unstarred_name == "table")
1075 float_type = unstarred_name;
1079 os << "placement " << p.getArg('[', ']') << '\n';
1080 os << "wide " << convert<string>(is_starred)
1081 << "\nsideways false"
1082 << "\nstatus open\n\n";
1083 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1085 // We don't need really a new paragraph, but
1086 // we must make sure that the next item gets a \begin_layout.
1087 parent_context.new_paragraph(os);
1089 // the float is parsed thus delete the type
1093 else if (unstarred_name == "sidewaysfigure"
1094 || unstarred_name == "sidewaystable") {
1095 eat_whitespace(p, os, parent_context, false);
1096 parent_context.check_layout(os);
1097 if (unstarred_name == "sidewaysfigure")
1098 begin_inset(os, "Float figure\n");
1100 begin_inset(os, "Float table\n");
1101 os << "wide " << convert<string>(is_starred)
1102 << "\nsideways true"
1103 << "\nstatus open\n\n";
1104 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1106 // We don't need really a new paragraph, but
1107 // we must make sure that the next item gets a \begin_layout.
1108 parent_context.new_paragraph(os);
1112 else if (name == "wrapfigure" || name == "wraptable") {
1113 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1114 eat_whitespace(p, os, parent_context, false);
1115 parent_context.check_layout(os);
1118 string overhang = "0col%";
1121 lines = p.getArg('[', ']');
1122 string const placement = p.getArg('{', '}');
1124 overhang = p.getArg('[', ']');
1125 string const width = p.getArg('{', '}');
1127 if (name == "wrapfigure")
1128 begin_inset(os, "Wrap figure\n");
1130 begin_inset(os, "Wrap table\n");
1131 os << "lines " << lines
1132 << "\nplacement " << placement
1133 << "\noverhang " << lyx::translate_len(overhang)
1134 << "\nwidth " << lyx::translate_len(width)
1135 << "\nstatus open\n\n";
1136 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1138 // We don't need really a new paragraph, but
1139 // we must make sure that the next item gets a \begin_layout.
1140 parent_context.new_paragraph(os);
1144 else if (name == "minipage") {
1145 eat_whitespace(p, os, parent_context, false);
1146 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1150 else if (name == "comment") {
1151 eat_whitespace(p, os, parent_context, false);
1152 parent_context.check_layout(os);
1153 begin_inset(os, "Note Comment\n");
1154 os << "status open\n";
1155 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1158 skip_braces(p); // eat {} that might by set by LyX behind comments
1161 else if (name == "lyxgreyedout") {
1162 eat_whitespace(p, os, parent_context, false);
1163 parent_context.check_layout(os);
1164 begin_inset(os, "Note Greyedout\n");
1165 os << "status open\n";
1166 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1171 else if (name == "framed" || name == "shaded") {
1172 eat_whitespace(p, os, parent_context, false);
1173 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1177 else if (name == "lstlisting") {
1178 eat_whitespace(p, os, parent_context, false);
1179 // FIXME handle listings with parameters
1181 parse_unknown_environment(p, name, os, FLAG_END,
1182 outer, parent_context);
1184 parse_listings(p, os, parent_context);
1188 else if (!parent_context.new_layout_allowed)
1189 parse_unknown_environment(p, name, os, FLAG_END, outer,
1192 // Alignment and spacing settings
1193 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1194 // therefore are totally broken!
1195 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1196 // they are commands not environments. They are furthermore switches that
1197 // can be ended by another switches, but also by commands like \footnote or
1198 // \parbox. So the only safe way is to leave them untouched.
1199 else if (name == "center" || name == "centering" ||
1200 name == "flushleft" || name == "flushright" ||
1201 name == "singlespace" || name == "onehalfspace" ||
1202 name == "doublespace" || name == "spacing") {
1203 eat_whitespace(p, os, parent_context, false);
1204 // We must begin a new paragraph if not already done
1205 if (! parent_context.atParagraphStart()) {
1206 parent_context.check_end_layout(os);
1207 parent_context.new_paragraph(os);
1209 if (name == "flushleft")
1210 parent_context.add_extra_stuff("\\align left\n");
1211 else if (name == "flushright")
1212 parent_context.add_extra_stuff("\\align right\n");
1213 else if (name == "center" || name == "centering")
1214 parent_context.add_extra_stuff("\\align center\n");
1215 else if (name == "singlespace")
1216 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1217 else if (name == "onehalfspace")
1218 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1219 else if (name == "doublespace")
1220 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1221 else if (name == "spacing")
1222 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1223 parse_text(p, os, FLAG_END, outer, parent_context);
1224 // Just in case the environment is empty
1225 parent_context.extra_stuff.erase();
1226 // We must begin a new paragraph to reset the alignment
1227 parent_context.new_paragraph(os);
1231 // The single '=' is meant here.
1232 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1233 eat_whitespace(p, os, parent_context, false);
1234 Context context(true, parent_context.textclass, newlayout,
1235 parent_context.layout, parent_context.font);
1236 if (parent_context.deeper_paragraph) {
1237 // We are beginning a nested environment after a
1238 // deeper paragraph inside the outer list environment.
1239 // Therefore we don't need to output a "begin deeper".
1240 context.need_end_deeper = true;
1242 parent_context.check_end_layout(os);
1243 if (last_env == name) {
1244 // we need to output a separator since LyX would export
1245 // the two environments as one otherwise (bug 5716)
1246 docstring const sep = from_ascii("--Separator--");
1247 TeX2LyXDocClass const & textclass(parent_context.textclass);
1248 if (textclass.hasLayout(sep)) {
1249 Context newcontext(parent_context);
1250 newcontext.layout = &(textclass[sep]);
1251 newcontext.check_layout(os);
1252 newcontext.check_end_layout(os);
1254 parent_context.check_layout(os);
1255 begin_inset(os, "Note Note\n");
1256 os << "status closed\n";
1257 Context newcontext(true, textclass,
1258 &(textclass.defaultLayout()));
1259 newcontext.check_layout(os);
1260 newcontext.check_end_layout(os);
1262 parent_context.check_end_layout(os);
1265 switch (context.layout->latextype) {
1266 case LATEX_LIST_ENVIRONMENT:
1267 context.add_par_extra_stuff("\\labelwidthstring "
1268 + p.verbatim_item() + '\n');
1271 case LATEX_BIB_ENVIRONMENT:
1272 p.verbatim_item(); // swallow next arg
1278 context.check_deeper(os);
1279 // handle known optional and required arguments
1280 // layouts require all optional arguments before the required ones
1281 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1282 // It is impossible to place anything after the environment name,
1283 // but before the first \\item.
1284 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1285 bool need_layout = true;
1286 unsigned int optargs = 0;
1287 while (optargs < context.layout->optargs) {
1288 eat_whitespace(p, os, context, false);
1289 if (p.next_token().cat() == catEscape ||
1290 p.next_token().character() != '[')
1292 p.get_token(); // eat '['
1294 context.check_layout(os);
1295 need_layout = false;
1297 begin_inset(os, "Argument\n");
1298 os << "status collapsed\n\n";
1299 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1301 eat_whitespace(p, os, context, false);
1304 unsigned int reqargs = 0;
1305 while (reqargs < context.layout->reqargs) {
1306 eat_whitespace(p, os, context, false);
1307 if (p.next_token().cat() != catBegin)
1309 p.get_token(); // eat '{'
1311 context.check_layout(os);
1312 need_layout = false;
1314 begin_inset(os, "Argument\n");
1315 os << "status collapsed\n\n";
1316 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1318 eat_whitespace(p, os, context, false);
1322 parse_text(p, os, FLAG_END, outer, context);
1323 context.check_end_layout(os);
1324 if (parent_context.deeper_paragraph) {
1325 // We must suppress the "end deeper" because we
1326 // suppressed the "begin deeper" above.
1327 context.need_end_deeper = false;
1329 context.check_end_deeper(os);
1330 parent_context.new_paragraph(os);
1332 if (!title_layout_found)
1333 title_layout_found = newlayout->intitle;
1336 // The single '=' is meant here.
1337 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1338 eat_whitespace(p, os, parent_context, false);
1339 parent_context.check_layout(os);
1340 begin_inset(os, "Flex ");
1341 os << to_utf8(newinsetlayout->name()) << '\n'
1342 << "status collapsed\n";
1343 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1347 else if (name == "appendix") {
1348 // This is no good latex style, but it works and is used in some documents...
1349 eat_whitespace(p, os, parent_context, false);
1350 parent_context.check_end_layout(os);
1351 Context context(true, parent_context.textclass, parent_context.layout,
1352 parent_context.layout, parent_context.font);
1353 context.check_layout(os);
1354 os << "\\start_of_appendix\n";
1355 parse_text(p, os, FLAG_END, outer, context);
1356 context.check_end_layout(os);
1360 else if (known_environments.find(name) != known_environments.end()) {
1361 vector<ArgumentType> arguments = known_environments[name];
1362 // The last "argument" denotes wether we may translate the
1363 // environment contents to LyX
1364 // The default required if no argument is given makes us
1365 // compatible with the reLyXre environment.
1366 ArgumentType contents = arguments.empty() ?
1369 if (!arguments.empty())
1370 arguments.pop_back();
1371 // See comment in parse_unknown_environment()
1372 bool const specialfont =
1373 (parent_context.font != parent_context.normalfont);
1374 bool const new_layout_allowed =
1375 parent_context.new_layout_allowed;
1377 parent_context.new_layout_allowed = false;
1378 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1379 outer, parent_context);
1380 if (contents == verbatim)
1381 handle_ert(os, p.verbatimEnvironment(name),
1384 parse_text_snippet(p, os, FLAG_END, outer,
1386 handle_ert(os, "\\end{" + name + "}", parent_context);
1388 parent_context.new_layout_allowed = new_layout_allowed;
1392 parse_unknown_environment(p, name, os, FLAG_END, outer,
1396 active_environments.pop_back();
1400 /// parses a comment and outputs it to \p os.
1401 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1403 LASSERT(t.cat() == catComment, return);
1404 if (!t.cs().empty()) {
1405 context.check_layout(os);
1406 handle_comment(os, '%' + t.cs(), context);
1407 if (p.next_token().cat() == catNewline) {
1408 // A newline after a comment line starts a new
1410 if (context.new_layout_allowed) {
1411 if(!context.atParagraphStart())
1412 // Only start a new paragraph if not already
1413 // done (we might get called recursively)
1414 context.new_paragraph(os);
1416 handle_ert(os, "\n", context);
1417 eat_whitespace(p, os, context, true);
1420 // "%\n" combination
1427 * Reads spaces and comments until the first non-space, non-comment token.
1428 * New paragraphs (double newlines or \\par) are handled like simple spaces
1429 * if \p eatParagraph is true.
1430 * Spaces are skipped, but comments are written to \p os.
1432 void eat_whitespace(Parser & p, ostream & os, Context & context,
1436 Token const & t = p.get_token();
1437 if (t.cat() == catComment)
1438 parse_comment(p, os, t, context);
1439 else if ((! eatParagraph && p.isParagraph()) ||
1440 (t.cat() != catSpace && t.cat() != catNewline)) {
1449 * Set a font attribute, parse text and reset the font attribute.
1450 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1451 * \param currentvalue Current value of the attribute. Is set to the new
1452 * value during parsing.
1453 * \param newvalue New value of the attribute
1455 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1456 Context & context, string const & attribute,
1457 string & currentvalue, string const & newvalue)
1459 context.check_layout(os);
1460 string const oldvalue = currentvalue;
1461 currentvalue = newvalue;
1462 os << '\n' << attribute << ' ' << newvalue << "\n";
1463 parse_text_snippet(p, os, flags, outer, context);
1464 context.check_layout(os);
1465 os << '\n' << attribute << ' ' << oldvalue << "\n";
1466 currentvalue = oldvalue;
1470 /// get the arguments of a natbib or jurabib citation command
1471 void get_cite_arguments(Parser & p, bool natbibOrder,
1472 string & before, string & after)
1474 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1476 // text before the citation
1478 // text after the citation
1479 after = p.getFullOpt();
1481 if (!after.empty()) {
1482 before = p.getFullOpt();
1483 if (natbibOrder && !before.empty())
1484 swap(before, after);
1489 /// Convert filenames with TeX macros and/or quotes to something LyX
1491 string const normalize_filename(string const & name)
1493 Parser p(trim(name, "\""));
1496 Token const & t = p.get_token();
1497 if (t.cat() != catEscape)
1499 else if (t.cs() == "lyxdot") {
1500 // This is used by LyX for simple dots in relative
1504 } else if (t.cs() == "space") {
1514 /// Convert \p name from TeX convention (relative to master file) to LyX
1515 /// convention (relative to .lyx file) if it is relative
1516 void fix_relative_filename(string & name)
1518 if (FileName::isAbsolute(name))
1521 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1522 from_utf8(getParentFilePath())));
1526 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1527 void parse_noweb(Parser & p, ostream & os, Context & context)
1529 // assemble the rest of the keyword
1533 Token const & t = p.get_token();
1534 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1537 scrap = (p.good() && p.next_token().asInput() == "=");
1539 name += p.get_token().asInput();
1542 name += t.asInput();
1545 if (!scrap || !context.new_layout_allowed ||
1546 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1547 cerr << "Warning: Could not interpret '" << name
1548 << "'. Ignoring it." << endl;
1552 // We use new_paragraph instead of check_end_layout because the stuff
1553 // following the noweb chunk needs to start with a \begin_layout.
1554 // This may create a new paragraph even if there was none in the
1555 // noweb file, but the alternative is an invalid LyX file. Since
1556 // noweb code chunks are implemented with a layout style in LyX they
1557 // always must be in an own paragraph.
1558 context.new_paragraph(os);
1559 Context newcontext(true, context.textclass,
1560 &context.textclass[from_ascii("Scrap")]);
1561 newcontext.check_layout(os);
1564 Token const & t = p.get_token();
1565 // We abuse the parser a bit, because this is no TeX syntax
1567 if (t.cat() == catEscape)
1568 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1571 Context tmp(false, context.textclass,
1572 &context.textclass[from_ascii("Scrap")]);
1573 tmp.need_end_layout = true;
1574 tmp.check_layout(oss);
1575 os << subst(t.asInput(), "\n", oss.str());
1577 // The scrap chunk is ended by an @ at the beginning of a line.
1578 // After the @ the line may contain a comment and/or
1579 // whitespace, but nothing else.
1580 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1581 (p.next_token().cat() == catSpace ||
1582 p.next_token().cat() == catNewline ||
1583 p.next_token().cat() == catComment)) {
1584 while (p.good() && p.next_token().cat() == catSpace)
1585 os << p.get_token().asInput();
1586 if (p.next_token().cat() == catComment)
1587 // The comment includes a final '\n'
1588 os << p.get_token().asInput();
1590 if (p.next_token().cat() == catNewline)
1597 newcontext.check_end_layout(os);
1601 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1602 bool is_macro(Parser & p)
1604 Token first = p.curr_token();
1605 if (first.cat() != catEscape || !p.good())
1607 if (first.cs() == "def")
1609 if (first.cs() != "global" && first.cs() != "long")
1611 Token second = p.get_token();
1613 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1614 second.cat() == catNewline || second.cat() == catComment)) {
1615 second = p.get_token();
1618 bool secondvalid = second.cat() == catEscape;
1620 bool thirdvalid = false;
1621 if (p.good() && first.cs() == "global" && secondvalid &&
1622 second.cs() == "long") {
1623 third = p.get_token();
1625 while (p.good() && !p.isParagraph() &&
1626 (third.cat() == catSpace ||
1627 third.cat() == catNewline ||
1628 third.cat() == catComment)) {
1629 third = p.get_token();
1632 thirdvalid = third.cat() == catEscape;
1634 for (int i = 0; i < pos; ++i)
1639 return (first.cs() == "global" || first.cs() == "long") &&
1640 second.cs() == "def";
1641 return first.cs() == "global" && second.cs() == "long" &&
1642 third.cs() == "def";
1646 /// Parse a macro definition (assumes that is_macro() returned true)
1647 void parse_macro(Parser & p, ostream & os, Context & context)
1649 context.check_layout(os);
1650 Token first = p.curr_token();
1653 string command = first.asInput();
1654 if (first.cs() != "def") {
1656 eat_whitespace(p, os, context, false);
1657 second = p.curr_token();
1658 command += second.asInput();
1659 if (second.cs() != "def") {
1661 eat_whitespace(p, os, context, false);
1662 third = p.curr_token();
1663 command += third.asInput();
1666 eat_whitespace(p, os, context, false);
1667 string const name = p.get_token().cs();
1668 eat_whitespace(p, os, context, false);
1674 while (p.next_token().cat() != catBegin) {
1675 if (p.next_token().cat() == catParameter) {
1680 // followed by number?
1681 if (p.next_token().cat() == catOther) {
1682 char c = p.getChar();
1684 // number = current arity + 1?
1685 if (c == arity + '0' + 1)
1690 paramtext += p.get_token().cs();
1692 paramtext += p.get_token().cs();
1697 // only output simple (i.e. compatible) macro as FormulaMacros
1698 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1700 context.check_layout(os);
1701 begin_inset(os, "FormulaMacro");
1702 os << "\n\\def" << ert;
1705 handle_ert(os, command + ert, context);
1708 } // anonymous namespace
1711 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1714 Layout const * newlayout = 0;
1715 InsetLayout const * newinsetlayout = 0;
1716 // Store the latest bibliographystyle and nocite{*} option
1717 // (needed for bibtex inset)
1719 string bibliographystyle;
1720 bool const use_natbib = preamble.isPackageUsed("natbib");
1721 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1723 bool title_layout_found = false;
1725 Token const & t = p.get_token();
1728 debugToken(cerr, t, flags);
1731 if (flags & FLAG_ITEM) {
1732 if (t.cat() == catSpace)
1735 flags &= ~FLAG_ITEM;
1736 if (t.cat() == catBegin) {
1737 // skip the brace and collect everything to the next matching
1739 flags |= FLAG_BRACE_LAST;
1743 // handle only this single token, leave the loop if done
1744 flags |= FLAG_LEAVE;
1747 if (t.cat() != catEscape && t.character() == ']' &&
1748 (flags & FLAG_BRACK_LAST))
1750 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1753 // If there is anything between \end{env} and \begin{env} we
1754 // don't need to output a separator.
1755 if (t.cat() != catSpace && t.cat() != catNewline &&
1756 t.asInput() != "\\begin")
1762 if (t.cat() == catMath) {
1763 // we are inside some text mode thingy, so opening new math is allowed
1764 context.check_layout(os);
1765 begin_inset(os, "Formula ");
1766 Token const & n = p.get_token();
1767 if (n.cat() == catMath && outer) {
1768 // TeX's $$...$$ syntax for displayed math
1770 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1772 p.get_token(); // skip the second '$' token
1774 // simple $...$ stuff
1777 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1783 else if (t.cat() == catSuper || t.cat() == catSub)
1784 cerr << "catcode " << t << " illegal in text mode\n";
1786 // Basic support for english quotes. This should be
1787 // extended to other quotes, but is not so easy (a
1788 // left english quote is the same as a right german
1790 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1791 context.check_layout(os);
1792 begin_inset(os, "Quotes ");
1798 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1799 context.check_layout(os);
1800 begin_inset(os, "Quotes ");
1807 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1808 context.check_layout(os);
1809 begin_inset(os, "Quotes ");
1816 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1817 context.check_layout(os);
1818 begin_inset(os, "Quotes ");
1825 else if (t.asInput() == "<"
1826 && p.next_token().asInput() == "<" && noweb_mode) {
1828 parse_noweb(p, os, context);
1831 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1832 check_space(p, os, context);
1834 else if (t.character() == '[' && noweb_mode &&
1835 p.next_token().character() == '[') {
1836 // These can contain underscores
1838 string const s = p.getFullOpt() + ']';
1839 if (p.next_token().character() == ']')
1842 cerr << "Warning: Inserting missing ']' in '"
1843 << s << "'." << endl;
1844 handle_ert(os, s, context);
1847 else if (t.cat() == catLetter) {
1848 context.check_layout(os);
1849 // Workaround for bug 4752.
1850 // FIXME: This whole code block needs to be removed
1851 // when the bug is fixed and tex2lyx produces
1852 // the updated file format.
1853 // The replacement algorithm in LyX is so stupid that
1854 // it even translates a phrase if it is part of a word.
1855 bool handled = false;
1856 for (int const * l = known_phrase_lengths; *l; ++l) {
1857 string phrase = t.cs();
1858 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1859 phrase += p.get_token().cs();
1860 if (is_known(phrase, known_coded_phrases)) {
1861 handle_ert(os, phrase, context);
1865 for (size_t i = 1; i < phrase.length(); ++i)
1873 else if (t.cat() == catOther ||
1874 t.cat() == catAlign ||
1875 t.cat() == catParameter) {
1876 // This translates "&" to "\\&" which may be wrong...
1877 context.check_layout(os);
1881 else if (p.isParagraph()) {
1882 if (context.new_layout_allowed)
1883 context.new_paragraph(os);
1885 handle_ert(os, "\\par ", context);
1886 eat_whitespace(p, os, context, true);
1889 else if (t.cat() == catActive) {
1890 context.check_layout(os);
1891 if (t.character() == '~') {
1892 if (context.layout->free_spacing)
1895 begin_inset(os, "space ~\n");
1902 else if (t.cat() == catBegin &&
1903 p.next_token().cat() == catEnd) {
1905 Token const prev = p.prev_token();
1907 if (p.next_token().character() == '`' ||
1908 (prev.character() == '-' &&
1909 p.next_token().character() == '-'))
1910 ; // ignore it in {}`` or -{}-
1912 handle_ert(os, "{}", context);
1916 else if (t.cat() == catBegin) {
1917 context.check_layout(os);
1918 // special handling of font attribute changes
1919 Token const prev = p.prev_token();
1920 Token const next = p.next_token();
1921 TeXFont const oldFont = context.font;
1922 if (next.character() == '[' ||
1923 next.character() == ']' ||
1924 next.character() == '*') {
1926 if (p.next_token().cat() == catEnd) {
1931 handle_ert(os, "{", context);
1932 parse_text_snippet(p, os,
1935 handle_ert(os, "}", context);
1937 } else if (! context.new_layout_allowed) {
1938 handle_ert(os, "{", context);
1939 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1941 handle_ert(os, "}", context);
1942 } else if (is_known(next.cs(), known_sizes)) {
1943 // next will change the size, so we must
1945 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1947 if (!context.atParagraphStart())
1949 << context.font.size << "\n";
1950 } else if (is_known(next.cs(), known_font_families)) {
1951 // next will change the font family, so we
1952 // must reset it here
1953 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1955 if (!context.atParagraphStart())
1957 << context.font.family << "\n";
1958 } else if (is_known(next.cs(), known_font_series)) {
1959 // next will change the font series, so we
1960 // must reset it here
1961 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1963 if (!context.atParagraphStart())
1965 << context.font.series << "\n";
1966 } else if (is_known(next.cs(), known_font_shapes)) {
1967 // next will change the font shape, so we
1968 // must reset it here
1969 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1971 if (!context.atParagraphStart())
1973 << context.font.shape << "\n";
1974 } else if (is_known(next.cs(), known_old_font_families) ||
1975 is_known(next.cs(), known_old_font_series) ||
1976 is_known(next.cs(), known_old_font_shapes)) {
1977 // next will change the font family, series
1978 // and shape, so we must reset it here
1979 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1981 if (!context.atParagraphStart())
1983 << context.font.family
1985 << context.font.series
1987 << context.font.shape << "\n";
1989 handle_ert(os, "{", context);
1990 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1992 handle_ert(os, "}", context);
1996 else if (t.cat() == catEnd) {
1997 if (flags & FLAG_BRACE_LAST) {
2000 cerr << "stray '}' in text\n";
2001 handle_ert(os, "}", context);
2004 else if (t.cat() == catComment)
2005 parse_comment(p, os, t, context);
2008 // control sequences
2011 else if (t.cs() == "(") {
2012 context.check_layout(os);
2013 begin_inset(os, "Formula");
2015 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2020 else if (t.cs() == "[") {
2021 context.check_layout(os);
2022 begin_inset(os, "Formula");
2024 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2029 else if (t.cs() == "begin")
2030 parse_environment(p, os, outer, last_env,
2031 title_layout_found, context);
2033 else if (t.cs() == "end") {
2034 if (flags & FLAG_END) {
2035 // eat environment name
2036 string const name = p.getArg('{', '}');
2037 if (name != active_environment())
2038 cerr << "\\end{" + name + "} does not match \\begin{"
2039 + active_environment() + "}\n";
2042 p.error("found 'end' unexpectedly");
2045 else if (t.cs() == "item") {
2048 bool optarg = false;
2049 if (p.next_token().cat() != catEscape &&
2050 p.next_token().character() == '[') {
2051 p.get_token(); // eat '['
2052 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2057 context.check_layout(os);
2058 if (context.has_item) {
2059 // An item in an unknown list-like environment
2060 // FIXME: Do this in check_layout()!
2061 context.has_item = false;
2063 handle_ert(os, "\\item", context);
2065 handle_ert(os, "\\item ", context);
2068 if (context.layout->labeltype != LABEL_MANUAL) {
2069 // LyX does not support \item[\mybullet]
2070 // in itemize environments
2071 handle_ert(os, "[", context);
2073 handle_ert(os, "]", context);
2074 } else if (!s.empty()) {
2075 // The space is needed to separate the
2076 // item from the rest of the sentence.
2078 eat_whitespace(p, os, context, false);
2083 else if (t.cs() == "bibitem") {
2085 context.check_layout(os);
2086 string label = convert_command_inset_arg(p.getArg('[', ']'));
2087 string key = convert_command_inset_arg(p.verbatim_item());
2088 if (contains(label, '\\') || contains(key, '\\')) {
2089 // LyX can't handle LaTeX commands in labels or keys
2090 handle_ert(os, t.asInput() + '[' + label +
2091 "]{" + p.verbatim_item() + '}',
2094 begin_command_inset(os, "bibitem", "bibitem");
2095 os << "label \"" << label << "\"\n"
2096 "key \"" << key << "\"\n";
2101 else if (is_macro(p))
2102 parse_macro(p, os, context);
2104 else if (t.cs() == "noindent") {
2106 context.add_par_extra_stuff("\\noindent\n");
2109 else if (t.cs() == "appendix") {
2110 context.add_par_extra_stuff("\\start_of_appendix\n");
2111 // We need to start a new paragraph. Otherwise the
2112 // appendix in 'bla\appendix\chapter{' would start
2114 context.new_paragraph(os);
2115 // We need to make sure that the paragraph is
2116 // generated even if it is empty. Otherwise the
2117 // appendix in '\par\appendix\par\chapter{' would
2119 context.check_layout(os);
2120 // FIXME: This is a hack to prevent paragraph
2121 // deletion if it is empty. Handle this better!
2123 "%dummy comment inserted by tex2lyx to "
2124 "ensure that this paragraph is not empty",
2126 // Both measures above may generate an additional
2127 // empty paragraph, but that does not hurt, because
2128 // whitespace does not matter here.
2129 eat_whitespace(p, os, context, true);
2132 // Must catch empty dates before findLayout is called below
2133 else if (t.cs() == "date") {
2134 string const date = p.verbatim_item();
2136 preamble.suppressDate(true);
2138 preamble.suppressDate(false);
2139 if (context.new_layout_allowed &&
2140 (newlayout = findLayout(context.textclass,
2143 output_command_layout(os, p, outer,
2144 context, newlayout);
2146 if (!title_layout_found)
2147 title_layout_found = newlayout->intitle;
2149 handle_ert(os, "\\date{" + date + '}',
2154 // Starred section headings
2155 // Must attempt to parse "Section*" before "Section".
2156 else if ((p.next_token().asInput() == "*") &&
2157 context.new_layout_allowed &&
2158 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2161 output_command_layout(os, p, outer, context, newlayout);
2163 if (!title_layout_found)
2164 title_layout_found = newlayout->intitle;
2167 // Section headings and the like
2168 else if (context.new_layout_allowed &&
2169 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2171 output_command_layout(os, p, outer, context, newlayout);
2173 if (!title_layout_found)
2174 title_layout_found = newlayout->intitle;
2177 else if (t.cs() == "caption") {
2179 context.check_layout(os);
2181 begin_inset(os, "Caption\n");
2182 Context newcontext(true, context.textclass);
2183 newcontext.font = context.font;
2184 newcontext.check_layout(os);
2185 if (p.next_token().cat() != catEscape &&
2186 p.next_token().character() == '[') {
2187 p.get_token(); // eat '['
2188 begin_inset(os, "Argument\n");
2189 os << "status collapsed\n";
2190 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2192 eat_whitespace(p, os, context, false);
2194 parse_text(p, os, FLAG_ITEM, outer, context);
2195 context.check_end_layout(os);
2196 // We don't need really a new paragraph, but
2197 // we must make sure that the next item gets a \begin_layout.
2198 context.new_paragraph(os);
2201 newcontext.check_end_layout(os);
2204 else if (t.cs() == "subfloat") {
2205 // the syntax is \subfloat[caption]{content}
2206 // if it is a table of figure depends on the surrounding float
2207 bool has_caption = false;
2209 // do nothing if there is no outer float
2210 if (!float_type.empty()) {
2211 context.check_layout(os);
2213 begin_inset(os, "Float " + float_type + "\n");
2215 << "\nsideways false"
2216 << "\nstatus collapsed\n\n";
2219 if (p.next_token().cat() != catEscape &&
2220 p.next_token().character() == '[') {
2221 p.get_token(); // eat '['
2222 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2226 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2227 // the caption comes always as the last
2229 // we must make sure that the caption gets a \begin_layout
2230 os << "\n\\begin_layout Plain Layout";
2232 begin_inset(os, "Caption\n");
2233 Context newcontext(true, context.textclass);
2234 newcontext.font = context.font;
2235 newcontext.check_layout(os);
2236 os << caption << "\n";
2237 newcontext.check_end_layout(os);
2238 // We don't need really a new paragraph, but
2239 // we must make sure that the next item gets a \begin_layout.
2240 //newcontext.new_paragraph(os);
2244 // We don't need really a new paragraph, but
2245 // we must make sure that the next item gets a \begin_layout.
2247 context.new_paragraph(os);
2250 context.check_end_layout(os);
2251 // close the layout we opened
2253 os << "\n\\end_layout\n";
2255 // if the float type is not supported or there is no surrounding float
2258 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2259 handle_ert(os, t.asInput() + '[' + opt_arg +
2260 "]{" + p.verbatim_item() + '}', context);
2262 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2266 else if (t.cs() == "includegraphics") {
2267 bool const clip = p.next_token().asInput() == "*";
2270 string const arg = p.getArg('[', ']');
2271 map<string, string> opts;
2272 vector<string> keys;
2273 split_map(arg, opts, keys);
2275 opts["clip"] = string();
2276 string name = normalize_filename(p.verbatim_item());
2278 string const path = getMasterFilePath();
2279 // We want to preserve relative / absolute filenames,
2280 // therefore path is only used for testing
2281 if (!makeAbsPath(name, path).exists()) {
2282 // The file extension is probably missing.
2283 // Now try to find it out.
2284 string const dvips_name =
2285 find_file(name, path,
2286 known_dvips_graphics_formats);
2287 string const pdftex_name =
2288 find_file(name, path,
2289 known_pdftex_graphics_formats);
2290 if (!dvips_name.empty()) {
2291 if (!pdftex_name.empty()) {
2292 cerr << "This file contains the "
2294 "\"\\includegraphics{"
2296 "However, files\n\""
2297 << dvips_name << "\" and\n\""
2298 << pdftex_name << "\"\n"
2299 "both exist, so I had to make a "
2300 "choice and took the first one.\n"
2301 "Please move the unwanted one "
2302 "someplace else and try again\n"
2303 "if my choice was wrong."
2307 } else if (!pdftex_name.empty()) {
2313 if (makeAbsPath(name, path).exists())
2314 fix_relative_filename(name);
2316 cerr << "Warning: Could not find graphics file '"
2317 << name << "'." << endl;
2319 context.check_layout(os);
2320 begin_inset(os, "Graphics ");
2321 os << "\n\tfilename " << name << '\n';
2322 if (opts.find("width") != opts.end())
2324 << translate_len(opts["width"]) << '\n';
2325 if (opts.find("height") != opts.end())
2327 << translate_len(opts["height"]) << '\n';
2328 if (opts.find("scale") != opts.end()) {
2329 istringstream iss(opts["scale"]);
2333 os << "\tscale " << val << '\n';
2335 if (opts.find("angle") != opts.end()) {
2336 os << "\trotateAngle "
2337 << opts["angle"] << '\n';
2338 vector<string>::const_iterator a =
2339 find(keys.begin(), keys.end(), "angle");
2340 vector<string>::const_iterator s =
2341 find(keys.begin(), keys.end(), "width");
2342 if (s == keys.end())
2343 s = find(keys.begin(), keys.end(), "height");
2344 if (s == keys.end())
2345 s = find(keys.begin(), keys.end(), "scale");
2346 if (s != keys.end() && distance(s, a) > 0)
2347 os << "\tscaleBeforeRotation\n";
2349 if (opts.find("origin") != opts.end()) {
2351 string const opt = opts["origin"];
2352 if (opt.find('l') != string::npos) ss << "left";
2353 if (opt.find('r') != string::npos) ss << "right";
2354 if (opt.find('c') != string::npos) ss << "center";
2355 if (opt.find('t') != string::npos) ss << "Top";
2356 if (opt.find('b') != string::npos) ss << "Bottom";
2357 if (opt.find('B') != string::npos) ss << "Baseline";
2358 if (!ss.str().empty())
2359 os << "\trotateOrigin " << ss.str() << '\n';
2361 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2363 if (opts.find("keepaspectratio") != opts.end())
2364 os << "\tkeepAspectRatio\n";
2365 if (opts.find("clip") != opts.end())
2367 if (opts.find("draft") != opts.end())
2369 if (opts.find("bb") != opts.end())
2370 os << "\tBoundingBox "
2371 << opts["bb"] << '\n';
2372 int numberOfbbOptions = 0;
2373 if (opts.find("bbllx") != opts.end())
2374 numberOfbbOptions++;
2375 if (opts.find("bblly") != opts.end())
2376 numberOfbbOptions++;
2377 if (opts.find("bburx") != opts.end())
2378 numberOfbbOptions++;
2379 if (opts.find("bbury") != opts.end())
2380 numberOfbbOptions++;
2381 if (numberOfbbOptions == 4)
2382 os << "\tBoundingBox "
2383 << opts["bbllx"] << " " << opts["bblly"] << " "
2384 << opts["bburx"] << " " << opts["bbury"] << '\n';
2385 else if (numberOfbbOptions > 0)
2386 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2387 numberOfbbOptions = 0;
2388 if (opts.find("natwidth") != opts.end())
2389 numberOfbbOptions++;
2390 if (opts.find("natheight") != opts.end())
2391 numberOfbbOptions++;
2392 if (numberOfbbOptions == 2)
2393 os << "\tBoundingBox 0bp 0bp "
2394 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2395 else if (numberOfbbOptions > 0)
2396 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2397 ostringstream special;
2398 if (opts.find("hiresbb") != opts.end())
2399 special << "hiresbb,";
2400 if (opts.find("trim") != opts.end())
2402 if (opts.find("viewport") != opts.end())
2403 special << "viewport=" << opts["viewport"] << ',';
2404 if (opts.find("totalheight") != opts.end())
2405 special << "totalheight=" << opts["totalheight"] << ',';
2406 if (opts.find("type") != opts.end())
2407 special << "type=" << opts["type"] << ',';
2408 if (opts.find("ext") != opts.end())
2409 special << "ext=" << opts["ext"] << ',';
2410 if (opts.find("read") != opts.end())
2411 special << "read=" << opts["read"] << ',';
2412 if (opts.find("command") != opts.end())
2413 special << "command=" << opts["command"] << ',';
2414 string s_special = special.str();
2415 if (!s_special.empty()) {
2416 // We had special arguments. Remove the trailing ','.
2417 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2419 // TODO: Handle the unknown settings better.
2420 // Warn about invalid options.
2421 // Check whether some option was given twice.
2425 else if (t.cs() == "footnote" ||
2426 (t.cs() == "thanks" && context.layout->intitle)) {
2428 context.check_layout(os);
2429 begin_inset(os, "Foot\n");
2430 os << "status collapsed\n\n";
2431 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2435 else if (t.cs() == "marginpar") {
2437 context.check_layout(os);
2438 begin_inset(os, "Marginal\n");
2439 os << "status collapsed\n\n";
2440 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2444 else if (t.cs() == "ensuremath") {
2446 context.check_layout(os);
2447 string const s = p.verbatim_item();
2448 //FIXME: this never triggers in UTF8
2449 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2452 handle_ert(os, "\\ensuremath{" + s + "}",
2456 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2457 if (title_layout_found) {
2459 skip_spaces_braces(p);
2461 handle_ert(os, t.asInput(), context);
2464 else if (t.cs() == "tableofcontents") {
2465 context.check_layout(os);
2466 begin_command_inset(os, "toc", "tableofcontents");
2468 skip_spaces_braces(p);
2471 else if (t.cs() == "listoffigures") {
2472 context.check_layout(os);
2473 begin_inset(os, "FloatList figure\n");
2475 skip_spaces_braces(p);
2478 else if (t.cs() == "listoftables") {
2479 context.check_layout(os);
2480 begin_inset(os, "FloatList table\n");
2482 skip_spaces_braces(p);
2485 else if (t.cs() == "listof") {
2486 p.skip_spaces(true);
2487 string const name = p.get_token().cs();
2488 if (context.textclass.floats().typeExist(name)) {
2489 context.check_layout(os);
2490 begin_inset(os, "FloatList ");
2493 p.get_token(); // swallow second arg
2495 handle_ert(os, "\\listof{" + name + "}", context);
2498 else if (t.cs() == "textrm")
2499 parse_text_attributes(p, os, FLAG_ITEM, outer,
2500 context, "\\family",
2501 context.font.family, "roman");
2503 else if (t.cs() == "textsf")
2504 parse_text_attributes(p, os, FLAG_ITEM, outer,
2505 context, "\\family",
2506 context.font.family, "sans");
2508 else if (t.cs() == "texttt")
2509 parse_text_attributes(p, os, FLAG_ITEM, outer,
2510 context, "\\family",
2511 context.font.family, "typewriter");
2513 else if (t.cs() == "textmd")
2514 parse_text_attributes(p, os, FLAG_ITEM, outer,
2515 context, "\\series",
2516 context.font.series, "medium");
2518 else if (t.cs() == "textbf")
2519 parse_text_attributes(p, os, FLAG_ITEM, outer,
2520 context, "\\series",
2521 context.font.series, "bold");
2523 else if (t.cs() == "textup")
2524 parse_text_attributes(p, os, FLAG_ITEM, outer,
2526 context.font.shape, "up");
2528 else if (t.cs() == "textit")
2529 parse_text_attributes(p, os, FLAG_ITEM, outer,
2531 context.font.shape, "italic");
2533 else if (t.cs() == "textsl")
2534 parse_text_attributes(p, os, FLAG_ITEM, outer,
2536 context.font.shape, "slanted");
2538 else if (t.cs() == "textsc")
2539 parse_text_attributes(p, os, FLAG_ITEM, outer,
2541 context.font.shape, "smallcaps");
2543 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2544 context.check_layout(os);
2545 TeXFont oldFont = context.font;
2546 context.font.init();
2547 context.font.size = oldFont.size;
2548 os << "\n\\family " << context.font.family << "\n";
2549 os << "\n\\series " << context.font.series << "\n";
2550 os << "\n\\shape " << context.font.shape << "\n";
2551 if (t.cs() == "textnormal") {
2552 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2553 output_font_change(os, context.font, oldFont);
2554 context.font = oldFont;
2556 eat_whitespace(p, os, context, false);
2559 else if (t.cs() == "textcolor") {
2560 // scheme is \textcolor{color name}{text}
2561 string const color = p.verbatim_item();
2562 // we only support the predefined colors of the color package
2563 if (color == "black" || color == "blue" || color == "cyan"
2564 || color == "green" || color == "magenta" || color == "red"
2565 || color == "white" || color == "yellow") {
2566 context.check_layout(os);
2567 os << "\n\\color " << color << "\n";
2568 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2569 context.check_layout(os);
2570 os << "\n\\color inherit\n";
2572 // for custom defined colors
2573 handle_ert(os, t.asInput() + "{" + color + "}", context);
2576 else if (t.cs() == "underbar" || t.cs() == "uline") {
2577 // \underbar is not 100% correct (LyX outputs \uline
2578 // of ulem.sty). The difference is that \ulem allows
2579 // line breaks, and \underbar does not.
2580 // Do NOT handle \underline.
2581 // \underbar cuts through y, g, q, p etc.,
2582 // \underline does not.
2583 context.check_layout(os);
2584 os << "\n\\bar under\n";
2585 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2586 context.check_layout(os);
2587 os << "\n\\bar default\n";
2590 else if (t.cs() == "sout") {
2591 context.check_layout(os);
2592 os << "\n\\strikeout on\n";
2593 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2594 context.check_layout(os);
2595 os << "\n\\strikeout default\n";
2598 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2599 t.cs() == "emph" || t.cs() == "noun") {
2600 context.check_layout(os);
2601 os << "\n\\" << t.cs() << " on\n";
2602 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2603 context.check_layout(os);
2604 os << "\n\\" << t.cs() << " default\n";
2607 // FIXME, the inset layout should be plain, not standard, see bug #7846
2608 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2609 t.cs() == "vphantom") {
2610 context.check_layout(os);
2611 if (t.cs() == "phantom")
2612 begin_inset(os, "Phantom Phantom\n");
2613 if (t.cs() == "hphantom")
2614 begin_inset(os, "Phantom HPhantom\n");
2615 if (t.cs() == "vphantom")
2616 begin_inset(os, "Phantom VPhantom\n");
2617 os << "status open\n";
2618 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2622 else if (t.cs() == "href") {
2623 context.check_layout(os);
2624 string target = p.getArg('{', '}');
2625 string name = p.getArg('{', '}');
2627 size_t i = target.find(':');
2628 if (i != string::npos) {
2629 type = target.substr(0, i + 1);
2630 if (type == "mailto:" || type == "file:")
2631 target = target.substr(i + 1);
2632 // handle the case that name is equal to target, except of "http://"
2633 else if (target.substr(i + 3) == name && type == "http:")
2636 begin_command_inset(os, "href", "href");
2638 os << "name \"" << name << "\"\n";
2639 os << "target \"" << target << "\"\n";
2640 if (type == "mailto:" || type == "file:")
2641 os << "type \"" << type << "\"\n";
2643 skip_spaces_braces(p);
2646 else if (t.cs() == "lyxline") {
2647 // swallow size argument (it is not used anyway)
2649 if (!context.atParagraphStart()) {
2650 // so our line is in the middle of a paragraph
2651 // we need to add a new line, lest this line
2652 // follow the other content on that line and
2653 // run off the side of the page
2654 // FIXME: This may create an empty paragraph,
2655 // but without that it would not be
2656 // possible to set noindent below.
2657 // Fortunately LaTeX does not care
2658 // about the empty paragraph.
2659 context.new_paragraph(os);
2661 if (preamble.indentParagraphs()) {
2662 // we need to unindent, lest the line be too long
2663 context.add_par_extra_stuff("\\noindent\n");
2665 context.check_layout(os);
2666 begin_command_inset(os, "line", "rule");
2667 os << "offset \"0.5ex\"\n"
2668 "width \"100line%\"\n"
2673 else if (t.cs() == "rule") {
2674 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2675 string const width = p.getArg('{', '}');
2676 string const thickness = p.getArg('{', '}');
2677 context.check_layout(os);
2678 begin_command_inset(os, "line", "rule");
2679 if (!offset.empty())
2680 os << "offset \"" << translate_len(offset) << "\"\n";
2681 os << "width \"" << translate_len(width) << "\"\n"
2682 "height \"" << translate_len(thickness) << "\"\n";
2686 else if (is_known(t.cs(), known_phrases) ||
2687 (t.cs() == "protect" &&
2688 p.next_token().cat() == catEscape &&
2689 is_known(p.next_token().cs(), known_phrases))) {
2690 // LyX sometimes puts a \protect in front, so we have to ignore it
2691 // FIXME: This needs to be changed when bug 4752 is fixed.
2692 char const * const * where = is_known(
2693 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2695 context.check_layout(os);
2696 os << known_coded_phrases[where - known_phrases];
2697 skip_spaces_braces(p);
2700 else if (is_known(t.cs(), known_ref_commands)) {
2701 string const opt = p.getOpt();
2703 context.check_layout(os);
2704 char const * const * where = is_known(t.cs(),
2705 known_ref_commands);
2706 begin_command_inset(os, "ref",
2707 known_coded_ref_commands[where - known_ref_commands]);
2708 os << "reference \""
2709 << convert_command_inset_arg(p.verbatim_item())
2713 // LyX does not support optional arguments of ref commands
2714 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2715 p.verbatim_item() + "}", context);
2719 else if (use_natbib &&
2720 is_known(t.cs(), known_natbib_commands) &&
2721 ((t.cs() != "citefullauthor" &&
2722 t.cs() != "citeyear" &&
2723 t.cs() != "citeyearpar") ||
2724 p.next_token().asInput() != "*")) {
2725 context.check_layout(os);
2726 string command = t.cs();
2727 if (p.next_token().asInput() == "*") {
2731 if (command == "citefullauthor")
2732 // alternative name for "\\citeauthor*"
2733 command = "citeauthor*";
2735 // text before the citation
2737 // text after the citation
2739 get_cite_arguments(p, true, before, after);
2741 if (command == "cite") {
2742 // \cite without optional argument means
2743 // \citet, \cite with at least one optional
2744 // argument means \citep.
2745 if (before.empty() && after.empty())
2750 if (before.empty() && after == "[]")
2751 // avoid \citet[]{a}
2753 else if (before == "[]" && after == "[]") {
2754 // avoid \citet[][]{a}
2758 // remove the brackets around after and before
2759 if (!after.empty()) {
2761 after.erase(after.length() - 1, 1);
2762 after = convert_command_inset_arg(after);
2764 if (!before.empty()) {
2766 before.erase(before.length() - 1, 1);
2767 before = convert_command_inset_arg(before);
2769 begin_command_inset(os, "citation", command);
2770 os << "after " << '"' << after << '"' << "\n";
2771 os << "before " << '"' << before << '"' << "\n";
2773 << convert_command_inset_arg(p.verbatim_item())
2778 else if (use_jurabib &&
2779 is_known(t.cs(), known_jurabib_commands) &&
2780 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2781 context.check_layout(os);
2782 string command = t.cs();
2783 if (p.next_token().asInput() == "*") {
2787 char argumentOrder = '\0';
2788 vector<string> const options =
2789 preamble.getPackageOptions("jurabib");
2790 if (find(options.begin(), options.end(),
2791 "natbiborder") != options.end())
2792 argumentOrder = 'n';
2793 else if (find(options.begin(), options.end(),
2794 "jurabiborder") != options.end())
2795 argumentOrder = 'j';
2797 // text before the citation
2799 // text after the citation
2801 get_cite_arguments(p, argumentOrder != 'j', before, after);
2803 string const citation = p.verbatim_item();
2804 if (!before.empty() && argumentOrder == '\0') {
2805 cerr << "Warning: Assuming argument order "
2806 "of jurabib version 0.6 for\n'"
2807 << command << before << after << '{'
2808 << citation << "}'.\n"
2809 "Add 'jurabiborder' to the jurabib "
2810 "package options if you used an\n"
2811 "earlier jurabib version." << endl;
2813 if (!after.empty()) {
2815 after.erase(after.length() - 1, 1);
2817 if (!before.empty()) {
2819 before.erase(before.length() - 1, 1);
2821 begin_command_inset(os, "citation", command);
2822 os << "after " << '"' << after << '"' << "\n";
2823 os << "before " << '"' << before << '"' << "\n";
2824 os << "key " << '"' << citation << '"' << "\n";
2828 else if (t.cs() == "cite"
2829 || t.cs() == "nocite") {
2830 context.check_layout(os);
2831 string after = convert_command_inset_arg(p.getArg('[', ']'));
2832 string key = convert_command_inset_arg(p.verbatim_item());
2833 // store the case that it is "\nocite{*}" to use it later for
2836 begin_command_inset(os, "citation", t.cs());
2837 os << "after " << '"' << after << '"' << "\n";
2838 os << "key " << '"' << key << '"' << "\n";
2840 } else if (t.cs() == "nocite")
2844 else if (t.cs() == "index") {
2845 context.check_layout(os);
2846 begin_inset(os, "Index idx\n");
2847 os << "status collapsed\n";
2848 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2852 else if (t.cs() == "nomenclature") {
2853 context.check_layout(os);
2854 begin_command_inset(os, "nomenclature", "nomenclature");
2855 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2856 if (!prefix.empty())
2857 os << "prefix " << '"' << prefix << '"' << "\n";
2858 os << "symbol " << '"'
2859 << convert_command_inset_arg(p.verbatim_item());
2860 os << "\"\ndescription \""
2861 << convert_command_inset_arg(p.verbatim_item())
2866 else if (t.cs() == "label") {
2867 context.check_layout(os);
2868 begin_command_inset(os, "label", "label");
2870 << convert_command_inset_arg(p.verbatim_item())
2875 else if (t.cs() == "printindex") {
2876 context.check_layout(os);
2877 begin_command_inset(os, "index_print", "printindex");
2878 os << "type \"idx\"\n";
2880 skip_spaces_braces(p);
2883 else if (t.cs() == "printnomenclature") {
2885 string width_type = "";
2886 context.check_layout(os);
2887 begin_command_inset(os, "nomencl_print", "printnomenclature");
2888 // case of a custom width
2890 width = p.getArg('[', ']');
2891 width = translate_len(width);
2892 width_type = "custom";
2894 // case of no custom width
2895 // the case of no custom width but the width set
2896 // via \settowidth{\nomlabelwidth}{***} cannot be supported
2897 // because the user could have set anything, not only the width
2898 // of the longest label (which would be width_type = "auto")
2899 string label = convert_command_inset_arg(p.getArg('{', '}'));
2900 if (label.empty() && width_type.empty())
2901 width_type = "none";
2902 os << "set_width \"" << width_type << "\"\n";
2903 if (width_type == "custom")
2904 os << "width \"" << width << '\"';
2906 skip_spaces_braces(p);
2909 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2910 context.check_layout(os);
2911 begin_inset(os, "script ");
2912 os << t.cs().substr(4) << '\n';
2913 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2917 else if (is_known(t.cs(), known_quotes)) {
2918 char const * const * where = is_known(t.cs(), known_quotes);
2919 context.check_layout(os);
2920 begin_inset(os, "Quotes ");
2921 os << known_coded_quotes[where - known_quotes];
2923 // LyX adds {} after the quote, so we have to eat
2924 // spaces here if there are any before a possible
2926 eat_whitespace(p, os, context, false);
2930 else if (is_known(t.cs(), known_sizes) &&
2931 context.new_layout_allowed) {
2932 char const * const * where = is_known(t.cs(), known_sizes);
2933 context.check_layout(os);
2934 TeXFont const oldFont = context.font;
2935 context.font.size = known_coded_sizes[where - known_sizes];
2936 output_font_change(os, oldFont, context.font);
2937 eat_whitespace(p, os, context, false);
2940 else if (is_known(t.cs(), known_font_families) &&
2941 context.new_layout_allowed) {
2942 char const * const * where =
2943 is_known(t.cs(), known_font_families);
2944 context.check_layout(os);
2945 TeXFont const oldFont = context.font;
2946 context.font.family =
2947 known_coded_font_families[where - known_font_families];
2948 output_font_change(os, oldFont, context.font);
2949 eat_whitespace(p, os, context, false);
2952 else if (is_known(t.cs(), known_font_series) &&
2953 context.new_layout_allowed) {
2954 char const * const * where =
2955 is_known(t.cs(), known_font_series);
2956 context.check_layout(os);
2957 TeXFont const oldFont = context.font;
2958 context.font.series =
2959 known_coded_font_series[where - known_font_series];
2960 output_font_change(os, oldFont, context.font);
2961 eat_whitespace(p, os, context, false);
2964 else if (is_known(t.cs(), known_font_shapes) &&
2965 context.new_layout_allowed) {
2966 char const * const * where =
2967 is_known(t.cs(), known_font_shapes);
2968 context.check_layout(os);
2969 TeXFont const oldFont = context.font;
2970 context.font.shape =
2971 known_coded_font_shapes[where - known_font_shapes];
2972 output_font_change(os, oldFont, context.font);
2973 eat_whitespace(p, os, context, false);
2975 else if (is_known(t.cs(), known_old_font_families) &&
2976 context.new_layout_allowed) {
2977 char const * const * where =
2978 is_known(t.cs(), known_old_font_families);
2979 context.check_layout(os);
2980 TeXFont const oldFont = context.font;
2981 context.font.init();
2982 context.font.size = oldFont.size;
2983 context.font.family =
2984 known_coded_font_families[where - known_old_font_families];
2985 output_font_change(os, oldFont, context.font);
2986 eat_whitespace(p, os, context, false);
2989 else if (is_known(t.cs(), known_old_font_series) &&
2990 context.new_layout_allowed) {
2991 char const * const * where =
2992 is_known(t.cs(), known_old_font_series);
2993 context.check_layout(os);
2994 TeXFont const oldFont = context.font;
2995 context.font.init();
2996 context.font.size = oldFont.size;
2997 context.font.series =
2998 known_coded_font_series[where - known_old_font_series];
2999 output_font_change(os, oldFont, context.font);
3000 eat_whitespace(p, os, context, false);
3003 else if (is_known(t.cs(), known_old_font_shapes) &&
3004 context.new_layout_allowed) {
3005 char const * const * where =
3006 is_known(t.cs(), known_old_font_shapes);
3007 context.check_layout(os);
3008 TeXFont const oldFont = context.font;
3009 context.font.init();
3010 context.font.size = oldFont.size;
3011 context.font.shape =
3012 known_coded_font_shapes[where - known_old_font_shapes];
3013 output_font_change(os, oldFont, context.font);
3014 eat_whitespace(p, os, context, false);
3017 else if (t.cs() == "selectlanguage") {
3018 context.check_layout(os);
3019 // save the language for the case that a
3020 // \foreignlanguage is used
3022 context.font.language = babel2lyx(p.verbatim_item());
3023 os << "\n\\lang " << context.font.language << "\n";
3026 else if (t.cs() == "foreignlanguage") {
3027 string const lang = babel2lyx(p.verbatim_item());
3028 parse_text_attributes(p, os, FLAG_ITEM, outer,
3030 context.font.language, lang);
3033 else if (t.cs() == "inputencoding") {
3034 // nothing to write here
3035 string const enc = subst(p.verbatim_item(), "\n", " ");
3039 else if (t.cs() == "ldots") {
3040 context.check_layout(os);
3041 os << "\\SpecialChar \\ldots{}\n";
3042 skip_spaces_braces(p);
3045 else if (t.cs() == "lyxarrow") {
3046 context.check_layout(os);
3047 os << "\\SpecialChar \\menuseparator\n";
3048 skip_spaces_braces(p);
3051 else if (t.cs() == "textcompwordmark") {
3052 context.check_layout(os);
3053 os << "\\SpecialChar \\textcompwordmark{}\n";
3054 skip_spaces_braces(p);
3057 else if (t.cs() == "slash") {
3058 context.check_layout(os);
3059 os << "\\SpecialChar \\slash{}\n";
3060 skip_spaces_braces(p);
3063 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3064 context.check_layout(os);
3065 os << "\\SpecialChar \\nobreakdash-\n";
3069 else if (t.cs() == "textquotedbl") {
3070 context.check_layout(os);
3075 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3076 context.check_layout(os);
3077 os << "\\SpecialChar \\@.\n";
3081 else if (t.cs() == "-") {
3082 context.check_layout(os);
3083 os << "\\SpecialChar \\-\n";
3086 else if (t.cs() == "textasciitilde") {
3087 context.check_layout(os);
3089 skip_spaces_braces(p);
3092 else if (t.cs() == "textasciicircum") {
3093 context.check_layout(os);
3095 skip_spaces_braces(p);
3098 else if (t.cs() == "textbackslash") {
3099 context.check_layout(os);
3100 os << "\n\\backslash\n";
3101 skip_spaces_braces(p);
3104 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3105 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3107 context.check_layout(os);
3111 else if (t.cs() == "char") {
3112 context.check_layout(os);
3113 if (p.next_token().character() == '`') {
3115 if (p.next_token().cs() == "\"") {
3120 handle_ert(os, "\\char`", context);
3123 handle_ert(os, "\\char", context);
3127 else if (t.cs() == "verb") {
3128 context.check_layout(os);
3129 char const delimiter = p.next_token().character();
3130 string const arg = p.getArg(delimiter, delimiter);
3132 oss << "\\verb" << delimiter << arg << delimiter;
3133 handle_ert(os, oss.str(), context);
3136 // Problem: \= creates a tabstop inside the tabbing environment
3137 // and else an accent. In the latter case we really would want
3138 // \={o} instead of \= o.
3139 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3140 handle_ert(os, t.asInput(), context);
3142 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3143 else if (t.cs().size() == 1
3144 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3145 context.check_layout(os);
3146 // try to see whether the string is in unicodesymbols
3148 string command = t.asInput() + "{"
3149 + trimSpaceAndEol(p.verbatim_item())
3151 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3154 cerr << "When parsing " << command
3155 << ", result is " << to_utf8(s)
3156 << "+" << to_utf8(rem) << endl;
3159 // we did not find a non-ert version
3160 handle_ert(os, command, context);
3163 else if (t.cs() == "\\") {
3164 context.check_layout(os);
3166 handle_ert(os, "\\\\" + p.getOpt(), context);
3167 else if (p.next_token().asInput() == "*") {
3169 // getOpt() eats the following space if there
3170 // is no optional argument, but that is OK
3171 // here since it has no effect in the output.
3172 handle_ert(os, "\\\\*" + p.getOpt(), context);
3175 begin_inset(os, "Newline newline");
3180 else if (t.cs() == "newline" ||
3181 (t.cs() == "linebreak" && !p.hasOpt())) {
3182 context.check_layout(os);
3183 begin_inset(os, "Newline ");
3186 skip_spaces_braces(p);
3189 else if (t.cs() == "input" || t.cs() == "include"
3190 || t.cs() == "verbatiminput") {
3191 string name = t.cs();
3192 if (t.cs() == "verbatiminput"
3193 && p.next_token().asInput() == "*")
3194 name += p.get_token().asInput();
3195 context.check_layout(os);
3196 string filename(normalize_filename(p.getArg('{', '}')));
3197 string const path = getMasterFilePath();
3198 // We want to preserve relative / absolute filenames,
3199 // therefore path is only used for testing
3200 if ((t.cs() == "include" || t.cs() == "input") &&
3201 !makeAbsPath(filename, path).exists()) {
3202 // The file extension is probably missing.
3203 // Now try to find it out.
3204 string const tex_name =
3205 find_file(filename, path,
3206 known_tex_extensions);
3207 if (!tex_name.empty())
3208 filename = tex_name;
3210 bool external = false;
3212 if (makeAbsPath(filename, path).exists()) {
3213 string const abstexname =
3214 makeAbsPath(filename, path).absFileName();
3215 string const abslyxname =
3216 changeExtension(abstexname, ".lyx");
3217 string const absfigname =
3218 changeExtension(abstexname, ".fig");
3219 fix_relative_filename(filename);
3220 string const lyxname =
3221 changeExtension(filename, ".lyx");
3223 external = FileName(absfigname).exists();
3224 if (t.cs() == "input") {
3225 string const ext = getExtension(abstexname);
3227 // Combined PS/LaTeX:
3228 // x.eps, x.pstex_t (old xfig)
3229 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3230 FileName const absepsname(
3231 changeExtension(abstexname, ".eps"));
3232 FileName const abspstexname(
3233 changeExtension(abstexname, ".pstex"));
3234 bool const xfigeps =
3235 (absepsname.exists() ||
3236 abspstexname.exists()) &&
3239 // Combined PDF/LaTeX:
3240 // x.pdf, x.pdftex_t (old xfig)
3241 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3242 FileName const abspdfname(
3243 changeExtension(abstexname, ".pdf"));
3244 bool const xfigpdf =
3245 abspdfname.exists() &&
3246 (ext == "pdftex_t" || ext == "pdf_t");
3250 // Combined PS/PDF/LaTeX:
3251 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3252 string const absbase2(
3253 removeExtension(abstexname) + "_pspdftex");
3254 FileName const abseps2name(
3255 addExtension(absbase2, ".eps"));
3256 FileName const abspdf2name(
3257 addExtension(absbase2, ".pdf"));
3258 bool const xfigboth =
3259 abspdf2name.exists() &&
3260 abseps2name.exists() && ext == "pspdftex";
3262 xfig = xfigpdf || xfigeps || xfigboth;
3263 external = external && xfig;
3266 outname = changeExtension(filename, ".fig");
3268 // Don't try to convert, the result
3269 // would be full of ERT.
3271 } else if (t.cs() != "verbatiminput" &&
3272 tex2lyx(abstexname, FileName(abslyxname),
3279 cerr << "Warning: Could not find included file '"
3280 << filename << "'." << endl;
3284 begin_inset(os, "External\n");
3285 os << "\ttemplate XFig\n"
3286 << "\tfilename " << outname << '\n';
3288 begin_command_inset(os, "include", name);
3289 os << "preview false\n"
3290 "filename \"" << outname << "\"\n";
3295 else if (t.cs() == "bibliographystyle") {
3296 // store new bibliographystyle
3297 bibliographystyle = p.verbatim_item();
3298 // If any other command than \bibliography and
3299 // \nocite{*} follows, we need to output the style
3300 // (because it might be used by that command).
3301 // Otherwise, it will automatically be output by LyX.
3304 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3305 if (t2.cat() == catBegin)
3307 if (t2.cat() != catEscape)
3309 if (t2.cs() == "nocite") {
3310 if (p.getArg('{', '}') == "*")
3312 } else if (t2.cs() == "bibliography")
3319 "\\bibliographystyle{" + bibliographystyle + '}',
3324 else if (t.cs() == "bibliography") {
3325 context.check_layout(os);
3326 begin_command_inset(os, "bibtex", "bibtex");
3327 if (!btprint.empty()) {
3328 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3329 // clear the string because the next BibTeX inset can be without the
3330 // \nocite{*} option
3333 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3334 // Do we have a bibliographystyle set?
3335 if (!bibliographystyle.empty())
3336 os << "options " << '"' << bibliographystyle << '"' << "\n";
3340 else if (t.cs() == "parbox")
3341 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3343 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3344 t.cs() == "shadowbox" || t.cs() == "doublebox")
3345 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3347 else if (t.cs() == "framebox") {
3348 string special = p.getFullOpt();
3349 special += p.getOpt();
3350 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3353 //\makebox() is part of the picture environment and different from \makebox{}
3354 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3355 else if (t.cs() == "makebox") {
3356 string arg = t.asInput();
3357 if (p.next_token().character() == '(')
3358 //the syntax is: \makebox(x,y)[position]{content}
3359 arg += p.getFullParentheseArg();
3361 //the syntax is: \makebox[width][position]{content}
3362 arg += p.getFullOpt();
3363 handle_ert(os, arg + p.getFullOpt(), context);
3366 else if (t.cs() == "smallskip" ||
3367 t.cs() == "medskip" ||
3368 t.cs() == "bigskip" ||
3369 t.cs() == "vfill") {
3370 context.check_layout(os);
3371 begin_inset(os, "VSpace ");
3374 skip_spaces_braces(p);
3377 else if (is_known(t.cs(), known_spaces)) {
3378 char const * const * where = is_known(t.cs(), known_spaces);
3379 context.check_layout(os);
3380 begin_inset(os, "space ");
3381 os << '\\' << known_coded_spaces[where - known_spaces]
3384 // LaTeX swallows whitespace after all spaces except
3385 // "\\,". We have to do that here, too, because LyX
3386 // adds "{}" which would make the spaces significant.
3388 eat_whitespace(p, os, context, false);
3389 // LyX adds "{}" after all spaces except "\\ " and
3390 // "\\,", so we have to remove "{}".
3391 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3392 // remove the braces after "\\,", too.
3397 else if (t.cs() == "newpage" ||
3398 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3399 t.cs() == "clearpage" ||
3400 t.cs() == "cleardoublepage") {
3401 context.check_layout(os);
3402 begin_inset(os, "Newpage ");
3405 skip_spaces_braces(p);
3408 else if (t.cs() == "DeclareRobustCommand" ||
3409 t.cs() == "DeclareRobustCommandx" ||
3410 t.cs() == "newcommand" ||
3411 t.cs() == "newcommandx" ||
3412 t.cs() == "providecommand" ||
3413 t.cs() == "providecommandx" ||
3414 t.cs() == "renewcommand" ||
3415 t.cs() == "renewcommandx") {
3416 // DeclareRobustCommand, DeclareRobustCommandx,
3417 // providecommand and providecommandx could be handled
3418 // by parse_command(), but we need to call
3419 // add_known_command() here.
3420 string name = t.asInput();
3421 if (p.next_token().asInput() == "*") {
3422 // Starred form. Eat '*'
3426 string const command = p.verbatim_item();
3427 string const opt1 = p.getFullOpt();
3428 string const opt2 = p.getFullOpt();
3429 add_known_command(command, opt1, !opt2.empty());
3430 string const ert = name + '{' + command + '}' +
3432 '{' + p.verbatim_item() + '}';
3434 if (t.cs() == "DeclareRobustCommand" ||
3435 t.cs() == "DeclareRobustCommandx" ||
3436 t.cs() == "providecommand" ||
3437 t.cs() == "providecommandx" ||
3438 name[name.length()-1] == '*')
3439 handle_ert(os, ert, context);
3441 context.check_layout(os);
3442 begin_inset(os, "FormulaMacro");
3448 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3449 // let could be handled by parse_command(),
3450 // but we need to call add_known_command() here.
3451 string ert = t.asInput();
3454 if (p.next_token().cat() == catBegin) {
3455 name = p.verbatim_item();
3456 ert += '{' + name + '}';
3458 name = p.verbatim_item();
3463 if (p.next_token().cat() == catBegin) {
3464 command = p.verbatim_item();
3465 ert += '{' + command + '}';
3467 command = p.verbatim_item();
3470 // If command is known, make name known too, to parse
3471 // its arguments correctly. For this reason we also
3472 // have commands in syntax.default that are hardcoded.
3473 CommandMap::iterator it = known_commands.find(command);
3474 if (it != known_commands.end())
3475 known_commands[t.asInput()] = it->second;
3476 handle_ert(os, ert, context);
3479 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3480 bool starred = false;
3481 if (p.next_token().asInput() == "*") {
3485 string name = t.asInput();
3486 string const length = p.verbatim_item();
3489 bool valid = splitLatexLength(length, valstring, unit);
3490 bool known_hspace = false;
3491 bool known_vspace = false;
3492 bool known_unit = false;
3495 istringstream iss(valstring);
3498 if (t.cs()[0] == 'h') {
3499 if (unit == "\\fill") {
3504 known_hspace = true;
3507 if (unit == "\\smallskipamount") {
3509 known_vspace = true;
3510 } else if (unit == "\\medskipamount") {
3512 known_vspace = true;
3513 } else if (unit == "\\bigskipamount") {
3515 known_vspace = true;
3516 } else if (unit == "\\fill") {
3518 known_vspace = true;
3522 if (!known_hspace && !known_vspace) {
3523 switch (unitFromString(unit)) {
3544 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3545 // Literal horizontal length or known variable
3546 context.check_layout(os);
3547 begin_inset(os, "space ");
3555 if (known_unit && !known_hspace)
3557 << translate_len(length);
3559 } else if (known_unit || known_vspace) {
3560 // Literal vertical length or known variable
3561 context.check_layout(os);
3562 begin_inset(os, "VSpace ");
3570 // LyX can't handle other length variables in Inset VSpace/space
3575 handle_ert(os, name + '{' + unit + '}', context);
3576 else if (value == -1.0)
3577 handle_ert(os, name + "{-" + unit + '}', context);
3579 handle_ert(os, name + '{' + valstring + unit + '}', context);
3581 handle_ert(os, name + '{' + length + '}', context);
3585 // The single '=' is meant here.
3586 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3588 context.check_layout(os);
3589 begin_inset(os, "Flex ");
3590 os << to_utf8(newinsetlayout->name()) << '\n'
3591 << "status collapsed\n";
3592 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3597 // try to see whether the string is in unicodesymbols
3598 // Only use text mode commands, since we are in text mode here,
3599 // and math commands may be invalid (bug 6797)
3601 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3602 rem, Encodings::TEXT_CMD);
3605 cerr << "When parsing " << t.cs()
3606 << ", result is " << to_utf8(s)
3607 << "+" << to_utf8(rem) << endl;
3608 context.check_layout(os);
3610 skip_spaces_braces(p);
3612 //cerr << "#: " << t << " mode: " << mode << endl;
3613 // heuristic: read up to next non-nested space
3615 string s = t.asInput();
3616 string z = p.verbatim_item();
3617 while (p.good() && z != " " && z.size()) {
3618 //cerr << "read: " << z << endl;
3620 z = p.verbatim_item();
3622 cerr << "found ERT: " << s << endl;
3623 handle_ert(os, s + ' ', context);
3626 string name = t.asInput();
3627 if (p.next_token().asInput() == "*") {
3628 // Starred commands like \vspace*{}
3629 p.get_token(); // Eat '*'
3632 if (!parse_command(name, p, os, outer, context))
3633 handle_ert(os, name, context);
3637 if (flags & FLAG_LEAVE) {
3638 flags &= ~FLAG_LEAVE;