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 preamble.registerAutomaticallyLoadedPackage("color");
869 } else if (outer_type == "doublebox")
871 else if (outer_type.empty())
874 os << outer_type << '\n';
875 os << "position \"" << position << "\"\n";
876 os << "hor_pos \"" << hor_pos << "\"\n";
877 os << "has_inner_box " << !inner_type.empty() << "\n";
878 os << "inner_pos \"" << inner_pos << "\"\n";
879 os << "use_parbox " << (inner_type == "parbox") << '\n';
880 os << "use_makebox 0\n";
881 os << "width \"" << width_value << width_unit << "\"\n";
882 os << "special \"none\"\n";
883 os << "height \"" << height_value << height_unit << "\"\n";
884 os << "height_special \"" << height_special << "\"\n";
885 os << "status open\n\n";
886 Context context(true, parent_context.textclass);
887 context.font = parent_context.font;
889 // FIXME, the inset layout should be plain, not standard, see bug #7846
891 // If we have no inner box the contens will be read with the outer box
892 if (!inner_type.empty())
893 parse_text(p, os, inner_flags, outer, context);
895 // Ensure that the end of the outer box is parsed correctly:
896 // The opening brace has been eaten by parse_outer_box()
897 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
898 outer_flags &= ~FLAG_ITEM;
899 outer_flags |= FLAG_BRACE_LAST;
902 // Find end of outer box, output contents if inner_type is
903 // empty and output possible comments
904 if (!outer_type.empty()) {
905 // This does not output anything but comments if
906 // inner_type is not empty (see use_ert)
907 parse_text(p, os, outer_flags, outer, context);
910 context.check_end_layout(os);
912 #ifdef PRESERVE_LAYOUT
913 // LyX puts a % after the end of the minipage
914 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
916 //handle_comment(os, "%dummy", parent_context);
919 parent_context.new_paragraph(os);
921 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
922 //handle_comment(os, "%dummy", parent_context);
925 // We add a protected space if something real follows
926 if (p.good() && p.next_token().cat() != catComment) {
927 begin_inset(os, "space ~\n");
936 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
937 Context & parent_context, string const & outer_type,
938 string const & special)
940 eat_whitespace(p, os, parent_context, false);
941 if (flags & FLAG_ITEM) {
943 if (p.next_token().cat() == catBegin)
946 cerr << "Warning: Ignoring missing '{' after \\"
947 << outer_type << '.' << endl;
948 eat_whitespace(p, os, parent_context, false);
951 unsigned int inner_flags = 0;
952 if (outer_type == "shaded") {
953 // These boxes never have an inner box
955 } else if (p.next_token().asInput() == "\\parbox") {
956 inner = p.get_token().cs();
957 inner_flags = FLAG_ITEM;
958 } else if (p.next_token().asInput() == "\\begin") {
959 // Is this a minipage?
962 inner = p.getArg('{', '}');
964 if (inner == "minipage") {
967 eat_whitespace(p, os, parent_context, false);
968 inner_flags = FLAG_END;
972 if (inner_flags == FLAG_END) {
973 active_environments.push_back(inner);
974 parse_box(p, os, flags, FLAG_END, outer, parent_context,
975 outer_type, special, inner);
976 active_environments.pop_back();
978 parse_box(p, os, flags, inner_flags, outer, parent_context,
979 outer_type, special, inner);
984 void parse_listings(Parser & p, ostream & os, Context & parent_context)
986 parent_context.check_layout(os);
987 begin_inset(os, "listings\n");
988 os << "inline false\n"
989 << "status collapsed\n";
990 Context context(true, parent_context.textclass);
991 context.layout = &parent_context.textclass.plainLayout();
992 context.check_layout(os);
993 string const s = p.verbatimEnvironment("lstlisting");
994 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
996 os << "\n\\backslash\n";
997 else if (*it == '\n') {
998 // avoid adding an empty paragraph at the end
1000 context.new_paragraph(os);
1001 context.check_layout(os);
1006 context.check_end_layout(os);
1011 /// parse an unknown environment
1012 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1013 unsigned flags, bool outer,
1014 Context & parent_context)
1016 if (name == "tabbing")
1017 // We need to remember that we have to handle '\=' specially
1018 flags |= FLAG_TABBING;
1020 // We need to translate font changes and paragraphs inside the
1021 // environment to ERT if we have a non standard font.
1022 // Otherwise things like
1023 // \large\begin{foo}\huge bar\end{foo}
1025 bool const specialfont =
1026 (parent_context.font != parent_context.normalfont);
1027 bool const new_layout_allowed = parent_context.new_layout_allowed;
1029 parent_context.new_layout_allowed = false;
1030 handle_ert(os, "\\begin{" + name + "}", parent_context);
1031 parse_text_snippet(p, os, flags, outer, parent_context);
1032 handle_ert(os, "\\end{" + name + "}", parent_context);
1034 parent_context.new_layout_allowed = new_layout_allowed;
1038 void parse_environment(Parser & p, ostream & os, bool outer,
1039 string & last_env, bool & title_layout_found,
1040 Context & parent_context)
1042 Layout const * newlayout;
1043 InsetLayout const * newinsetlayout = 0;
1044 string const name = p.getArg('{', '}');
1045 const bool is_starred = suffixIs(name, '*');
1046 string const unstarred_name = rtrim(name, "*");
1047 active_environments.push_back(name);
1049 if (is_math_env(name)) {
1050 parent_context.check_layout(os);
1051 begin_inset(os, "Formula ");
1052 os << "\\begin{" << name << "}";
1053 parse_math(p, os, FLAG_END, MATH_MODE);
1054 os << "\\end{" << name << "}";
1058 else if (name == "tabular" || name == "longtable") {
1059 eat_whitespace(p, os, parent_context, false);
1060 parent_context.check_layout(os);
1061 begin_inset(os, "Tabular ");
1062 handle_tabular(p, os, name == "longtable", parent_context);
1067 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1068 eat_whitespace(p, os, parent_context, false);
1069 parent_context.check_layout(os);
1070 begin_inset(os, "Float " + unstarred_name + "\n");
1071 // store the float type for subfloats
1072 // subfloats only work with figures and tables
1073 if (unstarred_name == "figure")
1074 float_type = unstarred_name;
1075 else if (unstarred_name == "table")
1076 float_type = unstarred_name;
1080 os << "placement " << p.getArg('[', ']') << '\n';
1081 os << "wide " << convert<string>(is_starred)
1082 << "\nsideways false"
1083 << "\nstatus open\n\n";
1084 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1086 // We don't need really a new paragraph, but
1087 // we must make sure that the next item gets a \begin_layout.
1088 parent_context.new_paragraph(os);
1090 // the float is parsed thus delete the type
1094 else if (unstarred_name == "sidewaysfigure"
1095 || unstarred_name == "sidewaystable") {
1096 eat_whitespace(p, os, parent_context, false);
1097 parent_context.check_layout(os);
1098 if (unstarred_name == "sidewaysfigure")
1099 begin_inset(os, "Float figure\n");
1101 begin_inset(os, "Float table\n");
1102 os << "wide " << convert<string>(is_starred)
1103 << "\nsideways true"
1104 << "\nstatus open\n\n";
1105 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1107 // We don't need really a new paragraph, but
1108 // we must make sure that the next item gets a \begin_layout.
1109 parent_context.new_paragraph(os);
1113 else if (name == "wrapfigure" || name == "wraptable") {
1114 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1115 eat_whitespace(p, os, parent_context, false);
1116 parent_context.check_layout(os);
1119 string overhang = "0col%";
1122 lines = p.getArg('[', ']');
1123 string const placement = p.getArg('{', '}');
1125 overhang = p.getArg('[', ']');
1126 string const width = p.getArg('{', '}');
1128 if (name == "wrapfigure")
1129 begin_inset(os, "Wrap figure\n");
1131 begin_inset(os, "Wrap table\n");
1132 os << "lines " << lines
1133 << "\nplacement " << placement
1134 << "\noverhang " << lyx::translate_len(overhang)
1135 << "\nwidth " << lyx::translate_len(width)
1136 << "\nstatus open\n\n";
1137 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1139 // We don't need really a new paragraph, but
1140 // we must make sure that the next item gets a \begin_layout.
1141 parent_context.new_paragraph(os);
1145 else if (name == "minipage") {
1146 eat_whitespace(p, os, parent_context, false);
1147 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1151 else if (name == "comment") {
1152 eat_whitespace(p, os, parent_context, false);
1153 parent_context.check_layout(os);
1154 begin_inset(os, "Note Comment\n");
1155 os << "status open\n";
1156 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1159 skip_braces(p); // eat {} that might by set by LyX behind comments
1162 else if (name == "lyxgreyedout") {
1163 eat_whitespace(p, os, parent_context, false);
1164 parent_context.check_layout(os);
1165 begin_inset(os, "Note Greyedout\n");
1166 os << "status open\n";
1167 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1170 if (!preamble.notefontcolor().empty())
1171 preamble.registerAutomaticallyLoadedPackage("color");
1174 else if (name == "framed" || name == "shaded") {
1175 eat_whitespace(p, os, parent_context, false);
1176 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1180 else if (name == "lstlisting") {
1181 eat_whitespace(p, os, parent_context, false);
1182 // FIXME handle listings with parameters
1183 // If this is added, don't forgot to handle the
1184 // automatic color package loading
1186 parse_unknown_environment(p, name, os, FLAG_END,
1187 outer, parent_context);
1189 parse_listings(p, os, parent_context);
1193 else if (!parent_context.new_layout_allowed)
1194 parse_unknown_environment(p, name, os, FLAG_END, outer,
1197 // Alignment and spacing settings
1198 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1199 // therefore are totally broken!
1200 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1201 // they are commands not environments. They are furthermore switches that
1202 // can be ended by another switches, but also by commands like \footnote or
1203 // \parbox. So the only safe way is to leave them untouched.
1204 else if (name == "center" || name == "centering" ||
1205 name == "flushleft" || name == "flushright" ||
1206 name == "singlespace" || name == "onehalfspace" ||
1207 name == "doublespace" || name == "spacing") {
1208 eat_whitespace(p, os, parent_context, false);
1209 // We must begin a new paragraph if not already done
1210 if (! parent_context.atParagraphStart()) {
1211 parent_context.check_end_layout(os);
1212 parent_context.new_paragraph(os);
1214 if (name == "flushleft")
1215 parent_context.add_extra_stuff("\\align left\n");
1216 else if (name == "flushright")
1217 parent_context.add_extra_stuff("\\align right\n");
1218 else if (name == "center" || name == "centering")
1219 parent_context.add_extra_stuff("\\align center\n");
1220 else if (name == "singlespace")
1221 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1222 else if (name == "onehalfspace")
1223 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1224 else if (name == "doublespace")
1225 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1226 else if (name == "spacing")
1227 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1228 parse_text(p, os, FLAG_END, outer, parent_context);
1229 // Just in case the environment is empty
1230 parent_context.extra_stuff.erase();
1231 // We must begin a new paragraph to reset the alignment
1232 parent_context.new_paragraph(os);
1236 // The single '=' is meant here.
1237 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1238 eat_whitespace(p, os, parent_context, false);
1239 Context context(true, parent_context.textclass, newlayout,
1240 parent_context.layout, parent_context.font);
1241 if (parent_context.deeper_paragraph) {
1242 // We are beginning a nested environment after a
1243 // deeper paragraph inside the outer list environment.
1244 // Therefore we don't need to output a "begin deeper".
1245 context.need_end_deeper = true;
1247 parent_context.check_end_layout(os);
1248 if (last_env == name) {
1249 // we need to output a separator since LyX would export
1250 // the two environments as one otherwise (bug 5716)
1251 docstring const sep = from_ascii("--Separator--");
1252 TeX2LyXDocClass const & textclass(parent_context.textclass);
1253 if (textclass.hasLayout(sep)) {
1254 Context newcontext(parent_context);
1255 newcontext.layout = &(textclass[sep]);
1256 newcontext.check_layout(os);
1257 newcontext.check_end_layout(os);
1259 parent_context.check_layout(os);
1260 begin_inset(os, "Note Note\n");
1261 os << "status closed\n";
1262 Context newcontext(true, textclass,
1263 &(textclass.defaultLayout()));
1264 newcontext.check_layout(os);
1265 newcontext.check_end_layout(os);
1267 parent_context.check_end_layout(os);
1270 switch (context.layout->latextype) {
1271 case LATEX_LIST_ENVIRONMENT:
1272 context.add_par_extra_stuff("\\labelwidthstring "
1273 + p.verbatim_item() + '\n');
1276 case LATEX_BIB_ENVIRONMENT:
1277 p.verbatim_item(); // swallow next arg
1283 context.check_deeper(os);
1284 // handle known optional and required arguments
1285 // layouts require all optional arguments before the required ones
1286 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1287 // It is impossible to place anything after the environment name,
1288 // but before the first \\item.
1289 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1290 bool need_layout = true;
1291 unsigned int optargs = 0;
1292 while (optargs < context.layout->optargs) {
1293 eat_whitespace(p, os, context, false);
1294 if (p.next_token().cat() == catEscape ||
1295 p.next_token().character() != '[')
1297 p.get_token(); // eat '['
1299 context.check_layout(os);
1300 need_layout = false;
1302 begin_inset(os, "Argument\n");
1303 os << "status collapsed\n\n";
1304 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1306 eat_whitespace(p, os, context, false);
1309 unsigned int reqargs = 0;
1310 while (reqargs < context.layout->reqargs) {
1311 eat_whitespace(p, os, context, false);
1312 if (p.next_token().cat() != catBegin)
1314 p.get_token(); // eat '{'
1316 context.check_layout(os);
1317 need_layout = false;
1319 begin_inset(os, "Argument\n");
1320 os << "status collapsed\n\n";
1321 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1323 eat_whitespace(p, os, context, false);
1327 parse_text(p, os, FLAG_END, outer, context);
1328 context.check_end_layout(os);
1329 if (parent_context.deeper_paragraph) {
1330 // We must suppress the "end deeper" because we
1331 // suppressed the "begin deeper" above.
1332 context.need_end_deeper = false;
1334 context.check_end_deeper(os);
1335 parent_context.new_paragraph(os);
1337 if (!title_layout_found)
1338 title_layout_found = newlayout->intitle;
1341 // The single '=' is meant here.
1342 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1343 eat_whitespace(p, os, parent_context, false);
1344 parent_context.check_layout(os);
1345 begin_inset(os, "Flex ");
1346 os << to_utf8(newinsetlayout->name()) << '\n'
1347 << "status collapsed\n";
1348 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1352 else if (name == "appendix") {
1353 // This is no good latex style, but it works and is used in some documents...
1354 eat_whitespace(p, os, parent_context, false);
1355 parent_context.check_end_layout(os);
1356 Context context(true, parent_context.textclass, parent_context.layout,
1357 parent_context.layout, parent_context.font);
1358 context.check_layout(os);
1359 os << "\\start_of_appendix\n";
1360 parse_text(p, os, FLAG_END, outer, context);
1361 context.check_end_layout(os);
1365 else if (known_environments.find(name) != known_environments.end()) {
1366 vector<ArgumentType> arguments = known_environments[name];
1367 // The last "argument" denotes wether we may translate the
1368 // environment contents to LyX
1369 // The default required if no argument is given makes us
1370 // compatible with the reLyXre environment.
1371 ArgumentType contents = arguments.empty() ?
1374 if (!arguments.empty())
1375 arguments.pop_back();
1376 // See comment in parse_unknown_environment()
1377 bool const specialfont =
1378 (parent_context.font != parent_context.normalfont);
1379 bool const new_layout_allowed =
1380 parent_context.new_layout_allowed;
1382 parent_context.new_layout_allowed = false;
1383 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1384 outer, parent_context);
1385 if (contents == verbatim)
1386 handle_ert(os, p.verbatimEnvironment(name),
1389 parse_text_snippet(p, os, FLAG_END, outer,
1391 handle_ert(os, "\\end{" + name + "}", parent_context);
1393 parent_context.new_layout_allowed = new_layout_allowed;
1397 parse_unknown_environment(p, name, os, FLAG_END, outer,
1401 active_environments.pop_back();
1405 /// parses a comment and outputs it to \p os.
1406 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1408 LASSERT(t.cat() == catComment, return);
1409 if (!t.cs().empty()) {
1410 context.check_layout(os);
1411 handle_comment(os, '%' + t.cs(), context);
1412 if (p.next_token().cat() == catNewline) {
1413 // A newline after a comment line starts a new
1415 if (context.new_layout_allowed) {
1416 if(!context.atParagraphStart())
1417 // Only start a new paragraph if not already
1418 // done (we might get called recursively)
1419 context.new_paragraph(os);
1421 handle_ert(os, "\n", context);
1422 eat_whitespace(p, os, context, true);
1425 // "%\n" combination
1432 * Reads spaces and comments until the first non-space, non-comment token.
1433 * New paragraphs (double newlines or \\par) are handled like simple spaces
1434 * if \p eatParagraph is true.
1435 * Spaces are skipped, but comments are written to \p os.
1437 void eat_whitespace(Parser & p, ostream & os, Context & context,
1441 Token const & t = p.get_token();
1442 if (t.cat() == catComment)
1443 parse_comment(p, os, t, context);
1444 else if ((! eatParagraph && p.isParagraph()) ||
1445 (t.cat() != catSpace && t.cat() != catNewline)) {
1454 * Set a font attribute, parse text and reset the font attribute.
1455 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1456 * \param currentvalue Current value of the attribute. Is set to the new
1457 * value during parsing.
1458 * \param newvalue New value of the attribute
1460 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1461 Context & context, string const & attribute,
1462 string & currentvalue, string const & newvalue)
1464 context.check_layout(os);
1465 string const oldvalue = currentvalue;
1466 currentvalue = newvalue;
1467 os << '\n' << attribute << ' ' << newvalue << "\n";
1468 parse_text_snippet(p, os, flags, outer, context);
1469 context.check_layout(os);
1470 os << '\n' << attribute << ' ' << oldvalue << "\n";
1471 currentvalue = oldvalue;
1475 /// get the arguments of a natbib or jurabib citation command
1476 void get_cite_arguments(Parser & p, bool natbibOrder,
1477 string & before, string & after)
1479 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1481 // text before the citation
1483 // text after the citation
1484 after = p.getFullOpt();
1486 if (!after.empty()) {
1487 before = p.getFullOpt();
1488 if (natbibOrder && !before.empty())
1489 swap(before, after);
1494 /// Convert filenames with TeX macros and/or quotes to something LyX
1496 string const normalize_filename(string const & name)
1498 Parser p(trim(name, "\""));
1501 Token const & t = p.get_token();
1502 if (t.cat() != catEscape)
1504 else if (t.cs() == "lyxdot") {
1505 // This is used by LyX for simple dots in relative
1509 } else if (t.cs() == "space") {
1519 /// Convert \p name from TeX convention (relative to master file) to LyX
1520 /// convention (relative to .lyx file) if it is relative
1521 void fix_relative_filename(string & name)
1523 if (FileName::isAbsolute(name))
1526 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1527 from_utf8(getParentFilePath())));
1531 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1532 void parse_noweb(Parser & p, ostream & os, Context & context)
1534 // assemble the rest of the keyword
1538 Token const & t = p.get_token();
1539 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1542 scrap = (p.good() && p.next_token().asInput() == "=");
1544 name += p.get_token().asInput();
1547 name += t.asInput();
1550 if (!scrap || !context.new_layout_allowed ||
1551 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1552 cerr << "Warning: Could not interpret '" << name
1553 << "'. Ignoring it." << endl;
1557 // We use new_paragraph instead of check_end_layout because the stuff
1558 // following the noweb chunk needs to start with a \begin_layout.
1559 // This may create a new paragraph even if there was none in the
1560 // noweb file, but the alternative is an invalid LyX file. Since
1561 // noweb code chunks are implemented with a layout style in LyX they
1562 // always must be in an own paragraph.
1563 context.new_paragraph(os);
1564 Context newcontext(true, context.textclass,
1565 &context.textclass[from_ascii("Scrap")]);
1566 newcontext.check_layout(os);
1569 Token const & t = p.get_token();
1570 // We abuse the parser a bit, because this is no TeX syntax
1572 if (t.cat() == catEscape)
1573 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1576 Context tmp(false, context.textclass,
1577 &context.textclass[from_ascii("Scrap")]);
1578 tmp.need_end_layout = true;
1579 tmp.check_layout(oss);
1580 os << subst(t.asInput(), "\n", oss.str());
1582 // The scrap chunk is ended by an @ at the beginning of a line.
1583 // After the @ the line may contain a comment and/or
1584 // whitespace, but nothing else.
1585 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1586 (p.next_token().cat() == catSpace ||
1587 p.next_token().cat() == catNewline ||
1588 p.next_token().cat() == catComment)) {
1589 while (p.good() && p.next_token().cat() == catSpace)
1590 os << p.get_token().asInput();
1591 if (p.next_token().cat() == catComment)
1592 // The comment includes a final '\n'
1593 os << p.get_token().asInput();
1595 if (p.next_token().cat() == catNewline)
1602 newcontext.check_end_layout(os);
1606 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1607 bool is_macro(Parser & p)
1609 Token first = p.curr_token();
1610 if (first.cat() != catEscape || !p.good())
1612 if (first.cs() == "def")
1614 if (first.cs() != "global" && first.cs() != "long")
1616 Token second = p.get_token();
1618 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1619 second.cat() == catNewline || second.cat() == catComment)) {
1620 second = p.get_token();
1623 bool secondvalid = second.cat() == catEscape;
1625 bool thirdvalid = false;
1626 if (p.good() && first.cs() == "global" && secondvalid &&
1627 second.cs() == "long") {
1628 third = p.get_token();
1630 while (p.good() && !p.isParagraph() &&
1631 (third.cat() == catSpace ||
1632 third.cat() == catNewline ||
1633 third.cat() == catComment)) {
1634 third = p.get_token();
1637 thirdvalid = third.cat() == catEscape;
1639 for (int i = 0; i < pos; ++i)
1644 return (first.cs() == "global" || first.cs() == "long") &&
1645 second.cs() == "def";
1646 return first.cs() == "global" && second.cs() == "long" &&
1647 third.cs() == "def";
1651 /// Parse a macro definition (assumes that is_macro() returned true)
1652 void parse_macro(Parser & p, ostream & os, Context & context)
1654 context.check_layout(os);
1655 Token first = p.curr_token();
1658 string command = first.asInput();
1659 if (first.cs() != "def") {
1661 eat_whitespace(p, os, context, false);
1662 second = p.curr_token();
1663 command += second.asInput();
1664 if (second.cs() != "def") {
1666 eat_whitespace(p, os, context, false);
1667 third = p.curr_token();
1668 command += third.asInput();
1671 eat_whitespace(p, os, context, false);
1672 string const name = p.get_token().cs();
1673 eat_whitespace(p, os, context, false);
1679 while (p.next_token().cat() != catBegin) {
1680 if (p.next_token().cat() == catParameter) {
1685 // followed by number?
1686 if (p.next_token().cat() == catOther) {
1687 char c = p.getChar();
1689 // number = current arity + 1?
1690 if (c == arity + '0' + 1)
1695 paramtext += p.get_token().cs();
1697 paramtext += p.get_token().cs();
1702 // only output simple (i.e. compatible) macro as FormulaMacros
1703 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1705 context.check_layout(os);
1706 begin_inset(os, "FormulaMacro");
1707 os << "\n\\def" << ert;
1710 handle_ert(os, command + ert, context);
1713 } // anonymous namespace
1716 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1719 Layout const * newlayout = 0;
1720 InsetLayout const * newinsetlayout = 0;
1721 // Store the latest bibliographystyle and nocite{*} option
1722 // (needed for bibtex inset)
1724 string bibliographystyle;
1725 bool const use_natbib = preamble.isPackageUsed("natbib");
1726 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1728 bool title_layout_found = false;
1730 Token const & t = p.get_token();
1733 debugToken(cerr, t, flags);
1736 if (flags & FLAG_ITEM) {
1737 if (t.cat() == catSpace)
1740 flags &= ~FLAG_ITEM;
1741 if (t.cat() == catBegin) {
1742 // skip the brace and collect everything to the next matching
1744 flags |= FLAG_BRACE_LAST;
1748 // handle only this single token, leave the loop if done
1749 flags |= FLAG_LEAVE;
1752 if (t.cat() != catEscape && t.character() == ']' &&
1753 (flags & FLAG_BRACK_LAST))
1755 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1758 // If there is anything between \end{env} and \begin{env} we
1759 // don't need to output a separator.
1760 if (t.cat() != catSpace && t.cat() != catNewline &&
1761 t.asInput() != "\\begin")
1767 if (t.cat() == catMath) {
1768 // we are inside some text mode thingy, so opening new math is allowed
1769 context.check_layout(os);
1770 begin_inset(os, "Formula ");
1771 Token const & n = p.get_token();
1772 if (n.cat() == catMath && outer) {
1773 // TeX's $$...$$ syntax for displayed math
1775 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1777 p.get_token(); // skip the second '$' token
1779 // simple $...$ stuff
1782 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1788 else if (t.cat() == catSuper || t.cat() == catSub)
1789 cerr << "catcode " << t << " illegal in text mode\n";
1791 // Basic support for english quotes. This should be
1792 // extended to other quotes, but is not so easy (a
1793 // left english quote is the same as a right german
1795 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1796 context.check_layout(os);
1797 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() == "<" && p.next_token().asInput() == "<") {
1822 context.check_layout(os);
1823 begin_inset(os, "Quotes ");
1830 else if (t.asInput() == "<"
1831 && p.next_token().asInput() == "<" && noweb_mode) {
1833 parse_noweb(p, os, context);
1836 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1837 check_space(p, os, context);
1839 else if (t.character() == '[' && noweb_mode &&
1840 p.next_token().character() == '[') {
1841 // These can contain underscores
1843 string const s = p.getFullOpt() + ']';
1844 if (p.next_token().character() == ']')
1847 cerr << "Warning: Inserting missing ']' in '"
1848 << s << "'." << endl;
1849 handle_ert(os, s, context);
1852 else if (t.cat() == catLetter) {
1853 context.check_layout(os);
1854 // Workaround for bug 4752.
1855 // FIXME: This whole code block needs to be removed
1856 // when the bug is fixed and tex2lyx produces
1857 // the updated file format.
1858 // The replacement algorithm in LyX is so stupid that
1859 // it even translates a phrase if it is part of a word.
1860 bool handled = false;
1861 for (int const * l = known_phrase_lengths; *l; ++l) {
1862 string phrase = t.cs();
1863 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1864 phrase += p.get_token().cs();
1865 if (is_known(phrase, known_coded_phrases)) {
1866 handle_ert(os, phrase, context);
1870 for (size_t i = 1; i < phrase.length(); ++i)
1878 else if (t.cat() == catOther ||
1879 t.cat() == catAlign ||
1880 t.cat() == catParameter) {
1881 // This translates "&" to "\\&" which may be wrong...
1882 context.check_layout(os);
1886 else if (p.isParagraph()) {
1887 if (context.new_layout_allowed)
1888 context.new_paragraph(os);
1890 handle_ert(os, "\\par ", context);
1891 eat_whitespace(p, os, context, true);
1894 else if (t.cat() == catActive) {
1895 context.check_layout(os);
1896 if (t.character() == '~') {
1897 if (context.layout->free_spacing)
1900 begin_inset(os, "space ~\n");
1907 else if (t.cat() == catBegin &&
1908 p.next_token().cat() == catEnd) {
1910 Token const prev = p.prev_token();
1912 if (p.next_token().character() == '`' ||
1913 (prev.character() == '-' &&
1914 p.next_token().character() == '-'))
1915 ; // ignore it in {}`` or -{}-
1917 handle_ert(os, "{}", context);
1921 else if (t.cat() == catBegin) {
1922 context.check_layout(os);
1923 // special handling of font attribute changes
1924 Token const prev = p.prev_token();
1925 Token const next = p.next_token();
1926 TeXFont const oldFont = context.font;
1927 if (next.character() == '[' ||
1928 next.character() == ']' ||
1929 next.character() == '*') {
1931 if (p.next_token().cat() == catEnd) {
1936 handle_ert(os, "{", context);
1937 parse_text_snippet(p, os,
1940 handle_ert(os, "}", context);
1942 } else if (! context.new_layout_allowed) {
1943 handle_ert(os, "{", context);
1944 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1946 handle_ert(os, "}", context);
1947 } else if (is_known(next.cs(), known_sizes)) {
1948 // next will change the size, so we must
1950 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1952 if (!context.atParagraphStart())
1954 << context.font.size << "\n";
1955 } else if (is_known(next.cs(), known_font_families)) {
1956 // next will change the font family, so we
1957 // must reset it here
1958 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1960 if (!context.atParagraphStart())
1962 << context.font.family << "\n";
1963 } else if (is_known(next.cs(), known_font_series)) {
1964 // next will change the font series, so we
1965 // must reset it here
1966 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1968 if (!context.atParagraphStart())
1970 << context.font.series << "\n";
1971 } else if (is_known(next.cs(), known_font_shapes)) {
1972 // next will change the font shape, so we
1973 // must reset it here
1974 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1976 if (!context.atParagraphStart())
1978 << context.font.shape << "\n";
1979 } else if (is_known(next.cs(), known_old_font_families) ||
1980 is_known(next.cs(), known_old_font_series) ||
1981 is_known(next.cs(), known_old_font_shapes)) {
1982 // next will change the font family, series
1983 // and shape, so we must reset it here
1984 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1986 if (!context.atParagraphStart())
1988 << context.font.family
1990 << context.font.series
1992 << context.font.shape << "\n";
1994 handle_ert(os, "{", context);
1995 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1997 handle_ert(os, "}", context);
2001 else if (t.cat() == catEnd) {
2002 if (flags & FLAG_BRACE_LAST) {
2005 cerr << "stray '}' in text\n";
2006 handle_ert(os, "}", context);
2009 else if (t.cat() == catComment)
2010 parse_comment(p, os, t, context);
2013 // control sequences
2016 else if (t.cs() == "(") {
2017 context.check_layout(os);
2018 begin_inset(os, "Formula");
2020 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2025 else if (t.cs() == "[") {
2026 context.check_layout(os);
2027 begin_inset(os, "Formula");
2029 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2034 else if (t.cs() == "begin")
2035 parse_environment(p, os, outer, last_env,
2036 title_layout_found, context);
2038 else if (t.cs() == "end") {
2039 if (flags & FLAG_END) {
2040 // eat environment name
2041 string const name = p.getArg('{', '}');
2042 if (name != active_environment())
2043 cerr << "\\end{" + name + "} does not match \\begin{"
2044 + active_environment() + "}\n";
2047 p.error("found 'end' unexpectedly");
2050 else if (t.cs() == "item") {
2053 bool optarg = false;
2054 if (p.next_token().cat() != catEscape &&
2055 p.next_token().character() == '[') {
2056 p.get_token(); // eat '['
2057 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2062 context.check_layout(os);
2063 if (context.has_item) {
2064 // An item in an unknown list-like environment
2065 // FIXME: Do this in check_layout()!
2066 context.has_item = false;
2068 handle_ert(os, "\\item", context);
2070 handle_ert(os, "\\item ", context);
2073 if (context.layout->labeltype != LABEL_MANUAL) {
2074 // LyX does not support \item[\mybullet]
2075 // in itemize environments
2076 handle_ert(os, "[", context);
2078 handle_ert(os, "]", context);
2079 } else if (!s.empty()) {
2080 // The space is needed to separate the
2081 // item from the rest of the sentence.
2083 eat_whitespace(p, os, context, false);
2088 else if (t.cs() == "bibitem") {
2090 context.check_layout(os);
2091 string label = convert_command_inset_arg(p.getArg('[', ']'));
2092 string key = convert_command_inset_arg(p.verbatim_item());
2093 if (contains(label, '\\') || contains(key, '\\')) {
2094 // LyX can't handle LaTeX commands in labels or keys
2095 handle_ert(os, t.asInput() + '[' + label +
2096 "]{" + p.verbatim_item() + '}',
2099 begin_command_inset(os, "bibitem", "bibitem");
2100 os << "label \"" << label << "\"\n"
2101 "key \"" << key << "\"\n";
2106 else if (is_macro(p))
2107 parse_macro(p, os, context);
2109 else if (t.cs() == "noindent") {
2111 context.add_par_extra_stuff("\\noindent\n");
2114 else if (t.cs() == "appendix") {
2115 context.add_par_extra_stuff("\\start_of_appendix\n");
2116 // We need to start a new paragraph. Otherwise the
2117 // appendix in 'bla\appendix\chapter{' would start
2119 context.new_paragraph(os);
2120 // We need to make sure that the paragraph is
2121 // generated even if it is empty. Otherwise the
2122 // appendix in '\par\appendix\par\chapter{' would
2124 context.check_layout(os);
2125 // FIXME: This is a hack to prevent paragraph
2126 // deletion if it is empty. Handle this better!
2128 "%dummy comment inserted by tex2lyx to "
2129 "ensure that this paragraph is not empty",
2131 // Both measures above may generate an additional
2132 // empty paragraph, but that does not hurt, because
2133 // whitespace does not matter here.
2134 eat_whitespace(p, os, context, true);
2137 // Must catch empty dates before findLayout is called below
2138 else if (t.cs() == "date") {
2139 string const date = p.verbatim_item();
2141 preamble.suppressDate(true);
2143 preamble.suppressDate(false);
2144 if (context.new_layout_allowed &&
2145 (newlayout = findLayout(context.textclass,
2148 output_command_layout(os, p, outer,
2149 context, newlayout);
2151 if (!title_layout_found)
2152 title_layout_found = newlayout->intitle;
2154 handle_ert(os, "\\date{" + date + '}',
2159 // Starred section headings
2160 // Must attempt to parse "Section*" before "Section".
2161 else if ((p.next_token().asInput() == "*") &&
2162 context.new_layout_allowed &&
2163 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2166 output_command_layout(os, p, outer, context, newlayout);
2168 if (!title_layout_found)
2169 title_layout_found = newlayout->intitle;
2172 // Section headings and the like
2173 else if (context.new_layout_allowed &&
2174 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2176 output_command_layout(os, p, outer, context, newlayout);
2178 if (!title_layout_found)
2179 title_layout_found = newlayout->intitle;
2182 else if (t.cs() == "caption") {
2184 context.check_layout(os);
2186 begin_inset(os, "Caption\n");
2187 Context newcontext(true, context.textclass);
2188 newcontext.font = context.font;
2189 newcontext.check_layout(os);
2190 if (p.next_token().cat() != catEscape &&
2191 p.next_token().character() == '[') {
2192 p.get_token(); // eat '['
2193 begin_inset(os, "Argument\n");
2194 os << "status collapsed\n";
2195 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2197 eat_whitespace(p, os, context, false);
2199 parse_text(p, os, FLAG_ITEM, outer, context);
2200 context.check_end_layout(os);
2201 // We don't need really a new paragraph, but
2202 // we must make sure that the next item gets a \begin_layout.
2203 context.new_paragraph(os);
2206 newcontext.check_end_layout(os);
2209 else if (t.cs() == "subfloat") {
2210 // the syntax is \subfloat[caption]{content}
2211 // if it is a table of figure depends on the surrounding float
2212 bool has_caption = false;
2214 // do nothing if there is no outer float
2215 if (!float_type.empty()) {
2216 context.check_layout(os);
2218 begin_inset(os, "Float " + float_type + "\n");
2220 << "\nsideways false"
2221 << "\nstatus collapsed\n\n";
2224 if (p.next_token().cat() != catEscape &&
2225 p.next_token().character() == '[') {
2226 p.get_token(); // eat '['
2227 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2231 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2232 // the caption comes always as the last
2234 // we must make sure that the caption gets a \begin_layout
2235 os << "\n\\begin_layout Plain Layout";
2237 begin_inset(os, "Caption\n");
2238 Context newcontext(true, context.textclass);
2239 newcontext.font = context.font;
2240 newcontext.check_layout(os);
2241 os << caption << "\n";
2242 newcontext.check_end_layout(os);
2243 // We don't need really a new paragraph, but
2244 // we must make sure that the next item gets a \begin_layout.
2245 //newcontext.new_paragraph(os);
2249 // We don't need really a new paragraph, but
2250 // we must make sure that the next item gets a \begin_layout.
2252 context.new_paragraph(os);
2255 context.check_end_layout(os);
2256 // close the layout we opened
2258 os << "\n\\end_layout\n";
2260 // if the float type is not supported or there is no surrounding float
2263 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2264 handle_ert(os, t.asInput() + '[' + opt_arg +
2265 "]{" + p.verbatim_item() + '}', context);
2267 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2271 else if (t.cs() == "includegraphics") {
2272 bool const clip = p.next_token().asInput() == "*";
2275 string const arg = p.getArg('[', ']');
2276 map<string, string> opts;
2277 vector<string> keys;
2278 split_map(arg, opts, keys);
2280 opts["clip"] = string();
2281 string name = normalize_filename(p.verbatim_item());
2283 string const path = getMasterFilePath();
2284 // We want to preserve relative / absolute filenames,
2285 // therefore path is only used for testing
2286 if (!makeAbsPath(name, path).exists()) {
2287 // The file extension is probably missing.
2288 // Now try to find it out.
2289 string const dvips_name =
2290 find_file(name, path,
2291 known_dvips_graphics_formats);
2292 string const pdftex_name =
2293 find_file(name, path,
2294 known_pdftex_graphics_formats);
2295 if (!dvips_name.empty()) {
2296 if (!pdftex_name.empty()) {
2297 cerr << "This file contains the "
2299 "\"\\includegraphics{"
2301 "However, files\n\""
2302 << dvips_name << "\" and\n\""
2303 << pdftex_name << "\"\n"
2304 "both exist, so I had to make a "
2305 "choice and took the first one.\n"
2306 "Please move the unwanted one "
2307 "someplace else and try again\n"
2308 "if my choice was wrong."
2312 } else if (!pdftex_name.empty()) {
2318 if (makeAbsPath(name, path).exists())
2319 fix_relative_filename(name);
2321 cerr << "Warning: Could not find graphics file '"
2322 << name << "'." << endl;
2324 context.check_layout(os);
2325 begin_inset(os, "Graphics ");
2326 os << "\n\tfilename " << name << '\n';
2327 if (opts.find("width") != opts.end())
2329 << translate_len(opts["width"]) << '\n';
2330 if (opts.find("height") != opts.end())
2332 << translate_len(opts["height"]) << '\n';
2333 if (opts.find("scale") != opts.end()) {
2334 istringstream iss(opts["scale"]);
2338 os << "\tscale " << val << '\n';
2340 if (opts.find("angle") != opts.end()) {
2341 os << "\trotateAngle "
2342 << opts["angle"] << '\n';
2343 vector<string>::const_iterator a =
2344 find(keys.begin(), keys.end(), "angle");
2345 vector<string>::const_iterator s =
2346 find(keys.begin(), keys.end(), "width");
2347 if (s == keys.end())
2348 s = find(keys.begin(), keys.end(), "height");
2349 if (s == keys.end())
2350 s = find(keys.begin(), keys.end(), "scale");
2351 if (s != keys.end() && distance(s, a) > 0)
2352 os << "\tscaleBeforeRotation\n";
2354 if (opts.find("origin") != opts.end()) {
2356 string const opt = opts["origin"];
2357 if (opt.find('l') != string::npos) ss << "left";
2358 if (opt.find('r') != string::npos) ss << "right";
2359 if (opt.find('c') != string::npos) ss << "center";
2360 if (opt.find('t') != string::npos) ss << "Top";
2361 if (opt.find('b') != string::npos) ss << "Bottom";
2362 if (opt.find('B') != string::npos) ss << "Baseline";
2363 if (!ss.str().empty())
2364 os << "\trotateOrigin " << ss.str() << '\n';
2366 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2368 if (opts.find("keepaspectratio") != opts.end())
2369 os << "\tkeepAspectRatio\n";
2370 if (opts.find("clip") != opts.end())
2372 if (opts.find("draft") != opts.end())
2374 if (opts.find("bb") != opts.end())
2375 os << "\tBoundingBox "
2376 << opts["bb"] << '\n';
2377 int numberOfbbOptions = 0;
2378 if (opts.find("bbllx") != opts.end())
2379 numberOfbbOptions++;
2380 if (opts.find("bblly") != opts.end())
2381 numberOfbbOptions++;
2382 if (opts.find("bburx") != opts.end())
2383 numberOfbbOptions++;
2384 if (opts.find("bbury") != opts.end())
2385 numberOfbbOptions++;
2386 if (numberOfbbOptions == 4)
2387 os << "\tBoundingBox "
2388 << opts["bbllx"] << " " << opts["bblly"] << " "
2389 << opts["bburx"] << " " << opts["bbury"] << '\n';
2390 else if (numberOfbbOptions > 0)
2391 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2392 numberOfbbOptions = 0;
2393 if (opts.find("natwidth") != opts.end())
2394 numberOfbbOptions++;
2395 if (opts.find("natheight") != opts.end())
2396 numberOfbbOptions++;
2397 if (numberOfbbOptions == 2)
2398 os << "\tBoundingBox 0bp 0bp "
2399 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2400 else if (numberOfbbOptions > 0)
2401 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2402 ostringstream special;
2403 if (opts.find("hiresbb") != opts.end())
2404 special << "hiresbb,";
2405 if (opts.find("trim") != opts.end())
2407 if (opts.find("viewport") != opts.end())
2408 special << "viewport=" << opts["viewport"] << ',';
2409 if (opts.find("totalheight") != opts.end())
2410 special << "totalheight=" << opts["totalheight"] << ',';
2411 if (opts.find("type") != opts.end())
2412 special << "type=" << opts["type"] << ',';
2413 if (opts.find("ext") != opts.end())
2414 special << "ext=" << opts["ext"] << ',';
2415 if (opts.find("read") != opts.end())
2416 special << "read=" << opts["read"] << ',';
2417 if (opts.find("command") != opts.end())
2418 special << "command=" << opts["command"] << ',';
2419 string s_special = special.str();
2420 if (!s_special.empty()) {
2421 // We had special arguments. Remove the trailing ','.
2422 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2424 // TODO: Handle the unknown settings better.
2425 // Warn about invalid options.
2426 // Check whether some option was given twice.
2430 else if (t.cs() == "footnote" ||
2431 (t.cs() == "thanks" && context.layout->intitle)) {
2433 context.check_layout(os);
2434 begin_inset(os, "Foot\n");
2435 os << "status collapsed\n\n";
2436 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2440 else if (t.cs() == "marginpar") {
2442 context.check_layout(os);
2443 begin_inset(os, "Marginal\n");
2444 os << "status collapsed\n\n";
2445 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2449 else if (t.cs() == "ensuremath") {
2451 context.check_layout(os);
2452 string const s = p.verbatim_item();
2453 //FIXME: this never triggers in UTF8
2454 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2457 handle_ert(os, "\\ensuremath{" + s + "}",
2461 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2462 if (title_layout_found) {
2464 skip_spaces_braces(p);
2466 handle_ert(os, t.asInput(), context);
2469 else if (t.cs() == "tableofcontents") {
2470 context.check_layout(os);
2471 begin_command_inset(os, "toc", "tableofcontents");
2473 skip_spaces_braces(p);
2476 else if (t.cs() == "listoffigures") {
2477 context.check_layout(os);
2478 begin_inset(os, "FloatList figure\n");
2480 skip_spaces_braces(p);
2483 else if (t.cs() == "listoftables") {
2484 context.check_layout(os);
2485 begin_inset(os, "FloatList table\n");
2487 skip_spaces_braces(p);
2490 else if (t.cs() == "listof") {
2491 p.skip_spaces(true);
2492 string const name = p.get_token().cs();
2493 if (context.textclass.floats().typeExist(name)) {
2494 context.check_layout(os);
2495 begin_inset(os, "FloatList ");
2498 p.get_token(); // swallow second arg
2500 handle_ert(os, "\\listof{" + name + "}", context);
2503 else if (t.cs() == "textrm")
2504 parse_text_attributes(p, os, FLAG_ITEM, outer,
2505 context, "\\family",
2506 context.font.family, "roman");
2508 else if (t.cs() == "textsf")
2509 parse_text_attributes(p, os, FLAG_ITEM, outer,
2510 context, "\\family",
2511 context.font.family, "sans");
2513 else if (t.cs() == "texttt")
2514 parse_text_attributes(p, os, FLAG_ITEM, outer,
2515 context, "\\family",
2516 context.font.family, "typewriter");
2518 else if (t.cs() == "textmd")
2519 parse_text_attributes(p, os, FLAG_ITEM, outer,
2520 context, "\\series",
2521 context.font.series, "medium");
2523 else if (t.cs() == "textbf")
2524 parse_text_attributes(p, os, FLAG_ITEM, outer,
2525 context, "\\series",
2526 context.font.series, "bold");
2528 else if (t.cs() == "textup")
2529 parse_text_attributes(p, os, FLAG_ITEM, outer,
2531 context.font.shape, "up");
2533 else if (t.cs() == "textit")
2534 parse_text_attributes(p, os, FLAG_ITEM, outer,
2536 context.font.shape, "italic");
2538 else if (t.cs() == "textsl")
2539 parse_text_attributes(p, os, FLAG_ITEM, outer,
2541 context.font.shape, "slanted");
2543 else if (t.cs() == "textsc")
2544 parse_text_attributes(p, os, FLAG_ITEM, outer,
2546 context.font.shape, "smallcaps");
2548 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2549 context.check_layout(os);
2550 TeXFont oldFont = context.font;
2551 context.font.init();
2552 context.font.size = oldFont.size;
2553 os << "\n\\family " << context.font.family << "\n";
2554 os << "\n\\series " << context.font.series << "\n";
2555 os << "\n\\shape " << context.font.shape << "\n";
2556 if (t.cs() == "textnormal") {
2557 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2558 output_font_change(os, context.font, oldFont);
2559 context.font = oldFont;
2561 eat_whitespace(p, os, context, false);
2564 else if (t.cs() == "textcolor") {
2565 // scheme is \textcolor{color name}{text}
2566 string const color = p.verbatim_item();
2567 // we only support the predefined colors of the color package
2568 if (color == "black" || color == "blue" || color == "cyan"
2569 || color == "green" || color == "magenta" || color == "red"
2570 || color == "white" || color == "yellow") {
2571 context.check_layout(os);
2572 os << "\n\\color " << color << "\n";
2573 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2574 context.check_layout(os);
2575 os << "\n\\color inherit\n";
2576 preamble.registerAutomaticallyLoadedPackage("color");
2578 // for custom defined colors
2579 handle_ert(os, t.asInput() + "{" + color + "}", context);
2582 else if (t.cs() == "underbar" || t.cs() == "uline") {
2583 // \underbar is not 100% correct (LyX outputs \uline
2584 // of ulem.sty). The difference is that \ulem allows
2585 // line breaks, and \underbar does not.
2586 // Do NOT handle \underline.
2587 // \underbar cuts through y, g, q, p etc.,
2588 // \underline does not.
2589 context.check_layout(os);
2590 os << "\n\\bar under\n";
2591 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2592 context.check_layout(os);
2593 os << "\n\\bar default\n";
2594 preamble.registerAutomaticallyLoadedPackage("ulem");
2597 else if (t.cs() == "sout") {
2598 context.check_layout(os);
2599 os << "\n\\strikeout on\n";
2600 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2601 context.check_layout(os);
2602 os << "\n\\strikeout default\n";
2603 preamble.registerAutomaticallyLoadedPackage("ulem");
2606 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2607 t.cs() == "emph" || t.cs() == "noun") {
2608 context.check_layout(os);
2609 os << "\n\\" << t.cs() << " on\n";
2610 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2611 context.check_layout(os);
2612 os << "\n\\" << t.cs() << " default\n";
2613 if (t.cs() == "uuline" || t.cs() == "uwave")
2614 preamble.registerAutomaticallyLoadedPackage("ulem");
2617 // FIXME, the inset layout should be plain, not standard, see bug #7846
2618 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2619 t.cs() == "vphantom") {
2620 context.check_layout(os);
2621 if (t.cs() == "phantom")
2622 begin_inset(os, "Phantom Phantom\n");
2623 if (t.cs() == "hphantom")
2624 begin_inset(os, "Phantom HPhantom\n");
2625 if (t.cs() == "vphantom")
2626 begin_inset(os, "Phantom VPhantom\n");
2627 os << "status open\n";
2628 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2632 else if (t.cs() == "href") {
2633 context.check_layout(os);
2634 string target = p.getArg('{', '}');
2635 string name = p.getArg('{', '}');
2637 size_t i = target.find(':');
2638 if (i != string::npos) {
2639 type = target.substr(0, i + 1);
2640 if (type == "mailto:" || type == "file:")
2641 target = target.substr(i + 1);
2642 // handle the case that name is equal to target, except of "http://"
2643 else if (target.substr(i + 3) == name && type == "http:")
2646 begin_command_inset(os, "href", "href");
2648 os << "name \"" << name << "\"\n";
2649 os << "target \"" << target << "\"\n";
2650 if (type == "mailto:" || type == "file:")
2651 os << "type \"" << type << "\"\n";
2653 skip_spaces_braces(p);
2656 else if (t.cs() == "lyxline") {
2657 // swallow size argument (it is not used anyway)
2659 if (!context.atParagraphStart()) {
2660 // so our line is in the middle of a paragraph
2661 // we need to add a new line, lest this line
2662 // follow the other content on that line and
2663 // run off the side of the page
2664 // FIXME: This may create an empty paragraph,
2665 // but without that it would not be
2666 // possible to set noindent below.
2667 // Fortunately LaTeX does not care
2668 // about the empty paragraph.
2669 context.new_paragraph(os);
2671 if (preamble.indentParagraphs()) {
2672 // we need to unindent, lest the line be too long
2673 context.add_par_extra_stuff("\\noindent\n");
2675 context.check_layout(os);
2676 begin_command_inset(os, "line", "rule");
2677 os << "offset \"0.5ex\"\n"
2678 "width \"100line%\"\n"
2683 else if (t.cs() == "rule") {
2684 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2685 string const width = p.getArg('{', '}');
2686 string const thickness = p.getArg('{', '}');
2687 context.check_layout(os);
2688 begin_command_inset(os, "line", "rule");
2689 if (!offset.empty())
2690 os << "offset \"" << translate_len(offset) << "\"\n";
2691 os << "width \"" << translate_len(width) << "\"\n"
2692 "height \"" << translate_len(thickness) << "\"\n";
2696 else if (is_known(t.cs(), known_phrases) ||
2697 (t.cs() == "protect" &&
2698 p.next_token().cat() == catEscape &&
2699 is_known(p.next_token().cs(), known_phrases))) {
2700 // LyX sometimes puts a \protect in front, so we have to ignore it
2701 // FIXME: This needs to be changed when bug 4752 is fixed.
2702 char const * const * where = is_known(
2703 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2705 context.check_layout(os);
2706 os << known_coded_phrases[where - known_phrases];
2707 skip_spaces_braces(p);
2710 else if (is_known(t.cs(), known_ref_commands)) {
2711 string const opt = p.getOpt();
2713 context.check_layout(os);
2714 char const * const * where = is_known(t.cs(),
2715 known_ref_commands);
2716 begin_command_inset(os, "ref",
2717 known_coded_ref_commands[where - known_ref_commands]);
2718 os << "reference \""
2719 << convert_command_inset_arg(p.verbatim_item())
2723 // LyX does not support optional arguments of ref commands
2724 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2725 p.verbatim_item() + "}", context);
2729 else if (use_natbib &&
2730 is_known(t.cs(), known_natbib_commands) &&
2731 ((t.cs() != "citefullauthor" &&
2732 t.cs() != "citeyear" &&
2733 t.cs() != "citeyearpar") ||
2734 p.next_token().asInput() != "*")) {
2735 context.check_layout(os);
2736 string command = t.cs();
2737 if (p.next_token().asInput() == "*") {
2741 if (command == "citefullauthor")
2742 // alternative name for "\\citeauthor*"
2743 command = "citeauthor*";
2745 // text before the citation
2747 // text after the citation
2749 get_cite_arguments(p, true, before, after);
2751 if (command == "cite") {
2752 // \cite without optional argument means
2753 // \citet, \cite with at least one optional
2754 // argument means \citep.
2755 if (before.empty() && after.empty())
2760 if (before.empty() && after == "[]")
2761 // avoid \citet[]{a}
2763 else if (before == "[]" && after == "[]") {
2764 // avoid \citet[][]{a}
2768 // remove the brackets around after and before
2769 if (!after.empty()) {
2771 after.erase(after.length() - 1, 1);
2772 after = convert_command_inset_arg(after);
2774 if (!before.empty()) {
2776 before.erase(before.length() - 1, 1);
2777 before = convert_command_inset_arg(before);
2779 begin_command_inset(os, "citation", command);
2780 os << "after " << '"' << after << '"' << "\n";
2781 os << "before " << '"' << before << '"' << "\n";
2783 << convert_command_inset_arg(p.verbatim_item())
2788 else if (use_jurabib &&
2789 is_known(t.cs(), known_jurabib_commands) &&
2790 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2791 context.check_layout(os);
2792 string command = t.cs();
2793 if (p.next_token().asInput() == "*") {
2797 char argumentOrder = '\0';
2798 vector<string> const options =
2799 preamble.getPackageOptions("jurabib");
2800 if (find(options.begin(), options.end(),
2801 "natbiborder") != options.end())
2802 argumentOrder = 'n';
2803 else if (find(options.begin(), options.end(),
2804 "jurabiborder") != options.end())
2805 argumentOrder = 'j';
2807 // text before the citation
2809 // text after the citation
2811 get_cite_arguments(p, argumentOrder != 'j', before, after);
2813 string const citation = p.verbatim_item();
2814 if (!before.empty() && argumentOrder == '\0') {
2815 cerr << "Warning: Assuming argument order "
2816 "of jurabib version 0.6 for\n'"
2817 << command << before << after << '{'
2818 << citation << "}'.\n"
2819 "Add 'jurabiborder' to the jurabib "
2820 "package options if you used an\n"
2821 "earlier jurabib version." << endl;
2823 if (!after.empty()) {
2825 after.erase(after.length() - 1, 1);
2827 if (!before.empty()) {
2829 before.erase(before.length() - 1, 1);
2831 begin_command_inset(os, "citation", command);
2832 os << "after " << '"' << after << '"' << "\n";
2833 os << "before " << '"' << before << '"' << "\n";
2834 os << "key " << '"' << citation << '"' << "\n";
2838 else if (t.cs() == "cite"
2839 || t.cs() == "nocite") {
2840 context.check_layout(os);
2841 string after = convert_command_inset_arg(p.getArg('[', ']'));
2842 string key = convert_command_inset_arg(p.verbatim_item());
2843 // store the case that it is "\nocite{*}" to use it later for
2846 begin_command_inset(os, "citation", t.cs());
2847 os << "after " << '"' << after << '"' << "\n";
2848 os << "key " << '"' << key << '"' << "\n";
2850 } else if (t.cs() == "nocite")
2854 else if (t.cs() == "index") {
2855 context.check_layout(os);
2856 begin_inset(os, "Index idx\n");
2857 os << "status collapsed\n";
2858 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2862 else if (t.cs() == "nomenclature") {
2863 context.check_layout(os);
2864 begin_command_inset(os, "nomenclature", "nomenclature");
2865 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2866 if (!prefix.empty())
2867 os << "prefix " << '"' << prefix << '"' << "\n";
2868 os << "symbol " << '"'
2869 << convert_command_inset_arg(p.verbatim_item());
2870 os << "\"\ndescription \""
2871 << convert_command_inset_arg(p.verbatim_item())
2876 else if (t.cs() == "label") {
2877 context.check_layout(os);
2878 begin_command_inset(os, "label", "label");
2880 << convert_command_inset_arg(p.verbatim_item())
2885 else if (t.cs() == "printindex") {
2886 context.check_layout(os);
2887 begin_command_inset(os, "index_print", "printindex");
2888 os << "type \"idx\"\n";
2890 skip_spaces_braces(p);
2893 else if (t.cs() == "printnomenclature") {
2895 string width_type = "";
2896 context.check_layout(os);
2897 begin_command_inset(os, "nomencl_print", "printnomenclature");
2898 // case of a custom width
2900 width = p.getArg('[', ']');
2901 width = translate_len(width);
2902 width_type = "custom";
2904 // case of no custom width
2905 // the case of no custom width but the width set
2906 // via \settowidth{\nomlabelwidth}{***} cannot be supported
2907 // because the user could have set anything, not only the width
2908 // of the longest label (which would be width_type = "auto")
2909 string label = convert_command_inset_arg(p.getArg('{', '}'));
2910 if (label.empty() && width_type.empty())
2911 width_type = "none";
2912 os << "set_width \"" << width_type << "\"\n";
2913 if (width_type == "custom")
2914 os << "width \"" << width << '\"';
2916 skip_spaces_braces(p);
2919 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2920 context.check_layout(os);
2921 begin_inset(os, "script ");
2922 os << t.cs().substr(4) << '\n';
2923 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2925 if (t.cs() == "textsubscript")
2926 preamble.registerAutomaticallyLoadedPackage("subscript");
2929 else if (is_known(t.cs(), known_quotes)) {
2930 char const * const * where = is_known(t.cs(), known_quotes);
2931 context.check_layout(os);
2932 begin_inset(os, "Quotes ");
2933 os << known_coded_quotes[where - known_quotes];
2935 // LyX adds {} after the quote, so we have to eat
2936 // spaces here if there are any before a possible
2938 eat_whitespace(p, os, context, false);
2942 else if (is_known(t.cs(), known_sizes) &&
2943 context.new_layout_allowed) {
2944 char const * const * where = is_known(t.cs(), known_sizes);
2945 context.check_layout(os);
2946 TeXFont const oldFont = context.font;
2947 context.font.size = known_coded_sizes[where - known_sizes];
2948 output_font_change(os, oldFont, context.font);
2949 eat_whitespace(p, os, context, false);
2952 else if (is_known(t.cs(), known_font_families) &&
2953 context.new_layout_allowed) {
2954 char const * const * where =
2955 is_known(t.cs(), known_font_families);
2956 context.check_layout(os);
2957 TeXFont const oldFont = context.font;
2958 context.font.family =
2959 known_coded_font_families[where - known_font_families];
2960 output_font_change(os, oldFont, context.font);
2961 eat_whitespace(p, os, context, false);
2964 else if (is_known(t.cs(), known_font_series) &&
2965 context.new_layout_allowed) {
2966 char const * const * where =
2967 is_known(t.cs(), known_font_series);
2968 context.check_layout(os);
2969 TeXFont const oldFont = context.font;
2970 context.font.series =
2971 known_coded_font_series[where - known_font_series];
2972 output_font_change(os, oldFont, context.font);
2973 eat_whitespace(p, os, context, false);
2976 else if (is_known(t.cs(), known_font_shapes) &&
2977 context.new_layout_allowed) {
2978 char const * const * where =
2979 is_known(t.cs(), known_font_shapes);
2980 context.check_layout(os);
2981 TeXFont const oldFont = context.font;
2982 context.font.shape =
2983 known_coded_font_shapes[where - known_font_shapes];
2984 output_font_change(os, oldFont, context.font);
2985 eat_whitespace(p, os, context, false);
2987 else if (is_known(t.cs(), known_old_font_families) &&
2988 context.new_layout_allowed) {
2989 char const * const * where =
2990 is_known(t.cs(), known_old_font_families);
2991 context.check_layout(os);
2992 TeXFont const oldFont = context.font;
2993 context.font.init();
2994 context.font.size = oldFont.size;
2995 context.font.family =
2996 known_coded_font_families[where - known_old_font_families];
2997 output_font_change(os, oldFont, context.font);
2998 eat_whitespace(p, os, context, false);
3001 else if (is_known(t.cs(), known_old_font_series) &&
3002 context.new_layout_allowed) {
3003 char const * const * where =
3004 is_known(t.cs(), known_old_font_series);
3005 context.check_layout(os);
3006 TeXFont const oldFont = context.font;
3007 context.font.init();
3008 context.font.size = oldFont.size;
3009 context.font.series =
3010 known_coded_font_series[where - known_old_font_series];
3011 output_font_change(os, oldFont, context.font);
3012 eat_whitespace(p, os, context, false);
3015 else if (is_known(t.cs(), known_old_font_shapes) &&
3016 context.new_layout_allowed) {
3017 char const * const * where =
3018 is_known(t.cs(), known_old_font_shapes);
3019 context.check_layout(os);
3020 TeXFont const oldFont = context.font;
3021 context.font.init();
3022 context.font.size = oldFont.size;
3023 context.font.shape =
3024 known_coded_font_shapes[where - known_old_font_shapes];
3025 output_font_change(os, oldFont, context.font);
3026 eat_whitespace(p, os, context, false);
3029 else if (t.cs() == "selectlanguage") {
3030 context.check_layout(os);
3031 // save the language for the case that a
3032 // \foreignlanguage is used
3034 context.font.language = babel2lyx(p.verbatim_item());
3035 os << "\n\\lang " << context.font.language << "\n";
3038 else if (t.cs() == "foreignlanguage") {
3039 string const lang = babel2lyx(p.verbatim_item());
3040 parse_text_attributes(p, os, FLAG_ITEM, outer,
3042 context.font.language, lang);
3045 else if (t.cs() == "inputencoding") {
3046 // nothing to write here
3047 string const enc = subst(p.verbatim_item(), "\n", " ");
3051 else if (t.cs() == "ldots") {
3052 context.check_layout(os);
3053 os << "\\SpecialChar \\ldots{}\n";
3054 skip_spaces_braces(p);
3057 else if (t.cs() == "lyxarrow") {
3058 context.check_layout(os);
3059 os << "\\SpecialChar \\menuseparator\n";
3060 skip_spaces_braces(p);
3063 else if (t.cs() == "textcompwordmark") {
3064 context.check_layout(os);
3065 os << "\\SpecialChar \\textcompwordmark{}\n";
3066 skip_spaces_braces(p);
3069 else if (t.cs() == "slash") {
3070 context.check_layout(os);
3071 os << "\\SpecialChar \\slash{}\n";
3072 skip_spaces_braces(p);
3075 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3076 context.check_layout(os);
3077 os << "\\SpecialChar \\nobreakdash-\n";
3081 else if (t.cs() == "textquotedbl") {
3082 context.check_layout(os);
3087 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3088 context.check_layout(os);
3089 os << "\\SpecialChar \\@.\n";
3093 else if (t.cs() == "-") {
3094 context.check_layout(os);
3095 os << "\\SpecialChar \\-\n";
3098 else if (t.cs() == "textasciitilde") {
3099 context.check_layout(os);
3101 skip_spaces_braces(p);
3104 else if (t.cs() == "textasciicircum") {
3105 context.check_layout(os);
3107 skip_spaces_braces(p);
3110 else if (t.cs() == "textbackslash") {
3111 context.check_layout(os);
3112 os << "\n\\backslash\n";
3113 skip_spaces_braces(p);
3116 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3117 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3119 context.check_layout(os);
3123 else if (t.cs() == "char") {
3124 context.check_layout(os);
3125 if (p.next_token().character() == '`') {
3127 if (p.next_token().cs() == "\"") {
3132 handle_ert(os, "\\char`", context);
3135 handle_ert(os, "\\char", context);
3139 else if (t.cs() == "verb") {
3140 context.check_layout(os);
3141 char const delimiter = p.next_token().character();
3142 string const arg = p.getArg(delimiter, delimiter);
3144 oss << "\\verb" << delimiter << arg << delimiter;
3145 handle_ert(os, oss.str(), context);
3148 // Problem: \= creates a tabstop inside the tabbing environment
3149 // and else an accent. In the latter case we really would want
3150 // \={o} instead of \= o.
3151 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3152 handle_ert(os, t.asInput(), context);
3154 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3155 else if (t.cs().size() == 1
3156 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3157 context.check_layout(os);
3158 // try to see whether the string is in unicodesymbols
3160 string command = t.asInput() + "{"
3161 + trimSpaceAndEol(p.verbatim_item())
3163 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3166 cerr << "When parsing " << command
3167 << ", result is " << to_utf8(s)
3168 << "+" << to_utf8(rem) << endl;
3171 // we did not find a non-ert version
3172 handle_ert(os, command, context);
3175 else if (t.cs() == "\\") {
3176 context.check_layout(os);
3178 handle_ert(os, "\\\\" + p.getOpt(), context);
3179 else if (p.next_token().asInput() == "*") {
3181 // getOpt() eats the following space if there
3182 // is no optional argument, but that is OK
3183 // here since it has no effect in the output.
3184 handle_ert(os, "\\\\*" + p.getOpt(), context);
3187 begin_inset(os, "Newline newline");
3192 else if (t.cs() == "newline" ||
3193 (t.cs() == "linebreak" && !p.hasOpt())) {
3194 context.check_layout(os);
3195 begin_inset(os, "Newline ");
3198 skip_spaces_braces(p);
3201 else if (t.cs() == "input" || t.cs() == "include"
3202 || t.cs() == "verbatiminput") {
3203 string name = t.cs();
3204 if (t.cs() == "verbatiminput"
3205 && p.next_token().asInput() == "*")
3206 name += p.get_token().asInput();
3207 context.check_layout(os);
3208 string filename(normalize_filename(p.getArg('{', '}')));
3209 string const path = getMasterFilePath();
3210 // We want to preserve relative / absolute filenames,
3211 // therefore path is only used for testing
3212 if ((t.cs() == "include" || t.cs() == "input") &&
3213 !makeAbsPath(filename, path).exists()) {
3214 // The file extension is probably missing.
3215 // Now try to find it out.
3216 string const tex_name =
3217 find_file(filename, path,
3218 known_tex_extensions);
3219 if (!tex_name.empty())
3220 filename = tex_name;
3222 bool external = false;
3224 if (makeAbsPath(filename, path).exists()) {
3225 string const abstexname =
3226 makeAbsPath(filename, path).absFileName();
3227 string const abslyxname =
3228 changeExtension(abstexname, ".lyx");
3229 string const absfigname =
3230 changeExtension(abstexname, ".fig");
3231 fix_relative_filename(filename);
3232 string const lyxname =
3233 changeExtension(filename, ".lyx");
3235 external = FileName(absfigname).exists();
3236 if (t.cs() == "input") {
3237 string const ext = getExtension(abstexname);
3239 // Combined PS/LaTeX:
3240 // x.eps, x.pstex_t (old xfig)
3241 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3242 FileName const absepsname(
3243 changeExtension(abstexname, ".eps"));
3244 FileName const abspstexname(
3245 changeExtension(abstexname, ".pstex"));
3246 bool const xfigeps =
3247 (absepsname.exists() ||
3248 abspstexname.exists()) &&
3251 // Combined PDF/LaTeX:
3252 // x.pdf, x.pdftex_t (old xfig)
3253 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3254 FileName const abspdfname(
3255 changeExtension(abstexname, ".pdf"));
3256 bool const xfigpdf =
3257 abspdfname.exists() &&
3258 (ext == "pdftex_t" || ext == "pdf_t");
3262 // Combined PS/PDF/LaTeX:
3263 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3264 string const absbase2(
3265 removeExtension(abstexname) + "_pspdftex");
3266 FileName const abseps2name(
3267 addExtension(absbase2, ".eps"));
3268 FileName const abspdf2name(
3269 addExtension(absbase2, ".pdf"));
3270 bool const xfigboth =
3271 abspdf2name.exists() &&
3272 abseps2name.exists() && ext == "pspdftex";
3274 xfig = xfigpdf || xfigeps || xfigboth;
3275 external = external && xfig;
3278 outname = changeExtension(filename, ".fig");
3280 // Don't try to convert, the result
3281 // would be full of ERT.
3283 } else if (t.cs() != "verbatiminput" &&
3284 tex2lyx(abstexname, FileName(abslyxname),
3291 cerr << "Warning: Could not find included file '"
3292 << filename << "'." << endl;
3296 begin_inset(os, "External\n");
3297 os << "\ttemplate XFig\n"
3298 << "\tfilename " << outname << '\n';
3300 begin_command_inset(os, "include", name);
3301 os << "preview false\n"
3302 "filename \"" << outname << "\"\n";
3307 else if (t.cs() == "bibliographystyle") {
3308 // store new bibliographystyle
3309 bibliographystyle = p.verbatim_item();
3310 // If any other command than \bibliography and
3311 // \nocite{*} follows, we need to output the style
3312 // (because it might be used by that command).
3313 // Otherwise, it will automatically be output by LyX.
3316 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3317 if (t2.cat() == catBegin)
3319 if (t2.cat() != catEscape)
3321 if (t2.cs() == "nocite") {
3322 if (p.getArg('{', '}') == "*")
3324 } else if (t2.cs() == "bibliography")
3331 "\\bibliographystyle{" + bibliographystyle + '}',
3336 else if (t.cs() == "bibliography") {
3337 context.check_layout(os);
3338 begin_command_inset(os, "bibtex", "bibtex");
3339 if (!btprint.empty()) {
3340 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3341 // clear the string because the next BibTeX inset can be without the
3342 // \nocite{*} option
3345 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3346 // Do we have a bibliographystyle set?
3347 if (!bibliographystyle.empty())
3348 os << "options " << '"' << bibliographystyle << '"' << "\n";
3352 else if (t.cs() == "parbox")
3353 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3355 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3356 t.cs() == "shadowbox" || t.cs() == "doublebox")
3357 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3359 else if (t.cs() == "framebox") {
3360 string special = p.getFullOpt();
3361 special += p.getOpt();
3362 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3365 //\makebox() is part of the picture environment and different from \makebox{}
3366 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3367 else if (t.cs() == "makebox") {
3368 string arg = t.asInput();
3369 if (p.next_token().character() == '(')
3370 //the syntax is: \makebox(x,y)[position]{content}
3371 arg += p.getFullParentheseArg();
3373 //the syntax is: \makebox[width][position]{content}
3374 arg += p.getFullOpt();
3375 handle_ert(os, arg + p.getFullOpt(), context);
3378 else if (t.cs() == "smallskip" ||
3379 t.cs() == "medskip" ||
3380 t.cs() == "bigskip" ||
3381 t.cs() == "vfill") {
3382 context.check_layout(os);
3383 begin_inset(os, "VSpace ");
3386 skip_spaces_braces(p);
3389 else if (is_known(t.cs(), known_spaces)) {
3390 char const * const * where = is_known(t.cs(), known_spaces);
3391 context.check_layout(os);
3392 begin_inset(os, "space ");
3393 os << '\\' << known_coded_spaces[where - known_spaces]
3396 // LaTeX swallows whitespace after all spaces except
3397 // "\\,". We have to do that here, too, because LyX
3398 // adds "{}" which would make the spaces significant.
3400 eat_whitespace(p, os, context, false);
3401 // LyX adds "{}" after all spaces except "\\ " and
3402 // "\\,", so we have to remove "{}".
3403 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3404 // remove the braces after "\\,", too.
3409 else if (t.cs() == "newpage" ||
3410 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3411 t.cs() == "clearpage" ||
3412 t.cs() == "cleardoublepage") {
3413 context.check_layout(os);
3414 begin_inset(os, "Newpage ");
3417 skip_spaces_braces(p);
3420 else if (t.cs() == "DeclareRobustCommand" ||
3421 t.cs() == "DeclareRobustCommandx" ||
3422 t.cs() == "newcommand" ||
3423 t.cs() == "newcommandx" ||
3424 t.cs() == "providecommand" ||
3425 t.cs() == "providecommandx" ||
3426 t.cs() == "renewcommand" ||
3427 t.cs() == "renewcommandx") {
3428 // DeclareRobustCommand, DeclareRobustCommandx,
3429 // providecommand and providecommandx could be handled
3430 // by parse_command(), but we need to call
3431 // add_known_command() here.
3432 string name = t.asInput();
3433 if (p.next_token().asInput() == "*") {
3434 // Starred form. Eat '*'
3438 string const command = p.verbatim_item();
3439 string const opt1 = p.getFullOpt();
3440 string const opt2 = p.getFullOpt();
3441 add_known_command(command, opt1, !opt2.empty());
3442 string const ert = name + '{' + command + '}' +
3444 '{' + p.verbatim_item() + '}';
3446 if (t.cs() == "DeclareRobustCommand" ||
3447 t.cs() == "DeclareRobustCommandx" ||
3448 t.cs() == "providecommand" ||
3449 t.cs() == "providecommandx" ||
3450 name[name.length()-1] == '*')
3451 handle_ert(os, ert, context);
3453 context.check_layout(os);
3454 begin_inset(os, "FormulaMacro");
3460 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3461 // let could be handled by parse_command(),
3462 // but we need to call add_known_command() here.
3463 string ert = t.asInput();
3466 if (p.next_token().cat() == catBegin) {
3467 name = p.verbatim_item();
3468 ert += '{' + name + '}';
3470 name = p.verbatim_item();
3475 if (p.next_token().cat() == catBegin) {
3476 command = p.verbatim_item();
3477 ert += '{' + command + '}';
3479 command = p.verbatim_item();
3482 // If command is known, make name known too, to parse
3483 // its arguments correctly. For this reason we also
3484 // have commands in syntax.default that are hardcoded.
3485 CommandMap::iterator it = known_commands.find(command);
3486 if (it != known_commands.end())
3487 known_commands[t.asInput()] = it->second;
3488 handle_ert(os, ert, context);
3491 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3492 bool starred = false;
3493 if (p.next_token().asInput() == "*") {
3497 string name = t.asInput();
3498 string const length = p.verbatim_item();
3501 bool valid = splitLatexLength(length, valstring, unit);
3502 bool known_hspace = false;
3503 bool known_vspace = false;
3504 bool known_unit = false;
3507 istringstream iss(valstring);
3510 if (t.cs()[0] == 'h') {
3511 if (unit == "\\fill") {
3516 known_hspace = true;
3519 if (unit == "\\smallskipamount") {
3521 known_vspace = true;
3522 } else if (unit == "\\medskipamount") {
3524 known_vspace = true;
3525 } else if (unit == "\\bigskipamount") {
3527 known_vspace = true;
3528 } else if (unit == "\\fill") {
3530 known_vspace = true;
3534 if (!known_hspace && !known_vspace) {
3535 switch (unitFromString(unit)) {
3556 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3557 // Literal horizontal length or known variable
3558 context.check_layout(os);
3559 begin_inset(os, "space ");
3567 if (known_unit && !known_hspace)
3569 << translate_len(length);
3571 } else if (known_unit || known_vspace) {
3572 // Literal vertical length or known variable
3573 context.check_layout(os);
3574 begin_inset(os, "VSpace ");
3582 // LyX can't handle other length variables in Inset VSpace/space
3587 handle_ert(os, name + '{' + unit + '}', context);
3588 else if (value == -1.0)
3589 handle_ert(os, name + "{-" + unit + '}', context);
3591 handle_ert(os, name + '{' + valstring + unit + '}', context);
3593 handle_ert(os, name + '{' + length + '}', context);
3597 // The single '=' is meant here.
3598 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3600 context.check_layout(os);
3601 begin_inset(os, "Flex ");
3602 os << to_utf8(newinsetlayout->name()) << '\n'
3603 << "status collapsed\n";
3604 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3609 // try to see whether the string is in unicodesymbols
3610 // Only use text mode commands, since we are in text mode here,
3611 // and math commands may be invalid (bug 6797)
3613 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3614 rem, Encodings::TEXT_CMD);
3617 cerr << "When parsing " << t.cs()
3618 << ", result is " << to_utf8(s)
3619 << "+" << to_utf8(rem) << endl;
3620 context.check_layout(os);
3622 skip_spaces_braces(p);
3624 //cerr << "#: " << t << " mode: " << mode << endl;
3625 // heuristic: read up to next non-nested space
3627 string s = t.asInput();
3628 string z = p.verbatim_item();
3629 while (p.good() && z != " " && z.size()) {
3630 //cerr << "read: " << z << endl;
3632 z = p.verbatim_item();
3634 cerr << "found ERT: " << s << endl;
3635 handle_ert(os, s + ' ', context);
3638 string name = t.asInput();
3639 if (p.next_token().asInput() == "*") {
3640 // Starred commands like \vspace*{}
3641 p.get_token(); // Eat '*'
3644 if (!parse_command(name, p, os, outer, context))
3645 handle_ert(os, name, context);
3649 if (flags & FLAG_LEAVE) {
3650 flags &= ~FLAG_LEAVE;