2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
25 #include "support/lassert.h"
26 #include "support/convert.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
38 using namespace lyx::support;
43 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
44 Context const & context)
46 Context newcontext(true, context.textclass);
47 newcontext.font = context.font;
48 parse_text(p, os, flags, outer, newcontext);
49 newcontext.check_end_layout(os);
55 /// parses a paragraph snippet, useful for example for \\emph{...}
56 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
59 Context newcontext(context);
60 // Don't inherit the paragraph-level extra stuff
61 newcontext.par_extra_stuff.clear();
62 parse_text(p, os, flags, outer, newcontext);
63 // Make sure that we don't create invalid .lyx files
64 context.need_layout = newcontext.need_layout;
65 context.need_end_layout = newcontext.need_end_layout;
70 * Thin wrapper around parse_text_snippet() using a string.
72 * We completely ignore \c context.need_layout and \c context.need_end_layout,
73 * because our return value is not used directly (otherwise the stream version
74 * of parse_text_snippet() could be used). That means that the caller needs
75 * to do layout management manually.
76 * This is intended to parse text that does not create any layout changes.
78 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
81 Context newcontext(context);
82 newcontext.need_layout = false;
83 newcontext.need_end_layout = false;
84 newcontext.new_layout_allowed = false;
85 // Avoid warning by Context::~Context()
86 newcontext.par_extra_stuff.clear();
88 parse_text_snippet(p, os, flags, outer, newcontext);
93 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
94 "vpageref", "prettyref", "eqref", 0 };
98 * The starred forms are also known except for "citefullauthor",
99 * "citeyear" and "citeyearpar".
101 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
102 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
103 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
107 * No starred form other than "cite*" known.
109 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
110 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
111 // jurabib commands not (yet) supported by LyX:
113 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
114 // "footciteauthor", "footciteyear", "footciteyearpar",
115 "citefield", "citetitle", 0 };
117 /// LaTeX names for quotes
118 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
119 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
120 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
121 "guilsinglleft", "frq", "guilsinglright", 0};
123 /// the same as known_quotes with .lyx names
124 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
125 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
126 "gld", "grd", "gls", "ers", "fls",
127 "fls", "frs", "frs", 0};
129 /// LaTeX names for font sizes
130 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
131 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
133 /// the same as known_sizes with .lyx names
134 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
135 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
137 /// LaTeX 2.09 names for font families
138 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
140 /// LaTeX names for font families
141 char const * const known_font_families[] = { "rmfamily", "sffamily",
144 /// the same as known_old_font_families and known_font_families with .lyx names
145 char const * const known_coded_font_families[] = { "roman", "sans",
148 /// LaTeX 2.09 names for font series
149 char const * const known_old_font_series[] = { "bf", 0};
151 /// LaTeX names for font series
152 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
154 /// the same as known_old_font_series and known_font_series with .lyx names
155 char const * const known_coded_font_series[] = { "bold", "medium", 0};
157 /// LaTeX 2.09 names for font shapes
158 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
160 /// LaTeX names for font shapes
161 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
164 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
165 char const * const known_coded_font_shapes[] = { "italic", "slanted",
166 "smallcaps", "up", 0};
169 * Graphics file extensions known by the dvips driver of the graphics package.
170 * These extensions are used to complete the filename of an included
171 * graphics file if it does not contain an extension.
172 * The order must be the same that latex uses to find a file, because we
173 * will use the first extension that matches.
174 * This is only an approximation for the common cases. If we would want to
175 * do it right in all cases, we would need to know which graphics driver is
176 * used and know the extensions of every driver of the graphics package.
178 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
179 "ps.gz", "eps.Z", "ps.Z", 0};
182 * Graphics file extensions known by the pdftex driver of the graphics package.
183 * \sa known_dvips_graphics_formats
185 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
189 * Known file extensions for TeX files as used by \\include.
191 char const * const known_tex_extensions[] = {"tex", 0};
193 /// spaces known by InsetSpace
194 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
195 "qquad", "enspace", "enskip", "negthinspace", "hfill", "dotfill", "hrulefill",
196 "leftarrowfill", "rightarrowfill", "upbracefill", "downbracefill", 0};
198 /// the same as known_spaces with .lyx names
199 char const * const known_coded_spaces[] = { "space{}", "space{}",
200 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
201 "negthinspace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
202 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
204 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
205 /// them in ERT. "LaTeXe" must come before "LaTeX"!
206 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
207 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
208 int const known_phrase_lengths[] = {3, 5, 7, 0};
211 /// splits "x=z, y=b" into a map and an ordered keyword vector
212 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
217 keys.resize(v.size());
218 for (size_t i = 0; i < v.size(); ++i) {
219 size_t const pos = v[i].find('=');
220 string const index = trim(v[i].substr(0, pos));
221 string const value = trim(v[i].substr(pos + 1, string::npos));
229 * Split a LaTeX length into value and unit.
230 * The latter can be a real unit like "pt", or a latex length variable
231 * like "\textwidth". The unit may contain additional stuff like glue
232 * lengths, but we don't care, because such lengths are ERT anyway.
233 * \returns true if \p value and \p unit are valid.
235 bool splitLatexLength(string const & len, string & value, string & unit)
239 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
240 //'4,5' is a valid LaTeX length number. Change it to '4.5'
241 string const length = subst(len, ',', '.');
242 if (i == string::npos)
245 if (len[0] == '\\') {
246 // We had something like \textwidth without a factor
252 value = trim(string(length, 0, i));
256 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
257 if (contains(len, '\\'))
258 unit = trim(string(len, i));
260 unit = ascii_lowercase(trim(string(len, i)));
265 /// A simple function to translate a latex length to something LyX can
266 /// understand. Not perfect, but rather best-effort.
267 bool translate_len(string const & length, string & valstring, string & unit)
269 if (!splitLatexLength(length, valstring, unit))
271 // LyX uses percent values
273 istringstream iss(valstring);
278 string const percentval = oss.str();
280 if (unit.empty() || unit[0] != '\\')
282 string::size_type const i = unit.find(' ');
283 string const endlen = (i == string::npos) ? string() : string(unit, i);
284 if (unit == "\\textwidth") {
285 valstring = percentval;
286 unit = "text%" + endlen;
287 } else if (unit == "\\columnwidth") {
288 valstring = percentval;
289 unit = "col%" + endlen;
290 } else if (unit == "\\paperwidth") {
291 valstring = percentval;
292 unit = "page%" + endlen;
293 } else if (unit == "\\linewidth") {
294 valstring = percentval;
295 unit = "line%" + endlen;
296 } else if (unit == "\\paperheight") {
297 valstring = percentval;
298 unit = "pheight%" + endlen;
299 } else if (unit == "\\textheight") {
300 valstring = percentval;
301 unit = "theight%" + endlen;
309 string translate_len(string const & length)
313 if (translate_len(length, value, unit))
315 // If the input is invalid, return what we have.
323 * Translates a LaTeX length into \p value, \p unit and
324 * \p special parts suitable for a box inset.
325 * The difference from translate_len() is that a box inset knows about
326 * some special "units" that are stored in \p special.
328 void translate_box_len(string const & length, string & value, string & unit, string & special)
330 if (translate_len(length, value, unit)) {
331 if (unit == "\\height" || unit == "\\depth" ||
332 unit == "\\totalheight" || unit == "\\width") {
333 special = unit.substr(1);
334 // The unit is not used, but LyX requires a dummy setting
347 * Find a file with basename \p name in path \p path and an extension
350 string find_file(string const & name, string const & path,
351 char const * const * extensions)
353 for (char const * const * what = extensions; *what; ++what) {
354 string const trial = addExtension(name, *what);
355 if (makeAbsPath(trial, path).exists())
362 void begin_inset(ostream & os, string const & name)
364 os << "\n\\begin_inset " << name;
368 void begin_command_inset(ostream & os, string const & name,
369 string const & latexname)
371 begin_inset(os, "CommandInset ");
372 os << name << "\nLatexCommand " << latexname << '\n';
376 void end_inset(ostream & os)
378 os << "\n\\end_inset\n\n";
382 bool skip_braces(Parser & p)
384 if (p.next_token().cat() != catBegin)
387 if (p.next_token().cat() == catEnd) {
396 void handle_ert(ostream & os, string const & s, Context & context)
398 // We must have a valid layout before outputting the ERT inset.
399 context.check_layout(os);
400 Context newcontext(true, context.textclass);
401 begin_inset(os, "ERT");
402 os << "\nstatus collapsed\n";
403 newcontext.check_layout(os);
404 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
406 os << "\n\\backslash\n";
407 else if (*it == '\n') {
408 newcontext.new_paragraph(os);
409 newcontext.check_layout(os);
413 newcontext.check_end_layout(os);
418 void handle_comment(ostream & os, string const & s, Context & context)
420 // TODO: Handle this better
421 Context newcontext(true, context.textclass);
422 begin_inset(os, "ERT");
423 os << "\nstatus collapsed\n";
424 newcontext.check_layout(os);
425 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
427 os << "\n\\backslash\n";
431 // make sure that our comment is the last thing on the line
432 newcontext.new_paragraph(os);
433 newcontext.check_layout(os);
434 newcontext.check_end_layout(os);
439 Layout const * findLayout(TextClass const & textclass, string const & name)
441 DocumentClass::const_iterator lit = textclass.begin();
442 DocumentClass::const_iterator len = textclass.end();
443 for (; lit != len; ++lit)
444 if (lit->latexname() == name)
450 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
452 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
453 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
454 for (; it != en; ++it)
455 if (it->second.latexname() == name &&
456 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
457 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
458 return &(it->second);
463 void eat_whitespace(Parser &, ostream &, Context &, bool);
467 * Skips whitespace and braces.
468 * This should be called after a command has been parsed that is not put into
469 * ERT, and where LyX adds "{}" if needed.
471 void skip_spaces_braces(Parser & p, bool keepws = false)
473 /* The following four examples produce the same typeset output and
474 should be handled by this function:
482 // Unfortunately we need to skip comments, too.
483 // We can't use eat_whitespace since writing them after the {}
484 // results in different output in some cases.
485 bool const skipped_spaces = p.skip_spaces(true);
486 bool const skipped_braces = skip_braces(p);
487 if (keepws && skipped_spaces && !skipped_braces)
488 // put back the space (it is better handled by check_space)
489 p.unskip_spaces(true);
493 void output_command_layout(ostream & os, Parser & p, bool outer,
494 Context & parent_context,
495 Layout const * newlayout)
497 TeXFont const oldFont = parent_context.font;
498 // save the current font size
499 string const size = oldFont.size;
500 // reset the font size to default, because the font size switches
501 // don't affect section headings and the like
502 parent_context.font.size = Context::normalfont.size;
503 // we only need to write the font change if we have an open layout
504 if (!parent_context.atParagraphStart())
505 output_font_change(os, oldFont, parent_context.font);
506 parent_context.check_end_layout(os);
507 Context context(true, parent_context.textclass, newlayout,
508 parent_context.layout, parent_context.font);
509 if (parent_context.deeper_paragraph) {
510 // We are beginning a nested environment after a
511 // deeper paragraph inside the outer list environment.
512 // Therefore we don't need to output a "begin deeper".
513 context.need_end_deeper = true;
515 context.check_deeper(os);
516 context.check_layout(os);
517 unsigned int optargs = 0;
518 while (optargs < context.layout->optargs) {
519 eat_whitespace(p, os, context, false);
520 if (p.next_token().cat() == catEscape ||
521 p.next_token().character() != '[')
523 p.get_token(); // eat '['
524 begin_inset(os, "OptArg\n");
525 os << "status collapsed\n\n";
526 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
528 eat_whitespace(p, os, context, false);
531 unsigned int reqargs = 0;
532 while (LYX_FORMAT >= 392 && reqargs < context.layout->reqargs) {
533 eat_whitespace(p, os, context, false);
534 if (p.next_token().cat() != catBegin)
536 p.get_token(); // eat '{'
537 begin_inset(os, "OptArg\n");
538 os << "status collapsed\n\n";
539 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
541 eat_whitespace(p, os, context, false);
544 parse_text(p, os, FLAG_ITEM, outer, context);
545 context.check_end_layout(os);
546 if (parent_context.deeper_paragraph) {
547 // We must suppress the "end deeper" because we
548 // suppressed the "begin deeper" above.
549 context.need_end_deeper = false;
551 context.check_end_deeper(os);
552 // We don't need really a new paragraph, but
553 // we must make sure that the next item gets a \begin_layout.
554 parent_context.new_paragraph(os);
555 // Set the font size to the original value. No need to output it here
556 // (Context::begin_layout() will do that if needed)
557 parent_context.font.size = size;
562 * Output a space if necessary.
563 * This function gets called for every whitespace token.
565 * We have three cases here:
566 * 1. A space must be suppressed. Example: The lyxcode case below
567 * 2. A space may be suppressed. Example: Spaces before "\par"
568 * 3. A space must not be suppressed. Example: A space between two words
570 * We currently handle only 1. and 3 and from 2. only the case of
571 * spaces before newlines as a side effect.
573 * 2. could be used to suppress as many spaces as possible. This has two effects:
574 * - Reimporting LyX generated LaTeX files changes almost no whitespace
575 * - Superflous whitespace from non LyX generated LaTeX files is removed.
576 * The drawback is that the logic inside the function becomes
577 * complicated, and that is the reason why it is not implemented.
579 void check_space(Parser & p, ostream & os, Context & context)
581 Token const next = p.next_token();
582 Token const curr = p.curr_token();
583 // A space before a single newline and vice versa must be ignored
584 // LyX emits a newline before \end{lyxcode}.
585 // This newline must be ignored,
586 // otherwise LyX will add an additional protected space.
587 if (next.cat() == catSpace ||
588 next.cat() == catNewline ||
589 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
592 context.check_layout(os);
598 * Parse all arguments of \p command
600 void parse_arguments(string const & command,
601 vector<ArgumentType> const & template_arguments,
602 Parser & p, ostream & os, bool outer, Context & context)
604 string ert = command;
605 size_t no_arguments = template_arguments.size();
606 for (size_t i = 0; i < no_arguments; ++i) {
607 switch (template_arguments[i]) {
609 // This argument contains regular LaTeX
610 handle_ert(os, ert + '{', context);
611 eat_whitespace(p, os, context, false);
612 parse_text(p, os, FLAG_ITEM, outer, context);
616 // This argument consists only of a single item.
617 // The presence of '{' or not must be preserved.
619 if (p.next_token().cat() == catBegin)
620 ert += '{' + p.verbatim_item() + '}';
622 ert += p.verbatim_item();
625 // This argument may contain special characters
626 ert += '{' + p.verbatim_item() + '}';
629 // true because we must not eat whitespace
630 ert += p.getOpt(true);
634 handle_ert(os, ert, context);
639 * Check whether \p command is a known command. If yes,
640 * handle the command with all arguments.
641 * \return true if the command was parsed, false otherwise.
643 bool parse_command(string const & command, Parser & p, ostream & os,
644 bool outer, Context & context)
646 if (known_commands.find(command) != known_commands.end()) {
647 parse_arguments(command, known_commands[command], p, os,
655 /// Parses a minipage or parbox
656 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
657 unsigned inner_flags, bool outer, Context & parent_context,
658 string const & outer_type, string const & special,
659 string const & inner_type)
663 string hor_pos = "c";
664 // We need to set the height to the LaTeX default of 1\\totalheight
665 // for the case when no height argument is given
666 string height_value = "1";
667 string height_unit = "in";
668 string height_special = "totalheight";
670 if (!inner_type.empty() && p.hasOpt()) {
671 position = p.getArg('[', ']');
672 if (position != "t" && position != "c" && position != "b") {
673 cerr << "invalid position " << position << " for "
674 << inner_type << endl;
678 latex_height = p.getArg('[', ']');
679 translate_box_len(latex_height, height_value, height_unit, height_special);
682 inner_pos = p.getArg('[', ']');
683 if (inner_pos != "c" && inner_pos != "t" &&
684 inner_pos != "b" && inner_pos != "s") {
685 cerr << "invalid inner_pos "
686 << inner_pos << " for "
687 << inner_type << endl;
688 inner_pos = position;
696 if (inner_type.empty()) {
698 latex_width = "\\columnwidth";
701 latex_width = p2.getOptContent();
702 string const opt = p2.getOptContent();
705 if (hor_pos != "l" && hor_pos != "c" &&
707 cerr << "invalid hor_pos " << hor_pos
708 << " for " << outer_type << endl;
714 latex_width = p.verbatim_item();
715 translate_len(latex_width, width_value, width_unit);
716 // LyX can't handle length variables
717 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
718 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
719 // Look whether there is some content after the end of the
720 // inner box, but before the end of the outer box.
721 // If yes, we need to output ERT.
723 if (inner_flags & FLAG_END)
724 p.verbatimEnvironment(inner_type);
728 if ((outer_type == "framed" && p.next_token().asInput() != "\\end") ||
729 (outer_type != "framed" && p.next_token().cat() != catEnd)) {
730 // something is between the end of the inner box and
731 // the end of the outer box, so we need to use ERT.
738 if (!outer_type.empty()) {
739 if (outer_flags & FLAG_END)
740 ss << "\\begin{" << outer_type << '}';
742 ss << '\\' << outer_type << '{';
743 if (!special.empty())
747 if (!inner_type.empty()) {
748 if (inner_flags & FLAG_END)
749 ss << "\\begin{" << inner_type << '}';
751 ss << '\\' << inner_type;
752 if (!position.empty())
753 ss << '[' << position << ']';
754 if (!latex_height.empty())
755 ss << '[' << latex_height << ']';
756 if (!inner_pos.empty())
757 ss << '[' << inner_pos << ']';
758 ss << '{' << latex_width << '}';
759 if (!(inner_flags & FLAG_END))
762 handle_ert(os, ss.str(), parent_context);
763 if (!inner_type.empty()) {
764 parse_text(p, os, inner_flags, outer, parent_context);
765 if (inner_flags & FLAG_END)
766 handle_ert(os, "\\end{" + inner_type + '}',
769 handle_ert(os, "}", parent_context);
771 if (!outer_type.empty()) {
772 parse_text(p, os, outer_flags, outer, parent_context);
773 if (outer_flags & FLAG_END)
774 handle_ert(os, "\\end{" + outer_type + '}',
777 handle_ert(os, "}", parent_context);
780 // LyX does not like empty positions, so we have
781 // to set them to the LaTeX default values here.
782 if (position.empty())
784 if (inner_pos.empty())
785 inner_pos = position;
786 parent_context.check_layout(os);
787 begin_inset(os, "Box ");
788 if (outer_type == "framed")
790 else if (outer_type == "framebox")
792 else if (outer_type == "shadowbox")
794 else if (outer_type == "shaded")
796 else if (outer_type == "doublebox")
798 else if (outer_type.empty())
801 os << outer_type << '\n';
802 os << "position \"" << position << "\"\n";
803 os << "hor_pos \"" << hor_pos << "\"\n";
804 os << "has_inner_box " << !inner_type.empty() << "\n";
805 os << "inner_pos \"" << inner_pos << "\"\n";
806 os << "use_parbox " << (inner_type == "parbox") << '\n';
807 os << "width \"" << width_value << width_unit << "\"\n";
808 os << "special \"none\"\n";
809 os << "height \"" << height_value << height_unit << "\"\n";
810 os << "height_special \"" << height_special << "\"\n";
811 os << "status open\n\n";
812 Context context(true, parent_context.textclass);
813 context.font = parent_context.font;
815 // If we have no inner box the contens will be read with the outer box
816 if (!inner_type.empty())
817 parse_text(p, os, inner_flags, outer, context);
819 // Ensure that the end of the outer box is parsed correctly:
820 // The opening brace has been eaten by parse_outer_box()
821 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
822 outer_flags &= ~FLAG_ITEM;
823 outer_flags |= FLAG_BRACE_LAST;
826 // Find end of outer box, output contents if inner_type is
827 // empty and output possible comments
828 if (!outer_type.empty()) {
829 // This does not output anything but comments if
830 // inner_type is not empty (see use_ert)
831 parse_text(p, os, outer_flags, outer, context);
834 context.check_end_layout(os);
836 #ifdef PRESERVE_LAYOUT
837 // LyX puts a % after the end of the minipage
838 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
840 //handle_comment(os, "%dummy", parent_context);
843 parent_context.new_paragraph(os);
845 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
846 //handle_comment(os, "%dummy", parent_context);
849 // We add a protected space if something real follows
850 if (p.good() && p.next_token().cat() != catComment) {
851 begin_inset(os, "space ~\n");
860 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
861 Context & parent_context, string const & outer_type,
862 string const & special)
864 eat_whitespace(p, os, parent_context, false);
865 if (flags & FLAG_ITEM) {
867 if (p.next_token().cat() == catBegin)
870 cerr << "Warning: Ignoring missing '{' after \\"
871 << outer_type << '.' << endl;
872 eat_whitespace(p, os, parent_context, false);
875 unsigned int inner_flags = 0;
876 if (outer_type == "shaded") {
877 // These boxes never have an inner box
879 } else if (p.next_token().asInput() == "\\parbox") {
880 inner = p.get_token().cs();
881 inner_flags = FLAG_ITEM;
882 } else if (p.next_token().asInput() == "\\begin") {
883 // Is this a minipage?
886 inner = p.getArg('{', '}');
888 if (inner == "minipage") {
891 eat_whitespace(p, os, parent_context, false);
892 inner_flags = FLAG_END;
896 if (inner_flags == FLAG_END) {
897 active_environments.push_back(inner);
898 parse_box(p, os, flags, FLAG_END, outer, parent_context,
899 outer_type, special, inner);
900 active_environments.pop_back();
902 parse_box(p, os, flags, inner_flags, outer, parent_context,
903 outer_type, special, inner);
908 /// parse an unknown environment
909 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
910 unsigned flags, bool outer,
911 Context & parent_context)
913 if (name == "tabbing")
914 // We need to remember that we have to handle '\=' specially
915 flags |= FLAG_TABBING;
917 // We need to translate font changes and paragraphs inside the
918 // environment to ERT if we have a non standard font.
919 // Otherwise things like
920 // \large\begin{foo}\huge bar\end{foo}
922 bool const specialfont =
923 (parent_context.font != parent_context.normalfont);
924 bool const new_layout_allowed = parent_context.new_layout_allowed;
926 parent_context.new_layout_allowed = false;
927 handle_ert(os, "\\begin{" + name + "}", parent_context);
928 parse_text_snippet(p, os, flags, outer, parent_context);
929 handle_ert(os, "\\end{" + name + "}", parent_context);
931 parent_context.new_layout_allowed = new_layout_allowed;
935 void parse_environment(Parser & p, ostream & os, bool outer,
936 string & last_env, Context & parent_context)
938 Layout const * newlayout;
939 string const name = p.getArg('{', '}');
940 const bool is_starred = suffixIs(name, '*');
941 string const unstarred_name = rtrim(name, "*");
942 active_environments.push_back(name);
944 if (is_math_env(name)) {
945 parent_context.check_layout(os);
946 begin_inset(os, "Formula ");
947 os << "\\begin{" << name << "}";
948 parse_math(p, os, FLAG_END, MATH_MODE);
949 os << "\\end{" << name << "}";
953 else if (name == "tabular" || name == "longtable") {
954 eat_whitespace(p, os, parent_context, false);
955 parent_context.check_layout(os);
956 begin_inset(os, "Tabular ");
957 handle_tabular(p, os, name == "longtable", parent_context);
962 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
963 eat_whitespace(p, os, parent_context, false);
964 parent_context.check_layout(os);
965 begin_inset(os, "Float " + unstarred_name + "\n");
967 os << "placement " << p.getArg('[', ']') << '\n';
968 os << "wide " << convert<string>(is_starred)
969 << "\nsideways false"
970 << "\nstatus open\n\n";
971 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
973 // We don't need really a new paragraph, but
974 // we must make sure that the next item gets a \begin_layout.
975 parent_context.new_paragraph(os);
979 else if (name == "minipage") {
980 eat_whitespace(p, os, parent_context, false);
981 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
985 else if (name == "comment") {
986 eat_whitespace(p, os, parent_context, false);
987 parent_context.check_layout(os);
988 begin_inset(os, "Note Comment\n");
989 os << "status open\n";
990 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
993 skip_braces(p); // eat {} that might by set by LyX behind comments
996 else if (name == "lyxgreyedout") {
997 eat_whitespace(p, os, parent_context, false);
998 parent_context.check_layout(os);
999 begin_inset(os, "Note Greyedout\n");
1000 os << "status open\n";
1001 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1006 else if (name == "framed" || name == "shaded") {
1007 eat_whitespace(p, os, parent_context, false);
1008 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1012 else if (!parent_context.new_layout_allowed)
1013 parse_unknown_environment(p, name, os, FLAG_END, outer,
1016 // Alignment and spacing settings
1017 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1018 // therefore are totally broken!
1019 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1020 // they are commands not environments. They are furthermore switches that
1021 // can be ended by another switches, but also by commands like \footnote or
1022 // \parbox. So the only safe way is to leave them untouched.
1023 else if (name == "center" || name == "centering" ||
1024 name == "flushleft" || name == "flushright" ||
1025 name == "singlespace" || name == "onehalfspace" ||
1026 name == "doublespace" || name == "spacing") {
1027 eat_whitespace(p, os, parent_context, false);
1028 // We must begin a new paragraph if not already done
1029 if (! parent_context.atParagraphStart()) {
1030 parent_context.check_end_layout(os);
1031 parent_context.new_paragraph(os);
1033 if (name == "flushleft")
1034 parent_context.add_extra_stuff("\\align left\n");
1035 else if (name == "flushright")
1036 parent_context.add_extra_stuff("\\align right\n");
1037 else if (name == "center" || name == "centering")
1038 parent_context.add_extra_stuff("\\align center\n");
1039 else if (name == "singlespace")
1040 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1041 else if (name == "onehalfspace")
1042 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1043 else if (name == "doublespace")
1044 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1045 else if (name == "spacing")
1046 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1047 parse_text(p, os, FLAG_END, outer, parent_context);
1048 // Just in case the environment is empty
1049 parent_context.extra_stuff.erase();
1050 // We must begin a new paragraph to reset the alignment
1051 parent_context.new_paragraph(os);
1055 // The single '=' is meant here.
1056 else if ((newlayout = findLayout(parent_context.textclass, name)) &&
1057 newlayout->isEnvironment()) {
1058 eat_whitespace(p, os, parent_context, false);
1059 Context context(true, parent_context.textclass, newlayout,
1060 parent_context.layout, parent_context.font);
1061 if (parent_context.deeper_paragraph) {
1062 // We are beginning a nested environment after a
1063 // deeper paragraph inside the outer list environment.
1064 // Therefore we don't need to output a "begin deeper".
1065 context.need_end_deeper = true;
1067 parent_context.check_end_layout(os);
1068 if (last_env == name) {
1069 // we need to output a separator since LyX would export
1070 // the two environments as one otherwise (bug 5716)
1071 docstring const sep = from_ascii("--Separator--");
1072 TeX2LyXDocClass const & textclass(parent_context.textclass);
1073 if (textclass.hasLayout(sep)) {
1074 Context newcontext(parent_context);
1075 newcontext.layout = &(textclass[sep]);
1076 newcontext.check_layout(os);
1077 newcontext.check_end_layout(os);
1079 parent_context.check_layout(os);
1080 begin_inset(os, "Note Note\n");
1081 os << "status closed\n";
1082 Context newcontext(true, textclass,
1083 &(textclass.defaultLayout()));
1084 newcontext.check_layout(os);
1085 newcontext.check_end_layout(os);
1087 parent_context.check_end_layout(os);
1090 switch (context.layout->latextype) {
1091 case LATEX_LIST_ENVIRONMENT:
1092 context.add_par_extra_stuff("\\labelwidthstring "
1093 + p.verbatim_item() + '\n');
1096 case LATEX_BIB_ENVIRONMENT:
1097 p.verbatim_item(); // swallow next arg
1103 context.check_deeper(os);
1104 parse_text(p, os, FLAG_END, outer, context);
1105 context.check_end_layout(os);
1106 if (parent_context.deeper_paragraph) {
1107 // We must suppress the "end deeper" because we
1108 // suppressed the "begin deeper" above.
1109 context.need_end_deeper = false;
1111 context.check_end_deeper(os);
1112 parent_context.new_paragraph(os);
1116 else if (name == "appendix") {
1117 // This is no good latex style, but it works and is used in some documents...
1118 eat_whitespace(p, os, parent_context, false);
1119 parent_context.check_end_layout(os);
1120 Context context(true, parent_context.textclass, parent_context.layout,
1121 parent_context.layout, parent_context.font);
1122 context.check_layout(os);
1123 os << "\\start_of_appendix\n";
1124 parse_text(p, os, FLAG_END, outer, context);
1125 context.check_end_layout(os);
1129 else if (known_environments.find(name) != known_environments.end()) {
1130 vector<ArgumentType> arguments = known_environments[name];
1131 // The last "argument" denotes wether we may translate the
1132 // environment contents to LyX
1133 // The default required if no argument is given makes us
1134 // compatible with the reLyXre environment.
1135 ArgumentType contents = arguments.empty() ?
1138 if (!arguments.empty())
1139 arguments.pop_back();
1140 // See comment in parse_unknown_environment()
1141 bool const specialfont =
1142 (parent_context.font != parent_context.normalfont);
1143 bool const new_layout_allowed =
1144 parent_context.new_layout_allowed;
1146 parent_context.new_layout_allowed = false;
1147 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1148 outer, parent_context);
1149 if (contents == verbatim)
1150 handle_ert(os, p.verbatimEnvironment(name),
1153 parse_text_snippet(p, os, FLAG_END, outer,
1155 handle_ert(os, "\\end{" + name + "}", parent_context);
1157 parent_context.new_layout_allowed = new_layout_allowed;
1161 parse_unknown_environment(p, name, os, FLAG_END, outer,
1165 active_environments.pop_back();
1169 /// parses a comment and outputs it to \p os.
1170 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1172 LASSERT(t.cat() == catComment, return);
1173 if (!t.cs().empty()) {
1174 context.check_layout(os);
1175 handle_comment(os, '%' + t.cs(), context);
1176 if (p.next_token().cat() == catNewline) {
1177 // A newline after a comment line starts a new
1179 if (context.new_layout_allowed) {
1180 if(!context.atParagraphStart())
1181 // Only start a new paragraph if not already
1182 // done (we might get called recursively)
1183 context.new_paragraph(os);
1185 handle_ert(os, "\n", context);
1186 eat_whitespace(p, os, context, true);
1189 // "%\n" combination
1196 * Reads spaces and comments until the first non-space, non-comment token.
1197 * New paragraphs (double newlines or \\par) are handled like simple spaces
1198 * if \p eatParagraph is true.
1199 * Spaces are skipped, but comments are written to \p os.
1201 void eat_whitespace(Parser & p, ostream & os, Context & context,
1205 Token const & t = p.get_token();
1206 if (t.cat() == catComment)
1207 parse_comment(p, os, t, context);
1208 else if ((! eatParagraph && p.isParagraph()) ||
1209 (t.cat() != catSpace && t.cat() != catNewline)) {
1218 * Set a font attribute, parse text and reset the font attribute.
1219 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1220 * \param currentvalue Current value of the attribute. Is set to the new
1221 * value during parsing.
1222 * \param newvalue New value of the attribute
1224 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1225 Context & context, string const & attribute,
1226 string & currentvalue, string const & newvalue)
1228 context.check_layout(os);
1229 string const oldvalue = currentvalue;
1230 currentvalue = newvalue;
1231 os << '\n' << attribute << ' ' << newvalue << "\n";
1232 parse_text_snippet(p, os, flags, outer, context);
1233 context.check_layout(os);
1234 os << '\n' << attribute << ' ' << oldvalue << "\n";
1235 currentvalue = oldvalue;
1239 /// get the arguments of a natbib or jurabib citation command
1240 void get_cite_arguments(Parser & p, bool natbibOrder,
1241 string & before, string & after)
1243 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1245 // text before the citation
1247 // text after the citation
1248 after = p.getFullOpt();
1250 if (!after.empty()) {
1251 before = p.getFullOpt();
1252 if (natbibOrder && !before.empty())
1253 swap(before, after);
1258 /// Convert filenames with TeX macros and/or quotes to something LyX
1260 string const normalize_filename(string const & name)
1262 Parser p(trim(name, "\""));
1265 Token const & t = p.get_token();
1266 if (t.cat() != catEscape)
1268 else if (t.cs() == "lyxdot") {
1269 // This is used by LyX for simple dots in relative
1273 } else if (t.cs() == "space") {
1283 /// Convert \p name from TeX convention (relative to master file) to LyX
1284 /// convention (relative to .lyx file) if it is relative
1285 void fix_relative_filename(string & name)
1287 if (FileName::isAbsolute(name))
1290 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1291 from_utf8(getParentFilePath())));
1295 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1296 void parse_noweb(Parser & p, ostream & os, Context & context)
1298 // assemble the rest of the keyword
1302 Token const & t = p.get_token();
1303 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1306 scrap = (p.good() && p.next_token().asInput() == "=");
1308 name += p.get_token().asInput();
1311 name += t.asInput();
1314 if (!scrap || !context.new_layout_allowed ||
1315 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1316 cerr << "Warning: Could not interpret '" << name
1317 << "'. Ignoring it." << endl;
1321 // We use new_paragraph instead of check_end_layout because the stuff
1322 // following the noweb chunk needs to start with a \begin_layout.
1323 // This may create a new paragraph even if there was none in the
1324 // noweb file, but the alternative is an invalid LyX file. Since
1325 // noweb code chunks are implemented with a layout style in LyX they
1326 // always must be in an own paragraph.
1327 context.new_paragraph(os);
1328 Context newcontext(true, context.textclass,
1329 &context.textclass[from_ascii("Scrap")]);
1330 newcontext.check_layout(os);
1333 Token const & t = p.get_token();
1334 // We abuse the parser a bit, because this is no TeX syntax
1336 if (t.cat() == catEscape)
1337 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1340 begin_inset(oss, "Newline newline");
1342 os << subst(t.asInput(), "\n", oss.str());
1344 // The scrap chunk is ended by an @ at the beginning of a line.
1345 // After the @ the line may contain a comment and/or
1346 // whitespace, but nothing else.
1347 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1348 (p.next_token().cat() == catSpace ||
1349 p.next_token().cat() == catNewline ||
1350 p.next_token().cat() == catComment)) {
1351 while (p.good() && p.next_token().cat() == catSpace)
1352 os << p.get_token().asInput();
1353 if (p.next_token().cat() == catComment)
1354 // The comment includes a final '\n'
1355 os << p.get_token().asInput();
1357 if (p.next_token().cat() == catNewline)
1364 newcontext.check_end_layout(os);
1368 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1369 bool is_macro(Parser & p)
1371 Token first = p.curr_token();
1372 if (first.cat() != catEscape || !p.good())
1374 if (first.cs() == "def")
1376 if (first.cs() != "global" && first.cs() != "long")
1378 Token second = p.get_token();
1380 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1381 second.cat() == catNewline || second.cat() == catComment)) {
1382 second = p.get_token();
1385 bool secondvalid = second.cat() == catEscape;
1387 bool thirdvalid = false;
1388 if (p.good() && first.cs() == "global" && secondvalid &&
1389 second.cs() == "long") {
1390 third = p.get_token();
1392 while (p.good() && !p.isParagraph() &&
1393 (third.cat() == catSpace ||
1394 third.cat() == catNewline ||
1395 third.cat() == catComment)) {
1396 third = p.get_token();
1399 thirdvalid = third.cat() == catEscape;
1401 for (int i = 0; i < pos; ++i)
1406 return (first.cs() == "global" || first.cs() == "long") &&
1407 second.cs() == "def";
1408 return first.cs() == "global" && second.cs() == "long" &&
1409 third.cs() == "def";
1413 /// Parse a macro definition (assumes that is_macro() returned true)
1414 void parse_macro(Parser & p, ostream & os, Context & context)
1416 context.check_layout(os);
1417 Token first = p.curr_token();
1420 string command = first.asInput();
1421 if (first.cs() != "def") {
1423 eat_whitespace(p, os, context, false);
1424 second = p.curr_token();
1425 command += second.asInput();
1426 if (second.cs() != "def") {
1428 eat_whitespace(p, os, context, false);
1429 third = p.curr_token();
1430 command += third.asInput();
1433 eat_whitespace(p, os, context, false);
1434 string const name = p.get_token().cs();
1435 eat_whitespace(p, os, context, false);
1441 while (p.next_token().cat() != catBegin) {
1442 if (p.next_token().cat() == catParameter) {
1447 // followed by number?
1448 if (p.next_token().cat() == catOther) {
1449 char c = p.getChar();
1451 // number = current arity + 1?
1452 if (c == arity + '0' + 1)
1457 paramtext += p.get_token().cs();
1459 paramtext += p.get_token().cs();
1464 // only output simple (i.e. compatible) macro as FormulaMacros
1465 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1467 context.check_layout(os);
1468 begin_inset(os, "FormulaMacro");
1469 os << "\n\\def" << ert;
1472 handle_ert(os, command + ert, context);
1475 } // anonymous namespace
1478 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1481 Layout const * newlayout = 0;
1482 InsetLayout const * newinsetlayout = 0;
1483 // Store the latest bibliographystyle and nocite{*} option
1484 // (needed for bibtex inset)
1486 string bibliographystyle;
1487 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1488 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1491 Token const & t = p.get_token();
1494 debugToken(cerr, t, flags);
1497 if (flags & FLAG_ITEM) {
1498 if (t.cat() == catSpace)
1501 flags &= ~FLAG_ITEM;
1502 if (t.cat() == catBegin) {
1503 // skip the brace and collect everything to the next matching
1505 flags |= FLAG_BRACE_LAST;
1509 // handle only this single token, leave the loop if done
1510 flags |= FLAG_LEAVE;
1513 if (t.cat() != catEscape && t.character() == ']' &&
1514 (flags & FLAG_BRACK_LAST))
1516 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1519 // If there is anything between \end{env} and \begin{env} we
1520 // don't need to output a separator.
1521 if (t.cat() != catSpace && t.cat() != catNewline &&
1522 t.asInput() != "\\begin")
1528 if (t.cat() == catMath) {
1529 // we are inside some text mode thingy, so opening new math is allowed
1530 context.check_layout(os);
1531 begin_inset(os, "Formula ");
1532 Token const & n = p.get_token();
1533 if (n.cat() == catMath && outer) {
1534 // TeX's $$...$$ syntax for displayed math
1536 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1538 p.get_token(); // skip the second '$' token
1540 // simple $...$ stuff
1543 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1549 else if (t.cat() == catSuper || t.cat() == catSub)
1550 cerr << "catcode " << t << " illegal in text mode\n";
1552 // Basic support for english quotes. This should be
1553 // extended to other quotes, but is not so easy (a
1554 // left english quote is the same as a right german
1556 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1557 context.check_layout(os);
1558 begin_inset(os, "Quotes ");
1564 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1565 context.check_layout(os);
1566 begin_inset(os, "Quotes ");
1573 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1574 context.check_layout(os);
1575 begin_inset(os, "Quotes ");
1582 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1583 context.check_layout(os);
1584 begin_inset(os, "Quotes ");
1591 else if (t.asInput() == "<"
1592 && p.next_token().asInput() == "<" && noweb_mode) {
1594 parse_noweb(p, os, context);
1597 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1598 check_space(p, os, context);
1600 else if (t.character() == '[' && noweb_mode &&
1601 p.next_token().character() == '[') {
1602 // These can contain underscores
1604 string const s = p.getFullOpt() + ']';
1605 if (p.next_token().character() == ']')
1608 cerr << "Warning: Inserting missing ']' in '"
1609 << s << "'." << endl;
1610 handle_ert(os, s, context);
1613 else if (t.cat() == catLetter) {
1614 context.check_layout(os);
1615 // Workaround for bug 4752.
1616 // FIXME: This whole code block needs to be removed
1617 // when the bug is fixed and tex2lyx produces
1618 // the updated file format.
1619 // The replacement algorithm in LyX is so stupid that
1620 // it even translates a phrase if it is part of a word.
1621 bool handled = false;
1622 for (int const * l = known_phrase_lengths; *l; ++l) {
1623 string phrase = t.cs();
1624 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1625 phrase += p.get_token().cs();
1626 if (is_known(phrase, known_coded_phrases)) {
1627 handle_ert(os, phrase, context);
1631 for (size_t i = 1; i < phrase.length(); ++i)
1639 else if (t.cat() == catOther ||
1640 t.cat() == catAlign ||
1641 t.cat() == catParameter) {
1642 // This translates "&" to "\\&" which may be wrong...
1643 context.check_layout(os);
1647 else if (p.isParagraph()) {
1648 if (context.new_layout_allowed)
1649 context.new_paragraph(os);
1651 handle_ert(os, "\\par ", context);
1652 eat_whitespace(p, os, context, true);
1655 else if (t.cat() == catActive) {
1656 context.check_layout(os);
1657 if (t.character() == '~') {
1658 if (context.layout->free_spacing)
1661 begin_inset(os, "space ~\n");
1668 else if (t.cat() == catBegin &&
1669 p.next_token().cat() == catEnd) {
1671 Token const prev = p.prev_token();
1673 if (p.next_token().character() == '`' ||
1674 (prev.character() == '-' &&
1675 p.next_token().character() == '-'))
1676 ; // ignore it in {}`` or -{}-
1678 handle_ert(os, "{}", context);
1682 else if (t.cat() == catBegin) {
1683 context.check_layout(os);
1684 // special handling of font attribute changes
1685 Token const prev = p.prev_token();
1686 Token const next = p.next_token();
1687 TeXFont const oldFont = context.font;
1688 if (next.character() == '[' ||
1689 next.character() == ']' ||
1690 next.character() == '*') {
1692 if (p.next_token().cat() == catEnd) {
1697 handle_ert(os, "{", context);
1698 parse_text_snippet(p, os,
1701 handle_ert(os, "}", context);
1703 } else if (! context.new_layout_allowed) {
1704 handle_ert(os, "{", context);
1705 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1707 handle_ert(os, "}", context);
1708 } else if (is_known(next.cs(), known_sizes)) {
1709 // next will change the size, so we must
1711 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1713 if (!context.atParagraphStart())
1715 << context.font.size << "\n";
1716 } else if (is_known(next.cs(), known_font_families)) {
1717 // next will change the font family, so we
1718 // must reset it here
1719 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1721 if (!context.atParagraphStart())
1723 << context.font.family << "\n";
1724 } else if (is_known(next.cs(), known_font_series)) {
1725 // next will change the font series, so we
1726 // must reset it here
1727 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1729 if (!context.atParagraphStart())
1731 << context.font.series << "\n";
1732 } else if (is_known(next.cs(), known_font_shapes)) {
1733 // next will change the font shape, so we
1734 // must reset it here
1735 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1737 if (!context.atParagraphStart())
1739 << context.font.shape << "\n";
1740 } else if (is_known(next.cs(), known_old_font_families) ||
1741 is_known(next.cs(), known_old_font_series) ||
1742 is_known(next.cs(), known_old_font_shapes)) {
1743 // next will change the font family, series
1744 // and shape, so we must reset it here
1745 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1747 if (!context.atParagraphStart())
1749 << context.font.family
1751 << context.font.series
1753 << context.font.shape << "\n";
1755 handle_ert(os, "{", context);
1756 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1758 handle_ert(os, "}", context);
1762 else if (t.cat() == catEnd) {
1763 if (flags & FLAG_BRACE_LAST) {
1766 cerr << "stray '}' in text\n";
1767 handle_ert(os, "}", context);
1770 else if (t.cat() == catComment)
1771 parse_comment(p, os, t, context);
1774 // control sequences
1777 else if (t.cs() == "(") {
1778 context.check_layout(os);
1779 begin_inset(os, "Formula");
1781 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1786 else if (t.cs() == "[") {
1787 context.check_layout(os);
1788 begin_inset(os, "Formula");
1790 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1795 else if (t.cs() == "begin")
1796 parse_environment(p, os, outer, last_env, context);
1798 else if (t.cs() == "end") {
1799 if (flags & FLAG_END) {
1800 // eat environment name
1801 string const name = p.getArg('{', '}');
1802 if (name != active_environment())
1803 cerr << "\\end{" + name + "} does not match \\begin{"
1804 + active_environment() + "}\n";
1807 p.error("found 'end' unexpectedly");
1810 else if (t.cs() == "item") {
1813 bool optarg = false;
1814 if (p.next_token().cat() != catEscape &&
1815 p.next_token().character() == '[') {
1816 p.get_token(); // eat '['
1817 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1822 context.check_layout(os);
1823 if (context.has_item) {
1824 // An item in an unknown list-like environment
1825 // FIXME: Do this in check_layout()!
1826 context.has_item = false;
1828 handle_ert(os, "\\item", context);
1830 handle_ert(os, "\\item ", context);
1833 if (context.layout->labeltype != LABEL_MANUAL) {
1834 // LyX does not support \item[\mybullet]
1835 // in itemize environments
1836 handle_ert(os, "[", context);
1838 handle_ert(os, "]", context);
1839 } else if (!s.empty()) {
1840 // The space is needed to separate the
1841 // item from the rest of the sentence.
1843 eat_whitespace(p, os, context, false);
1848 else if (t.cs() == "bibitem") {
1850 context.check_layout(os);
1851 begin_command_inset(os, "bibitem", "bibitem");
1852 os << "label \"" << p.getOptContent() << "\"\n";
1853 os << "key \"" << p.verbatim_item() << "\"\n";
1857 else if (is_macro(p))
1858 parse_macro(p, os, context);
1860 else if (t.cs() == "noindent") {
1862 context.add_par_extra_stuff("\\noindent\n");
1865 else if (t.cs() == "appendix") {
1866 context.add_par_extra_stuff("\\start_of_appendix\n");
1867 // We need to start a new paragraph. Otherwise the
1868 // appendix in 'bla\appendix\chapter{' would start
1870 context.new_paragraph(os);
1871 // We need to make sure that the paragraph is
1872 // generated even if it is empty. Otherwise the
1873 // appendix in '\par\appendix\par\chapter{' would
1875 context.check_layout(os);
1876 // FIXME: This is a hack to prevent paragraph
1877 // deletion if it is empty. Handle this better!
1879 "%dummy comment inserted by tex2lyx to "
1880 "ensure that this paragraph is not empty",
1882 // Both measures above may generate an additional
1883 // empty paragraph, but that does not hurt, because
1884 // whitespace does not matter here.
1885 eat_whitespace(p, os, context, true);
1888 // Starred section headings
1889 // Must attempt to parse "Section*" before "Section".
1890 else if ((p.next_token().asInput() == "*") &&
1891 context.new_layout_allowed &&
1892 (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1893 newlayout->isCommand()) {
1896 output_command_layout(os, p, outer, context, newlayout);
1900 // Section headings and the like
1901 else if (context.new_layout_allowed &&
1902 (newlayout = findLayout(context.textclass, t.cs())) &&
1903 newlayout->isCommand()) {
1905 output_command_layout(os, p, outer, context, newlayout);
1909 else if (t.cs() == "caption") {
1911 context.check_layout(os);
1913 begin_inset(os, "Caption\n\n");
1914 Context newcontext(true, context.textclass);
1915 newcontext.font = context.font;
1916 newcontext.check_layout(os);
1917 if (p.next_token().cat() != catEscape &&
1918 p.next_token().character() == '[') {
1919 p.get_token(); // eat '['
1920 begin_inset(os, "OptArg\n");
1921 os << "status collapsed\n";
1922 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1924 eat_whitespace(p, os, context, false);
1926 parse_text(p, os, FLAG_ITEM, outer, context);
1927 context.check_end_layout(os);
1928 // We don't need really a new paragraph, but
1929 // we must make sure that the next item gets a \begin_layout.
1930 context.new_paragraph(os);
1933 newcontext.check_end_layout(os);
1936 else if (t.cs() == "includegraphics") {
1937 bool const clip = p.next_token().asInput() == "*";
1940 string const arg = p.getArg('[', ']');
1941 map<string, string> opts;
1942 vector<string> keys;
1943 split_map(arg, opts, keys);
1945 opts["clip"] = string();
1946 string name = normalize_filename(p.verbatim_item());
1948 string const path = getMasterFilePath();
1949 // We want to preserve relative / absolute filenames,
1950 // therefore path is only used for testing
1951 if (!makeAbsPath(name, path).exists()) {
1952 // The file extension is probably missing.
1953 // Now try to find it out.
1954 string const dvips_name =
1955 find_file(name, path,
1956 known_dvips_graphics_formats);
1957 string const pdftex_name =
1958 find_file(name, path,
1959 known_pdftex_graphics_formats);
1960 if (!dvips_name.empty()) {
1961 if (!pdftex_name.empty()) {
1962 cerr << "This file contains the "
1964 "\"\\includegraphics{"
1966 "However, files\n\""
1967 << dvips_name << "\" and\n\""
1968 << pdftex_name << "\"\n"
1969 "both exist, so I had to make a "
1970 "choice and took the first one.\n"
1971 "Please move the unwanted one "
1972 "someplace else and try again\n"
1973 "if my choice was wrong."
1977 } else if (!pdftex_name.empty()) {
1983 if (makeAbsPath(name, path).exists())
1984 fix_relative_filename(name);
1986 cerr << "Warning: Could not find graphics file '"
1987 << name << "'." << endl;
1989 context.check_layout(os);
1990 begin_inset(os, "Graphics ");
1991 os << "\n\tfilename " << name << '\n';
1992 if (opts.find("width") != opts.end())
1994 << translate_len(opts["width"]) << '\n';
1995 if (opts.find("height") != opts.end())
1997 << translate_len(opts["height"]) << '\n';
1998 if (opts.find("scale") != opts.end()) {
1999 istringstream iss(opts["scale"]);
2003 os << "\tscale " << val << '\n';
2005 if (opts.find("angle") != opts.end()) {
2006 os << "\trotateAngle "
2007 << opts["angle"] << '\n';
2008 vector<string>::const_iterator a =
2009 find(keys.begin(), keys.end(), "angle");
2010 vector<string>::const_iterator s =
2011 find(keys.begin(), keys.end(), "width");
2012 if (s == keys.end())
2013 s = find(keys.begin(), keys.end(), "height");
2014 if (s == keys.end())
2015 s = find(keys.begin(), keys.end(), "scale");
2016 if (s != keys.end() && distance(s, a) > 0)
2017 os << "\tscaleBeforeRotation\n";
2019 if (opts.find("origin") != opts.end()) {
2021 string const opt = opts["origin"];
2022 if (opt.find('l') != string::npos) ss << "left";
2023 if (opt.find('r') != string::npos) ss << "right";
2024 if (opt.find('c') != string::npos) ss << "center";
2025 if (opt.find('t') != string::npos) ss << "Top";
2026 if (opt.find('b') != string::npos) ss << "Bottom";
2027 if (opt.find('B') != string::npos) ss << "Baseline";
2028 if (!ss.str().empty())
2029 os << "\trotateOrigin " << ss.str() << '\n';
2031 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2033 if (opts.find("keepaspectratio") != opts.end())
2034 os << "\tkeepAspectRatio\n";
2035 if (opts.find("clip") != opts.end())
2037 if (opts.find("draft") != opts.end())
2039 if (opts.find("bb") != opts.end())
2040 os << "\tBoundingBox "
2041 << opts["bb"] << '\n';
2042 int numberOfbbOptions = 0;
2043 if (opts.find("bbllx") != opts.end())
2044 numberOfbbOptions++;
2045 if (opts.find("bblly") != opts.end())
2046 numberOfbbOptions++;
2047 if (opts.find("bburx") != opts.end())
2048 numberOfbbOptions++;
2049 if (opts.find("bbury") != opts.end())
2050 numberOfbbOptions++;
2051 if (numberOfbbOptions == 4)
2052 os << "\tBoundingBox "
2053 << opts["bbllx"] << " " << opts["bblly"] << " "
2054 << opts["bburx"] << " " << opts["bbury"] << '\n';
2055 else if (numberOfbbOptions > 0)
2056 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2057 numberOfbbOptions = 0;
2058 if (opts.find("natwidth") != opts.end())
2059 numberOfbbOptions++;
2060 if (opts.find("natheight") != opts.end())
2061 numberOfbbOptions++;
2062 if (numberOfbbOptions == 2)
2063 os << "\tBoundingBox 0bp 0bp "
2064 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2065 else if (numberOfbbOptions > 0)
2066 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2067 ostringstream special;
2068 if (opts.find("hiresbb") != opts.end())
2069 special << "hiresbb,";
2070 if (opts.find("trim") != opts.end())
2072 if (opts.find("viewport") != opts.end())
2073 special << "viewport=" << opts["viewport"] << ',';
2074 if (opts.find("totalheight") != opts.end())
2075 special << "totalheight=" << opts["totalheight"] << ',';
2076 if (opts.find("type") != opts.end())
2077 special << "type=" << opts["type"] << ',';
2078 if (opts.find("ext") != opts.end())
2079 special << "ext=" << opts["ext"] << ',';
2080 if (opts.find("read") != opts.end())
2081 special << "read=" << opts["read"] << ',';
2082 if (opts.find("command") != opts.end())
2083 special << "command=" << opts["command"] << ',';
2084 string s_special = special.str();
2085 if (!s_special.empty()) {
2086 // We had special arguments. Remove the trailing ','.
2087 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2089 // TODO: Handle the unknown settings better.
2090 // Warn about invalid options.
2091 // Check whether some option was given twice.
2095 else if (t.cs() == "footnote" ||
2096 (t.cs() == "thanks" && context.layout->intitle)) {
2098 context.check_layout(os);
2099 begin_inset(os, "Foot\n");
2100 os << "status collapsed\n\n";
2101 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2105 else if (t.cs() == "marginpar") {
2107 context.check_layout(os);
2108 begin_inset(os, "Marginal\n");
2109 os << "status collapsed\n\n";
2110 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2114 else if (t.cs() == "ensuremath") {
2116 context.check_layout(os);
2117 string const s = p.verbatim_item();
2118 //FIXME: this never triggers in UTF8
2119 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2122 handle_ert(os, "\\ensuremath{" + s + "}",
2126 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2127 // FIXME: Somehow prevent title layouts if
2128 // "maketitle" was not found
2130 skip_spaces_braces(p);
2133 else if (t.cs() == "tableofcontents") {
2134 context.check_layout(os);
2135 begin_command_inset(os, "toc", "tableofcontents");
2137 skip_spaces_braces(p);
2140 else if (t.cs() == "listoffigures") {
2141 context.check_layout(os);
2142 begin_inset(os, "FloatList figure\n");
2144 skip_spaces_braces(p);
2147 else if (t.cs() == "listoftables") {
2148 context.check_layout(os);
2149 begin_inset(os, "FloatList table\n");
2151 skip_spaces_braces(p);
2154 else if (t.cs() == "listof") {
2155 p.skip_spaces(true);
2156 string const name = p.get_token().cs();
2157 if (context.textclass.floats().typeExist(name)) {
2158 context.check_layout(os);
2159 begin_inset(os, "FloatList ");
2162 p.get_token(); // swallow second arg
2164 handle_ert(os, "\\listof{" + name + "}", context);
2167 else if (t.cs() == "textrm")
2168 parse_text_attributes(p, os, FLAG_ITEM, outer,
2169 context, "\\family",
2170 context.font.family, "roman");
2172 else if (t.cs() == "textsf")
2173 parse_text_attributes(p, os, FLAG_ITEM, outer,
2174 context, "\\family",
2175 context.font.family, "sans");
2177 else if (t.cs() == "texttt")
2178 parse_text_attributes(p, os, FLAG_ITEM, outer,
2179 context, "\\family",
2180 context.font.family, "typewriter");
2182 else if (t.cs() == "textmd")
2183 parse_text_attributes(p, os, FLAG_ITEM, outer,
2184 context, "\\series",
2185 context.font.series, "medium");
2187 else if (t.cs() == "textbf")
2188 parse_text_attributes(p, os, FLAG_ITEM, outer,
2189 context, "\\series",
2190 context.font.series, "bold");
2192 else if (t.cs() == "textup")
2193 parse_text_attributes(p, os, FLAG_ITEM, outer,
2195 context.font.shape, "up");
2197 else if (t.cs() == "textit")
2198 parse_text_attributes(p, os, FLAG_ITEM, outer,
2200 context.font.shape, "italic");
2202 else if (t.cs() == "textsl")
2203 parse_text_attributes(p, os, FLAG_ITEM, outer,
2205 context.font.shape, "slanted");
2207 else if (t.cs() == "textsc")
2208 parse_text_attributes(p, os, FLAG_ITEM, outer,
2210 context.font.shape, "smallcaps");
2212 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2213 context.check_layout(os);
2214 TeXFont oldFont = context.font;
2215 context.font.init();
2216 context.font.size = oldFont.size;
2217 os << "\n\\family " << context.font.family << "\n";
2218 os << "\n\\series " << context.font.series << "\n";
2219 os << "\n\\shape " << context.font.shape << "\n";
2220 if (t.cs() == "textnormal") {
2221 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2222 output_font_change(os, context.font, oldFont);
2223 context.font = oldFont;
2225 eat_whitespace(p, os, context, false);
2228 else if (t.cs() == "textcolor") {
2229 // scheme is \textcolor{color name}{text}
2230 string const color = p.verbatim_item();
2231 // we only support the predefined colors of the color package
2232 if (color == "black" || color == "blue" || color == "cyan"
2233 || color == "green" || color == "magenta" || color == "red"
2234 || color == "white" || color == "yellow") {
2235 context.check_layout(os);
2236 os << "\n\\color " << color << "\n";
2237 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2238 context.check_layout(os);
2239 os << "\n\\color inherit\n";
2241 // for custom defined colors
2242 handle_ert(os, t.asInput() + "{" + color + "}", context);
2245 else if (t.cs() == "underbar") {
2246 // Do NOT handle \underline.
2247 // \underbar cuts through y, g, q, p etc.,
2248 // \underline does not.
2249 context.check_layout(os);
2250 os << "\n\\bar under\n";
2251 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2252 context.check_layout(os);
2253 os << "\n\\bar default\n";
2256 else if (t.cs() == "emph" || t.cs() == "noun") {
2257 context.check_layout(os);
2258 os << "\n\\" << t.cs() << " on\n";
2259 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2260 context.check_layout(os);
2261 os << "\n\\" << t.cs() << " default\n";
2264 else if (t.cs() == "lyxline") {
2265 context.check_layout(os);
2269 else if (is_known(t.cs(), known_phrases) ||
2270 (t.cs() == "protect" &&
2271 p.next_token().cat() == catEscape &&
2272 is_known(p.next_token().cs(), known_phrases))) {
2273 // LyX sometimes puts a \protect in front, so we have to ignore it
2274 // FIXME: This needs to be changed when bug 4752 is fixed.
2275 char const * const * where = is_known(
2276 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2278 context.check_layout(os);
2279 os << known_coded_phrases[where - known_phrases];
2280 skip_spaces_braces(p);
2283 else if (is_known(t.cs(), known_ref_commands)) {
2284 context.check_layout(os);
2285 begin_command_inset(os, "ref", t.cs());
2286 // LyX cannot handle newlines in a latex command
2287 // FIXME: Move the substitution into parser::getOpt()?
2288 os << subst(p.getOpt(), "\n", " ");
2289 os << "reference " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2293 else if (use_natbib &&
2294 is_known(t.cs(), known_natbib_commands) &&
2295 ((t.cs() != "citefullauthor" &&
2296 t.cs() != "citeyear" &&
2297 t.cs() != "citeyearpar") ||
2298 p.next_token().asInput() != "*")) {
2299 context.check_layout(os);
2300 string command = t.cs();
2301 if (p.next_token().asInput() == "*") {
2305 if (command == "citefullauthor")
2306 // alternative name for "\\citeauthor*"
2307 command = "citeauthor*";
2309 // text before the citation
2311 // text after the citation
2313 get_cite_arguments(p, true, before, after);
2315 if (command == "cite") {
2316 // \cite without optional argument means
2317 // \citet, \cite with at least one optional
2318 // argument means \citep.
2319 if (before.empty() && after.empty())
2324 if (before.empty() && after == "[]")
2325 // avoid \citet[]{a}
2327 else if (before == "[]" && after == "[]") {
2328 // avoid \citet[][]{a}
2332 // remove the brackets around after and before
2333 if (!after.empty()) {
2335 after.erase(after.length() - 1, 1);
2336 // LyX cannot handle newlines in the parameter
2337 after = subst(after, "\n", " ");
2339 if (!before.empty()) {
2341 before.erase(before.length() - 1, 1);
2342 // LyX cannot handle newlines in the parameter
2343 before = subst(before, "\n", " ");
2345 begin_command_inset(os, "citation", command);
2346 os << "after " << '"' << after << '"' << "\n";
2347 os << "before " << '"' << before << '"' << "\n";
2348 os << "key " << '"' << p.verbatim_item() << '"' << "\n";
2352 else if (use_jurabib &&
2353 is_known(t.cs(), known_jurabib_commands) &&
2354 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2355 context.check_layout(os);
2356 string command = t.cs();
2357 if (p.next_token().asInput() == "*") {
2361 char argumentOrder = '\0';
2362 vector<string> const & options = used_packages["jurabib"];
2363 if (find(options.begin(), options.end(),
2364 "natbiborder") != options.end())
2365 argumentOrder = 'n';
2366 else if (find(options.begin(), options.end(),
2367 "jurabiborder") != options.end())
2368 argumentOrder = 'j';
2370 // text before the citation
2372 // text after the citation
2374 get_cite_arguments(p, argumentOrder != 'j', before, after);
2376 string const citation = p.verbatim_item();
2377 if (!before.empty() && argumentOrder == '\0') {
2378 cerr << "Warning: Assuming argument order "
2379 "of jurabib version 0.6 for\n'"
2380 << command << before << after << '{'
2381 << citation << "}'.\n"
2382 "Add 'jurabiborder' to the jurabib "
2383 "package options if you used an\n"
2384 "earlier jurabib version." << endl;
2386 if (!after.empty()) {
2388 after.erase(after.length() - 1, 1);
2390 if (!before.empty()) {
2392 before.erase(before.length() - 1, 1);
2394 begin_command_inset(os, "citation", command);
2395 os << "after " << '"' << after << '"' << "\n";
2396 os << "before " << '"' << before << '"' << "\n";
2397 os << "key " << '"' << citation << '"' << "\n";
2401 else if (t.cs() == "cite"
2402 || t.cs() == "nocite") {
2403 context.check_layout(os);
2404 // LyX cannot handle newlines in a latex command
2405 string after = subst(p.getOptContent(), "\n", " ");
2406 string key = subst(p.verbatim_item(), "\n", " ");
2407 // store the case that it is "\nocite{*}" to use it later for
2410 begin_command_inset(os, "citation", t.cs());
2411 os << "after " << '"' << after << '"' << "\n";
2412 os << "key " << '"' << key << '"' << "\n";
2414 } else if (t.cs() == "nocite")
2418 else if (t.cs() == "index") {
2419 context.check_layout(os);
2420 begin_inset(os, "Index\n");
2421 os << "status collapsed\n";
2422 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2426 else if (t.cs() == "nomenclature") {
2427 context.check_layout(os);
2428 begin_command_inset(os, "nomenclature", "nomenclature");
2429 // LyX cannot handle newlines in a latex command
2430 string prefix = subst(p.getOptContent(), "\n", " ");
2431 if (!prefix.empty())
2432 os << "prefix " << '"' << prefix << '"' << "\n";
2433 os << "symbol " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2434 os << "description " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2438 else if (t.cs() == "label") {
2439 context.check_layout(os);
2440 begin_command_inset(os, "label", "label");
2441 // LyX cannot handle newlines in a latex command
2442 os << "name " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2446 else if (t.cs() == "printindex") {
2447 context.check_layout(os);
2448 begin_command_inset(os, "index_print", "printindex");
2450 skip_spaces_braces(p);
2453 else if (t.cs() == "printnomenclature") {
2454 context.check_layout(os);
2455 begin_command_inset(os, "nomencl_print", "printnomenclature");
2457 skip_spaces_braces(p);
2460 else if (t.cs() == "url") {
2461 context.check_layout(os);
2462 begin_inset(os, "Flex URL\n");
2463 os << "status collapsed\n";
2464 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2468 else if (LYX_FORMAT >= 408 &&
2469 (t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2470 context.check_layout(os);
2471 begin_inset(os, "script ");
2472 os << t.cs().substr(4) << '\n';
2473 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2477 else if (is_known(t.cs(), known_quotes)) {
2478 char const * const * where = is_known(t.cs(), known_quotes);
2479 context.check_layout(os);
2480 begin_inset(os, "Quotes ");
2481 os << known_coded_quotes[where - known_quotes];
2483 // LyX adds {} after the quote, so we have to eat
2484 // spaces here if there are any before a possible
2486 eat_whitespace(p, os, context, false);
2490 else if (is_known(t.cs(), known_sizes) &&
2491 context.new_layout_allowed) {
2492 char const * const * where = is_known(t.cs(), known_sizes);
2493 context.check_layout(os);
2494 TeXFont const oldFont = context.font;
2495 context.font.size = known_coded_sizes[where - known_sizes];
2496 output_font_change(os, oldFont, context.font);
2497 eat_whitespace(p, os, context, false);
2500 else if (is_known(t.cs(), known_font_families) &&
2501 context.new_layout_allowed) {
2502 char const * const * where =
2503 is_known(t.cs(), known_font_families);
2504 context.check_layout(os);
2505 TeXFont const oldFont = context.font;
2506 context.font.family =
2507 known_coded_font_families[where - known_font_families];
2508 output_font_change(os, oldFont, context.font);
2509 eat_whitespace(p, os, context, false);
2512 else if (is_known(t.cs(), known_font_series) &&
2513 context.new_layout_allowed) {
2514 char const * const * where =
2515 is_known(t.cs(), known_font_series);
2516 context.check_layout(os);
2517 TeXFont const oldFont = context.font;
2518 context.font.series =
2519 known_coded_font_series[where - known_font_series];
2520 output_font_change(os, oldFont, context.font);
2521 eat_whitespace(p, os, context, false);
2524 else if (is_known(t.cs(), known_font_shapes) &&
2525 context.new_layout_allowed) {
2526 char const * const * where =
2527 is_known(t.cs(), known_font_shapes);
2528 context.check_layout(os);
2529 TeXFont const oldFont = context.font;
2530 context.font.shape =
2531 known_coded_font_shapes[where - known_font_shapes];
2532 output_font_change(os, oldFont, context.font);
2533 eat_whitespace(p, os, context, false);
2535 else if (is_known(t.cs(), known_old_font_families) &&
2536 context.new_layout_allowed) {
2537 char const * const * where =
2538 is_known(t.cs(), known_old_font_families);
2539 context.check_layout(os);
2540 TeXFont const oldFont = context.font;
2541 context.font.init();
2542 context.font.size = oldFont.size;
2543 context.font.family =
2544 known_coded_font_families[where - known_old_font_families];
2545 output_font_change(os, oldFont, context.font);
2546 eat_whitespace(p, os, context, false);
2549 else if (is_known(t.cs(), known_old_font_series) &&
2550 context.new_layout_allowed) {
2551 char const * const * where =
2552 is_known(t.cs(), known_old_font_series);
2553 context.check_layout(os);
2554 TeXFont const oldFont = context.font;
2555 context.font.init();
2556 context.font.size = oldFont.size;
2557 context.font.series =
2558 known_coded_font_series[where - known_old_font_series];
2559 output_font_change(os, oldFont, context.font);
2560 eat_whitespace(p, os, context, false);
2563 else if (is_known(t.cs(), known_old_font_shapes) &&
2564 context.new_layout_allowed) {
2565 char const * const * where =
2566 is_known(t.cs(), known_old_font_shapes);
2567 context.check_layout(os);
2568 TeXFont const oldFont = context.font;
2569 context.font.init();
2570 context.font.size = oldFont.size;
2571 context.font.shape =
2572 known_coded_font_shapes[where - known_old_font_shapes];
2573 output_font_change(os, oldFont, context.font);
2574 eat_whitespace(p, os, context, false);
2577 else if (t.cs() == "selectlanguage") {
2578 context.check_layout(os);
2579 // save the language for the case that a
2580 // \foreignlanguage is used
2582 context.font.language = babel2lyx(p.verbatim_item());
2583 os << "\n\\lang " << context.font.language << "\n";
2586 else if (t.cs() == "foreignlanguage") {
2587 string const lang = babel2lyx(p.verbatim_item());
2588 parse_text_attributes(p, os, FLAG_ITEM, outer,
2590 context.font.language, lang);
2593 else if (t.cs() == "inputencoding") {
2594 // nothing to write here
2595 string const enc = subst(p.verbatim_item(), "\n", " ");
2599 else if (t.cs() == "ldots") {
2600 context.check_layout(os);
2601 os << "\\SpecialChar \\ldots{}\n";
2602 skip_spaces_braces(p);
2605 else if (t.cs() == "lyxarrow") {
2606 context.check_layout(os);
2607 os << "\\SpecialChar \\menuseparator\n";
2608 skip_spaces_braces(p);
2611 else if (t.cs() == "textcompwordmark") {
2612 context.check_layout(os);
2613 os << "\\SpecialChar \\textcompwordmark{}\n";
2614 skip_spaces_braces(p);
2617 else if (t.cs() == "slash") {
2618 context.check_layout(os);
2619 os << "\\SpecialChar \\slash{}\n";
2620 skip_spaces_braces(p);
2623 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2624 context.check_layout(os);
2625 os << "\\SpecialChar \\nobreakdash-\n";
2629 else if (t.cs() == "textquotedbl") {
2630 context.check_layout(os);
2635 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2636 context.check_layout(os);
2637 os << "\\SpecialChar \\@.\n";
2641 else if (t.cs() == "-") {
2642 context.check_layout(os);
2643 os << "\\SpecialChar \\-\n";
2646 else if (t.cs() == "textasciitilde") {
2647 context.check_layout(os);
2649 skip_spaces_braces(p);
2652 else if (t.cs() == "textasciicircum") {
2653 context.check_layout(os);
2655 skip_spaces_braces(p);
2658 else if (t.cs() == "textbackslash") {
2659 context.check_layout(os);
2660 os << "\n\\backslash\n";
2661 skip_spaces_braces(p);
2664 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2665 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2667 context.check_layout(os);
2671 else if (t.cs() == "char") {
2672 context.check_layout(os);
2673 if (p.next_token().character() == '`') {
2675 if (p.next_token().cs() == "\"") {
2680 handle_ert(os, "\\char`", context);
2683 handle_ert(os, "\\char", context);
2687 else if (t.cs() == "verb") {
2688 context.check_layout(os);
2689 char const delimiter = p.next_token().character();
2690 string const arg = p.getArg(delimiter, delimiter);
2692 oss << "\\verb" << delimiter << arg << delimiter;
2693 handle_ert(os, oss.str(), context);
2696 // Problem: \= creates a tabstop inside the tabbing environment
2697 // and else an accent. In the latter case we really would want
2698 // \={o} instead of \= o.
2699 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2700 handle_ert(os, t.asInput(), context);
2702 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2703 else if (t.cs().size() == 1
2704 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2705 context.check_layout(os);
2706 // try to see whether the string is in unicodesymbols
2708 string command = t.asInput() + "{"
2709 + trim(p.verbatim_item())
2711 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2714 cerr << "When parsing " << command
2715 << ", result is " << to_utf8(s)
2716 << "+" << to_utf8(rem) << endl;
2719 // we did not find a non-ert version
2720 handle_ert(os, command, context);
2723 else if (t.cs() == "\\") {
2724 context.check_layout(os);
2726 handle_ert(os, "\\\\" + p.getOpt(), context);
2727 else if (p.next_token().asInput() == "*") {
2729 // getOpt() eats the following space if there
2730 // is no optional argument, but that is OK
2731 // here since it has no effect in the output.
2732 handle_ert(os, "\\\\*" + p.getOpt(), context);
2735 begin_inset(os, "Newline newline");
2740 else if (t.cs() == "newline" ||
2741 (t.cs() == "linebreak" && !p.hasOpt())) {
2742 context.check_layout(os);
2743 begin_inset(os, "Newline ");
2746 skip_spaces_braces(p);
2749 else if (t.cs() == "input" || t.cs() == "include"
2750 || t.cs() == "verbatiminput") {
2751 string name = t.cs();
2752 if (t.cs() == "verbatiminput"
2753 && p.next_token().asInput() == "*")
2754 name += p.get_token().asInput();
2755 context.check_layout(os);
2756 string filename(normalize_filename(p.getArg('{', '}')));
2757 string const path = getMasterFilePath();
2758 // We want to preserve relative / absolute filenames,
2759 // therefore path is only used for testing
2760 if ((t.cs() == "include" || t.cs() == "input") &&
2761 !makeAbsPath(filename, path).exists()) {
2762 // The file extension is probably missing.
2763 // Now try to find it out.
2764 string const tex_name =
2765 find_file(filename, path,
2766 known_tex_extensions);
2767 if (!tex_name.empty())
2768 filename = tex_name;
2770 bool external = false;
2772 if (makeAbsPath(filename, path).exists()) {
2773 string const abstexname =
2774 makeAbsPath(filename, path).absFileName();
2775 string const abslyxname =
2776 changeExtension(abstexname, ".lyx");
2777 string const absfigname =
2778 changeExtension(abstexname, ".fig");
2779 fix_relative_filename(filename);
2780 string const lyxname =
2781 changeExtension(filename, ".lyx");
2783 external = FileName(absfigname).exists();
2784 if (t.cs() == "input") {
2785 string const ext = getExtension(abstexname);
2787 // Combined PS/LaTeX:
2788 // x.eps, x.pstex_t (old xfig)
2789 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
2790 FileName const absepsname(
2791 changeExtension(abstexname, ".eps"));
2792 FileName const abspstexname(
2793 changeExtension(abstexname, ".pstex"));
2794 bool const xfigeps =
2795 (absepsname.exists() ||
2796 abspstexname.exists()) &&
2799 // Combined PDF/LaTeX:
2800 // x.pdf, x.pdftex_t (old xfig)
2801 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
2802 FileName const abspdfname(
2803 changeExtension(abstexname, ".pdf"));
2804 bool const xfigpdf =
2805 abspdfname.exists() &&
2806 (ext == "pdftex_t" || ext == "pdf_t");
2810 // Combined PS/PDF/LaTeX:
2811 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
2812 string const absbase2(
2813 removeExtension(abstexname) + "_pspdftex");
2814 FileName const abseps2name(
2815 addExtension(absbase2, ".eps"));
2816 FileName const abspdf2name(
2817 addExtension(absbase2, ".pdf"));
2818 bool const xfigboth =
2819 abspdf2name.exists() &&
2820 abseps2name.exists() && ext == "pspdftex";
2822 xfig = xfigpdf || xfigeps || xfigboth;
2823 external = external && xfig;
2826 outname = changeExtension(filename, ".fig");
2828 // Don't try to convert, the result
2829 // would be full of ERT.
2831 } else if (t.cs() != "verbatiminput" &&
2832 tex2lyx(abstexname, FileName(abslyxname),
2839 cerr << "Warning: Could not find included file '"
2840 << filename << "'." << endl;
2844 begin_inset(os, "External\n");
2845 os << "\ttemplate XFig\n"
2846 << "\tfilename " << outname << '\n';
2848 begin_command_inset(os, "include", name);
2849 os << "preview false\n"
2850 "filename \"" << outname << "\"\n";
2855 else if (t.cs() == "bibliographystyle") {
2856 // store new bibliographystyle
2857 bibliographystyle = p.verbatim_item();
2858 // If any other command than \bibliography and
2859 // \nocite{*} follows, we need to output the style
2860 // (because it might be used by that command).
2861 // Otherwise, it will automatically be output by LyX.
2864 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
2865 if (t2.cat() == catBegin)
2867 if (t2.cat() != catEscape)
2869 if (t2.cs() == "nocite") {
2870 if (p.getArg('{', '}') == "*")
2872 } else if (t2.cs() == "bibliography")
2879 "\\bibliographystyle{" + bibliographystyle + '}',
2884 else if (t.cs() == "bibliography") {
2885 context.check_layout(os);
2886 begin_command_inset(os, "bibtex", "bibtex");
2887 if (!btprint.empty()) {
2888 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2889 // clear the string because the next BibTeX inset can be without the
2890 // \nocite{*} option
2893 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
2894 // Do we have a bibliographystyle set?
2895 if (!bibliographystyle.empty())
2896 os << "options " << '"' << bibliographystyle << '"' << "\n";
2900 else if (t.cs() == "parbox")
2901 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
2903 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
2904 t.cs() == "shadowbox" || t.cs() == "doublebox")
2905 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
2907 else if (t.cs() == "framebox") {
2908 string special = p.getOpt();
2909 special += p.getOpt();
2910 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
2913 //\makebox() is part of the picture environment and different from \makebox{}
2914 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
2915 else if (t.cs() == "makebox") {
2916 string arg = t.asInput();
2917 if (p.next_token().character() == '(')
2918 //the syntax is: \makebox(x,y)[position]{content}
2919 arg += p.getFullParentheseArg();
2921 //the syntax is: \makebox[width][position]{content}
2922 arg += p.getFullOpt();
2923 handle_ert(os, arg + p.getFullOpt(), context);
2926 else if (t.cs() == "smallskip" ||
2927 t.cs() == "medskip" ||
2928 t.cs() == "bigskip" ||
2929 t.cs() == "vfill") {
2930 context.check_layout(os);
2931 begin_inset(os, "VSpace ");
2934 skip_spaces_braces(p);
2937 else if (is_known(t.cs(), known_spaces)) {
2938 char const * const * where = is_known(t.cs(), known_spaces);
2939 context.check_layout(os);
2940 begin_inset(os, "space ");
2941 os << '\\' << known_coded_spaces[where - known_spaces]
2944 // LaTeX swallows whitespace after all spaces except
2945 // "\\,". We have to do that here, too, because LyX
2946 // adds "{}" which would make the spaces significant.
2948 eat_whitespace(p, os, context, false);
2949 // LyX adds "{}" after all spaces except "\\ " and
2950 // "\\,", so we have to remove "{}".
2951 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2952 // remove the braces after "\\,", too.
2957 else if (t.cs() == "newpage" ||
2958 (t.cs() == "pagebreak" && !p.hasOpt()) ||
2959 t.cs() == "clearpage" ||
2960 t.cs() == "cleardoublepage") {
2961 context.check_layout(os);
2962 begin_inset(os, "Newpage ");
2965 skip_spaces_braces(p);
2968 else if (t.cs() == "newcommand" ||
2969 t.cs() == "providecommand" ||
2970 t.cs() == "renewcommand") {
2971 // providecommand could be handled by parse_command(),
2972 // but we need to call add_known_command() here.
2973 string name = t.asInput();
2974 if (p.next_token().asInput() == "*") {
2975 // Starred form. Eat '*'
2979 string const command = p.verbatim_item();
2980 string const opt1 = p.getOpt();
2981 string const opt2 = p.getFullOpt();
2982 add_known_command(command, opt1, !opt2.empty());
2983 string const ert = name + '{' + command + '}' +
2985 '{' + p.verbatim_item() + '}';
2987 if (t.cs() == "providecommand" ||
2988 name[name.length()-1] == '*')
2989 handle_ert(os, ert, context);
2991 context.check_layout(os);
2992 begin_inset(os, "FormulaMacro");
2998 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
2999 // let could be handled by parse_command(),
3000 // but we need to call add_known_command() here.
3001 string ert = t.asInput();
3004 if (p.next_token().cat() == catBegin) {
3005 name = p.verbatim_item();
3006 ert += '{' + name + '}';
3008 name = p.verbatim_item();
3013 if (p.next_token().cat() == catBegin) {
3014 command = p.verbatim_item();
3015 ert += '{' + command + '}';
3017 command = p.verbatim_item();
3020 // If command is known, make name known too, to parse
3021 // its arguments correctly. For this reason we also
3022 // have commands in syntax.default that are hardcoded.
3023 CommandMap::iterator it = known_commands.find(command);
3024 if (it != known_commands.end())
3025 known_commands[t.asInput()] = it->second;
3026 handle_ert(os, ert, context);
3029 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3030 bool starred = false;
3031 if (p.next_token().asInput() == "*") {
3035 string name = t.asInput();
3036 string const length = p.verbatim_item();
3039 bool valid = splitLatexLength(length, valstring, unit);
3040 bool known_hspace = false;
3041 bool known_vspace = false;
3042 bool known_unit = false;
3045 istringstream iss(valstring);
3048 if (t.cs()[0] == 'h') {
3049 if (unit == "\\fill") {
3054 known_hspace = true;
3057 if (unit == "\\smallskipamount") {
3059 known_vspace = true;
3060 } else if (unit == "\\medskipamount") {
3062 known_vspace = true;
3063 } else if (unit == "\\bigskipamount") {
3065 known_vspace = true;
3066 } else if (unit == "\\fill") {
3068 known_vspace = true;
3072 if (!known_hspace && !known_vspace) {
3073 switch (unitFromString(unit)) {
3094 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3095 // Literal horizontal length or known variable
3096 context.check_layout(os);
3097 begin_inset(os, "space ");
3105 if (known_unit && !known_hspace)
3107 << translate_len(length);
3109 } else if (known_unit || known_vspace) {
3110 // Literal vertical length or known variable
3111 context.check_layout(os);
3112 begin_inset(os, "VSpace ");
3120 // LyX can't handle other length variables in Inset VSpace/space
3125 handle_ert(os, name + '{' + unit + '}', context);
3126 else if (value == -1.0)
3127 handle_ert(os, name + "{-" + unit + '}', context);
3129 handle_ert(os, name + '{' + valstring + unit + '}', context);
3131 handle_ert(os, name + '{' + length + '}', context);
3135 // The single '=' is meant here.
3136 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3138 context.check_layout(os);
3139 begin_inset(os, "Flex ");
3140 os << to_utf8(newinsetlayout->name()) << '\n'
3141 << "status collapsed\n";
3142 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3147 // try to see whether the string is in unicodesymbols
3148 // Only use text mode commands, since we are in text mode here,
3149 // and math commands may be invalid (bug 6797)
3151 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3152 rem, Encodings::TEXT_CMD);
3155 cerr << "When parsing " << t.cs()
3156 << ", result is " << to_utf8(s)
3157 << "+" << to_utf8(rem) << endl;
3158 context.check_layout(os);
3160 skip_spaces_braces(p);
3162 //cerr << "#: " << t << " mode: " << mode << endl;
3163 // heuristic: read up to next non-nested space
3165 string s = t.asInput();
3166 string z = p.verbatim_item();
3167 while (p.good() && z != " " && z.size()) {
3168 //cerr << "read: " << z << endl;
3170 z = p.verbatim_item();
3172 cerr << "found ERT: " << s << endl;
3173 handle_ert(os, s + ' ', context);
3176 string name = t.asInput();
3177 if (p.next_token().asInput() == "*") {
3178 // Starred commands like \vspace*{}
3179 p.get_token(); // Eat '*'
3182 if (!parse_command(name, p, os, outer, context))
3183 handle_ert(os, name, context);
3187 if (flags & FLAG_LEAVE) {
3188 flags &= ~FLAG_LEAVE;