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"
22 #include "LaTeXPackages.h"
27 #include "support/lassert.h"
28 #include "support/convert.h"
29 #include "support/FileName.h"
30 #include "support/filetools.h"
31 #include "support/lstrings.h"
32 #include "support/lyxtime.h"
41 using namespace lyx::support;
46 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
47 Context const & context, InsetLayout const * layout)
49 bool const forcePlainLayout =
50 layout ? layout->forcePlainLayout() : false;
51 Context newcontext(true, context.textclass);
53 newcontext.layout = &context.textclass.plainLayout();
55 newcontext.font = context.font;
56 parse_text(p, os, flags, outer, newcontext);
57 newcontext.check_end_layout(os);
63 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
64 Context const & context, string const & name)
66 InsetLayout const * layout = 0;
67 DocumentClass::InsetLayouts::const_iterator it =
68 context.textclass.insetLayouts().find(from_ascii(name));
69 if (it != context.textclass.insetLayouts().end())
70 layout = &(it->second);
71 parse_text_in_inset(p, os, flags, outer, context, layout);
74 /// parses a paragraph snippet, useful for example for \\emph{...}
75 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
78 Context newcontext(context);
79 // Don't inherit the paragraph-level extra stuff
80 newcontext.par_extra_stuff.clear();
81 parse_text(p, os, flags, outer, newcontext);
82 // Make sure that we don't create invalid .lyx files
83 context.need_layout = newcontext.need_layout;
84 context.need_end_layout = newcontext.need_end_layout;
89 * Thin wrapper around parse_text_snippet() using a string.
91 * We completely ignore \c context.need_layout and \c context.need_end_layout,
92 * because our return value is not used directly (otherwise the stream version
93 * of parse_text_snippet() could be used). That means that the caller needs
94 * to do layout management manually.
95 * This is intended to parse text that does not create any layout changes.
97 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
100 Context newcontext(context);
101 newcontext.need_layout = false;
102 newcontext.need_end_layout = false;
103 newcontext.new_layout_allowed = false;
104 // Avoid warning by Context::~Context()
105 newcontext.par_extra_stuff.clear();
107 parse_text_snippet(p, os, flags, outer, newcontext);
112 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
113 "vpageref", "prettyref", "eqref", 0 };
115 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
116 "vpageref", "formatted", "eqref", 0 };
120 * The starred forms are also known except for "citefullauthor",
121 * "citeyear" and "citeyearpar".
123 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
124 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
125 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
129 * No starred form other than "cite*" known.
131 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
132 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
133 // jurabib commands not (yet) supported by LyX:
135 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
136 // "footciteauthor", "footciteyear", "footciteyearpar",
137 "citefield", "citetitle", 0 };
139 /// LaTeX names for quotes
140 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
141 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
142 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
143 "guilsinglleft", "frq", "guilsinglright", 0};
145 /// the same as known_quotes with .lyx names
146 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
147 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
148 "gld", "grd", "gls", "ers", "fls",
149 "fls", "frs", "frs", 0};
151 /// LaTeX names for font sizes
152 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
153 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
155 /// the same as known_sizes with .lyx names
156 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
157 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
159 /// LaTeX 2.09 names for font families
160 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
162 /// LaTeX names for font families
163 char const * const known_font_families[] = { "rmfamily", "sffamily",
166 /// the same as known_old_font_families and known_font_families with .lyx names
167 char const * const known_coded_font_families[] = { "roman", "sans",
170 /// LaTeX 2.09 names for font series
171 char const * const known_old_font_series[] = { "bf", 0};
173 /// LaTeX names for font series
174 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
176 /// the same as known_old_font_series and known_font_series with .lyx names
177 char const * const known_coded_font_series[] = { "bold", "medium", 0};
179 /// LaTeX 2.09 names for font shapes
180 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
182 /// LaTeX names for font shapes
183 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
186 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
187 char const * const known_coded_font_shapes[] = { "italic", "slanted",
188 "smallcaps", "up", 0};
191 * Graphics file extensions known by the dvips driver of the graphics package.
192 * These extensions are used to complete the filename of an included
193 * graphics file if it does not contain an extension.
194 * The order must be the same that latex uses to find a file, because we
195 * will use the first extension that matches.
196 * This is only an approximation for the common cases. If we would want to
197 * do it right in all cases, we would need to know which graphics driver is
198 * used and know the extensions of every driver of the graphics package.
200 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
201 "ps.gz", "eps.Z", "ps.Z", 0};
204 * Graphics file extensions known by the pdftex driver of the graphics package.
205 * \sa known_dvips_graphics_formats
207 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
211 * Known file extensions for TeX files as used by \\include.
213 char const * const known_tex_extensions[] = {"tex", 0};
215 /// spaces known by InsetSpace
216 char const * const known_spaces[] = { " ", "space", ",",
217 "thinspace", "quad", "qquad", "enspace", "enskip",
218 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
219 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
220 "upbracefill", "downbracefill", 0};
222 /// the same as known_spaces with .lyx names
223 char const * const known_coded_spaces[] = { "space{}", "space{}",
224 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
225 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
226 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
227 "upbracefill{}", "downbracefill{}", 0};
229 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
230 /// them in ERT. "LaTeXe" must come before "LaTeX"!
231 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
232 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
233 int const known_phrase_lengths[] = {3, 5, 7, 0};
235 // string to store the float type to be able to determine the type of subfloats
236 string float_type = "";
239 /// splits "x=z, y=b" into a map and an ordered keyword vector
240 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
245 keys.resize(v.size());
246 for (size_t i = 0; i < v.size(); ++i) {
247 size_t const pos = v[i].find('=');
248 string const index = trimSpaceAndEol(v[i].substr(0, pos));
249 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
257 * Split a LaTeX length into value and unit.
258 * The latter can be a real unit like "pt", or a latex length variable
259 * like "\textwidth". The unit may contain additional stuff like glue
260 * lengths, but we don't care, because such lengths are ERT anyway.
261 * \returns true if \p value and \p unit are valid.
263 bool splitLatexLength(string const & len, string & value, string & unit)
267 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
268 //'4,5' is a valid LaTeX length number. Change it to '4.5'
269 string const length = subst(len, ',', '.');
270 if (i == string::npos)
273 if (len[0] == '\\') {
274 // We had something like \textwidth without a factor
280 value = trimSpaceAndEol(string(length, 0, i));
284 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
285 if (contains(len, '\\'))
286 unit = trimSpaceAndEol(string(len, i));
288 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
293 /// A simple function to translate a latex length to something LyX can
294 /// understand. Not perfect, but rather best-effort.
295 bool translate_len(string const & length, string & valstring, string & unit)
297 if (!splitLatexLength(length, valstring, unit))
299 // LyX uses percent values
301 istringstream iss(valstring);
306 string const percentval = oss.str();
308 if (unit.empty() || unit[0] != '\\')
310 string::size_type const i = unit.find(' ');
311 string const endlen = (i == string::npos) ? string() : string(unit, i);
312 if (unit == "\\textwidth") {
313 valstring = percentval;
314 unit = "text%" + endlen;
315 } else if (unit == "\\columnwidth") {
316 valstring = percentval;
317 unit = "col%" + endlen;
318 } else if (unit == "\\paperwidth") {
319 valstring = percentval;
320 unit = "page%" + endlen;
321 } else if (unit == "\\linewidth") {
322 valstring = percentval;
323 unit = "line%" + endlen;
324 } else if (unit == "\\paperheight") {
325 valstring = percentval;
326 unit = "pheight%" + endlen;
327 } else if (unit == "\\textheight") {
328 valstring = percentval;
329 unit = "theight%" + endlen;
337 string translate_len(string const & length)
341 if (translate_len(length, value, unit))
343 // If the input is invalid, return what we have.
351 * Translates a LaTeX length into \p value, \p unit and
352 * \p special parts suitable for a box inset.
353 * The difference from translate_len() is that a box inset knows about
354 * some special "units" that are stored in \p special.
356 void translate_box_len(string const & length, string & value, string & unit, string & special)
358 if (translate_len(length, value, unit)) {
359 if (unit == "\\height" || unit == "\\depth" ||
360 unit == "\\totalheight" || unit == "\\width") {
361 special = unit.substr(1);
362 // The unit is not used, but LyX requires a dummy setting
375 * Find a file with basename \p name in path \p path and an extension
378 string find_file(string const & name, string const & path,
379 char const * const * extensions)
381 for (char const * const * what = extensions; *what; ++what) {
382 string const trial = addExtension(name, *what);
383 if (makeAbsPath(trial, path).exists())
390 void begin_inset(ostream & os, string const & name)
392 os << "\n\\begin_inset " << name;
396 void begin_command_inset(ostream & os, string const & name,
397 string const & latexname)
399 begin_inset(os, "CommandInset ");
400 os << name << "\nLatexCommand " << latexname << '\n';
404 void end_inset(ostream & os)
406 os << "\n\\end_inset\n\n";
410 bool skip_braces(Parser & p)
412 if (p.next_token().cat() != catBegin)
415 if (p.next_token().cat() == catEnd) {
424 /// replace LaTeX commands in \p s from the unicodesymbols file with their
426 docstring convert_unicodesymbols(docstring s)
429 for (size_t i = 0; i < s.size();) {
436 docstring parsed = encodings.fromLaTeXCommand(s, rem,
437 Encodings::TEXT_CMD);
440 if (s.empty() || s[0] != '\\')
449 /// try to convert \p s to a valid InsetCommand argument
450 string convert_command_inset_arg(string s)
453 // since we don't know the input encoding we can't use from_utf8
454 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
455 // LyX cannot handle newlines in a latex command
456 return subst(s, "\n", " ");
460 void handle_backslash(ostream & os, string const & s)
462 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
464 os << "\n\\backslash\n";
471 void handle_ert(ostream & os, string const & s, Context & context)
473 // We must have a valid layout before outputting the ERT inset.
474 context.check_layout(os);
475 Context newcontext(true, context.textclass);
476 begin_inset(os, "ERT");
477 os << "\nstatus collapsed\n";
478 newcontext.check_layout(os);
479 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
481 os << "\n\\backslash\n";
482 else if (*it == '\n') {
483 newcontext.new_paragraph(os);
484 newcontext.check_layout(os);
488 newcontext.check_end_layout(os);
493 void handle_comment(ostream & os, string const & s, Context & context)
495 // TODO: Handle this better
496 Context newcontext(true, context.textclass);
497 begin_inset(os, "ERT");
498 os << "\nstatus collapsed\n";
499 newcontext.check_layout(os);
500 handle_backslash(os, s);
501 // make sure that our comment is the last thing on the line
502 newcontext.new_paragraph(os);
503 newcontext.check_layout(os);
504 newcontext.check_end_layout(os);
509 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
511 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
514 if (checkModule(name, command))
515 return findLayoutWithoutModule(textclass, name, command);
520 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
522 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
525 if (checkModule(name, command))
526 return findInsetLayoutWithoutModule(textclass, name, command);
531 void eat_whitespace(Parser &, ostream &, Context &, bool);
535 * Skips whitespace and braces.
536 * This should be called after a command has been parsed that is not put into
537 * ERT, and where LyX adds "{}" if needed.
539 void skip_spaces_braces(Parser & p, bool keepws = false)
541 /* The following four examples produce the same typeset output and
542 should be handled by this function:
550 // Unfortunately we need to skip comments, too.
551 // We can't use eat_whitespace since writing them after the {}
552 // results in different output in some cases.
553 bool const skipped_spaces = p.skip_spaces(true);
554 bool const skipped_braces = skip_braces(p);
555 if (keepws && skipped_spaces && !skipped_braces)
556 // put back the space (it is better handled by check_space)
557 p.unskip_spaces(true);
561 void output_command_layout(ostream & os, Parser & p, bool outer,
562 Context & parent_context,
563 Layout const * newlayout)
565 TeXFont const oldFont = parent_context.font;
566 // save the current font size
567 string const size = oldFont.size;
568 // reset the font size to default, because the font size switches
569 // don't affect section headings and the like
570 parent_context.font.size = Context::normalfont.size;
571 // we only need to write the font change if we have an open layout
572 if (!parent_context.atParagraphStart())
573 output_font_change(os, oldFont, parent_context.font);
574 parent_context.check_end_layout(os);
575 Context context(true, parent_context.textclass, newlayout,
576 parent_context.layout, parent_context.font);
577 if (parent_context.deeper_paragraph) {
578 // We are beginning a nested environment after a
579 // deeper paragraph inside the outer list environment.
580 // Therefore we don't need to output a "begin deeper".
581 context.need_end_deeper = true;
583 context.check_deeper(os);
584 context.check_layout(os);
585 unsigned int optargs = 0;
586 while (optargs < context.layout->optargs) {
587 eat_whitespace(p, os, context, false);
588 if (p.next_token().cat() == catEscape ||
589 p.next_token().character() != '[')
591 p.get_token(); // eat '['
592 begin_inset(os, "Argument\n");
593 os << "status collapsed\n\n";
594 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
596 eat_whitespace(p, os, context, false);
599 unsigned int reqargs = 0;
600 while (reqargs < context.layout->reqargs) {
601 eat_whitespace(p, os, context, false);
602 if (p.next_token().cat() != catBegin)
604 p.get_token(); // eat '{'
605 begin_inset(os, "Argument\n");
606 os << "status collapsed\n\n";
607 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
609 eat_whitespace(p, os, context, false);
612 parse_text(p, os, FLAG_ITEM, outer, context);
613 context.check_end_layout(os);
614 if (parent_context.deeper_paragraph) {
615 // We must suppress the "end deeper" because we
616 // suppressed the "begin deeper" above.
617 context.need_end_deeper = false;
619 context.check_end_deeper(os);
620 // We don't need really a new paragraph, but
621 // we must make sure that the next item gets a \begin_layout.
622 parent_context.new_paragraph(os);
623 // Set the font size to the original value. No need to output it here
624 // (Context::begin_layout() will do that if needed)
625 parent_context.font.size = size;
630 * Output a space if necessary.
631 * This function gets called for every whitespace token.
633 * We have three cases here:
634 * 1. A space must be suppressed. Example: The lyxcode case below
635 * 2. A space may be suppressed. Example: Spaces before "\par"
636 * 3. A space must not be suppressed. Example: A space between two words
638 * We currently handle only 1. and 3 and from 2. only the case of
639 * spaces before newlines as a side effect.
641 * 2. could be used to suppress as many spaces as possible. This has two effects:
642 * - Reimporting LyX generated LaTeX files changes almost no whitespace
643 * - Superflous whitespace from non LyX generated LaTeX files is removed.
644 * The drawback is that the logic inside the function becomes
645 * complicated, and that is the reason why it is not implemented.
647 void check_space(Parser & p, ostream & os, Context & context)
649 Token const next = p.next_token();
650 Token const curr = p.curr_token();
651 // A space before a single newline and vice versa must be ignored
652 // LyX emits a newline before \end{lyxcode}.
653 // This newline must be ignored,
654 // otherwise LyX will add an additional protected space.
655 if (next.cat() == catSpace ||
656 next.cat() == catNewline ||
657 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
660 context.check_layout(os);
666 * Parse all arguments of \p command
668 void parse_arguments(string const & command,
669 vector<ArgumentType> const & template_arguments,
670 Parser & p, ostream & os, bool outer, Context & context)
672 string ert = command;
673 size_t no_arguments = template_arguments.size();
674 for (size_t i = 0; i < no_arguments; ++i) {
675 switch (template_arguments[i]) {
677 // This argument contains regular LaTeX
678 handle_ert(os, ert + '{', context);
679 eat_whitespace(p, os, context, false);
680 parse_text(p, os, FLAG_ITEM, outer, context);
684 // This argument consists only of a single item.
685 // The presence of '{' or not must be preserved.
687 if (p.next_token().cat() == catBegin)
688 ert += '{' + p.verbatim_item() + '}';
690 ert += p.verbatim_item();
694 // This argument may contain special characters
695 ert += '{' + p.verbatim_item() + '}';
698 // true because we must not eat whitespace
699 // if an optional arg follows we must not strip the
700 // brackets from this one
701 if (i < no_arguments - 1 &&
702 template_arguments[i+1] == optional)
703 ert += p.getFullOpt(true);
705 ert += p.getOpt(true);
709 handle_ert(os, ert, context);
714 * Check whether \p command is a known command. If yes,
715 * handle the command with all arguments.
716 * \return true if the command was parsed, false otherwise.
718 bool parse_command(string const & command, Parser & p, ostream & os,
719 bool outer, Context & context)
721 if (known_commands.find(command) != known_commands.end()) {
722 parse_arguments(command, known_commands[command], p, os,
730 /// Parses a minipage or parbox
731 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
732 unsigned inner_flags, bool outer, Context & parent_context,
733 string const & outer_type, string const & special,
734 string const & inner_type)
738 string hor_pos = "c";
739 // We need to set the height to the LaTeX default of 1\\totalheight
740 // for the case when no height argument is given
741 string height_value = "1";
742 string height_unit = "in";
743 string height_special = "totalheight";
748 string width_special = "none";
749 if (!inner_type.empty() && p.hasOpt()) {
750 if (inner_type != "makebox")
751 position = p.getArg('[', ']');
753 latex_width = p.getArg('[', ']');
754 translate_box_len(latex_width, width_value, width_unit, width_special);
757 if (position != "t" && position != "c" && position != "b") {
758 cerr << "invalid position " << position << " for "
759 << inner_type << endl;
763 if (inner_type != "makebox") {
764 latex_height = p.getArg('[', ']');
765 translate_box_len(latex_height, height_value, height_unit, height_special);
767 hor_pos = p.getArg('[', ']');
770 inner_pos = p.getArg('[', ']');
771 if (inner_pos != "c" && inner_pos != "t" &&
772 inner_pos != "b" && inner_pos != "s") {
773 cerr << "invalid inner_pos "
774 << inner_pos << " for "
775 << inner_type << endl;
776 inner_pos = position;
781 if (inner_type.empty()) {
782 if (special.empty() && outer_type != "framebox")
783 latex_width = "1\\columnwidth";
786 latex_width = p2.getArg('[', ']');
787 string const opt = p2.getArg('[', ']');
790 if (hor_pos != "l" && hor_pos != "c" &&
792 cerr << "invalid hor_pos " << hor_pos
793 << " for " << outer_type << endl;
798 } else if (inner_type != "makebox")
799 latex_width = p.verbatim_item();
800 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
801 // as this is LyX's standard for such cases (except for makebox)
802 // \framebox is more special and handled below
803 if (latex_width.empty() && inner_type != "makebox"
804 && outer_type != "framebox")
805 latex_width = "1\\columnwidth";
807 translate_len(latex_width, width_value, width_unit);
809 bool shadedparbox = false;
810 if (inner_type == "shaded") {
811 eat_whitespace(p, os, parent_context, false);
812 if (outer_type == "parbox") {
814 if (p.next_token().cat() == catBegin)
816 eat_whitespace(p, os, parent_context, false);
822 // If we already read the inner box we have to push the inner env
823 if (!outer_type.empty() && !inner_type.empty() &&
824 (inner_flags & FLAG_END))
825 active_environments.push_back(inner_type);
826 // LyX can't handle length variables
827 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
828 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
829 // Look whether there is some content after the end of the
830 // inner box, but before the end of the outer box.
831 // If yes, we need to output ERT.
833 if (inner_flags & FLAG_END)
834 p.verbatimEnvironment(inner_type);
838 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
839 if ((outer_env && p.next_token().asInput() != "\\end") ||
840 (!outer_env && p.next_token().cat() != catEnd)) {
841 // something is between the end of the inner box and
842 // the end of the outer box, so we need to use ERT.
847 // if only \makebox{content} was used we can set its width to 1\width
848 // because this identic and also identic to \mbox
849 // this doesn't work for \framebox{content}, thus we have to use ERT for this
850 if (latex_width.empty() && inner_type == "makebox") {
853 width_special = "width";
854 } else if (latex_width.empty() && outer_type == "framebox") {
859 if (!outer_type.empty()) {
860 if (outer_flags & FLAG_END)
861 ss << "\\begin{" << outer_type << '}';
863 ss << '\\' << outer_type << '{';
864 if (!special.empty())
868 if (!inner_type.empty()) {
869 if (inner_type != "shaded") {
870 if (inner_flags & FLAG_END)
871 ss << "\\begin{" << inner_type << '}';
873 ss << '\\' << inner_type;
875 if (!position.empty())
876 ss << '[' << position << ']';
877 if (!latex_height.empty())
878 ss << '[' << latex_height << ']';
879 if (!inner_pos.empty())
880 ss << '[' << inner_pos << ']';
881 ss << '{' << latex_width << '}';
882 if (!(inner_flags & FLAG_END))
885 if (inner_type == "shaded")
886 ss << "\\begin{shaded}";
887 handle_ert(os, ss.str(), parent_context);
888 if (!inner_type.empty()) {
889 parse_text(p, os, inner_flags, outer, parent_context);
890 if (inner_flags & FLAG_END)
891 handle_ert(os, "\\end{" + inner_type + '}',
894 handle_ert(os, "}", parent_context);
896 if (!outer_type.empty()) {
897 // If we already read the inner box we have to pop
899 if (!inner_type.empty() && (inner_flags & FLAG_END))
900 active_environments.pop_back();
902 // Ensure that the end of the outer box is parsed correctly:
903 // The opening brace has been eaten by parse_outer_box()
904 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
905 outer_flags &= ~FLAG_ITEM;
906 outer_flags |= FLAG_BRACE_LAST;
908 parse_text(p, os, outer_flags, outer, parent_context);
909 if (outer_flags & FLAG_END)
910 handle_ert(os, "\\end{" + outer_type + '}',
912 else if (inner_type.empty() && outer_type == "framebox")
913 // in this case it is already closed later
916 handle_ert(os, "}", parent_context);
919 // LyX does not like empty positions, so we have
920 // to set them to the LaTeX default values here.
921 if (position.empty())
923 if (inner_pos.empty())
924 inner_pos = position;
925 parent_context.check_layout(os);
926 begin_inset(os, "Box ");
927 if (outer_type == "framed")
929 else if (outer_type == "framebox")
931 else if (outer_type == "shadowbox")
933 else if ((outer_type == "shaded" && inner_type.empty()) ||
934 (outer_type == "minipage" && inner_type == "shaded") ||
935 (outer_type == "parbox" && inner_type == "shaded")) {
937 preamble.registerAutomaticallyLoadedPackage("color");
938 } else if (outer_type == "doublebox")
940 else if (outer_type.empty())
943 os << outer_type << '\n';
944 os << "position \"" << position << "\"\n";
945 os << "hor_pos \"" << hor_pos << "\"\n";
946 os << "has_inner_box " << !inner_type.empty() << "\n";
947 os << "inner_pos \"" << inner_pos << "\"\n";
948 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
950 os << "use_makebox " << (inner_type == "makebox") << '\n';
951 os << "width \"" << width_value << width_unit << "\"\n";
952 os << "special \"" << width_special << "\"\n";
953 os << "height \"" << height_value << height_unit << "\"\n";
954 os << "height_special \"" << height_special << "\"\n";
955 os << "status open\n\n";
957 // Unfortunately we can't use parse_text_in_inset:
958 // InsetBox::forcePlainLayout() is hard coded and does not
959 // use the inset layout. Apart from that do we call parse_text
960 // up to two times, but need only one check_end_layout.
961 bool const forcePlainLayout =
962 (!inner_type.empty() || inner_type == "makebox") &&
963 outer_type != "shaded" && outer_type != "framed";
964 Context context(true, parent_context.textclass);
965 if (forcePlainLayout)
966 context.layout = &context.textclass.plainLayout();
968 context.font = parent_context.font;
970 // If we have no inner box the contents will be read with the outer box
971 if (!inner_type.empty())
972 parse_text(p, os, inner_flags, outer, context);
974 // Ensure that the end of the outer box is parsed correctly:
975 // The opening brace has been eaten by parse_outer_box()
976 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
977 outer_flags &= ~FLAG_ITEM;
978 outer_flags |= FLAG_BRACE_LAST;
981 // Find end of outer box, output contents if inner_type is
982 // empty and output possible comments
983 if (!outer_type.empty()) {
984 // If we already read the inner box we have to pop
986 if (!inner_type.empty() && (inner_flags & FLAG_END))
987 active_environments.pop_back();
988 // This does not output anything but comments if
989 // inner_type is not empty (see use_ert)
990 parse_text(p, os, outer_flags, outer, context);
993 context.check_end_layout(os);
995 #ifdef PRESERVE_LAYOUT
996 // LyX puts a % after the end of the minipage
997 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
999 //handle_comment(os, "%dummy", parent_context);
1002 parent_context.new_paragraph(os);
1004 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1005 //handle_comment(os, "%dummy", parent_context);
1008 // We add a protected space if something real follows
1009 if (p.good() && p.next_token().cat() != catComment) {
1010 begin_inset(os, "space ~\n");
1019 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1020 Context & parent_context, string const & outer_type,
1021 string const & special)
1023 eat_whitespace(p, os, parent_context, false);
1024 if (flags & FLAG_ITEM) {
1026 if (p.next_token().cat() == catBegin)
1029 cerr << "Warning: Ignoring missing '{' after \\"
1030 << outer_type << '.' << endl;
1031 eat_whitespace(p, os, parent_context, false);
1034 unsigned int inner_flags = 0;
1036 if (outer_type == "minipage" || outer_type == "parbox") {
1037 p.skip_spaces(true);
1038 while (p.hasOpt()) {
1040 p.skip_spaces(true);
1043 p.skip_spaces(true);
1044 if (outer_type == "parbox") {
1046 if (p.next_token().cat() == catBegin)
1048 p.skip_spaces(true);
1051 if (outer_type == "shaded") {
1052 // These boxes never have an inner box
1054 } else if (p.next_token().asInput() == "\\parbox") {
1055 inner = p.get_token().cs();
1056 inner_flags = FLAG_ITEM;
1057 } else if (p.next_token().asInput() == "\\begin") {
1058 // Is this a minipage or shaded box?
1061 inner = p.getArg('{', '}');
1063 if (inner == "minipage" || inner == "shaded")
1064 inner_flags = FLAG_END;
1069 if (inner_flags == FLAG_END) {
1070 if (inner != "shaded")
1074 eat_whitespace(p, os, parent_context, false);
1076 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1077 outer_type, special, inner);
1079 if (inner_flags == FLAG_ITEM) {
1081 eat_whitespace(p, os, parent_context, false);
1083 parse_box(p, os, flags, inner_flags, outer, parent_context,
1084 outer_type, special, inner);
1089 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1091 parent_context.check_layout(os);
1092 begin_inset(os, "listings\n");
1093 os << "inline false\n"
1094 << "status collapsed\n";
1095 Context context(true, parent_context.textclass);
1096 context.layout = &parent_context.textclass.plainLayout();
1097 context.check_layout(os);
1098 string const s = p.verbatimEnvironment("lstlisting");
1099 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1101 os << "\n\\backslash\n";
1102 else if (*it == '\n') {
1103 // avoid adding an empty paragraph at the end
1105 context.new_paragraph(os);
1106 context.check_layout(os);
1111 context.check_end_layout(os);
1116 /// parse an unknown environment
1117 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1118 unsigned flags, bool outer,
1119 Context & parent_context)
1121 if (name == "tabbing")
1122 // We need to remember that we have to handle '\=' specially
1123 flags |= FLAG_TABBING;
1125 // We need to translate font changes and paragraphs inside the
1126 // environment to ERT if we have a non standard font.
1127 // Otherwise things like
1128 // \large\begin{foo}\huge bar\end{foo}
1130 bool const specialfont =
1131 (parent_context.font != parent_context.normalfont);
1132 bool const new_layout_allowed = parent_context.new_layout_allowed;
1134 parent_context.new_layout_allowed = false;
1135 handle_ert(os, "\\begin{" + name + "}", parent_context);
1136 parse_text_snippet(p, os, flags, outer, parent_context);
1137 handle_ert(os, "\\end{" + name + "}", parent_context);
1139 parent_context.new_layout_allowed = new_layout_allowed;
1143 void parse_environment(Parser & p, ostream & os, bool outer,
1144 string & last_env, bool & title_layout_found,
1145 Context & parent_context)
1147 Layout const * newlayout;
1148 InsetLayout const * newinsetlayout = 0;
1149 string const name = p.getArg('{', '}');
1150 const bool is_starred = suffixIs(name, '*');
1151 string const unstarred_name = rtrim(name, "*");
1152 active_environments.push_back(name);
1154 if (is_math_env(name)) {
1155 parent_context.check_layout(os);
1156 begin_inset(os, "Formula ");
1157 os << "\\begin{" << name << "}";
1158 parse_math(p, os, FLAG_END, MATH_MODE);
1159 os << "\\end{" << name << "}";
1161 if (is_display_math_env(name)) {
1162 // Prevent the conversion of a line break to a space
1163 // (bug 7668). This does not change the output, but
1164 // looks ugly in LyX.
1165 eat_whitespace(p, os, parent_context, false);
1169 else if (unstarred_name == "tabular" || name == "longtable") {
1170 eat_whitespace(p, os, parent_context, false);
1171 string width = "0pt";
1172 if (name == "tabular*") {
1173 width = lyx::translate_len(p.getArg('{', '}'));
1174 eat_whitespace(p, os, parent_context, false);
1176 parent_context.check_layout(os);
1177 begin_inset(os, "Tabular ");
1178 handle_tabular(p, os, name, width, parent_context);
1183 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1184 eat_whitespace(p, os, parent_context, false);
1185 parent_context.check_layout(os);
1186 begin_inset(os, "Float " + unstarred_name + "\n");
1187 // store the float type for subfloats
1188 // subfloats only work with figures and tables
1189 if (unstarred_name == "figure")
1190 float_type = unstarred_name;
1191 else if (unstarred_name == "table")
1192 float_type = unstarred_name;
1196 os << "placement " << p.getArg('[', ']') << '\n';
1197 os << "wide " << convert<string>(is_starred)
1198 << "\nsideways false"
1199 << "\nstatus open\n\n";
1200 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1202 // We don't need really a new paragraph, but
1203 // we must make sure that the next item gets a \begin_layout.
1204 parent_context.new_paragraph(os);
1206 // the float is parsed thus delete the type
1210 else if (unstarred_name == "sidewaysfigure"
1211 || unstarred_name == "sidewaystable") {
1212 eat_whitespace(p, os, parent_context, false);
1213 parent_context.check_layout(os);
1214 if (unstarred_name == "sidewaysfigure")
1215 begin_inset(os, "Float figure\n");
1217 begin_inset(os, "Float table\n");
1218 os << "wide " << convert<string>(is_starred)
1219 << "\nsideways true"
1220 << "\nstatus open\n\n";
1221 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1223 // We don't need really a new paragraph, but
1224 // we must make sure that the next item gets a \begin_layout.
1225 parent_context.new_paragraph(os);
1229 else if (name == "wrapfigure" || name == "wraptable") {
1230 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1231 eat_whitespace(p, os, parent_context, false);
1232 parent_context.check_layout(os);
1235 string overhang = "0col%";
1238 lines = p.getArg('[', ']');
1239 string const placement = p.getArg('{', '}');
1241 overhang = p.getArg('[', ']');
1242 string const width = p.getArg('{', '}');
1244 if (name == "wrapfigure")
1245 begin_inset(os, "Wrap figure\n");
1247 begin_inset(os, "Wrap table\n");
1248 os << "lines " << lines
1249 << "\nplacement " << placement
1250 << "\noverhang " << lyx::translate_len(overhang)
1251 << "\nwidth " << lyx::translate_len(width)
1252 << "\nstatus open\n\n";
1253 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1255 // We don't need really a new paragraph, but
1256 // we must make sure that the next item gets a \begin_layout.
1257 parent_context.new_paragraph(os);
1261 else if (name == "minipage") {
1262 eat_whitespace(p, os, parent_context, false);
1263 // Test whether this is an outer box of a shaded box
1265 // swallow arguments
1266 while (p.hasOpt()) {
1268 p.skip_spaces(true);
1271 p.skip_spaces(true);
1272 Token t = p.get_token();
1273 bool shaded = false;
1274 if (t.asInput() == "\\begin") {
1275 p.skip_spaces(true);
1276 if (p.getArg('{', '}') == "shaded")
1281 parse_outer_box(p, os, FLAG_END, outer,
1282 parent_context, name, "shaded");
1284 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1289 else if (name == "comment") {
1290 eat_whitespace(p, os, parent_context, false);
1291 parent_context.check_layout(os);
1292 begin_inset(os, "Note Comment\n");
1293 os << "status open\n";
1294 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1297 skip_braces(p); // eat {} that might by set by LyX behind comments
1300 else if (name == "lyxgreyedout") {
1301 eat_whitespace(p, os, parent_context, false);
1302 parent_context.check_layout(os);
1303 begin_inset(os, "Note Greyedout\n");
1304 os << "status open\n";
1305 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1308 if (!preamble.notefontcolor().empty())
1309 preamble.registerAutomaticallyLoadedPackage("color");
1312 else if (name == "framed" || name == "shaded") {
1313 eat_whitespace(p, os, parent_context, false);
1314 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1318 else if (name == "lstlisting") {
1319 eat_whitespace(p, os, parent_context, false);
1320 // FIXME handle listings with parameters
1321 // If this is added, don't forgot to handle the
1322 // automatic color package loading
1324 parse_unknown_environment(p, name, os, FLAG_END,
1325 outer, parent_context);
1327 parse_listings(p, os, parent_context);
1331 else if (!parent_context.new_layout_allowed)
1332 parse_unknown_environment(p, name, os, FLAG_END, outer,
1335 // Alignment and spacing settings
1336 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1337 // therefore are totally broken!
1338 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1339 // they are commands not environments. They are furthermore switches that
1340 // can be ended by another switches, but also by commands like \footnote or
1341 // \parbox. So the only safe way is to leave them untouched.
1342 else if (name == "center" || name == "centering" ||
1343 name == "flushleft" || name == "flushright" ||
1344 name == "singlespace" || name == "onehalfspace" ||
1345 name == "doublespace" || name == "spacing") {
1346 eat_whitespace(p, os, parent_context, false);
1347 // We must begin a new paragraph if not already done
1348 if (! parent_context.atParagraphStart()) {
1349 parent_context.check_end_layout(os);
1350 parent_context.new_paragraph(os);
1352 if (name == "flushleft")
1353 parent_context.add_extra_stuff("\\align left\n");
1354 else if (name == "flushright")
1355 parent_context.add_extra_stuff("\\align right\n");
1356 else if (name == "center" || name == "centering")
1357 parent_context.add_extra_stuff("\\align center\n");
1358 else if (name == "singlespace")
1359 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1360 else if (name == "onehalfspace")
1361 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1362 else if (name == "doublespace")
1363 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1364 else if (name == "spacing")
1365 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1366 parse_text(p, os, FLAG_END, outer, parent_context);
1367 // Just in case the environment is empty
1368 parent_context.extra_stuff.erase();
1369 // We must begin a new paragraph to reset the alignment
1370 parent_context.new_paragraph(os);
1374 // The single '=' is meant here.
1375 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1376 eat_whitespace(p, os, parent_context, false);
1377 Context context(true, parent_context.textclass, newlayout,
1378 parent_context.layout, parent_context.font);
1379 if (parent_context.deeper_paragraph) {
1380 // We are beginning a nested environment after a
1381 // deeper paragraph inside the outer list environment.
1382 // Therefore we don't need to output a "begin deeper".
1383 context.need_end_deeper = true;
1385 parent_context.check_end_layout(os);
1386 if (last_env == name) {
1387 // we need to output a separator since LyX would export
1388 // the two environments as one otherwise (bug 5716)
1389 docstring const sep = from_ascii("--Separator--");
1390 TeX2LyXDocClass const & textclass(parent_context.textclass);
1391 if (textclass.hasLayout(sep)) {
1392 Context newcontext(parent_context);
1393 newcontext.layout = &(textclass[sep]);
1394 newcontext.check_layout(os);
1395 newcontext.check_end_layout(os);
1397 parent_context.check_layout(os);
1398 begin_inset(os, "Note Note\n");
1399 os << "status closed\n";
1400 Context newcontext(true, textclass,
1401 &(textclass.defaultLayout()));
1402 newcontext.check_layout(os);
1403 newcontext.check_end_layout(os);
1405 parent_context.check_end_layout(os);
1408 switch (context.layout->latextype) {
1409 case LATEX_LIST_ENVIRONMENT:
1410 context.add_par_extra_stuff("\\labelwidthstring "
1411 + p.verbatim_item() + '\n');
1414 case LATEX_BIB_ENVIRONMENT:
1415 p.verbatim_item(); // swallow next arg
1421 context.check_deeper(os);
1422 // handle known optional and required arguments
1423 // layouts require all optional arguments before the required ones
1424 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1425 // It is impossible to place anything after the environment name,
1426 // but before the first \\item.
1427 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1428 bool need_layout = true;
1429 unsigned int optargs = 0;
1430 while (optargs < context.layout->optargs) {
1431 eat_whitespace(p, os, context, false);
1432 if (p.next_token().cat() == catEscape ||
1433 p.next_token().character() != '[')
1435 p.get_token(); // eat '['
1437 context.check_layout(os);
1438 need_layout = false;
1440 begin_inset(os, "Argument\n");
1441 os << "status collapsed\n\n";
1442 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1444 eat_whitespace(p, os, context, false);
1447 unsigned int reqargs = 0;
1448 while (reqargs < context.layout->reqargs) {
1449 eat_whitespace(p, os, context, false);
1450 if (p.next_token().cat() != catBegin)
1452 p.get_token(); // eat '{'
1454 context.check_layout(os);
1455 need_layout = false;
1457 begin_inset(os, "Argument\n");
1458 os << "status collapsed\n\n";
1459 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1461 eat_whitespace(p, os, context, false);
1465 parse_text(p, os, FLAG_END, outer, context);
1466 context.check_end_layout(os);
1467 if (parent_context.deeper_paragraph) {
1468 // We must suppress the "end deeper" because we
1469 // suppressed the "begin deeper" above.
1470 context.need_end_deeper = false;
1472 context.check_end_deeper(os);
1473 parent_context.new_paragraph(os);
1475 if (!title_layout_found)
1476 title_layout_found = newlayout->intitle;
1479 // The single '=' is meant here.
1480 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1481 eat_whitespace(p, os, parent_context, false);
1482 parent_context.check_layout(os);
1483 begin_inset(os, "Flex ");
1484 os << to_utf8(newinsetlayout->name()) << '\n'
1485 << "status collapsed\n";
1486 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1490 else if (name == "appendix") {
1491 // This is no good latex style, but it works and is used in some documents...
1492 eat_whitespace(p, os, parent_context, false);
1493 parent_context.check_end_layout(os);
1494 Context context(true, parent_context.textclass, parent_context.layout,
1495 parent_context.layout, parent_context.font);
1496 context.check_layout(os);
1497 os << "\\start_of_appendix\n";
1498 parse_text(p, os, FLAG_END, outer, context);
1499 context.check_end_layout(os);
1503 else if (known_environments.find(name) != known_environments.end()) {
1504 vector<ArgumentType> arguments = known_environments[name];
1505 // The last "argument" denotes wether we may translate the
1506 // environment contents to LyX
1507 // The default required if no argument is given makes us
1508 // compatible with the reLyXre environment.
1509 ArgumentType contents = arguments.empty() ?
1512 if (!arguments.empty())
1513 arguments.pop_back();
1514 // See comment in parse_unknown_environment()
1515 bool const specialfont =
1516 (parent_context.font != parent_context.normalfont);
1517 bool const new_layout_allowed =
1518 parent_context.new_layout_allowed;
1520 parent_context.new_layout_allowed = false;
1521 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1522 outer, parent_context);
1523 if (contents == verbatim)
1524 handle_ert(os, p.verbatimEnvironment(name),
1527 parse_text_snippet(p, os, FLAG_END, outer,
1529 handle_ert(os, "\\end{" + name + "}", parent_context);
1531 parent_context.new_layout_allowed = new_layout_allowed;
1535 parse_unknown_environment(p, name, os, FLAG_END, outer,
1539 active_environments.pop_back();
1543 /// parses a comment and outputs it to \p os.
1544 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1546 LASSERT(t.cat() == catComment, return);
1547 if (!t.cs().empty()) {
1548 context.check_layout(os);
1549 handle_comment(os, '%' + t.cs(), context);
1550 if (p.next_token().cat() == catNewline) {
1551 // A newline after a comment line starts a new
1553 if (context.new_layout_allowed) {
1554 if(!context.atParagraphStart())
1555 // Only start a new paragraph if not already
1556 // done (we might get called recursively)
1557 context.new_paragraph(os);
1559 handle_ert(os, "\n", context);
1560 eat_whitespace(p, os, context, true);
1563 // "%\n" combination
1570 * Reads spaces and comments until the first non-space, non-comment token.
1571 * New paragraphs (double newlines or \\par) are handled like simple spaces
1572 * if \p eatParagraph is true.
1573 * Spaces are skipped, but comments are written to \p os.
1575 void eat_whitespace(Parser & p, ostream & os, Context & context,
1579 Token const & t = p.get_token();
1580 if (t.cat() == catComment)
1581 parse_comment(p, os, t, context);
1582 else if ((! eatParagraph && p.isParagraph()) ||
1583 (t.cat() != catSpace && t.cat() != catNewline)) {
1592 * Set a font attribute, parse text and reset the font attribute.
1593 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1594 * \param currentvalue Current value of the attribute. Is set to the new
1595 * value during parsing.
1596 * \param newvalue New value of the attribute
1598 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1599 Context & context, string const & attribute,
1600 string & currentvalue, string const & newvalue)
1602 context.check_layout(os);
1603 string const oldvalue = currentvalue;
1604 currentvalue = newvalue;
1605 os << '\n' << attribute << ' ' << newvalue << "\n";
1606 parse_text_snippet(p, os, flags, outer, context);
1607 context.check_layout(os);
1608 os << '\n' << attribute << ' ' << oldvalue << "\n";
1609 currentvalue = oldvalue;
1613 /// get the arguments of a natbib or jurabib citation command
1614 void get_cite_arguments(Parser & p, bool natbibOrder,
1615 string & before, string & after)
1617 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1619 // text before the citation
1621 // text after the citation
1622 after = p.getFullOpt();
1624 if (!after.empty()) {
1625 before = p.getFullOpt();
1626 if (natbibOrder && !before.empty())
1627 swap(before, after);
1632 /// Convert filenames with TeX macros and/or quotes to something LyX
1634 string const normalize_filename(string const & name)
1636 Parser p(trim(name, "\""));
1639 Token const & t = p.get_token();
1640 if (t.cat() != catEscape)
1642 else if (t.cs() == "lyxdot") {
1643 // This is used by LyX for simple dots in relative
1647 } else if (t.cs() == "space") {
1657 /// Convert \p name from TeX convention (relative to master file) to LyX
1658 /// convention (relative to .lyx file) if it is relative
1659 void fix_relative_filename(string & name)
1661 if (FileName::isAbsolute(name))
1664 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1665 from_utf8(getParentFilePath())));
1669 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1670 void parse_noweb(Parser & p, ostream & os, Context & context)
1672 // assemble the rest of the keyword
1676 Token const & t = p.get_token();
1677 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1680 scrap = (p.good() && p.next_token().asInput() == "=");
1682 name += p.get_token().asInput();
1685 name += t.asInput();
1688 if (!scrap || !context.new_layout_allowed ||
1689 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1690 cerr << "Warning: Could not interpret '" << name
1691 << "'. Ignoring it." << endl;
1695 // We use new_paragraph instead of check_end_layout because the stuff
1696 // following the noweb chunk needs to start with a \begin_layout.
1697 // This may create a new paragraph even if there was none in the
1698 // noweb file, but the alternative is an invalid LyX file. Since
1699 // noweb code chunks are implemented with a layout style in LyX they
1700 // always must be in an own paragraph.
1701 context.new_paragraph(os);
1702 Context newcontext(true, context.textclass,
1703 &context.textclass[from_ascii("Scrap")]);
1704 newcontext.check_layout(os);
1707 Token const & t = p.get_token();
1708 // We abuse the parser a bit, because this is no TeX syntax
1710 if (t.cat() == catEscape)
1711 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1714 Context tmp(false, context.textclass,
1715 &context.textclass[from_ascii("Scrap")]);
1716 tmp.need_end_layout = true;
1717 tmp.check_layout(oss);
1718 os << subst(t.asInput(), "\n", oss.str());
1720 // The scrap chunk is ended by an @ at the beginning of a line.
1721 // After the @ the line may contain a comment and/or
1722 // whitespace, but nothing else.
1723 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1724 (p.next_token().cat() == catSpace ||
1725 p.next_token().cat() == catNewline ||
1726 p.next_token().cat() == catComment)) {
1727 while (p.good() && p.next_token().cat() == catSpace)
1728 os << p.get_token().asInput();
1729 if (p.next_token().cat() == catComment)
1730 // The comment includes a final '\n'
1731 os << p.get_token().asInput();
1733 if (p.next_token().cat() == catNewline)
1740 newcontext.check_end_layout(os);
1744 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1745 bool is_macro(Parser & p)
1747 Token first = p.curr_token();
1748 if (first.cat() != catEscape || !p.good())
1750 if (first.cs() == "def")
1752 if (first.cs() != "global" && first.cs() != "long")
1754 Token second = p.get_token();
1756 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1757 second.cat() == catNewline || second.cat() == catComment)) {
1758 second = p.get_token();
1761 bool secondvalid = second.cat() == catEscape;
1763 bool thirdvalid = false;
1764 if (p.good() && first.cs() == "global" && secondvalid &&
1765 second.cs() == "long") {
1766 third = p.get_token();
1768 while (p.good() && !p.isParagraph() &&
1769 (third.cat() == catSpace ||
1770 third.cat() == catNewline ||
1771 third.cat() == catComment)) {
1772 third = p.get_token();
1775 thirdvalid = third.cat() == catEscape;
1777 for (int i = 0; i < pos; ++i)
1782 return (first.cs() == "global" || first.cs() == "long") &&
1783 second.cs() == "def";
1784 return first.cs() == "global" && second.cs() == "long" &&
1785 third.cs() == "def";
1789 /// Parse a macro definition (assumes that is_macro() returned true)
1790 void parse_macro(Parser & p, ostream & os, Context & context)
1792 context.check_layout(os);
1793 Token first = p.curr_token();
1796 string command = first.asInput();
1797 if (first.cs() != "def") {
1799 eat_whitespace(p, os, context, false);
1800 second = p.curr_token();
1801 command += second.asInput();
1802 if (second.cs() != "def") {
1804 eat_whitespace(p, os, context, false);
1805 third = p.curr_token();
1806 command += third.asInput();
1809 eat_whitespace(p, os, context, false);
1810 string const name = p.get_token().cs();
1811 eat_whitespace(p, os, context, false);
1817 while (p.next_token().cat() != catBegin) {
1818 if (p.next_token().cat() == catParameter) {
1823 // followed by number?
1824 if (p.next_token().cat() == catOther) {
1825 char c = p.getChar();
1827 // number = current arity + 1?
1828 if (c == arity + '0' + 1)
1833 paramtext += p.get_token().cs();
1835 paramtext += p.get_token().cs();
1840 // only output simple (i.e. compatible) macro as FormulaMacros
1841 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1843 context.check_layout(os);
1844 begin_inset(os, "FormulaMacro");
1845 os << "\n\\def" << ert;
1848 handle_ert(os, command + ert, context);
1851 } // anonymous namespace
1854 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1857 Layout const * newlayout = 0;
1858 InsetLayout const * newinsetlayout = 0;
1859 // Store the latest bibliographystyle and nocite{*} option
1860 // (needed for bibtex inset)
1862 string bibliographystyle;
1863 bool const use_natbib = preamble.isPackageUsed("natbib");
1864 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1866 bool title_layout_found = false;
1868 Token const & t = p.get_token();
1871 debugToken(cerr, t, flags);
1874 if (flags & FLAG_ITEM) {
1875 if (t.cat() == catSpace)
1878 flags &= ~FLAG_ITEM;
1879 if (t.cat() == catBegin) {
1880 // skip the brace and collect everything to the next matching
1882 flags |= FLAG_BRACE_LAST;
1886 // handle only this single token, leave the loop if done
1887 flags |= FLAG_LEAVE;
1890 if (t.cat() != catEscape && t.character() == ']' &&
1891 (flags & FLAG_BRACK_LAST))
1893 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1896 // If there is anything between \end{env} and \begin{env} we
1897 // don't need to output a separator.
1898 if (t.cat() != catSpace && t.cat() != catNewline &&
1899 t.asInput() != "\\begin")
1905 if (t.cat() == catMath) {
1906 // we are inside some text mode thingy, so opening new math is allowed
1907 context.check_layout(os);
1908 begin_inset(os, "Formula ");
1909 Token const & n = p.get_token();
1910 bool const display(n.cat() == catMath && outer);
1912 // TeX's $$...$$ syntax for displayed math
1914 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1916 p.get_token(); // skip the second '$' token
1918 // simple $...$ stuff
1921 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1926 // Prevent the conversion of a line break to a
1927 // space (bug 7668). This does not change the
1928 // output, but looks ugly in LyX.
1929 eat_whitespace(p, os, context, false);
1933 else if (t.cat() == catSuper || t.cat() == catSub)
1934 cerr << "catcode " << t << " illegal in text mode\n";
1936 // Basic support for english quotes. This should be
1937 // extended to other quotes, but is not so easy (a
1938 // left english quote is the same as a right german
1940 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1941 context.check_layout(os);
1942 begin_inset(os, "Quotes ");
1948 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1949 context.check_layout(os);
1950 begin_inset(os, "Quotes ");
1957 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1958 context.check_layout(os);
1959 begin_inset(os, "Quotes ");
1966 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1967 context.check_layout(os);
1968 begin_inset(os, "Quotes ");
1975 else if (t.asInput() == "<"
1976 && p.next_token().asInput() == "<" && noweb_mode) {
1978 parse_noweb(p, os, context);
1981 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1982 check_space(p, os, context);
1984 else if (t.character() == '[' && noweb_mode &&
1985 p.next_token().character() == '[') {
1986 // These can contain underscores
1988 string const s = p.getFullOpt() + ']';
1989 if (p.next_token().character() == ']')
1992 cerr << "Warning: Inserting missing ']' in '"
1993 << s << "'." << endl;
1994 handle_ert(os, s, context);
1997 else if (t.cat() == catLetter) {
1998 context.check_layout(os);
1999 // Workaround for bug 4752.
2000 // FIXME: This whole code block needs to be removed
2001 // when the bug is fixed and tex2lyx produces
2002 // the updated file format.
2003 // The replacement algorithm in LyX is so stupid that
2004 // it even translates a phrase if it is part of a word.
2005 bool handled = false;
2006 for (int const * l = known_phrase_lengths; *l; ++l) {
2007 string phrase = t.cs();
2008 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2009 phrase += p.get_token().cs();
2010 if (is_known(phrase, known_coded_phrases)) {
2011 handle_ert(os, phrase, context);
2015 for (size_t i = 1; i < phrase.length(); ++i)
2023 else if (t.cat() == catOther ||
2024 t.cat() == catAlign ||
2025 t.cat() == catParameter) {
2026 // This translates "&" to "\\&" which may be wrong...
2027 context.check_layout(os);
2031 else if (p.isParagraph()) {
2032 if (context.new_layout_allowed)
2033 context.new_paragraph(os);
2035 handle_ert(os, "\\par ", context);
2036 eat_whitespace(p, os, context, true);
2039 else if (t.cat() == catActive) {
2040 context.check_layout(os);
2041 if (t.character() == '~') {
2042 if (context.layout->free_spacing)
2045 begin_inset(os, "space ~\n");
2052 else if (t.cat() == catBegin &&
2053 p.next_token().cat() == catEnd) {
2055 Token const prev = p.prev_token();
2057 if (p.next_token().character() == '`' ||
2058 (prev.character() == '-' &&
2059 p.next_token().character() == '-'))
2060 ; // ignore it in {}`` or -{}-
2062 handle_ert(os, "{}", context);
2066 else if (t.cat() == catBegin) {
2067 context.check_layout(os);
2068 // special handling of font attribute changes
2069 Token const prev = p.prev_token();
2070 Token const next = p.next_token();
2071 TeXFont const oldFont = context.font;
2072 if (next.character() == '[' ||
2073 next.character() == ']' ||
2074 next.character() == '*') {
2076 if (p.next_token().cat() == catEnd) {
2081 handle_ert(os, "{", context);
2082 parse_text_snippet(p, os,
2085 handle_ert(os, "}", context);
2087 } else if (! context.new_layout_allowed) {
2088 handle_ert(os, "{", context);
2089 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2091 handle_ert(os, "}", context);
2092 } else if (is_known(next.cs(), known_sizes)) {
2093 // next will change the size, so we must
2095 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2097 if (!context.atParagraphStart())
2099 << context.font.size << "\n";
2100 } else if (is_known(next.cs(), known_font_families)) {
2101 // next will change the font family, so we
2102 // must reset it here
2103 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2105 if (!context.atParagraphStart())
2107 << context.font.family << "\n";
2108 } else if (is_known(next.cs(), known_font_series)) {
2109 // next will change the font series, so we
2110 // must reset it here
2111 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2113 if (!context.atParagraphStart())
2115 << context.font.series << "\n";
2116 } else if (is_known(next.cs(), known_font_shapes)) {
2117 // next will change the font shape, so we
2118 // must reset it here
2119 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2121 if (!context.atParagraphStart())
2123 << context.font.shape << "\n";
2124 } else if (is_known(next.cs(), known_old_font_families) ||
2125 is_known(next.cs(), known_old_font_series) ||
2126 is_known(next.cs(), known_old_font_shapes)) {
2127 // next will change the font family, series
2128 // and shape, so we must reset it here
2129 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2131 if (!context.atParagraphStart())
2133 << context.font.family
2135 << context.font.series
2137 << context.font.shape << "\n";
2139 handle_ert(os, "{", context);
2140 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2142 handle_ert(os, "}", context);
2146 else if (t.cat() == catEnd) {
2147 if (flags & FLAG_BRACE_LAST) {
2150 cerr << "stray '}' in text\n";
2151 handle_ert(os, "}", context);
2154 else if (t.cat() == catComment)
2155 parse_comment(p, os, t, context);
2158 // control sequences
2161 else if (t.cs() == "(") {
2162 context.check_layout(os);
2163 begin_inset(os, "Formula");
2165 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2170 else if (t.cs() == "[") {
2171 context.check_layout(os);
2172 begin_inset(os, "Formula");
2174 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2177 // Prevent the conversion of a line break to a space
2178 // (bug 7668). This does not change the output, but
2179 // looks ugly in LyX.
2180 eat_whitespace(p, os, context, false);
2183 else if (t.cs() == "begin")
2184 parse_environment(p, os, outer, last_env,
2185 title_layout_found, context);
2187 else if (t.cs() == "end") {
2188 if (flags & FLAG_END) {
2189 // eat environment name
2190 string const name = p.getArg('{', '}');
2191 if (name != active_environment())
2192 cerr << "\\end{" + name + "} does not match \\begin{"
2193 + active_environment() + "}\n";
2196 p.error("found 'end' unexpectedly");
2199 else if (t.cs() == "item") {
2201 bool const optarg = p.hasOpt();
2203 // FIXME: This swallows comments, but we cannot use
2204 // eat_whitespace() since we must not output
2205 // anything before the item.
2206 s = p.getArg('[', ']');
2208 p.skip_spaces(false);
2210 context.check_layout(os);
2211 if (context.has_item) {
2212 // An item in an unknown list-like environment
2213 // FIXME: Do this in check_layout()!
2214 context.has_item = false;
2216 handle_ert(os, "\\item", context);
2218 handle_ert(os, "\\item ", context);
2221 if (context.layout->labeltype != LABEL_MANUAL) {
2222 // LyX does not support \item[\mybullet]
2223 // in itemize environments
2225 os << parse_text_snippet(p2,
2226 FLAG_BRACK_LAST, outer, context);
2227 } else if (!s.empty()) {
2228 // LyX adds braces around the argument,
2229 // so we need to remove them here.
2230 if (s.size() > 2 && s[0] == '{' &&
2231 s[s.size()-1] == '}')
2232 s = s.substr(1, s.size()-2);
2233 // If the argument contains a space we
2234 // must put it into ERT: Otherwise LyX
2235 // would misinterpret the space as
2236 // item delimiter (bug 7663)
2237 if (contains(s, ' ')) {
2238 handle_ert(os, s, context);
2241 os << parse_text_snippet(p2,
2245 // The space is needed to separate the
2246 // item from the rest of the sentence.
2248 eat_whitespace(p, os, context, false);
2253 else if (t.cs() == "bibitem") {
2255 context.check_layout(os);
2256 string label = convert_command_inset_arg(p.getArg('[', ']'));
2257 string key = convert_command_inset_arg(p.verbatim_item());
2258 if (contains(label, '\\') || contains(key, '\\')) {
2259 // LyX can't handle LaTeX commands in labels or keys
2260 handle_ert(os, t.asInput() + '[' + label +
2261 "]{" + p.verbatim_item() + '}',
2264 begin_command_inset(os, "bibitem", "bibitem");
2265 os << "label \"" << label << "\"\n"
2266 "key \"" << key << "\"\n";
2271 else if (is_macro(p))
2272 parse_macro(p, os, context);
2274 else if (t.cs() == "noindent") {
2276 context.add_par_extra_stuff("\\noindent\n");
2279 else if (t.cs() == "appendix") {
2280 context.add_par_extra_stuff("\\start_of_appendix\n");
2281 // We need to start a new paragraph. Otherwise the
2282 // appendix in 'bla\appendix\chapter{' would start
2284 context.new_paragraph(os);
2285 // We need to make sure that the paragraph is
2286 // generated even if it is empty. Otherwise the
2287 // appendix in '\par\appendix\par\chapter{' would
2289 context.check_layout(os);
2290 // FIXME: This is a hack to prevent paragraph
2291 // deletion if it is empty. Handle this better!
2293 "%dummy comment inserted by tex2lyx to "
2294 "ensure that this paragraph is not empty",
2296 // Both measures above may generate an additional
2297 // empty paragraph, but that does not hurt, because
2298 // whitespace does not matter here.
2299 eat_whitespace(p, os, context, true);
2302 // Must catch empty dates before findLayout is called below
2303 else if (t.cs() == "date") {
2304 string const date = p.verbatim_item();
2306 preamble.suppressDate(true);
2308 preamble.suppressDate(false);
2309 if (context.new_layout_allowed &&
2310 (newlayout = findLayout(context.textclass,
2313 output_command_layout(os, p, outer,
2314 context, newlayout);
2316 if (!title_layout_found)
2317 title_layout_found = newlayout->intitle;
2319 handle_ert(os, "\\date{" + date + '}',
2324 // Starred section headings
2325 // Must attempt to parse "Section*" before "Section".
2326 else if ((p.next_token().asInput() == "*") &&
2327 context.new_layout_allowed &&
2328 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2331 output_command_layout(os, p, outer, context, newlayout);
2333 if (!title_layout_found)
2334 title_layout_found = newlayout->intitle;
2337 // Section headings and the like
2338 else if (context.new_layout_allowed &&
2339 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2341 output_command_layout(os, p, outer, context, newlayout);
2343 if (!title_layout_found)
2344 title_layout_found = newlayout->intitle;
2347 else if (t.cs() == "caption") {
2349 context.check_layout(os);
2351 begin_inset(os, "Caption\n");
2352 Context newcontext(true, context.textclass);
2353 newcontext.font = context.font;
2354 newcontext.check_layout(os);
2355 if (p.next_token().cat() != catEscape &&
2356 p.next_token().character() == '[') {
2357 p.get_token(); // eat '['
2358 begin_inset(os, "Argument\n");
2359 os << "status collapsed\n";
2360 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2362 eat_whitespace(p, os, context, false);
2364 parse_text(p, os, FLAG_ITEM, outer, context);
2365 context.check_end_layout(os);
2366 // We don't need really a new paragraph, but
2367 // we must make sure that the next item gets a \begin_layout.
2368 context.new_paragraph(os);
2371 newcontext.check_end_layout(os);
2374 else if (t.cs() == "subfloat") {
2375 // the syntax is \subfloat[caption]{content}
2376 // if it is a table of figure depends on the surrounding float
2377 bool has_caption = false;
2379 // do nothing if there is no outer float
2380 if (!float_type.empty()) {
2381 context.check_layout(os);
2383 begin_inset(os, "Float " + float_type + "\n");
2385 << "\nsideways false"
2386 << "\nstatus collapsed\n\n";
2389 if (p.next_token().cat() != catEscape &&
2390 p.next_token().character() == '[') {
2391 p.get_token(); // eat '['
2392 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2396 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2397 // the caption comes always as the last
2399 // we must make sure that the caption gets a \begin_layout
2400 os << "\n\\begin_layout Plain Layout";
2402 begin_inset(os, "Caption\n");
2403 Context newcontext(true, context.textclass);
2404 newcontext.font = context.font;
2405 newcontext.check_layout(os);
2406 os << caption << "\n";
2407 newcontext.check_end_layout(os);
2408 // We don't need really a new paragraph, but
2409 // we must make sure that the next item gets a \begin_layout.
2410 //newcontext.new_paragraph(os);
2414 // We don't need really a new paragraph, but
2415 // we must make sure that the next item gets a \begin_layout.
2417 context.new_paragraph(os);
2420 context.check_end_layout(os);
2421 // close the layout we opened
2423 os << "\n\\end_layout\n";
2425 // if the float type is not supported or there is no surrounding float
2428 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2429 handle_ert(os, t.asInput() + '[' + opt_arg +
2430 "]{" + p.verbatim_item() + '}', context);
2432 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2436 else if (t.cs() == "includegraphics") {
2437 bool const clip = p.next_token().asInput() == "*";
2440 string const arg = p.getArg('[', ']');
2441 map<string, string> opts;
2442 vector<string> keys;
2443 split_map(arg, opts, keys);
2445 opts["clip"] = string();
2446 string name = normalize_filename(p.verbatim_item());
2448 string const path = getMasterFilePath();
2449 // We want to preserve relative / absolute filenames,
2450 // therefore path is only used for testing
2451 if (!makeAbsPath(name, path).exists()) {
2452 // The file extension is probably missing.
2453 // Now try to find it out.
2454 string const dvips_name =
2455 find_file(name, path,
2456 known_dvips_graphics_formats);
2457 string const pdftex_name =
2458 find_file(name, path,
2459 known_pdftex_graphics_formats);
2460 if (!dvips_name.empty()) {
2461 if (!pdftex_name.empty()) {
2462 cerr << "This file contains the "
2464 "\"\\includegraphics{"
2466 "However, files\n\""
2467 << dvips_name << "\" and\n\""
2468 << pdftex_name << "\"\n"
2469 "both exist, so I had to make a "
2470 "choice and took the first one.\n"
2471 "Please move the unwanted one "
2472 "someplace else and try again\n"
2473 "if my choice was wrong."
2477 } else if (!pdftex_name.empty()) {
2483 if (makeAbsPath(name, path).exists())
2484 fix_relative_filename(name);
2486 cerr << "Warning: Could not find graphics file '"
2487 << name << "'." << endl;
2489 context.check_layout(os);
2490 begin_inset(os, "Graphics ");
2491 os << "\n\tfilename " << name << '\n';
2492 if (opts.find("width") != opts.end())
2494 << translate_len(opts["width"]) << '\n';
2495 if (opts.find("height") != opts.end())
2497 << translate_len(opts["height"]) << '\n';
2498 if (opts.find("scale") != opts.end()) {
2499 istringstream iss(opts["scale"]);
2503 os << "\tscale " << val << '\n';
2505 if (opts.find("angle") != opts.end()) {
2506 os << "\trotateAngle "
2507 << opts["angle"] << '\n';
2508 vector<string>::const_iterator a =
2509 find(keys.begin(), keys.end(), "angle");
2510 vector<string>::const_iterator s =
2511 find(keys.begin(), keys.end(), "width");
2512 if (s == keys.end())
2513 s = find(keys.begin(), keys.end(), "height");
2514 if (s == keys.end())
2515 s = find(keys.begin(), keys.end(), "scale");
2516 if (s != keys.end() && distance(s, a) > 0)
2517 os << "\tscaleBeforeRotation\n";
2519 if (opts.find("origin") != opts.end()) {
2521 string const opt = opts["origin"];
2522 if (opt.find('l') != string::npos) ss << "left";
2523 if (opt.find('r') != string::npos) ss << "right";
2524 if (opt.find('c') != string::npos) ss << "center";
2525 if (opt.find('t') != string::npos) ss << "Top";
2526 if (opt.find('b') != string::npos) ss << "Bottom";
2527 if (opt.find('B') != string::npos) ss << "Baseline";
2528 if (!ss.str().empty())
2529 os << "\trotateOrigin " << ss.str() << '\n';
2531 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2533 if (opts.find("keepaspectratio") != opts.end())
2534 os << "\tkeepAspectRatio\n";
2535 if (opts.find("clip") != opts.end())
2537 if (opts.find("draft") != opts.end())
2539 if (opts.find("bb") != opts.end())
2540 os << "\tBoundingBox "
2541 << opts["bb"] << '\n';
2542 int numberOfbbOptions = 0;
2543 if (opts.find("bbllx") != opts.end())
2544 numberOfbbOptions++;
2545 if (opts.find("bblly") != opts.end())
2546 numberOfbbOptions++;
2547 if (opts.find("bburx") != opts.end())
2548 numberOfbbOptions++;
2549 if (opts.find("bbury") != opts.end())
2550 numberOfbbOptions++;
2551 if (numberOfbbOptions == 4)
2552 os << "\tBoundingBox "
2553 << opts["bbllx"] << " " << opts["bblly"] << " "
2554 << opts["bburx"] << " " << opts["bbury"] << '\n';
2555 else if (numberOfbbOptions > 0)
2556 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2557 numberOfbbOptions = 0;
2558 if (opts.find("natwidth") != opts.end())
2559 numberOfbbOptions++;
2560 if (opts.find("natheight") != opts.end())
2561 numberOfbbOptions++;
2562 if (numberOfbbOptions == 2)
2563 os << "\tBoundingBox 0bp 0bp "
2564 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2565 else if (numberOfbbOptions > 0)
2566 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2567 ostringstream special;
2568 if (opts.find("hiresbb") != opts.end())
2569 special << "hiresbb,";
2570 if (opts.find("trim") != opts.end())
2572 if (opts.find("viewport") != opts.end())
2573 special << "viewport=" << opts["viewport"] << ',';
2574 if (opts.find("totalheight") != opts.end())
2575 special << "totalheight=" << opts["totalheight"] << ',';
2576 if (opts.find("type") != opts.end())
2577 special << "type=" << opts["type"] << ',';
2578 if (opts.find("ext") != opts.end())
2579 special << "ext=" << opts["ext"] << ',';
2580 if (opts.find("read") != opts.end())
2581 special << "read=" << opts["read"] << ',';
2582 if (opts.find("command") != opts.end())
2583 special << "command=" << opts["command"] << ',';
2584 string s_special = special.str();
2585 if (!s_special.empty()) {
2586 // We had special arguments. Remove the trailing ','.
2587 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2589 // TODO: Handle the unknown settings better.
2590 // Warn about invalid options.
2591 // Check whether some option was given twice.
2595 else if (t.cs() == "footnote" ||
2596 (t.cs() == "thanks" && context.layout->intitle)) {
2598 context.check_layout(os);
2599 begin_inset(os, "Foot\n");
2600 os << "status collapsed\n\n";
2601 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2605 else if (t.cs() == "marginpar") {
2607 context.check_layout(os);
2608 begin_inset(os, "Marginal\n");
2609 os << "status collapsed\n\n";
2610 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2614 else if (t.cs() == "ensuremath") {
2616 context.check_layout(os);
2617 string const s = p.verbatim_item();
2618 //FIXME: this never triggers in UTF8
2619 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2622 handle_ert(os, "\\ensuremath{" + s + "}",
2626 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2627 if (title_layout_found) {
2629 skip_spaces_braces(p);
2631 handle_ert(os, t.asInput(), context);
2634 else if (t.cs() == "tableofcontents") {
2635 context.check_layout(os);
2636 begin_command_inset(os, "toc", "tableofcontents");
2638 skip_spaces_braces(p);
2641 else if (t.cs() == "listoffigures") {
2642 context.check_layout(os);
2643 begin_inset(os, "FloatList figure\n");
2645 skip_spaces_braces(p);
2648 else if (t.cs() == "listoftables") {
2649 context.check_layout(os);
2650 begin_inset(os, "FloatList table\n");
2652 skip_spaces_braces(p);
2655 else if (t.cs() == "listof") {
2656 p.skip_spaces(true);
2657 string const name = p.get_token().cs();
2658 if (context.textclass.floats().typeExist(name)) {
2659 context.check_layout(os);
2660 begin_inset(os, "FloatList ");
2663 p.get_token(); // swallow second arg
2665 handle_ert(os, "\\listof{" + name + "}", context);
2668 else if (t.cs() == "textrm")
2669 parse_text_attributes(p, os, FLAG_ITEM, outer,
2670 context, "\\family",
2671 context.font.family, "roman");
2673 else if (t.cs() == "textsf")
2674 parse_text_attributes(p, os, FLAG_ITEM, outer,
2675 context, "\\family",
2676 context.font.family, "sans");
2678 else if (t.cs() == "texttt")
2679 parse_text_attributes(p, os, FLAG_ITEM, outer,
2680 context, "\\family",
2681 context.font.family, "typewriter");
2683 else if (t.cs() == "textmd")
2684 parse_text_attributes(p, os, FLAG_ITEM, outer,
2685 context, "\\series",
2686 context.font.series, "medium");
2688 else if (t.cs() == "textbf")
2689 parse_text_attributes(p, os, FLAG_ITEM, outer,
2690 context, "\\series",
2691 context.font.series, "bold");
2693 else if (t.cs() == "textup")
2694 parse_text_attributes(p, os, FLAG_ITEM, outer,
2696 context.font.shape, "up");
2698 else if (t.cs() == "textit")
2699 parse_text_attributes(p, os, FLAG_ITEM, outer,
2701 context.font.shape, "italic");
2703 else if (t.cs() == "textsl")
2704 parse_text_attributes(p, os, FLAG_ITEM, outer,
2706 context.font.shape, "slanted");
2708 else if (t.cs() == "textsc")
2709 parse_text_attributes(p, os, FLAG_ITEM, outer,
2711 context.font.shape, "smallcaps");
2713 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2714 context.check_layout(os);
2715 TeXFont oldFont = context.font;
2716 context.font.init();
2717 context.font.size = oldFont.size;
2718 os << "\n\\family " << context.font.family << "\n";
2719 os << "\n\\series " << context.font.series << "\n";
2720 os << "\n\\shape " << context.font.shape << "\n";
2721 if (t.cs() == "textnormal") {
2722 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2723 output_font_change(os, context.font, oldFont);
2724 context.font = oldFont;
2726 eat_whitespace(p, os, context, false);
2729 else if (t.cs() == "textcolor") {
2730 // scheme is \textcolor{color name}{text}
2731 string const color = p.verbatim_item();
2732 // we only support the predefined colors of the color package
2733 if (color == "black" || color == "blue" || color == "cyan"
2734 || color == "green" || color == "magenta" || color == "red"
2735 || color == "white" || color == "yellow") {
2736 context.check_layout(os);
2737 os << "\n\\color " << color << "\n";
2738 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2739 context.check_layout(os);
2740 os << "\n\\color inherit\n";
2741 preamble.registerAutomaticallyLoadedPackage("color");
2743 // for custom defined colors
2744 handle_ert(os, t.asInput() + "{" + color + "}", context);
2747 else if (t.cs() == "underbar" || t.cs() == "uline") {
2748 // \underbar is not 100% correct (LyX outputs \uline
2749 // of ulem.sty). The difference is that \ulem allows
2750 // line breaks, and \underbar does not.
2751 // Do NOT handle \underline.
2752 // \underbar cuts through y, g, q, p etc.,
2753 // \underline does not.
2754 context.check_layout(os);
2755 os << "\n\\bar under\n";
2756 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2757 context.check_layout(os);
2758 os << "\n\\bar default\n";
2759 preamble.registerAutomaticallyLoadedPackage("ulem");
2762 else if (t.cs() == "sout") {
2763 context.check_layout(os);
2764 os << "\n\\strikeout on\n";
2765 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2766 context.check_layout(os);
2767 os << "\n\\strikeout default\n";
2768 preamble.registerAutomaticallyLoadedPackage("ulem");
2771 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2772 t.cs() == "emph" || t.cs() == "noun") {
2773 context.check_layout(os);
2774 os << "\n\\" << t.cs() << " on\n";
2775 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2776 context.check_layout(os);
2777 os << "\n\\" << t.cs() << " default\n";
2778 if (t.cs() == "uuline" || t.cs() == "uwave")
2779 preamble.registerAutomaticallyLoadedPackage("ulem");
2782 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2783 context.check_layout(os);
2784 string name = p.getArg('{', '}');
2785 string localtime = p.getArg('{', '}');
2786 preamble.registerAuthor(name);
2787 Author const & author = preamble.getAuthor(name);
2788 // from_ctime() will fail if LyX decides to output the
2789 // time in the text language. It might also use a wrong
2790 // time zone (if the original LyX document was exported
2791 // with a different time zone).
2792 time_t ptime = from_ctime(localtime);
2793 if (ptime == static_cast<time_t>(-1)) {
2794 cerr << "Warning: Could not parse time `" << localtime
2795 << "´ for change tracking, using current time instead.\n";
2796 ptime = current_time();
2798 if (t.cs() == "lyxadded")
2799 os << "\n\\change_inserted ";
2801 os << "\n\\change_deleted ";
2802 os << author.bufferId() << ' ' << ptime << '\n';
2803 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2804 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2805 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2806 LaTeXPackages::isAvailable("xcolor");
2807 // No need to test for luatex, since luatex comes in
2808 // two flavours (dvi and pdf), like latex, and those
2809 // are detected by pdflatex.
2810 if (pdflatex || xetex) {
2812 preamble.registerAutomaticallyLoadedPackage("ulem");
2813 preamble.registerAutomaticallyLoadedPackage("xcolor");
2814 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2818 preamble.registerAutomaticallyLoadedPackage("dvipost");
2819 } else if (xcolorulem) {
2820 preamble.registerAutomaticallyLoadedPackage("ulem");
2821 preamble.registerAutomaticallyLoadedPackage("xcolor");
2826 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2827 t.cs() == "vphantom") {
2828 context.check_layout(os);
2829 if (t.cs() == "phantom")
2830 begin_inset(os, "Phantom Phantom\n");
2831 if (t.cs() == "hphantom")
2832 begin_inset(os, "Phantom HPhantom\n");
2833 if (t.cs() == "vphantom")
2834 begin_inset(os, "Phantom VPhantom\n");
2835 os << "status open\n";
2836 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2841 else if (t.cs() == "href") {
2842 context.check_layout(os);
2843 string target = p.getArg('{', '}');
2844 string name = p.getArg('{', '}');
2846 size_t i = target.find(':');
2847 if (i != string::npos) {
2848 type = target.substr(0, i + 1);
2849 if (type == "mailto:" || type == "file:")
2850 target = target.substr(i + 1);
2851 // handle the case that name is equal to target, except of "http://"
2852 else if (target.substr(i + 3) == name && type == "http:")
2855 begin_command_inset(os, "href", "href");
2857 os << "name \"" << name << "\"\n";
2858 os << "target \"" << target << "\"\n";
2859 if (type == "mailto:" || type == "file:")
2860 os << "type \"" << type << "\"\n";
2862 skip_spaces_braces(p);
2865 else if (t.cs() == "lyxline") {
2866 // swallow size argument (it is not used anyway)
2868 if (!context.atParagraphStart()) {
2869 // so our line is in the middle of a paragraph
2870 // we need to add a new line, lest this line
2871 // follow the other content on that line and
2872 // run off the side of the page
2873 // FIXME: This may create an empty paragraph,
2874 // but without that it would not be
2875 // possible to set noindent below.
2876 // Fortunately LaTeX does not care
2877 // about the empty paragraph.
2878 context.new_paragraph(os);
2880 if (preamble.indentParagraphs()) {
2881 // we need to unindent, lest the line be too long
2882 context.add_par_extra_stuff("\\noindent\n");
2884 context.check_layout(os);
2885 begin_command_inset(os, "line", "rule");
2886 os << "offset \"0.5ex\"\n"
2887 "width \"100line%\"\n"
2892 else if (t.cs() == "rule") {
2893 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2894 string const width = p.getArg('{', '}');
2895 string const thickness = p.getArg('{', '}');
2896 context.check_layout(os);
2897 begin_command_inset(os, "line", "rule");
2898 if (!offset.empty())
2899 os << "offset \"" << translate_len(offset) << "\"\n";
2900 os << "width \"" << translate_len(width) << "\"\n"
2901 "height \"" << translate_len(thickness) << "\"\n";
2905 else if (is_known(t.cs(), known_phrases) ||
2906 (t.cs() == "protect" &&
2907 p.next_token().cat() == catEscape &&
2908 is_known(p.next_token().cs(), known_phrases))) {
2909 // LyX sometimes puts a \protect in front, so we have to ignore it
2910 // FIXME: This needs to be changed when bug 4752 is fixed.
2911 char const * const * where = is_known(
2912 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2914 context.check_layout(os);
2915 os << known_coded_phrases[where - known_phrases];
2916 skip_spaces_braces(p);
2919 else if (is_known(t.cs(), known_ref_commands)) {
2920 string const opt = p.getOpt();
2922 context.check_layout(os);
2923 char const * const * where = is_known(t.cs(),
2924 known_ref_commands);
2925 begin_command_inset(os, "ref",
2926 known_coded_ref_commands[where - known_ref_commands]);
2927 os << "reference \""
2928 << convert_command_inset_arg(p.verbatim_item())
2932 // LyX does not support optional arguments of ref commands
2933 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2934 p.verbatim_item() + "}", context);
2938 else if (use_natbib &&
2939 is_known(t.cs(), known_natbib_commands) &&
2940 ((t.cs() != "citefullauthor" &&
2941 t.cs() != "citeyear" &&
2942 t.cs() != "citeyearpar") ||
2943 p.next_token().asInput() != "*")) {
2944 context.check_layout(os);
2945 string command = t.cs();
2946 if (p.next_token().asInput() == "*") {
2950 if (command == "citefullauthor")
2951 // alternative name for "\\citeauthor*"
2952 command = "citeauthor*";
2954 // text before the citation
2956 // text after the citation
2958 get_cite_arguments(p, true, before, after);
2960 if (command == "cite") {
2961 // \cite without optional argument means
2962 // \citet, \cite with at least one optional
2963 // argument means \citep.
2964 if (before.empty() && after.empty())
2969 if (before.empty() && after == "[]")
2970 // avoid \citet[]{a}
2972 else if (before == "[]" && after == "[]") {
2973 // avoid \citet[][]{a}
2977 // remove the brackets around after and before
2978 if (!after.empty()) {
2980 after.erase(after.length() - 1, 1);
2981 after = convert_command_inset_arg(after);
2983 if (!before.empty()) {
2985 before.erase(before.length() - 1, 1);
2986 before = convert_command_inset_arg(before);
2988 begin_command_inset(os, "citation", command);
2989 os << "after " << '"' << after << '"' << "\n";
2990 os << "before " << '"' << before << '"' << "\n";
2992 << convert_command_inset_arg(p.verbatim_item())
2997 else if (use_jurabib &&
2998 is_known(t.cs(), known_jurabib_commands) &&
2999 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3000 context.check_layout(os);
3001 string command = t.cs();
3002 if (p.next_token().asInput() == "*") {
3006 char argumentOrder = '\0';
3007 vector<string> const options =
3008 preamble.getPackageOptions("jurabib");
3009 if (find(options.begin(), options.end(),
3010 "natbiborder") != options.end())
3011 argumentOrder = 'n';
3012 else if (find(options.begin(), options.end(),
3013 "jurabiborder") != options.end())
3014 argumentOrder = 'j';
3016 // text before the citation
3018 // text after the citation
3020 get_cite_arguments(p, argumentOrder != 'j', before, after);
3022 string const citation = p.verbatim_item();
3023 if (!before.empty() && argumentOrder == '\0') {
3024 cerr << "Warning: Assuming argument order "
3025 "of jurabib version 0.6 for\n'"
3026 << command << before << after << '{'
3027 << citation << "}'.\n"
3028 "Add 'jurabiborder' to the jurabib "
3029 "package options if you used an\n"
3030 "earlier jurabib version." << endl;
3032 if (!after.empty()) {
3034 after.erase(after.length() - 1, 1);
3036 if (!before.empty()) {
3038 before.erase(before.length() - 1, 1);
3040 begin_command_inset(os, "citation", command);
3041 os << "after " << '"' << after << '"' << "\n";
3042 os << "before " << '"' << before << '"' << "\n";
3043 os << "key " << '"' << citation << '"' << "\n";
3047 else if (t.cs() == "cite"
3048 || t.cs() == "nocite") {
3049 context.check_layout(os);
3050 string after = convert_command_inset_arg(p.getArg('[', ']'));
3051 string key = convert_command_inset_arg(p.verbatim_item());
3052 // store the case that it is "\nocite{*}" to use it later for
3055 begin_command_inset(os, "citation", t.cs());
3056 os << "after " << '"' << after << '"' << "\n";
3057 os << "key " << '"' << key << '"' << "\n";
3059 } else if (t.cs() == "nocite")
3063 else if (t.cs() == "index") {
3064 context.check_layout(os);
3065 begin_inset(os, "Index idx\n");
3066 os << "status collapsed\n";
3067 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3071 else if (t.cs() == "nomenclature") {
3072 context.check_layout(os);
3073 begin_command_inset(os, "nomenclature", "nomenclature");
3074 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3075 if (!prefix.empty())
3076 os << "prefix " << '"' << prefix << '"' << "\n";
3077 os << "symbol " << '"'
3078 << convert_command_inset_arg(p.verbatim_item());
3079 os << "\"\ndescription \""
3080 << convert_command_inset_arg(p.verbatim_item())
3085 else if (t.cs() == "label") {
3086 context.check_layout(os);
3087 begin_command_inset(os, "label", "label");
3089 << convert_command_inset_arg(p.verbatim_item())
3094 else if (t.cs() == "printindex") {
3095 context.check_layout(os);
3096 begin_command_inset(os, "index_print", "printindex");
3097 os << "type \"idx\"\n";
3099 skip_spaces_braces(p);
3102 else if (t.cs() == "printnomenclature") {
3104 string width_type = "";
3105 context.check_layout(os);
3106 begin_command_inset(os, "nomencl_print", "printnomenclature");
3107 // case of a custom width
3109 width = p.getArg('[', ']');
3110 width = translate_len(width);
3111 width_type = "custom";
3113 // case of no custom width
3114 // the case of no custom width but the width set
3115 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3116 // because the user could have set anything, not only the width
3117 // of the longest label (which would be width_type = "auto")
3118 string label = convert_command_inset_arg(p.getArg('{', '}'));
3119 if (label.empty() && width_type.empty())
3120 width_type = "none";
3121 os << "set_width \"" << width_type << "\"\n";
3122 if (width_type == "custom")
3123 os << "width \"" << width << '\"';
3125 skip_spaces_braces(p);
3128 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3129 context.check_layout(os);
3130 begin_inset(os, "script ");
3131 os << t.cs().substr(4) << '\n';
3132 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3134 if (t.cs() == "textsubscript")
3135 preamble.registerAutomaticallyLoadedPackage("subscript");
3138 else if (is_known(t.cs(), known_quotes)) {
3139 char const * const * where = is_known(t.cs(), known_quotes);
3140 context.check_layout(os);
3141 begin_inset(os, "Quotes ");
3142 os << known_coded_quotes[where - known_quotes];
3144 // LyX adds {} after the quote, so we have to eat
3145 // spaces here if there are any before a possible
3147 eat_whitespace(p, os, context, false);
3151 else if (is_known(t.cs(), known_sizes) &&
3152 context.new_layout_allowed) {
3153 char const * const * where = is_known(t.cs(), known_sizes);
3154 context.check_layout(os);
3155 TeXFont const oldFont = context.font;
3156 context.font.size = known_coded_sizes[where - known_sizes];
3157 output_font_change(os, oldFont, context.font);
3158 eat_whitespace(p, os, context, false);
3161 else if (is_known(t.cs(), known_font_families) &&
3162 context.new_layout_allowed) {
3163 char const * const * where =
3164 is_known(t.cs(), known_font_families);
3165 context.check_layout(os);
3166 TeXFont const oldFont = context.font;
3167 context.font.family =
3168 known_coded_font_families[where - known_font_families];
3169 output_font_change(os, oldFont, context.font);
3170 eat_whitespace(p, os, context, false);
3173 else if (is_known(t.cs(), known_font_series) &&
3174 context.new_layout_allowed) {
3175 char const * const * where =
3176 is_known(t.cs(), known_font_series);
3177 context.check_layout(os);
3178 TeXFont const oldFont = context.font;
3179 context.font.series =
3180 known_coded_font_series[where - known_font_series];
3181 output_font_change(os, oldFont, context.font);
3182 eat_whitespace(p, os, context, false);
3185 else if (is_known(t.cs(), known_font_shapes) &&
3186 context.new_layout_allowed) {
3187 char const * const * where =
3188 is_known(t.cs(), known_font_shapes);
3189 context.check_layout(os);
3190 TeXFont const oldFont = context.font;
3191 context.font.shape =
3192 known_coded_font_shapes[where - known_font_shapes];
3193 output_font_change(os, oldFont, context.font);
3194 eat_whitespace(p, os, context, false);
3196 else if (is_known(t.cs(), known_old_font_families) &&
3197 context.new_layout_allowed) {
3198 char const * const * where =
3199 is_known(t.cs(), known_old_font_families);
3200 context.check_layout(os);
3201 TeXFont const oldFont = context.font;
3202 context.font.init();
3203 context.font.size = oldFont.size;
3204 context.font.family =
3205 known_coded_font_families[where - known_old_font_families];
3206 output_font_change(os, oldFont, context.font);
3207 eat_whitespace(p, os, context, false);
3210 else if (is_known(t.cs(), known_old_font_series) &&
3211 context.new_layout_allowed) {
3212 char const * const * where =
3213 is_known(t.cs(), known_old_font_series);
3214 context.check_layout(os);
3215 TeXFont const oldFont = context.font;
3216 context.font.init();
3217 context.font.size = oldFont.size;
3218 context.font.series =
3219 known_coded_font_series[where - known_old_font_series];
3220 output_font_change(os, oldFont, context.font);
3221 eat_whitespace(p, os, context, false);
3224 else if (is_known(t.cs(), known_old_font_shapes) &&
3225 context.new_layout_allowed) {
3226 char const * const * where =
3227 is_known(t.cs(), known_old_font_shapes);
3228 context.check_layout(os);
3229 TeXFont const oldFont = context.font;
3230 context.font.init();
3231 context.font.size = oldFont.size;
3232 context.font.shape =
3233 known_coded_font_shapes[where - known_old_font_shapes];
3234 output_font_change(os, oldFont, context.font);
3235 eat_whitespace(p, os, context, false);
3238 else if (t.cs() == "selectlanguage") {
3239 context.check_layout(os);
3240 // save the language for the case that a
3241 // \foreignlanguage is used
3243 context.font.language = babel2lyx(p.verbatim_item());
3244 os << "\n\\lang " << context.font.language << "\n";
3247 else if (t.cs() == "foreignlanguage") {
3248 string const lang = babel2lyx(p.verbatim_item());
3249 parse_text_attributes(p, os, FLAG_ITEM, outer,
3251 context.font.language, lang);
3254 else if (t.cs() == "inputencoding") {
3255 // nothing to write here
3256 string const enc = subst(p.verbatim_item(), "\n", " ");
3260 else if (t.cs() == "ldots") {
3261 context.check_layout(os);
3262 os << "\\SpecialChar \\ldots{}\n";
3263 skip_spaces_braces(p);
3266 else if (t.cs() == "lyxarrow") {
3267 context.check_layout(os);
3268 os << "\\SpecialChar \\menuseparator\n";
3269 skip_spaces_braces(p);
3272 else if (t.cs() == "textcompwordmark") {
3273 context.check_layout(os);
3274 os << "\\SpecialChar \\textcompwordmark{}\n";
3275 skip_spaces_braces(p);
3278 else if (t.cs() == "slash") {
3279 context.check_layout(os);
3280 os << "\\SpecialChar \\slash{}\n";
3281 skip_spaces_braces(p);
3284 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3285 context.check_layout(os);
3286 os << "\\SpecialChar \\nobreakdash-\n";
3290 else if (t.cs() == "textquotedbl") {
3291 context.check_layout(os);
3296 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3297 context.check_layout(os);
3298 os << "\\SpecialChar \\@.\n";
3302 else if (t.cs() == "-") {
3303 context.check_layout(os);
3304 os << "\\SpecialChar \\-\n";
3307 else if (t.cs() == "textasciitilde") {
3308 context.check_layout(os);
3310 skip_spaces_braces(p);
3313 else if (t.cs() == "textasciicircum") {
3314 context.check_layout(os);
3316 skip_spaces_braces(p);
3319 else if (t.cs() == "textbackslash") {
3320 context.check_layout(os);
3321 os << "\n\\backslash\n";
3322 skip_spaces_braces(p);
3325 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3326 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3328 context.check_layout(os);
3332 else if (t.cs() == "char") {
3333 context.check_layout(os);
3334 if (p.next_token().character() == '`') {
3336 if (p.next_token().cs() == "\"") {
3341 handle_ert(os, "\\char`", context);
3344 handle_ert(os, "\\char", context);
3348 else if (t.cs() == "verb") {
3349 context.check_layout(os);
3350 char const delimiter = p.next_token().character();
3351 string const arg = p.getArg(delimiter, delimiter);
3353 oss << "\\verb" << delimiter << arg << delimiter;
3354 handle_ert(os, oss.str(), context);
3357 // Problem: \= creates a tabstop inside the tabbing environment
3358 // and else an accent. In the latter case we really would want
3359 // \={o} instead of \= o.
3360 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3361 handle_ert(os, t.asInput(), context);
3363 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3364 else if (t.cs().size() == 1
3365 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3366 context.check_layout(os);
3367 // try to see whether the string is in unicodesymbols
3369 string command = t.asInput() + "{"
3370 + trimSpaceAndEol(p.verbatim_item())
3372 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3375 cerr << "When parsing " << command
3376 << ", result is " << to_utf8(s)
3377 << "+" << to_utf8(rem) << endl;
3380 // we did not find a non-ert version
3381 handle_ert(os, command, context);
3384 else if (t.cs() == "\\") {
3385 context.check_layout(os);
3387 handle_ert(os, "\\\\" + p.getOpt(), context);
3388 else if (p.next_token().asInput() == "*") {
3390 // getOpt() eats the following space if there
3391 // is no optional argument, but that is OK
3392 // here since it has no effect in the output.
3393 handle_ert(os, "\\\\*" + p.getOpt(), context);
3396 begin_inset(os, "Newline newline");
3401 else if (t.cs() == "newline" ||
3402 (t.cs() == "linebreak" && !p.hasOpt())) {
3403 context.check_layout(os);
3404 begin_inset(os, "Newline ");
3407 skip_spaces_braces(p);
3410 else if (t.cs() == "input" || t.cs() == "include"
3411 || t.cs() == "verbatiminput") {
3412 string name = t.cs();
3413 if (t.cs() == "verbatiminput"
3414 && p.next_token().asInput() == "*")
3415 name += p.get_token().asInput();
3416 context.check_layout(os);
3417 string filename(normalize_filename(p.getArg('{', '}')));
3418 string const path = getMasterFilePath();
3419 // We want to preserve relative / absolute filenames,
3420 // therefore path is only used for testing
3421 if ((t.cs() == "include" || t.cs() == "input") &&
3422 !makeAbsPath(filename, path).exists()) {
3423 // The file extension is probably missing.
3424 // Now try to find it out.
3425 string const tex_name =
3426 find_file(filename, path,
3427 known_tex_extensions);
3428 if (!tex_name.empty())
3429 filename = tex_name;
3431 bool external = false;
3433 if (makeAbsPath(filename, path).exists()) {
3434 string const abstexname =
3435 makeAbsPath(filename, path).absFileName();
3436 string const abslyxname =
3437 changeExtension(abstexname, ".lyx");
3438 string const absfigname =
3439 changeExtension(abstexname, ".fig");
3440 fix_relative_filename(filename);
3441 string const lyxname =
3442 changeExtension(filename, ".lyx");
3444 external = FileName(absfigname).exists();
3445 if (t.cs() == "input") {
3446 string const ext = getExtension(abstexname);
3448 // Combined PS/LaTeX:
3449 // x.eps, x.pstex_t (old xfig)
3450 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3451 FileName const absepsname(
3452 changeExtension(abstexname, ".eps"));
3453 FileName const abspstexname(
3454 changeExtension(abstexname, ".pstex"));
3455 bool const xfigeps =
3456 (absepsname.exists() ||
3457 abspstexname.exists()) &&
3460 // Combined PDF/LaTeX:
3461 // x.pdf, x.pdftex_t (old xfig)
3462 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3463 FileName const abspdfname(
3464 changeExtension(abstexname, ".pdf"));
3465 bool const xfigpdf =
3466 abspdfname.exists() &&
3467 (ext == "pdftex_t" || ext == "pdf_t");
3471 // Combined PS/PDF/LaTeX:
3472 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3473 string const absbase2(
3474 removeExtension(abstexname) + "_pspdftex");
3475 FileName const abseps2name(
3476 addExtension(absbase2, ".eps"));
3477 FileName const abspdf2name(
3478 addExtension(absbase2, ".pdf"));
3479 bool const xfigboth =
3480 abspdf2name.exists() &&
3481 abseps2name.exists() && ext == "pspdftex";
3483 xfig = xfigpdf || xfigeps || xfigboth;
3484 external = external && xfig;
3487 outname = changeExtension(filename, ".fig");
3489 // Don't try to convert, the result
3490 // would be full of ERT.
3492 } else if (t.cs() != "verbatiminput" &&
3493 tex2lyx(abstexname, FileName(abslyxname),
3500 cerr << "Warning: Could not find included file '"
3501 << filename << "'." << endl;
3505 begin_inset(os, "External\n");
3506 os << "\ttemplate XFig\n"
3507 << "\tfilename " << outname << '\n';
3509 begin_command_inset(os, "include", name);
3510 os << "preview false\n"
3511 "filename \"" << outname << "\"\n";
3516 else if (t.cs() == "bibliographystyle") {
3517 // store new bibliographystyle
3518 bibliographystyle = p.verbatim_item();
3519 // If any other command than \bibliography and
3520 // \nocite{*} follows, we need to output the style
3521 // (because it might be used by that command).
3522 // Otherwise, it will automatically be output by LyX.
3525 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3526 if (t2.cat() == catBegin)
3528 if (t2.cat() != catEscape)
3530 if (t2.cs() == "nocite") {
3531 if (p.getArg('{', '}') == "*")
3533 } else if (t2.cs() == "bibliography")
3540 "\\bibliographystyle{" + bibliographystyle + '}',
3545 else if (t.cs() == "bibliography") {
3546 context.check_layout(os);
3547 begin_command_inset(os, "bibtex", "bibtex");
3548 if (!btprint.empty()) {
3549 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3550 // clear the string because the next BibTeX inset can be without the
3551 // \nocite{*} option
3554 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3555 // Do we have a bibliographystyle set?
3556 if (!bibliographystyle.empty())
3557 os << "options " << '"' << bibliographystyle << '"' << "\n";
3561 else if (t.cs() == "parbox") {
3562 // Test whether this is an outer box of a shaded box
3564 // swallow arguments
3565 while (p.hasOpt()) {
3567 p.skip_spaces(true);
3570 p.skip_spaces(true);
3572 if (p.next_token().cat() == catBegin)
3574 p.skip_spaces(true);
3575 Token to = p.get_token();
3576 bool shaded = false;
3577 if (to.asInput() == "\\begin") {
3578 p.skip_spaces(true);
3579 if (p.getArg('{', '}') == "shaded")
3584 parse_outer_box(p, os, FLAG_ITEM, outer,
3585 context, "parbox", "shaded");
3587 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3591 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3592 t.cs() == "shadowbox" || t.cs() == "doublebox")
3593 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3595 else if (t.cs() == "framebox") {
3596 string special = p.getFullOpt();
3597 special += p.getOpt();
3598 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3601 //\makebox() is part of the picture environment and different from \makebox{}
3602 //\makebox{} will be parsed by parse_box
3603 else if (t.cs() == "makebox") {
3604 string arg = t.asInput();
3605 if (p.next_token().character() == '(') {
3606 //the syntax is: \makebox(x,y)[position]{content}
3607 arg += p.getFullParentheseArg();
3608 arg += p.getFullOpt();
3609 eat_whitespace(p, os, context, false);
3610 handle_ert(os, arg + '{', context);
3611 eat_whitespace(p, os, context, false);
3612 parse_text(p, os, FLAG_ITEM, outer, context);
3613 handle_ert(os, "}", context);
3615 //the syntax is: \makebox[width][position]{content}
3616 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3620 else if (t.cs() == "smallskip" ||
3621 t.cs() == "medskip" ||
3622 t.cs() == "bigskip" ||
3623 t.cs() == "vfill") {
3624 context.check_layout(os);
3625 begin_inset(os, "VSpace ");
3628 skip_spaces_braces(p);
3631 else if (is_known(t.cs(), known_spaces)) {
3632 char const * const * where = is_known(t.cs(), known_spaces);
3633 context.check_layout(os);
3634 begin_inset(os, "space ");
3635 os << '\\' << known_coded_spaces[where - known_spaces]
3638 // LaTeX swallows whitespace after all spaces except
3639 // "\\,". We have to do that here, too, because LyX
3640 // adds "{}" which would make the spaces significant.
3642 eat_whitespace(p, os, context, false);
3643 // LyX adds "{}" after all spaces except "\\ " and
3644 // "\\,", so we have to remove "{}".
3645 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3646 // remove the braces after "\\,", too.
3651 else if (t.cs() == "newpage" ||
3652 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3653 t.cs() == "clearpage" ||
3654 t.cs() == "cleardoublepage") {
3655 context.check_layout(os);
3656 begin_inset(os, "Newpage ");
3659 skip_spaces_braces(p);
3662 else if (t.cs() == "DeclareRobustCommand" ||
3663 t.cs() == "DeclareRobustCommandx" ||
3664 t.cs() == "newcommand" ||
3665 t.cs() == "newcommandx" ||
3666 t.cs() == "providecommand" ||
3667 t.cs() == "providecommandx" ||
3668 t.cs() == "renewcommand" ||
3669 t.cs() == "renewcommandx") {
3670 // DeclareRobustCommand, DeclareRobustCommandx,
3671 // providecommand and providecommandx could be handled
3672 // by parse_command(), but we need to call
3673 // add_known_command() here.
3674 string name = t.asInput();
3675 if (p.next_token().asInput() == "*") {
3676 // Starred form. Eat '*'
3680 string const command = p.verbatim_item();
3681 string const opt1 = p.getFullOpt();
3682 string const opt2 = p.getFullOpt();
3683 add_known_command(command, opt1, !opt2.empty());
3684 string const ert = name + '{' + command + '}' +
3686 '{' + p.verbatim_item() + '}';
3688 if (t.cs() == "DeclareRobustCommand" ||
3689 t.cs() == "DeclareRobustCommandx" ||
3690 t.cs() == "providecommand" ||
3691 t.cs() == "providecommandx" ||
3692 name[name.length()-1] == '*')
3693 handle_ert(os, ert, context);
3695 context.check_layout(os);
3696 begin_inset(os, "FormulaMacro");
3702 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3703 // let could be handled by parse_command(),
3704 // but we need to call add_known_command() here.
3705 string ert = t.asInput();
3708 if (p.next_token().cat() == catBegin) {
3709 name = p.verbatim_item();
3710 ert += '{' + name + '}';
3712 name = p.verbatim_item();
3717 if (p.next_token().cat() == catBegin) {
3718 command = p.verbatim_item();
3719 ert += '{' + command + '}';
3721 command = p.verbatim_item();
3724 // If command is known, make name known too, to parse
3725 // its arguments correctly. For this reason we also
3726 // have commands in syntax.default that are hardcoded.
3727 CommandMap::iterator it = known_commands.find(command);
3728 if (it != known_commands.end())
3729 known_commands[t.asInput()] = it->second;
3730 handle_ert(os, ert, context);
3733 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3734 bool starred = false;
3735 if (p.next_token().asInput() == "*") {
3739 string name = t.asInput();
3740 string const length = p.verbatim_item();
3743 bool valid = splitLatexLength(length, valstring, unit);
3744 bool known_hspace = false;
3745 bool known_vspace = false;
3746 bool known_unit = false;
3749 istringstream iss(valstring);
3752 if (t.cs()[0] == 'h') {
3753 if (unit == "\\fill") {
3758 known_hspace = true;
3761 if (unit == "\\smallskipamount") {
3763 known_vspace = true;
3764 } else if (unit == "\\medskipamount") {
3766 known_vspace = true;
3767 } else if (unit == "\\bigskipamount") {
3769 known_vspace = true;
3770 } else if (unit == "\\fill") {
3772 known_vspace = true;
3776 if (!known_hspace && !known_vspace) {
3777 switch (unitFromString(unit)) {
3798 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3799 // Literal horizontal length or known variable
3800 context.check_layout(os);
3801 begin_inset(os, "space ");
3809 if (known_unit && !known_hspace)
3811 << translate_len(length);
3813 } else if (known_unit || known_vspace) {
3814 // Literal vertical length or known variable
3815 context.check_layout(os);
3816 begin_inset(os, "VSpace ");
3824 // LyX can't handle other length variables in Inset VSpace/space
3829 handle_ert(os, name + '{' + unit + '}', context);
3830 else if (value == -1.0)
3831 handle_ert(os, name + "{-" + unit + '}', context);
3833 handle_ert(os, name + '{' + valstring + unit + '}', context);
3835 handle_ert(os, name + '{' + length + '}', context);
3839 // The single '=' is meant here.
3840 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3842 context.check_layout(os);
3843 begin_inset(os, "Flex ");
3844 os << to_utf8(newinsetlayout->name()) << '\n'
3845 << "status collapsed\n";
3846 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3851 // try to see whether the string is in unicodesymbols
3852 // Only use text mode commands, since we are in text mode here,
3853 // and math commands may be invalid (bug 6797)
3855 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3856 rem, Encodings::TEXT_CMD);
3859 cerr << "When parsing " << t.cs()
3860 << ", result is " << to_utf8(s)
3861 << "+" << to_utf8(rem) << endl;
3862 context.check_layout(os);
3864 skip_spaces_braces(p);
3866 //cerr << "#: " << t << " mode: " << mode << endl;
3867 // heuristic: read up to next non-nested space
3869 string s = t.asInput();
3870 string z = p.verbatim_item();
3871 while (p.good() && z != " " && z.size()) {
3872 //cerr << "read: " << z << endl;
3874 z = p.verbatim_item();
3876 cerr << "found ERT: " << s << endl;
3877 handle_ert(os, s + ' ', context);
3880 string name = t.asInput();
3881 if (p.next_token().asInput() == "*") {
3882 // Starred commands like \vspace*{}
3883 p.get_token(); // Eat '*'
3886 if (!parse_command(name, p, os, outer, context))
3887 handle_ert(os, name, context);
3891 if (flags & FLAG_LEAVE) {
3892 flags &= ~FLAG_LEAVE;