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, Context & parent_context)
1040 Layout const * newlayout;
1041 InsetLayout const * newinsetlayout = 0;
1042 string const name = p.getArg('{', '}');
1043 const bool is_starred = suffixIs(name, '*');
1044 string const unstarred_name = rtrim(name, "*");
1045 active_environments.push_back(name);
1047 if (is_math_env(name)) {
1048 parent_context.check_layout(os);
1049 begin_inset(os, "Formula ");
1050 os << "\\begin{" << name << "}";
1051 parse_math(p, os, FLAG_END, MATH_MODE);
1052 os << "\\end{" << name << "}";
1056 else if (name == "tabular" || name == "longtable") {
1057 eat_whitespace(p, os, parent_context, false);
1058 parent_context.check_layout(os);
1059 begin_inset(os, "Tabular ");
1060 handle_tabular(p, os, name == "longtable", parent_context);
1065 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1066 eat_whitespace(p, os, parent_context, false);
1067 parent_context.check_layout(os);
1068 begin_inset(os, "Float " + unstarred_name + "\n");
1069 // store the float type for subfloats
1070 // subfloats only work with figures and tables
1071 if (unstarred_name == "figure")
1072 float_type = unstarred_name;
1073 else if (unstarred_name == "table")
1074 float_type = unstarred_name;
1078 os << "placement " << p.getArg('[', ']') << '\n';
1079 os << "wide " << convert<string>(is_starred)
1080 << "\nsideways false"
1081 << "\nstatus open\n\n";
1082 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1084 // We don't need really a new paragraph, but
1085 // we must make sure that the next item gets a \begin_layout.
1086 parent_context.new_paragraph(os);
1088 // the float is parsed thus delete the type
1092 else if (unstarred_name == "sidewaysfigure"
1093 || unstarred_name == "sidewaystable") {
1094 eat_whitespace(p, os, parent_context, false);
1095 parent_context.check_layout(os);
1096 if (unstarred_name == "sidewaysfigure")
1097 begin_inset(os, "Float figure\n");
1099 begin_inset(os, "Float table\n");
1100 os << "wide " << convert<string>(is_starred)
1101 << "\nsideways true"
1102 << "\nstatus open\n\n";
1103 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1105 // We don't need really a new paragraph, but
1106 // we must make sure that the next item gets a \begin_layout.
1107 parent_context.new_paragraph(os);
1111 else if (name == "wrapfigure" || name == "wraptable") {
1112 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1113 eat_whitespace(p, os, parent_context, false);
1114 parent_context.check_layout(os);
1117 string overhang = "0col%";
1120 lines = p.getArg('[', ']');
1121 string const placement = p.getArg('{', '}');
1123 overhang = p.getArg('[', ']');
1124 string const width = p.getArg('{', '}');
1126 if (name == "wrapfigure")
1127 begin_inset(os, "Wrap figure\n");
1129 begin_inset(os, "Wrap table\n");
1130 os << "lines " << lines
1131 << "\nplacement " << placement
1132 << "\noverhang " << lyx::translate_len(overhang)
1133 << "\nwidth " << lyx::translate_len(width)
1134 << "\nstatus open\n\n";
1135 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1137 // We don't need really a new paragraph, but
1138 // we must make sure that the next item gets a \begin_layout.
1139 parent_context.new_paragraph(os);
1143 else if (name == "minipage") {
1144 eat_whitespace(p, os, parent_context, false);
1145 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1149 else if (name == "comment") {
1150 eat_whitespace(p, os, parent_context, false);
1151 parent_context.check_layout(os);
1152 begin_inset(os, "Note Comment\n");
1153 os << "status open\n";
1154 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1157 skip_braces(p); // eat {} that might by set by LyX behind comments
1160 else if (name == "lyxgreyedout") {
1161 eat_whitespace(p, os, parent_context, false);
1162 parent_context.check_layout(os);
1163 begin_inset(os, "Note Greyedout\n");
1164 os << "status open\n";
1165 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1170 else if (name == "framed" || name == "shaded") {
1171 eat_whitespace(p, os, parent_context, false);
1172 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1176 else if (name == "lstlisting") {
1177 eat_whitespace(p, os, parent_context, false);
1178 // FIXME handle listings with parameters
1180 parse_unknown_environment(p, name, os, FLAG_END,
1181 outer, parent_context);
1183 parse_listings(p, os, parent_context);
1187 else if (!parent_context.new_layout_allowed)
1188 parse_unknown_environment(p, name, os, FLAG_END, outer,
1191 // Alignment and spacing settings
1192 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1193 // therefore are totally broken!
1194 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1195 // they are commands not environments. They are furthermore switches that
1196 // can be ended by another switches, but also by commands like \footnote or
1197 // \parbox. So the only safe way is to leave them untouched.
1198 else if (name == "center" || name == "centering" ||
1199 name == "flushleft" || name == "flushright" ||
1200 name == "singlespace" || name == "onehalfspace" ||
1201 name == "doublespace" || name == "spacing") {
1202 eat_whitespace(p, os, parent_context, false);
1203 // We must begin a new paragraph if not already done
1204 if (! parent_context.atParagraphStart()) {
1205 parent_context.check_end_layout(os);
1206 parent_context.new_paragraph(os);
1208 if (name == "flushleft")
1209 parent_context.add_extra_stuff("\\align left\n");
1210 else if (name == "flushright")
1211 parent_context.add_extra_stuff("\\align right\n");
1212 else if (name == "center" || name == "centering")
1213 parent_context.add_extra_stuff("\\align center\n");
1214 else if (name == "singlespace")
1215 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1216 else if (name == "onehalfspace")
1217 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1218 else if (name == "doublespace")
1219 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1220 else if (name == "spacing")
1221 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1222 parse_text(p, os, FLAG_END, outer, parent_context);
1223 // Just in case the environment is empty
1224 parent_context.extra_stuff.erase();
1225 // We must begin a new paragraph to reset the alignment
1226 parent_context.new_paragraph(os);
1230 // The single '=' is meant here.
1231 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1232 eat_whitespace(p, os, parent_context, false);
1233 Context context(true, parent_context.textclass, newlayout,
1234 parent_context.layout, parent_context.font);
1235 if (parent_context.deeper_paragraph) {
1236 // We are beginning a nested environment after a
1237 // deeper paragraph inside the outer list environment.
1238 // Therefore we don't need to output a "begin deeper".
1239 context.need_end_deeper = true;
1241 parent_context.check_end_layout(os);
1242 if (last_env == name) {
1243 // we need to output a separator since LyX would export
1244 // the two environments as one otherwise (bug 5716)
1245 docstring const sep = from_ascii("--Separator--");
1246 TeX2LyXDocClass const & textclass(parent_context.textclass);
1247 if (textclass.hasLayout(sep)) {
1248 Context newcontext(parent_context);
1249 newcontext.layout = &(textclass[sep]);
1250 newcontext.check_layout(os);
1251 newcontext.check_end_layout(os);
1253 parent_context.check_layout(os);
1254 begin_inset(os, "Note Note\n");
1255 os << "status closed\n";
1256 Context newcontext(true, textclass,
1257 &(textclass.defaultLayout()));
1258 newcontext.check_layout(os);
1259 newcontext.check_end_layout(os);
1261 parent_context.check_end_layout(os);
1264 switch (context.layout->latextype) {
1265 case LATEX_LIST_ENVIRONMENT:
1266 context.add_par_extra_stuff("\\labelwidthstring "
1267 + p.verbatim_item() + '\n');
1270 case LATEX_BIB_ENVIRONMENT:
1271 p.verbatim_item(); // swallow next arg
1277 context.check_deeper(os);
1278 // handle known optional and required arguments
1279 // layouts require all optional arguments before the required ones
1280 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1281 // It is impossible to place anything after the environment name,
1282 // but before the first \\item.
1283 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1284 bool need_layout = true;
1285 unsigned int optargs = 0;
1286 while (optargs < context.layout->optargs) {
1287 eat_whitespace(p, os, context, false);
1288 if (p.next_token().cat() == catEscape ||
1289 p.next_token().character() != '[')
1291 p.get_token(); // eat '['
1293 context.check_layout(os);
1294 need_layout = false;
1296 begin_inset(os, "Argument\n");
1297 os << "status collapsed\n\n";
1298 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1300 eat_whitespace(p, os, context, false);
1303 unsigned int reqargs = 0;
1304 while (reqargs < context.layout->reqargs) {
1305 eat_whitespace(p, os, context, false);
1306 if (p.next_token().cat() != catBegin)
1308 p.get_token(); // eat '{'
1310 context.check_layout(os);
1311 need_layout = false;
1313 begin_inset(os, "Argument\n");
1314 os << "status collapsed\n\n";
1315 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1317 eat_whitespace(p, os, context, false);
1321 parse_text(p, os, FLAG_END, outer, context);
1322 context.check_end_layout(os);
1323 if (parent_context.deeper_paragraph) {
1324 // We must suppress the "end deeper" because we
1325 // suppressed the "begin deeper" above.
1326 context.need_end_deeper = false;
1328 context.check_end_deeper(os);
1329 parent_context.new_paragraph(os);
1333 // The single '=' is meant here.
1334 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1335 eat_whitespace(p, os, parent_context, false);
1336 parent_context.check_layout(os);
1337 begin_inset(os, "Flex ");
1338 os << to_utf8(newinsetlayout->name()) << '\n'
1339 << "status collapsed\n";
1340 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1344 else if (name == "appendix") {
1345 // This is no good latex style, but it works and is used in some documents...
1346 eat_whitespace(p, os, parent_context, false);
1347 parent_context.check_end_layout(os);
1348 Context context(true, parent_context.textclass, parent_context.layout,
1349 parent_context.layout, parent_context.font);
1350 context.check_layout(os);
1351 os << "\\start_of_appendix\n";
1352 parse_text(p, os, FLAG_END, outer, context);
1353 context.check_end_layout(os);
1357 else if (known_environments.find(name) != known_environments.end()) {
1358 vector<ArgumentType> arguments = known_environments[name];
1359 // The last "argument" denotes wether we may translate the
1360 // environment contents to LyX
1361 // The default required if no argument is given makes us
1362 // compatible with the reLyXre environment.
1363 ArgumentType contents = arguments.empty() ?
1366 if (!arguments.empty())
1367 arguments.pop_back();
1368 // See comment in parse_unknown_environment()
1369 bool const specialfont =
1370 (parent_context.font != parent_context.normalfont);
1371 bool const new_layout_allowed =
1372 parent_context.new_layout_allowed;
1374 parent_context.new_layout_allowed = false;
1375 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1376 outer, parent_context);
1377 if (contents == verbatim)
1378 handle_ert(os, p.verbatimEnvironment(name),
1381 parse_text_snippet(p, os, FLAG_END, outer,
1383 handle_ert(os, "\\end{" + name + "}", parent_context);
1385 parent_context.new_layout_allowed = new_layout_allowed;
1389 parse_unknown_environment(p, name, os, FLAG_END, outer,
1393 active_environments.pop_back();
1397 /// parses a comment and outputs it to \p os.
1398 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1400 LASSERT(t.cat() == catComment, return);
1401 if (!t.cs().empty()) {
1402 context.check_layout(os);
1403 handle_comment(os, '%' + t.cs(), context);
1404 if (p.next_token().cat() == catNewline) {
1405 // A newline after a comment line starts a new
1407 if (context.new_layout_allowed) {
1408 if(!context.atParagraphStart())
1409 // Only start a new paragraph if not already
1410 // done (we might get called recursively)
1411 context.new_paragraph(os);
1413 handle_ert(os, "\n", context);
1414 eat_whitespace(p, os, context, true);
1417 // "%\n" combination
1424 * Reads spaces and comments until the first non-space, non-comment token.
1425 * New paragraphs (double newlines or \\par) are handled like simple spaces
1426 * if \p eatParagraph is true.
1427 * Spaces are skipped, but comments are written to \p os.
1429 void eat_whitespace(Parser & p, ostream & os, Context & context,
1433 Token const & t = p.get_token();
1434 if (t.cat() == catComment)
1435 parse_comment(p, os, t, context);
1436 else if ((! eatParagraph && p.isParagraph()) ||
1437 (t.cat() != catSpace && t.cat() != catNewline)) {
1446 * Set a font attribute, parse text and reset the font attribute.
1447 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1448 * \param currentvalue Current value of the attribute. Is set to the new
1449 * value during parsing.
1450 * \param newvalue New value of the attribute
1452 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1453 Context & context, string const & attribute,
1454 string & currentvalue, string const & newvalue)
1456 context.check_layout(os);
1457 string const oldvalue = currentvalue;
1458 currentvalue = newvalue;
1459 os << '\n' << attribute << ' ' << newvalue << "\n";
1460 parse_text_snippet(p, os, flags, outer, context);
1461 context.check_layout(os);
1462 os << '\n' << attribute << ' ' << oldvalue << "\n";
1463 currentvalue = oldvalue;
1467 /// get the arguments of a natbib or jurabib citation command
1468 void get_cite_arguments(Parser & p, bool natbibOrder,
1469 string & before, string & after)
1471 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1473 // text before the citation
1475 // text after the citation
1476 after = p.getFullOpt();
1478 if (!after.empty()) {
1479 before = p.getFullOpt();
1480 if (natbibOrder && !before.empty())
1481 swap(before, after);
1486 /// Convert filenames with TeX macros and/or quotes to something LyX
1488 string const normalize_filename(string const & name)
1490 Parser p(trim(name, "\""));
1493 Token const & t = p.get_token();
1494 if (t.cat() != catEscape)
1496 else if (t.cs() == "lyxdot") {
1497 // This is used by LyX for simple dots in relative
1501 } else if (t.cs() == "space") {
1511 /// Convert \p name from TeX convention (relative to master file) to LyX
1512 /// convention (relative to .lyx file) if it is relative
1513 void fix_relative_filename(string & name)
1515 if (FileName::isAbsolute(name))
1518 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1519 from_utf8(getParentFilePath())));
1523 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1524 void parse_noweb(Parser & p, ostream & os, Context & context)
1526 // assemble the rest of the keyword
1530 Token const & t = p.get_token();
1531 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1534 scrap = (p.good() && p.next_token().asInput() == "=");
1536 name += p.get_token().asInput();
1539 name += t.asInput();
1542 if (!scrap || !context.new_layout_allowed ||
1543 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1544 cerr << "Warning: Could not interpret '" << name
1545 << "'. Ignoring it." << endl;
1549 // We use new_paragraph instead of check_end_layout because the stuff
1550 // following the noweb chunk needs to start with a \begin_layout.
1551 // This may create a new paragraph even if there was none in the
1552 // noweb file, but the alternative is an invalid LyX file. Since
1553 // noweb code chunks are implemented with a layout style in LyX they
1554 // always must be in an own paragraph.
1555 context.new_paragraph(os);
1556 Context newcontext(true, context.textclass,
1557 &context.textclass[from_ascii("Scrap")]);
1558 newcontext.check_layout(os);
1561 Token const & t = p.get_token();
1562 // We abuse the parser a bit, because this is no TeX syntax
1564 if (t.cat() == catEscape)
1565 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1568 Context tmp(false, context.textclass,
1569 &context.textclass[from_ascii("Scrap")]);
1570 tmp.need_end_layout = true;
1571 tmp.check_layout(oss);
1572 os << subst(t.asInput(), "\n", oss.str());
1574 // The scrap chunk is ended by an @ at the beginning of a line.
1575 // After the @ the line may contain a comment and/or
1576 // whitespace, but nothing else.
1577 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1578 (p.next_token().cat() == catSpace ||
1579 p.next_token().cat() == catNewline ||
1580 p.next_token().cat() == catComment)) {
1581 while (p.good() && p.next_token().cat() == catSpace)
1582 os << p.get_token().asInput();
1583 if (p.next_token().cat() == catComment)
1584 // The comment includes a final '\n'
1585 os << p.get_token().asInput();
1587 if (p.next_token().cat() == catNewline)
1594 newcontext.check_end_layout(os);
1598 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1599 bool is_macro(Parser & p)
1601 Token first = p.curr_token();
1602 if (first.cat() != catEscape || !p.good())
1604 if (first.cs() == "def")
1606 if (first.cs() != "global" && first.cs() != "long")
1608 Token second = p.get_token();
1610 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1611 second.cat() == catNewline || second.cat() == catComment)) {
1612 second = p.get_token();
1615 bool secondvalid = second.cat() == catEscape;
1617 bool thirdvalid = false;
1618 if (p.good() && first.cs() == "global" && secondvalid &&
1619 second.cs() == "long") {
1620 third = p.get_token();
1622 while (p.good() && !p.isParagraph() &&
1623 (third.cat() == catSpace ||
1624 third.cat() == catNewline ||
1625 third.cat() == catComment)) {
1626 third = p.get_token();
1629 thirdvalid = third.cat() == catEscape;
1631 for (int i = 0; i < pos; ++i)
1636 return (first.cs() == "global" || first.cs() == "long") &&
1637 second.cs() == "def";
1638 return first.cs() == "global" && second.cs() == "long" &&
1639 third.cs() == "def";
1643 /// Parse a macro definition (assumes that is_macro() returned true)
1644 void parse_macro(Parser & p, ostream & os, Context & context)
1646 context.check_layout(os);
1647 Token first = p.curr_token();
1650 string command = first.asInput();
1651 if (first.cs() != "def") {
1653 eat_whitespace(p, os, context, false);
1654 second = p.curr_token();
1655 command += second.asInput();
1656 if (second.cs() != "def") {
1658 eat_whitespace(p, os, context, false);
1659 third = p.curr_token();
1660 command += third.asInput();
1663 eat_whitespace(p, os, context, false);
1664 string const name = p.get_token().cs();
1665 eat_whitespace(p, os, context, false);
1671 while (p.next_token().cat() != catBegin) {
1672 if (p.next_token().cat() == catParameter) {
1677 // followed by number?
1678 if (p.next_token().cat() == catOther) {
1679 char c = p.getChar();
1681 // number = current arity + 1?
1682 if (c == arity + '0' + 1)
1687 paramtext += p.get_token().cs();
1689 paramtext += p.get_token().cs();
1694 // only output simple (i.e. compatible) macro as FormulaMacros
1695 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1697 context.check_layout(os);
1698 begin_inset(os, "FormulaMacro");
1699 os << "\n\\def" << ert;
1702 handle_ert(os, command + ert, context);
1705 } // anonymous namespace
1708 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1711 Layout const * newlayout = 0;
1712 InsetLayout const * newinsetlayout = 0;
1713 // Store the latest bibliographystyle and nocite{*} option
1714 // (needed for bibtex inset)
1716 string bibliographystyle;
1717 bool const use_natbib = preamble.isPackageUsed("natbib");
1718 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1721 Token const & t = p.get_token();
1724 debugToken(cerr, t, flags);
1727 if (flags & FLAG_ITEM) {
1728 if (t.cat() == catSpace)
1731 flags &= ~FLAG_ITEM;
1732 if (t.cat() == catBegin) {
1733 // skip the brace and collect everything to the next matching
1735 flags |= FLAG_BRACE_LAST;
1739 // handle only this single token, leave the loop if done
1740 flags |= FLAG_LEAVE;
1743 if (t.cat() != catEscape && t.character() == ']' &&
1744 (flags & FLAG_BRACK_LAST))
1746 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1749 // If there is anything between \end{env} and \begin{env} we
1750 // don't need to output a separator.
1751 if (t.cat() != catSpace && t.cat() != catNewline &&
1752 t.asInput() != "\\begin")
1758 if (t.cat() == catMath) {
1759 // we are inside some text mode thingy, so opening new math is allowed
1760 context.check_layout(os);
1761 begin_inset(os, "Formula ");
1762 Token const & n = p.get_token();
1763 if (n.cat() == catMath && outer) {
1764 // TeX's $$...$$ syntax for displayed math
1766 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1768 p.get_token(); // skip the second '$' token
1770 // simple $...$ stuff
1773 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1779 else if (t.cat() == catSuper || t.cat() == catSub)
1780 cerr << "catcode " << t << " illegal in text mode\n";
1782 // Basic support for english quotes. This should be
1783 // extended to other quotes, but is not so easy (a
1784 // left english quote is the same as a right german
1786 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1787 context.check_layout(os);
1788 begin_inset(os, "Quotes ");
1794 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1795 context.check_layout(os);
1796 begin_inset(os, "Quotes ");
1803 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1804 context.check_layout(os);
1805 begin_inset(os, "Quotes ");
1812 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1813 context.check_layout(os);
1814 begin_inset(os, "Quotes ");
1821 else if (t.asInput() == "<"
1822 && p.next_token().asInput() == "<" && noweb_mode) {
1824 parse_noweb(p, os, context);
1827 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1828 check_space(p, os, context);
1830 else if (t.character() == '[' && noweb_mode &&
1831 p.next_token().character() == '[') {
1832 // These can contain underscores
1834 string const s = p.getFullOpt() + ']';
1835 if (p.next_token().character() == ']')
1838 cerr << "Warning: Inserting missing ']' in '"
1839 << s << "'." << endl;
1840 handle_ert(os, s, context);
1843 else if (t.cat() == catLetter) {
1844 context.check_layout(os);
1845 // Workaround for bug 4752.
1846 // FIXME: This whole code block needs to be removed
1847 // when the bug is fixed and tex2lyx produces
1848 // the updated file format.
1849 // The replacement algorithm in LyX is so stupid that
1850 // it even translates a phrase if it is part of a word.
1851 bool handled = false;
1852 for (int const * l = known_phrase_lengths; *l; ++l) {
1853 string phrase = t.cs();
1854 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1855 phrase += p.get_token().cs();
1856 if (is_known(phrase, known_coded_phrases)) {
1857 handle_ert(os, phrase, context);
1861 for (size_t i = 1; i < phrase.length(); ++i)
1869 else if (t.cat() == catOther ||
1870 t.cat() == catAlign ||
1871 t.cat() == catParameter) {
1872 // This translates "&" to "\\&" which may be wrong...
1873 context.check_layout(os);
1877 else if (p.isParagraph()) {
1878 if (context.new_layout_allowed)
1879 context.new_paragraph(os);
1881 handle_ert(os, "\\par ", context);
1882 eat_whitespace(p, os, context, true);
1885 else if (t.cat() == catActive) {
1886 context.check_layout(os);
1887 if (t.character() == '~') {
1888 if (context.layout->free_spacing)
1891 begin_inset(os, "space ~\n");
1898 else if (t.cat() == catBegin &&
1899 p.next_token().cat() == catEnd) {
1901 Token const prev = p.prev_token();
1903 if (p.next_token().character() == '`' ||
1904 (prev.character() == '-' &&
1905 p.next_token().character() == '-'))
1906 ; // ignore it in {}`` or -{}-
1908 handle_ert(os, "{}", context);
1912 else if (t.cat() == catBegin) {
1913 context.check_layout(os);
1914 // special handling of font attribute changes
1915 Token const prev = p.prev_token();
1916 Token const next = p.next_token();
1917 TeXFont const oldFont = context.font;
1918 if (next.character() == '[' ||
1919 next.character() == ']' ||
1920 next.character() == '*') {
1922 if (p.next_token().cat() == catEnd) {
1927 handle_ert(os, "{", context);
1928 parse_text_snippet(p, os,
1931 handle_ert(os, "}", context);
1933 } else if (! context.new_layout_allowed) {
1934 handle_ert(os, "{", context);
1935 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1937 handle_ert(os, "}", context);
1938 } else if (is_known(next.cs(), known_sizes)) {
1939 // next will change the size, so we must
1941 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1943 if (!context.atParagraphStart())
1945 << context.font.size << "\n";
1946 } else if (is_known(next.cs(), known_font_families)) {
1947 // next will change the font family, so we
1948 // must reset it here
1949 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1951 if (!context.atParagraphStart())
1953 << context.font.family << "\n";
1954 } else if (is_known(next.cs(), known_font_series)) {
1955 // next will change the font series, so we
1956 // must reset it here
1957 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1959 if (!context.atParagraphStart())
1961 << context.font.series << "\n";
1962 } else if (is_known(next.cs(), known_font_shapes)) {
1963 // next will change the font shape, so we
1964 // must reset it here
1965 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1967 if (!context.atParagraphStart())
1969 << context.font.shape << "\n";
1970 } else if (is_known(next.cs(), known_old_font_families) ||
1971 is_known(next.cs(), known_old_font_series) ||
1972 is_known(next.cs(), known_old_font_shapes)) {
1973 // next will change the font family, series
1974 // and shape, so we must reset it here
1975 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1977 if (!context.atParagraphStart())
1979 << context.font.family
1981 << context.font.series
1983 << context.font.shape << "\n";
1985 handle_ert(os, "{", context);
1986 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1988 handle_ert(os, "}", context);
1992 else if (t.cat() == catEnd) {
1993 if (flags & FLAG_BRACE_LAST) {
1996 cerr << "stray '}' in text\n";
1997 handle_ert(os, "}", context);
2000 else if (t.cat() == catComment)
2001 parse_comment(p, os, t, context);
2004 // control sequences
2007 else if (t.cs() == "(") {
2008 context.check_layout(os);
2009 begin_inset(os, "Formula");
2011 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2016 else if (t.cs() == "[") {
2017 context.check_layout(os);
2018 begin_inset(os, "Formula");
2020 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2025 else if (t.cs() == "begin")
2026 parse_environment(p, os, outer, last_env, context);
2028 else if (t.cs() == "end") {
2029 if (flags & FLAG_END) {
2030 // eat environment name
2031 string const name = p.getArg('{', '}');
2032 if (name != active_environment())
2033 cerr << "\\end{" + name + "} does not match \\begin{"
2034 + active_environment() + "}\n";
2037 p.error("found 'end' unexpectedly");
2040 else if (t.cs() == "item") {
2043 bool optarg = false;
2044 if (p.next_token().cat() != catEscape &&
2045 p.next_token().character() == '[') {
2046 p.get_token(); // eat '['
2047 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2052 context.check_layout(os);
2053 if (context.has_item) {
2054 // An item in an unknown list-like environment
2055 // FIXME: Do this in check_layout()!
2056 context.has_item = false;
2058 handle_ert(os, "\\item", context);
2060 handle_ert(os, "\\item ", context);
2063 if (context.layout->labeltype != LABEL_MANUAL) {
2064 // LyX does not support \item[\mybullet]
2065 // in itemize environments
2066 handle_ert(os, "[", context);
2068 handle_ert(os, "]", context);
2069 } else if (!s.empty()) {
2070 // The space is needed to separate the
2071 // item from the rest of the sentence.
2073 eat_whitespace(p, os, context, false);
2078 else if (t.cs() == "bibitem") {
2080 context.check_layout(os);
2081 string label = convert_command_inset_arg(p.getArg('[', ']'));
2082 string key = convert_command_inset_arg(p.verbatim_item());
2083 if (contains(label, '\\') || contains(key, '\\')) {
2084 // LyX can't handle LaTeX commands in labels or keys
2085 handle_ert(os, t.asInput() + '[' + label +
2086 "]{" + p.verbatim_item() + '}',
2089 begin_command_inset(os, "bibitem", "bibitem");
2090 os << "label \"" << label << "\"\n"
2091 "key \"" << key << "\"\n";
2096 else if (is_macro(p))
2097 parse_macro(p, os, context);
2099 else if (t.cs() == "noindent") {
2101 context.add_par_extra_stuff("\\noindent\n");
2104 else if (t.cs() == "appendix") {
2105 context.add_par_extra_stuff("\\start_of_appendix\n");
2106 // We need to start a new paragraph. Otherwise the
2107 // appendix in 'bla\appendix\chapter{' would start
2109 context.new_paragraph(os);
2110 // We need to make sure that the paragraph is
2111 // generated even if it is empty. Otherwise the
2112 // appendix in '\par\appendix\par\chapter{' would
2114 context.check_layout(os);
2115 // FIXME: This is a hack to prevent paragraph
2116 // deletion if it is empty. Handle this better!
2118 "%dummy comment inserted by tex2lyx to "
2119 "ensure that this paragraph is not empty",
2121 // Both measures above may generate an additional
2122 // empty paragraph, but that does not hurt, because
2123 // whitespace does not matter here.
2124 eat_whitespace(p, os, context, true);
2127 // Starred section headings
2128 // Must attempt to parse "Section*" before "Section".
2129 else if ((p.next_token().asInput() == "*") &&
2130 context.new_layout_allowed &&
2131 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2134 output_command_layout(os, p, outer, context, newlayout);
2138 // Section headings and the like
2139 else if (context.new_layout_allowed &&
2140 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2142 output_command_layout(os, p, outer, context, newlayout);
2146 else if (t.cs() == "caption") {
2148 context.check_layout(os);
2150 begin_inset(os, "Caption\n");
2151 Context newcontext(true, context.textclass);
2152 newcontext.font = context.font;
2153 newcontext.check_layout(os);
2154 if (p.next_token().cat() != catEscape &&
2155 p.next_token().character() == '[') {
2156 p.get_token(); // eat '['
2157 begin_inset(os, "Argument\n");
2158 os << "status collapsed\n";
2159 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2161 eat_whitespace(p, os, context, false);
2163 parse_text(p, os, FLAG_ITEM, outer, context);
2164 context.check_end_layout(os);
2165 // We don't need really a new paragraph, but
2166 // we must make sure that the next item gets a \begin_layout.
2167 context.new_paragraph(os);
2170 newcontext.check_end_layout(os);
2173 else if (t.cs() == "subfloat") {
2174 // the syntax is \subfloat[caption]{content}
2175 // if it is a table of figure depends on the surrounding float
2176 bool has_caption = false;
2178 // do nothing if there is no outer float
2179 if (!float_type.empty()) {
2180 context.check_layout(os);
2182 begin_inset(os, "Float " + float_type + "\n");
2184 << "\nsideways false"
2185 << "\nstatus collapsed\n\n";
2188 if (p.next_token().cat() != catEscape &&
2189 p.next_token().character() == '[') {
2190 p.get_token(); // eat '['
2191 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2195 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2196 // the caption comes always as the last
2198 // we must make sure that the caption gets a \begin_layout
2199 os << "\n\\begin_layout Plain Layout";
2201 begin_inset(os, "Caption\n");
2202 Context newcontext(true, context.textclass);
2203 newcontext.font = context.font;
2204 newcontext.check_layout(os);
2205 os << caption << "\n";
2206 newcontext.check_end_layout(os);
2207 // We don't need really a new paragraph, but
2208 // we must make sure that the next item gets a \begin_layout.
2209 //newcontext.new_paragraph(os);
2213 // We don't need really a new paragraph, but
2214 // we must make sure that the next item gets a \begin_layout.
2216 context.new_paragraph(os);
2219 context.check_end_layout(os);
2220 // close the layout we opened
2222 os << "\n\\end_layout\n";
2224 // if the float type is not supported or there is no surrounding float
2227 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2228 handle_ert(os, t.asInput() + '[' + opt_arg +
2229 "]{" + p.verbatim_item() + '}', context);
2231 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2235 else if (t.cs() == "includegraphics") {
2236 bool const clip = p.next_token().asInput() == "*";
2239 string const arg = p.getArg('[', ']');
2240 map<string, string> opts;
2241 vector<string> keys;
2242 split_map(arg, opts, keys);
2244 opts["clip"] = string();
2245 string name = normalize_filename(p.verbatim_item());
2247 string const path = getMasterFilePath();
2248 // We want to preserve relative / absolute filenames,
2249 // therefore path is only used for testing
2250 if (!makeAbsPath(name, path).exists()) {
2251 // The file extension is probably missing.
2252 // Now try to find it out.
2253 string const dvips_name =
2254 find_file(name, path,
2255 known_dvips_graphics_formats);
2256 string const pdftex_name =
2257 find_file(name, path,
2258 known_pdftex_graphics_formats);
2259 if (!dvips_name.empty()) {
2260 if (!pdftex_name.empty()) {
2261 cerr << "This file contains the "
2263 "\"\\includegraphics{"
2265 "However, files\n\""
2266 << dvips_name << "\" and\n\""
2267 << pdftex_name << "\"\n"
2268 "both exist, so I had to make a "
2269 "choice and took the first one.\n"
2270 "Please move the unwanted one "
2271 "someplace else and try again\n"
2272 "if my choice was wrong."
2276 } else if (!pdftex_name.empty()) {
2282 if (makeAbsPath(name, path).exists())
2283 fix_relative_filename(name);
2285 cerr << "Warning: Could not find graphics file '"
2286 << name << "'." << endl;
2288 context.check_layout(os);
2289 begin_inset(os, "Graphics ");
2290 os << "\n\tfilename " << name << '\n';
2291 if (opts.find("width") != opts.end())
2293 << translate_len(opts["width"]) << '\n';
2294 if (opts.find("height") != opts.end())
2296 << translate_len(opts["height"]) << '\n';
2297 if (opts.find("scale") != opts.end()) {
2298 istringstream iss(opts["scale"]);
2302 os << "\tscale " << val << '\n';
2304 if (opts.find("angle") != opts.end()) {
2305 os << "\trotateAngle "
2306 << opts["angle"] << '\n';
2307 vector<string>::const_iterator a =
2308 find(keys.begin(), keys.end(), "angle");
2309 vector<string>::const_iterator s =
2310 find(keys.begin(), keys.end(), "width");
2311 if (s == keys.end())
2312 s = find(keys.begin(), keys.end(), "height");
2313 if (s == keys.end())
2314 s = find(keys.begin(), keys.end(), "scale");
2315 if (s != keys.end() && distance(s, a) > 0)
2316 os << "\tscaleBeforeRotation\n";
2318 if (opts.find("origin") != opts.end()) {
2320 string const opt = opts["origin"];
2321 if (opt.find('l') != string::npos) ss << "left";
2322 if (opt.find('r') != string::npos) ss << "right";
2323 if (opt.find('c') != string::npos) ss << "center";
2324 if (opt.find('t') != string::npos) ss << "Top";
2325 if (opt.find('b') != string::npos) ss << "Bottom";
2326 if (opt.find('B') != string::npos) ss << "Baseline";
2327 if (!ss.str().empty())
2328 os << "\trotateOrigin " << ss.str() << '\n';
2330 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2332 if (opts.find("keepaspectratio") != opts.end())
2333 os << "\tkeepAspectRatio\n";
2334 if (opts.find("clip") != opts.end())
2336 if (opts.find("draft") != opts.end())
2338 if (opts.find("bb") != opts.end())
2339 os << "\tBoundingBox "
2340 << opts["bb"] << '\n';
2341 int numberOfbbOptions = 0;
2342 if (opts.find("bbllx") != opts.end())
2343 numberOfbbOptions++;
2344 if (opts.find("bblly") != opts.end())
2345 numberOfbbOptions++;
2346 if (opts.find("bburx") != opts.end())
2347 numberOfbbOptions++;
2348 if (opts.find("bbury") != opts.end())
2349 numberOfbbOptions++;
2350 if (numberOfbbOptions == 4)
2351 os << "\tBoundingBox "
2352 << opts["bbllx"] << " " << opts["bblly"] << " "
2353 << opts["bburx"] << " " << opts["bbury"] << '\n';
2354 else if (numberOfbbOptions > 0)
2355 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2356 numberOfbbOptions = 0;
2357 if (opts.find("natwidth") != opts.end())
2358 numberOfbbOptions++;
2359 if (opts.find("natheight") != opts.end())
2360 numberOfbbOptions++;
2361 if (numberOfbbOptions == 2)
2362 os << "\tBoundingBox 0bp 0bp "
2363 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2364 else if (numberOfbbOptions > 0)
2365 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2366 ostringstream special;
2367 if (opts.find("hiresbb") != opts.end())
2368 special << "hiresbb,";
2369 if (opts.find("trim") != opts.end())
2371 if (opts.find("viewport") != opts.end())
2372 special << "viewport=" << opts["viewport"] << ',';
2373 if (opts.find("totalheight") != opts.end())
2374 special << "totalheight=" << opts["totalheight"] << ',';
2375 if (opts.find("type") != opts.end())
2376 special << "type=" << opts["type"] << ',';
2377 if (opts.find("ext") != opts.end())
2378 special << "ext=" << opts["ext"] << ',';
2379 if (opts.find("read") != opts.end())
2380 special << "read=" << opts["read"] << ',';
2381 if (opts.find("command") != opts.end())
2382 special << "command=" << opts["command"] << ',';
2383 string s_special = special.str();
2384 if (!s_special.empty()) {
2385 // We had special arguments. Remove the trailing ','.
2386 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2388 // TODO: Handle the unknown settings better.
2389 // Warn about invalid options.
2390 // Check whether some option was given twice.
2394 else if (t.cs() == "footnote" ||
2395 (t.cs() == "thanks" && context.layout->intitle)) {
2397 context.check_layout(os);
2398 begin_inset(os, "Foot\n");
2399 os << "status collapsed\n\n";
2400 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2404 else if (t.cs() == "marginpar") {
2406 context.check_layout(os);
2407 begin_inset(os, "Marginal\n");
2408 os << "status collapsed\n\n";
2409 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2413 else if (t.cs() == "ensuremath") {
2415 context.check_layout(os);
2416 string const s = p.verbatim_item();
2417 //FIXME: this never triggers in UTF8
2418 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2421 handle_ert(os, "\\ensuremath{" + s + "}",
2425 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2426 // FIXME: Somehow prevent title layouts if
2427 // "maketitle" was not found
2429 skip_spaces_braces(p);
2432 else if (t.cs() == "tableofcontents") {
2433 context.check_layout(os);
2434 begin_command_inset(os, "toc", "tableofcontents");
2436 skip_spaces_braces(p);
2439 else if (t.cs() == "listoffigures") {
2440 context.check_layout(os);
2441 begin_inset(os, "FloatList figure\n");
2443 skip_spaces_braces(p);
2446 else if (t.cs() == "listoftables") {
2447 context.check_layout(os);
2448 begin_inset(os, "FloatList table\n");
2450 skip_spaces_braces(p);
2453 else if (t.cs() == "listof") {
2454 p.skip_spaces(true);
2455 string const name = p.get_token().cs();
2456 if (context.textclass.floats().typeExist(name)) {
2457 context.check_layout(os);
2458 begin_inset(os, "FloatList ");
2461 p.get_token(); // swallow second arg
2463 handle_ert(os, "\\listof{" + name + "}", context);
2466 else if (t.cs() == "textrm")
2467 parse_text_attributes(p, os, FLAG_ITEM, outer,
2468 context, "\\family",
2469 context.font.family, "roman");
2471 else if (t.cs() == "textsf")
2472 parse_text_attributes(p, os, FLAG_ITEM, outer,
2473 context, "\\family",
2474 context.font.family, "sans");
2476 else if (t.cs() == "texttt")
2477 parse_text_attributes(p, os, FLAG_ITEM, outer,
2478 context, "\\family",
2479 context.font.family, "typewriter");
2481 else if (t.cs() == "textmd")
2482 parse_text_attributes(p, os, FLAG_ITEM, outer,
2483 context, "\\series",
2484 context.font.series, "medium");
2486 else if (t.cs() == "textbf")
2487 parse_text_attributes(p, os, FLAG_ITEM, outer,
2488 context, "\\series",
2489 context.font.series, "bold");
2491 else if (t.cs() == "textup")
2492 parse_text_attributes(p, os, FLAG_ITEM, outer,
2494 context.font.shape, "up");
2496 else if (t.cs() == "textit")
2497 parse_text_attributes(p, os, FLAG_ITEM, outer,
2499 context.font.shape, "italic");
2501 else if (t.cs() == "textsl")
2502 parse_text_attributes(p, os, FLAG_ITEM, outer,
2504 context.font.shape, "slanted");
2506 else if (t.cs() == "textsc")
2507 parse_text_attributes(p, os, FLAG_ITEM, outer,
2509 context.font.shape, "smallcaps");
2511 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2512 context.check_layout(os);
2513 TeXFont oldFont = context.font;
2514 context.font.init();
2515 context.font.size = oldFont.size;
2516 os << "\n\\family " << context.font.family << "\n";
2517 os << "\n\\series " << context.font.series << "\n";
2518 os << "\n\\shape " << context.font.shape << "\n";
2519 if (t.cs() == "textnormal") {
2520 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2521 output_font_change(os, context.font, oldFont);
2522 context.font = oldFont;
2524 eat_whitespace(p, os, context, false);
2527 else if (t.cs() == "textcolor") {
2528 // scheme is \textcolor{color name}{text}
2529 string const color = p.verbatim_item();
2530 // we only support the predefined colors of the color package
2531 if (color == "black" || color == "blue" || color == "cyan"
2532 || color == "green" || color == "magenta" || color == "red"
2533 || color == "white" || color == "yellow") {
2534 context.check_layout(os);
2535 os << "\n\\color " << color << "\n";
2536 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2537 context.check_layout(os);
2538 os << "\n\\color inherit\n";
2540 // for custom defined colors
2541 handle_ert(os, t.asInput() + "{" + color + "}", context);
2544 else if (t.cs() == "underbar" || t.cs() == "uline") {
2545 // \underbar is not 100% correct (LyX outputs \uline
2546 // of ulem.sty). The difference is that \ulem allows
2547 // line breaks, and \underbar does not.
2548 // Do NOT handle \underline.
2549 // \underbar cuts through y, g, q, p etc.,
2550 // \underline does not.
2551 context.check_layout(os);
2552 os << "\n\\bar under\n";
2553 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2554 context.check_layout(os);
2555 os << "\n\\bar default\n";
2558 else if (t.cs() == "sout") {
2559 context.check_layout(os);
2560 os << "\n\\strikeout on\n";
2561 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2562 context.check_layout(os);
2563 os << "\n\\strikeout default\n";
2566 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2567 t.cs() == "emph" || t.cs() == "noun") {
2568 context.check_layout(os);
2569 os << "\n\\" << t.cs() << " on\n";
2570 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2571 context.check_layout(os);
2572 os << "\n\\" << t.cs() << " default\n";
2575 // FIXME, the inset layout should be plain, not standard, see bug #7846
2576 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2577 t.cs() == "vphantom") {
2578 context.check_layout(os);
2579 if (t.cs() == "phantom")
2580 begin_inset(os, "Phantom Phantom\n");
2581 if (t.cs() == "hphantom")
2582 begin_inset(os, "Phantom HPhantom\n");
2583 if (t.cs() == "vphantom")
2584 begin_inset(os, "Phantom VPhantom\n");
2585 os << "status open\n";
2586 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2590 else if (t.cs() == "href") {
2591 context.check_layout(os);
2592 string target = p.getArg('{', '}');
2593 string name = p.getArg('{', '}');
2595 size_t i = target.find(':');
2596 if (i != string::npos) {
2597 type = target.substr(0, i + 1);
2598 if (type == "mailto:" || type == "file:")
2599 target = target.substr(i + 1);
2600 // handle the case that name is equal to target, except of "http://"
2601 else if (target.substr(i + 3) == name && type == "http:")
2604 begin_command_inset(os, "href", "href");
2606 os << "name \"" << name << "\"\n";
2607 os << "target \"" << target << "\"\n";
2608 if (type == "mailto:" || type == "file:")
2609 os << "type \"" << type << "\"\n";
2611 skip_spaces_braces(p);
2614 else if (t.cs() == "lyxline") {
2615 // swallow size argument (it is not used anyway)
2617 if (!context.atParagraphStart()) {
2618 // so our line is in the middle of a paragraph
2619 // we need to add a new line, lest this line
2620 // follow the other content on that line and
2621 // run off the side of the page
2622 // FIXME: This may create an empty paragraph,
2623 // but without that it would not be
2624 // possible to set noindent below.
2625 // Fortunately LaTeX does not care
2626 // about the empty paragraph.
2627 context.new_paragraph(os);
2629 if (preamble.indentParagraphs()) {
2630 // we need to unindent, lest the line be too long
2631 context.add_par_extra_stuff("\\noindent\n");
2633 context.check_layout(os);
2634 begin_command_inset(os, "line", "rule");
2635 os << "offset \"0.5ex\"\n"
2636 "width \"100line%\"\n"
2641 else if (t.cs() == "rule") {
2642 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2643 string const width = p.getArg('{', '}');
2644 string const thickness = p.getArg('{', '}');
2645 context.check_layout(os);
2646 begin_command_inset(os, "line", "rule");
2647 if (!offset.empty())
2648 os << "offset \"" << translate_len(offset) << "\"\n";
2649 os << "width \"" << translate_len(width) << "\"\n"
2650 "height \"" << translate_len(thickness) << "\"\n";
2654 else if (is_known(t.cs(), known_phrases) ||
2655 (t.cs() == "protect" &&
2656 p.next_token().cat() == catEscape &&
2657 is_known(p.next_token().cs(), known_phrases))) {
2658 // LyX sometimes puts a \protect in front, so we have to ignore it
2659 // FIXME: This needs to be changed when bug 4752 is fixed.
2660 char const * const * where = is_known(
2661 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2663 context.check_layout(os);
2664 os << known_coded_phrases[where - known_phrases];
2665 skip_spaces_braces(p);
2668 else if (is_known(t.cs(), known_ref_commands)) {
2669 string const opt = p.getOpt();
2671 context.check_layout(os);
2672 char const * const * where = is_known(t.cs(),
2673 known_ref_commands);
2674 begin_command_inset(os, "ref",
2675 known_coded_ref_commands[where - known_ref_commands]);
2676 os << "reference \""
2677 << convert_command_inset_arg(p.verbatim_item())
2681 // LyX does not support optional arguments of ref commands
2682 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2683 p.verbatim_item() + "}", context);
2687 else if (use_natbib &&
2688 is_known(t.cs(), known_natbib_commands) &&
2689 ((t.cs() != "citefullauthor" &&
2690 t.cs() != "citeyear" &&
2691 t.cs() != "citeyearpar") ||
2692 p.next_token().asInput() != "*")) {
2693 context.check_layout(os);
2694 string command = t.cs();
2695 if (p.next_token().asInput() == "*") {
2699 if (command == "citefullauthor")
2700 // alternative name for "\\citeauthor*"
2701 command = "citeauthor*";
2703 // text before the citation
2705 // text after the citation
2707 get_cite_arguments(p, true, before, after);
2709 if (command == "cite") {
2710 // \cite without optional argument means
2711 // \citet, \cite with at least one optional
2712 // argument means \citep.
2713 if (before.empty() && after.empty())
2718 if (before.empty() && after == "[]")
2719 // avoid \citet[]{a}
2721 else if (before == "[]" && after == "[]") {
2722 // avoid \citet[][]{a}
2726 // remove the brackets around after and before
2727 if (!after.empty()) {
2729 after.erase(after.length() - 1, 1);
2730 after = convert_command_inset_arg(after);
2732 if (!before.empty()) {
2734 before.erase(before.length() - 1, 1);
2735 before = convert_command_inset_arg(before);
2737 begin_command_inset(os, "citation", command);
2738 os << "after " << '"' << after << '"' << "\n";
2739 os << "before " << '"' << before << '"' << "\n";
2741 << convert_command_inset_arg(p.verbatim_item())
2746 else if (use_jurabib &&
2747 is_known(t.cs(), known_jurabib_commands) &&
2748 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2749 context.check_layout(os);
2750 string command = t.cs();
2751 if (p.next_token().asInput() == "*") {
2755 char argumentOrder = '\0';
2756 vector<string> const options =
2757 preamble.getPackageOptions("jurabib");
2758 if (find(options.begin(), options.end(),
2759 "natbiborder") != options.end())
2760 argumentOrder = 'n';
2761 else if (find(options.begin(), options.end(),
2762 "jurabiborder") != options.end())
2763 argumentOrder = 'j';
2765 // text before the citation
2767 // text after the citation
2769 get_cite_arguments(p, argumentOrder != 'j', before, after);
2771 string const citation = p.verbatim_item();
2772 if (!before.empty() && argumentOrder == '\0') {
2773 cerr << "Warning: Assuming argument order "
2774 "of jurabib version 0.6 for\n'"
2775 << command << before << after << '{'
2776 << citation << "}'.\n"
2777 "Add 'jurabiborder' to the jurabib "
2778 "package options if you used an\n"
2779 "earlier jurabib version." << endl;
2781 if (!after.empty()) {
2783 after.erase(after.length() - 1, 1);
2785 if (!before.empty()) {
2787 before.erase(before.length() - 1, 1);
2789 begin_command_inset(os, "citation", command);
2790 os << "after " << '"' << after << '"' << "\n";
2791 os << "before " << '"' << before << '"' << "\n";
2792 os << "key " << '"' << citation << '"' << "\n";
2796 else if (t.cs() == "cite"
2797 || t.cs() == "nocite") {
2798 context.check_layout(os);
2799 string after = convert_command_inset_arg(p.getArg('[', ']'));
2800 string key = convert_command_inset_arg(p.verbatim_item());
2801 // store the case that it is "\nocite{*}" to use it later for
2804 begin_command_inset(os, "citation", t.cs());
2805 os << "after " << '"' << after << '"' << "\n";
2806 os << "key " << '"' << key << '"' << "\n";
2808 } else if (t.cs() == "nocite")
2812 else if (t.cs() == "index") {
2813 context.check_layout(os);
2814 begin_inset(os, "Index idx\n");
2815 os << "status collapsed\n";
2816 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2820 else if (t.cs() == "nomenclature") {
2821 context.check_layout(os);
2822 begin_command_inset(os, "nomenclature", "nomenclature");
2823 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2824 if (!prefix.empty())
2825 os << "prefix " << '"' << prefix << '"' << "\n";
2826 os << "symbol " << '"'
2827 << convert_command_inset_arg(p.verbatim_item());
2828 os << "\"\ndescription \""
2829 << convert_command_inset_arg(p.verbatim_item())
2834 else if (t.cs() == "label") {
2835 context.check_layout(os);
2836 begin_command_inset(os, "label", "label");
2838 << convert_command_inset_arg(p.verbatim_item())
2843 else if (t.cs() == "printindex") {
2844 context.check_layout(os);
2845 begin_command_inset(os, "index_print", "printindex");
2846 os << "type \"idx\"\n";
2848 skip_spaces_braces(p);
2851 else if (t.cs() == "printnomenclature") {
2853 string width_type = "";
2854 context.check_layout(os);
2855 begin_command_inset(os, "nomencl_print", "printnomenclature");
2856 // case of a custom width
2858 width = p.getArg('[', ']');
2859 width = translate_len(width);
2860 width_type = "custom";
2862 // case of no custom width
2863 // the case of no custom width but the width set
2864 // via \settowidth{\nomlabelwidth}{***} cannot be supported
2865 // because the user could have set anything, not only the width
2866 // of the longest label (which would be width_type = "auto")
2867 string label = convert_command_inset_arg(p.getArg('{', '}'));
2868 if (label.empty() && width_type.empty())
2869 width_type = "none";
2870 os << "set_width \"" << width_type << "\"\n";
2871 if (width_type == "custom")
2872 os << "width \"" << width << '\"';
2874 skip_spaces_braces(p);
2877 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2878 context.check_layout(os);
2879 begin_inset(os, "script ");
2880 os << t.cs().substr(4) << '\n';
2881 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2885 else if (is_known(t.cs(), known_quotes)) {
2886 char const * const * where = is_known(t.cs(), known_quotes);
2887 context.check_layout(os);
2888 begin_inset(os, "Quotes ");
2889 os << known_coded_quotes[where - known_quotes];
2891 // LyX adds {} after the quote, so we have to eat
2892 // spaces here if there are any before a possible
2894 eat_whitespace(p, os, context, false);
2898 else if (is_known(t.cs(), known_sizes) &&
2899 context.new_layout_allowed) {
2900 char const * const * where = is_known(t.cs(), known_sizes);
2901 context.check_layout(os);
2902 TeXFont const oldFont = context.font;
2903 context.font.size = known_coded_sizes[where - known_sizes];
2904 output_font_change(os, oldFont, context.font);
2905 eat_whitespace(p, os, context, false);
2908 else if (is_known(t.cs(), known_font_families) &&
2909 context.new_layout_allowed) {
2910 char const * const * where =
2911 is_known(t.cs(), known_font_families);
2912 context.check_layout(os);
2913 TeXFont const oldFont = context.font;
2914 context.font.family =
2915 known_coded_font_families[where - known_font_families];
2916 output_font_change(os, oldFont, context.font);
2917 eat_whitespace(p, os, context, false);
2920 else if (is_known(t.cs(), known_font_series) &&
2921 context.new_layout_allowed) {
2922 char const * const * where =
2923 is_known(t.cs(), known_font_series);
2924 context.check_layout(os);
2925 TeXFont const oldFont = context.font;
2926 context.font.series =
2927 known_coded_font_series[where - known_font_series];
2928 output_font_change(os, oldFont, context.font);
2929 eat_whitespace(p, os, context, false);
2932 else if (is_known(t.cs(), known_font_shapes) &&
2933 context.new_layout_allowed) {
2934 char const * const * where =
2935 is_known(t.cs(), known_font_shapes);
2936 context.check_layout(os);
2937 TeXFont const oldFont = context.font;
2938 context.font.shape =
2939 known_coded_font_shapes[where - known_font_shapes];
2940 output_font_change(os, oldFont, context.font);
2941 eat_whitespace(p, os, context, false);
2943 else if (is_known(t.cs(), known_old_font_families) &&
2944 context.new_layout_allowed) {
2945 char const * const * where =
2946 is_known(t.cs(), known_old_font_families);
2947 context.check_layout(os);
2948 TeXFont const oldFont = context.font;
2949 context.font.init();
2950 context.font.size = oldFont.size;
2951 context.font.family =
2952 known_coded_font_families[where - known_old_font_families];
2953 output_font_change(os, oldFont, context.font);
2954 eat_whitespace(p, os, context, false);
2957 else if (is_known(t.cs(), known_old_font_series) &&
2958 context.new_layout_allowed) {
2959 char const * const * where =
2960 is_known(t.cs(), known_old_font_series);
2961 context.check_layout(os);
2962 TeXFont const oldFont = context.font;
2963 context.font.init();
2964 context.font.size = oldFont.size;
2965 context.font.series =
2966 known_coded_font_series[where - known_old_font_series];
2967 output_font_change(os, oldFont, context.font);
2968 eat_whitespace(p, os, context, false);
2971 else if (is_known(t.cs(), known_old_font_shapes) &&
2972 context.new_layout_allowed) {
2973 char const * const * where =
2974 is_known(t.cs(), known_old_font_shapes);
2975 context.check_layout(os);
2976 TeXFont const oldFont = context.font;
2977 context.font.init();
2978 context.font.size = oldFont.size;
2979 context.font.shape =
2980 known_coded_font_shapes[where - known_old_font_shapes];
2981 output_font_change(os, oldFont, context.font);
2982 eat_whitespace(p, os, context, false);
2985 else if (t.cs() == "selectlanguage") {
2986 context.check_layout(os);
2987 // save the language for the case that a
2988 // \foreignlanguage is used
2990 context.font.language = babel2lyx(p.verbatim_item());
2991 os << "\n\\lang " << context.font.language << "\n";
2994 else if (t.cs() == "foreignlanguage") {
2995 string const lang = babel2lyx(p.verbatim_item());
2996 parse_text_attributes(p, os, FLAG_ITEM, outer,
2998 context.font.language, lang);
3001 else if (t.cs() == "inputencoding") {
3002 // nothing to write here
3003 string const enc = subst(p.verbatim_item(), "\n", " ");
3007 else if (t.cs() == "ldots") {
3008 context.check_layout(os);
3009 os << "\\SpecialChar \\ldots{}\n";
3010 skip_spaces_braces(p);
3013 else if (t.cs() == "lyxarrow") {
3014 context.check_layout(os);
3015 os << "\\SpecialChar \\menuseparator\n";
3016 skip_spaces_braces(p);
3019 else if (t.cs() == "textcompwordmark") {
3020 context.check_layout(os);
3021 os << "\\SpecialChar \\textcompwordmark{}\n";
3022 skip_spaces_braces(p);
3025 else if (t.cs() == "slash") {
3026 context.check_layout(os);
3027 os << "\\SpecialChar \\slash{}\n";
3028 skip_spaces_braces(p);
3031 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3032 context.check_layout(os);
3033 os << "\\SpecialChar \\nobreakdash-\n";
3037 else if (t.cs() == "textquotedbl") {
3038 context.check_layout(os);
3043 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3044 context.check_layout(os);
3045 os << "\\SpecialChar \\@.\n";
3049 else if (t.cs() == "-") {
3050 context.check_layout(os);
3051 os << "\\SpecialChar \\-\n";
3054 else if (t.cs() == "textasciitilde") {
3055 context.check_layout(os);
3057 skip_spaces_braces(p);
3060 else if (t.cs() == "textasciicircum") {
3061 context.check_layout(os);
3063 skip_spaces_braces(p);
3066 else if (t.cs() == "textbackslash") {
3067 context.check_layout(os);
3068 os << "\n\\backslash\n";
3069 skip_spaces_braces(p);
3072 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3073 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3075 context.check_layout(os);
3079 else if (t.cs() == "char") {
3080 context.check_layout(os);
3081 if (p.next_token().character() == '`') {
3083 if (p.next_token().cs() == "\"") {
3088 handle_ert(os, "\\char`", context);
3091 handle_ert(os, "\\char", context);
3095 else if (t.cs() == "verb") {
3096 context.check_layout(os);
3097 char const delimiter = p.next_token().character();
3098 string const arg = p.getArg(delimiter, delimiter);
3100 oss << "\\verb" << delimiter << arg << delimiter;
3101 handle_ert(os, oss.str(), context);
3104 // Problem: \= creates a tabstop inside the tabbing environment
3105 // and else an accent. In the latter case we really would want
3106 // \={o} instead of \= o.
3107 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3108 handle_ert(os, t.asInput(), context);
3110 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3111 else if (t.cs().size() == 1
3112 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3113 context.check_layout(os);
3114 // try to see whether the string is in unicodesymbols
3116 string command = t.asInput() + "{"
3117 + trimSpaceAndEol(p.verbatim_item())
3119 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3122 cerr << "When parsing " << command
3123 << ", result is " << to_utf8(s)
3124 << "+" << to_utf8(rem) << endl;
3127 // we did not find a non-ert version
3128 handle_ert(os, command, context);
3131 else if (t.cs() == "\\") {
3132 context.check_layout(os);
3134 handle_ert(os, "\\\\" + p.getOpt(), context);
3135 else if (p.next_token().asInput() == "*") {
3137 // getOpt() eats the following space if there
3138 // is no optional argument, but that is OK
3139 // here since it has no effect in the output.
3140 handle_ert(os, "\\\\*" + p.getOpt(), context);
3143 begin_inset(os, "Newline newline");
3148 else if (t.cs() == "newline" ||
3149 (t.cs() == "linebreak" && !p.hasOpt())) {
3150 context.check_layout(os);
3151 begin_inset(os, "Newline ");
3154 skip_spaces_braces(p);
3157 else if (t.cs() == "input" || t.cs() == "include"
3158 || t.cs() == "verbatiminput") {
3159 string name = t.cs();
3160 if (t.cs() == "verbatiminput"
3161 && p.next_token().asInput() == "*")
3162 name += p.get_token().asInput();
3163 context.check_layout(os);
3164 string filename(normalize_filename(p.getArg('{', '}')));
3165 string const path = getMasterFilePath();
3166 // We want to preserve relative / absolute filenames,
3167 // therefore path is only used for testing
3168 if ((t.cs() == "include" || t.cs() == "input") &&
3169 !makeAbsPath(filename, path).exists()) {
3170 // The file extension is probably missing.
3171 // Now try to find it out.
3172 string const tex_name =
3173 find_file(filename, path,
3174 known_tex_extensions);
3175 if (!tex_name.empty())
3176 filename = tex_name;
3178 bool external = false;
3180 if (makeAbsPath(filename, path).exists()) {
3181 string const abstexname =
3182 makeAbsPath(filename, path).absFileName();
3183 string const abslyxname =
3184 changeExtension(abstexname, ".lyx");
3185 string const absfigname =
3186 changeExtension(abstexname, ".fig");
3187 fix_relative_filename(filename);
3188 string const lyxname =
3189 changeExtension(filename, ".lyx");
3191 external = FileName(absfigname).exists();
3192 if (t.cs() == "input") {
3193 string const ext = getExtension(abstexname);
3195 // Combined PS/LaTeX:
3196 // x.eps, x.pstex_t (old xfig)
3197 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3198 FileName const absepsname(
3199 changeExtension(abstexname, ".eps"));
3200 FileName const abspstexname(
3201 changeExtension(abstexname, ".pstex"));
3202 bool const xfigeps =
3203 (absepsname.exists() ||
3204 abspstexname.exists()) &&
3207 // Combined PDF/LaTeX:
3208 // x.pdf, x.pdftex_t (old xfig)
3209 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3210 FileName const abspdfname(
3211 changeExtension(abstexname, ".pdf"));
3212 bool const xfigpdf =
3213 abspdfname.exists() &&
3214 (ext == "pdftex_t" || ext == "pdf_t");
3218 // Combined PS/PDF/LaTeX:
3219 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3220 string const absbase2(
3221 removeExtension(abstexname) + "_pspdftex");
3222 FileName const abseps2name(
3223 addExtension(absbase2, ".eps"));
3224 FileName const abspdf2name(
3225 addExtension(absbase2, ".pdf"));
3226 bool const xfigboth =
3227 abspdf2name.exists() &&
3228 abseps2name.exists() && ext == "pspdftex";
3230 xfig = xfigpdf || xfigeps || xfigboth;
3231 external = external && xfig;
3234 outname = changeExtension(filename, ".fig");
3236 // Don't try to convert, the result
3237 // would be full of ERT.
3239 } else if (t.cs() != "verbatiminput" &&
3240 tex2lyx(abstexname, FileName(abslyxname),
3247 cerr << "Warning: Could not find included file '"
3248 << filename << "'." << endl;
3252 begin_inset(os, "External\n");
3253 os << "\ttemplate XFig\n"
3254 << "\tfilename " << outname << '\n';
3256 begin_command_inset(os, "include", name);
3257 os << "preview false\n"
3258 "filename \"" << outname << "\"\n";
3263 else if (t.cs() == "bibliographystyle") {
3264 // store new bibliographystyle
3265 bibliographystyle = p.verbatim_item();
3266 // If any other command than \bibliography and
3267 // \nocite{*} follows, we need to output the style
3268 // (because it might be used by that command).
3269 // Otherwise, it will automatically be output by LyX.
3272 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3273 if (t2.cat() == catBegin)
3275 if (t2.cat() != catEscape)
3277 if (t2.cs() == "nocite") {
3278 if (p.getArg('{', '}') == "*")
3280 } else if (t2.cs() == "bibliography")
3287 "\\bibliographystyle{" + bibliographystyle + '}',
3292 else if (t.cs() == "bibliography") {
3293 context.check_layout(os);
3294 begin_command_inset(os, "bibtex", "bibtex");
3295 if (!btprint.empty()) {
3296 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3297 // clear the string because the next BibTeX inset can be without the
3298 // \nocite{*} option
3301 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3302 // Do we have a bibliographystyle set?
3303 if (!bibliographystyle.empty())
3304 os << "options " << '"' << bibliographystyle << '"' << "\n";
3308 else if (t.cs() == "parbox")
3309 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3311 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3312 t.cs() == "shadowbox" || t.cs() == "doublebox")
3313 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3315 else if (t.cs() == "framebox") {
3316 string special = p.getFullOpt();
3317 special += p.getOpt();
3318 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3321 //\makebox() is part of the picture environment and different from \makebox{}
3322 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3323 else if (t.cs() == "makebox") {
3324 string arg = t.asInput();
3325 if (p.next_token().character() == '(')
3326 //the syntax is: \makebox(x,y)[position]{content}
3327 arg += p.getFullParentheseArg();
3329 //the syntax is: \makebox[width][position]{content}
3330 arg += p.getFullOpt();
3331 handle_ert(os, arg + p.getFullOpt(), context);
3334 else if (t.cs() == "smallskip" ||
3335 t.cs() == "medskip" ||
3336 t.cs() == "bigskip" ||
3337 t.cs() == "vfill") {
3338 context.check_layout(os);
3339 begin_inset(os, "VSpace ");
3342 skip_spaces_braces(p);
3345 else if (is_known(t.cs(), known_spaces)) {
3346 char const * const * where = is_known(t.cs(), known_spaces);
3347 context.check_layout(os);
3348 begin_inset(os, "space ");
3349 os << '\\' << known_coded_spaces[where - known_spaces]
3352 // LaTeX swallows whitespace after all spaces except
3353 // "\\,". We have to do that here, too, because LyX
3354 // adds "{}" which would make the spaces significant.
3356 eat_whitespace(p, os, context, false);
3357 // LyX adds "{}" after all spaces except "\\ " and
3358 // "\\,", so we have to remove "{}".
3359 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3360 // remove the braces after "\\,", too.
3365 else if (t.cs() == "newpage" ||
3366 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3367 t.cs() == "clearpage" ||
3368 t.cs() == "cleardoublepage") {
3369 context.check_layout(os);
3370 begin_inset(os, "Newpage ");
3373 skip_spaces_braces(p);
3376 else if (t.cs() == "DeclareRobustCommand" ||
3377 t.cs() == "DeclareRobustCommandx" ||
3378 t.cs() == "newcommand" ||
3379 t.cs() == "newcommandx" ||
3380 t.cs() == "providecommand" ||
3381 t.cs() == "providecommandx" ||
3382 t.cs() == "renewcommand" ||
3383 t.cs() == "renewcommandx") {
3384 // DeclareRobustCommand, DeclareRobustCommandx,
3385 // providecommand and providecommandx could be handled
3386 // by parse_command(), but we need to call
3387 // add_known_command() here.
3388 string name = t.asInput();
3389 if (p.next_token().asInput() == "*") {
3390 // Starred form. Eat '*'
3394 string const command = p.verbatim_item();
3395 string const opt1 = p.getFullOpt();
3396 string const opt2 = p.getFullOpt();
3397 add_known_command(command, opt1, !opt2.empty());
3398 string const ert = name + '{' + command + '}' +
3400 '{' + p.verbatim_item() + '}';
3402 if (t.cs() == "DeclareRobustCommand" ||
3403 t.cs() == "DeclareRobustCommandx" ||
3404 t.cs() == "providecommand" ||
3405 t.cs() == "providecommandx" ||
3406 name[name.length()-1] == '*')
3407 handle_ert(os, ert, context);
3409 context.check_layout(os);
3410 begin_inset(os, "FormulaMacro");
3416 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3417 // let could be handled by parse_command(),
3418 // but we need to call add_known_command() here.
3419 string ert = t.asInput();
3422 if (p.next_token().cat() == catBegin) {
3423 name = p.verbatim_item();
3424 ert += '{' + name + '}';
3426 name = p.verbatim_item();
3431 if (p.next_token().cat() == catBegin) {
3432 command = p.verbatim_item();
3433 ert += '{' + command + '}';
3435 command = p.verbatim_item();
3438 // If command is known, make name known too, to parse
3439 // its arguments correctly. For this reason we also
3440 // have commands in syntax.default that are hardcoded.
3441 CommandMap::iterator it = known_commands.find(command);
3442 if (it != known_commands.end())
3443 known_commands[t.asInput()] = it->second;
3444 handle_ert(os, ert, context);
3447 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3448 bool starred = false;
3449 if (p.next_token().asInput() == "*") {
3453 string name = t.asInput();
3454 string const length = p.verbatim_item();
3457 bool valid = splitLatexLength(length, valstring, unit);
3458 bool known_hspace = false;
3459 bool known_vspace = false;
3460 bool known_unit = false;
3463 istringstream iss(valstring);
3466 if (t.cs()[0] == 'h') {
3467 if (unit == "\\fill") {
3472 known_hspace = true;
3475 if (unit == "\\smallskipamount") {
3477 known_vspace = true;
3478 } else if (unit == "\\medskipamount") {
3480 known_vspace = true;
3481 } else if (unit == "\\bigskipamount") {
3483 known_vspace = true;
3484 } else if (unit == "\\fill") {
3486 known_vspace = true;
3490 if (!known_hspace && !known_vspace) {
3491 switch (unitFromString(unit)) {
3512 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3513 // Literal horizontal length or known variable
3514 context.check_layout(os);
3515 begin_inset(os, "space ");
3523 if (known_unit && !known_hspace)
3525 << translate_len(length);
3527 } else if (known_unit || known_vspace) {
3528 // Literal vertical length or known variable
3529 context.check_layout(os);
3530 begin_inset(os, "VSpace ");
3538 // LyX can't handle other length variables in Inset VSpace/space
3543 handle_ert(os, name + '{' + unit + '}', context);
3544 else if (value == -1.0)
3545 handle_ert(os, name + "{-" + unit + '}', context);
3547 handle_ert(os, name + '{' + valstring + unit + '}', context);
3549 handle_ert(os, name + '{' + length + '}', context);
3553 // The single '=' is meant here.
3554 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3556 context.check_layout(os);
3557 begin_inset(os, "Flex ");
3558 os << to_utf8(newinsetlayout->name()) << '\n'
3559 << "status collapsed\n";
3560 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3565 // try to see whether the string is in unicodesymbols
3566 // Only use text mode commands, since we are in text mode here,
3567 // and math commands may be invalid (bug 6797)
3569 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3570 rem, Encodings::TEXT_CMD);
3573 cerr << "When parsing " << t.cs()
3574 << ", result is " << to_utf8(s)
3575 << "+" << to_utf8(rem) << endl;
3576 context.check_layout(os);
3578 skip_spaces_braces(p);
3580 //cerr << "#: " << t << " mode: " << mode << endl;
3581 // heuristic: read up to next non-nested space
3583 string s = t.asInput();
3584 string z = p.verbatim_item();
3585 while (p.good() && z != " " && z.size()) {
3586 //cerr << "read: " << z << endl;
3588 z = p.verbatim_item();
3590 cerr << "found ERT: " << s << endl;
3591 handle_ert(os, s + ' ', context);
3594 string name = t.asInput();
3595 if (p.next_token().asInput() == "*") {
3596 // Starred commands like \vspace*{}
3597 p.get_token(); // Eat '*'
3600 if (!parse_command(name, p, os, outer, context))
3601 handle_ert(os, name, context);
3605 if (flags & FLAG_LEAVE) {
3606 flags &= ~FLAG_LEAVE;