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]) {
678 // This argument contains regular LaTeX
679 handle_ert(os, ert + '{', context);
680 eat_whitespace(p, os, context, false);
681 if (template_arguments[i] == required)
682 parse_text(p, os, FLAG_ITEM, outer, context);
684 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
688 // This argument consists only of a single item.
689 // The presence of '{' or not must be preserved.
691 if (p.next_token().cat() == catBegin)
692 ert += '{' + p.verbatim_item() + '}';
694 ert += p.verbatim_item();
698 // This argument may contain special characters
699 ert += '{' + p.verbatim_item() + '}';
703 // true because we must not eat whitespace
704 // if an optional arg follows we must not strip the
705 // brackets from this one
706 if (i < no_arguments - 1 &&
707 template_arguments[i+1] == optional)
708 ert += p.getFullOpt(true);
710 ert += p.getOpt(true);
714 handle_ert(os, ert, context);
719 * Check whether \p command is a known command. If yes,
720 * handle the command with all arguments.
721 * \return true if the command was parsed, false otherwise.
723 bool parse_command(string const & command, Parser & p, ostream & os,
724 bool outer, Context & context)
726 if (known_commands.find(command) != known_commands.end()) {
727 parse_arguments(command, known_commands[command], p, os,
735 /// Parses a minipage or parbox
736 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
737 unsigned inner_flags, bool outer, Context & parent_context,
738 string const & outer_type, string const & special,
739 string const & inner_type)
743 string hor_pos = "c";
744 // We need to set the height to the LaTeX default of 1\\totalheight
745 // for the case when no height argument is given
746 string height_value = "1";
747 string height_unit = "in";
748 string height_special = "totalheight";
753 string width_special = "none";
754 if (!inner_type.empty() && p.hasOpt()) {
755 if (inner_type != "makebox")
756 position = p.getArg('[', ']');
758 latex_width = p.getArg('[', ']');
759 translate_box_len(latex_width, width_value, width_unit, width_special);
762 if (position != "t" && position != "c" && position != "b") {
763 cerr << "invalid position " << position << " for "
764 << inner_type << endl;
768 if (inner_type != "makebox") {
769 latex_height = p.getArg('[', ']');
770 translate_box_len(latex_height, height_value, height_unit, height_special);
772 hor_pos = p.getArg('[', ']');
775 inner_pos = p.getArg('[', ']');
776 if (inner_pos != "c" && inner_pos != "t" &&
777 inner_pos != "b" && inner_pos != "s") {
778 cerr << "invalid inner_pos "
779 << inner_pos << " for "
780 << inner_type << endl;
781 inner_pos = position;
786 if (inner_type.empty()) {
787 if (special.empty() && outer_type != "framebox")
788 latex_width = "1\\columnwidth";
791 latex_width = p2.getArg('[', ']');
792 string const opt = p2.getArg('[', ']');
795 if (hor_pos != "l" && hor_pos != "c" &&
797 cerr << "invalid hor_pos " << hor_pos
798 << " for " << outer_type << endl;
803 } else if (inner_type != "makebox")
804 latex_width = p.verbatim_item();
805 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
806 // as this is LyX's standard for such cases (except for makebox)
807 // \framebox is more special and handled below
808 if (latex_width.empty() && inner_type != "makebox"
809 && outer_type != "framebox")
810 latex_width = "1\\columnwidth";
812 translate_len(latex_width, width_value, width_unit);
814 bool shadedparbox = false;
815 if (inner_type == "shaded") {
816 eat_whitespace(p, os, parent_context, false);
817 if (outer_type == "parbox") {
819 if (p.next_token().cat() == catBegin)
821 eat_whitespace(p, os, parent_context, false);
827 // If we already read the inner box we have to push the inner env
828 if (!outer_type.empty() && !inner_type.empty() &&
829 (inner_flags & FLAG_END))
830 active_environments.push_back(inner_type);
831 // LyX can't handle length variables
832 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
833 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
834 // Look whether there is some content after the end of the
835 // inner box, but before the end of the outer box.
836 // If yes, we need to output ERT.
838 if (inner_flags & FLAG_END)
839 p.verbatimEnvironment(inner_type);
843 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
844 if ((outer_env && p.next_token().asInput() != "\\end") ||
845 (!outer_env && p.next_token().cat() != catEnd)) {
846 // something is between the end of the inner box and
847 // the end of the outer box, so we need to use ERT.
852 // if only \makebox{content} was used we can set its width to 1\width
853 // because this identic and also identic to \mbox
854 // this doesn't work for \framebox{content}, thus we have to use ERT for this
855 if (latex_width.empty() && inner_type == "makebox") {
858 width_special = "width";
859 } else if (latex_width.empty() && outer_type == "framebox") {
864 if (!outer_type.empty()) {
865 if (outer_flags & FLAG_END)
866 ss << "\\begin{" << outer_type << '}';
868 ss << '\\' << outer_type << '{';
869 if (!special.empty())
873 if (!inner_type.empty()) {
874 if (inner_type != "shaded") {
875 if (inner_flags & FLAG_END)
876 ss << "\\begin{" << inner_type << '}';
878 ss << '\\' << inner_type;
880 if (!position.empty())
881 ss << '[' << position << ']';
882 if (!latex_height.empty())
883 ss << '[' << latex_height << ']';
884 if (!inner_pos.empty())
885 ss << '[' << inner_pos << ']';
886 ss << '{' << latex_width << '}';
887 if (!(inner_flags & FLAG_END))
890 if (inner_type == "shaded")
891 ss << "\\begin{shaded}";
892 handle_ert(os, ss.str(), parent_context);
893 if (!inner_type.empty()) {
894 parse_text(p, os, inner_flags, outer, parent_context);
895 if (inner_flags & FLAG_END)
896 handle_ert(os, "\\end{" + inner_type + '}',
899 handle_ert(os, "}", parent_context);
901 if (!outer_type.empty()) {
902 // If we already read the inner box we have to pop
904 if (!inner_type.empty() && (inner_flags & FLAG_END))
905 active_environments.pop_back();
907 // Ensure that the end of the outer box is parsed correctly:
908 // The opening brace has been eaten by parse_outer_box()
909 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
910 outer_flags &= ~FLAG_ITEM;
911 outer_flags |= FLAG_BRACE_LAST;
913 parse_text(p, os, outer_flags, outer, parent_context);
914 if (outer_flags & FLAG_END)
915 handle_ert(os, "\\end{" + outer_type + '}',
917 else if (inner_type.empty() && outer_type == "framebox")
918 // in this case it is already closed later
921 handle_ert(os, "}", parent_context);
924 // LyX does not like empty positions, so we have
925 // to set them to the LaTeX default values here.
926 if (position.empty())
928 if (inner_pos.empty())
929 inner_pos = position;
930 parent_context.check_layout(os);
931 begin_inset(os, "Box ");
932 if (outer_type == "framed")
934 else if (outer_type == "framebox")
936 else if (outer_type == "shadowbox")
938 else if ((outer_type == "shaded" && inner_type.empty()) ||
939 (outer_type == "minipage" && inner_type == "shaded") ||
940 (outer_type == "parbox" && inner_type == "shaded")) {
942 preamble.registerAutomaticallyLoadedPackage("color");
943 } else if (outer_type == "doublebox")
945 else if (outer_type.empty())
948 os << outer_type << '\n';
949 os << "position \"" << position << "\"\n";
950 os << "hor_pos \"" << hor_pos << "\"\n";
951 os << "has_inner_box " << !inner_type.empty() << "\n";
952 os << "inner_pos \"" << inner_pos << "\"\n";
953 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
955 os << "use_makebox " << (inner_type == "makebox") << '\n';
956 os << "width \"" << width_value << width_unit << "\"\n";
957 os << "special \"" << width_special << "\"\n";
958 os << "height \"" << height_value << height_unit << "\"\n";
959 os << "height_special \"" << height_special << "\"\n";
960 os << "status open\n\n";
962 // Unfortunately we can't use parse_text_in_inset:
963 // InsetBox::forcePlainLayout() is hard coded and does not
964 // use the inset layout. Apart from that do we call parse_text
965 // up to two times, but need only one check_end_layout.
966 bool const forcePlainLayout =
967 (!inner_type.empty() || inner_type == "makebox") &&
968 outer_type != "shaded" && outer_type != "framed";
969 Context context(true, parent_context.textclass);
970 if (forcePlainLayout)
971 context.layout = &context.textclass.plainLayout();
973 context.font = parent_context.font;
975 // If we have no inner box the contents will be read with the outer box
976 if (!inner_type.empty())
977 parse_text(p, os, inner_flags, outer, context);
979 // Ensure that the end of the outer box is parsed correctly:
980 // The opening brace has been eaten by parse_outer_box()
981 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
982 outer_flags &= ~FLAG_ITEM;
983 outer_flags |= FLAG_BRACE_LAST;
986 // Find end of outer box, output contents if inner_type is
987 // empty and output possible comments
988 if (!outer_type.empty()) {
989 // If we already read the inner box we have to pop
991 if (!inner_type.empty() && (inner_flags & FLAG_END))
992 active_environments.pop_back();
993 // This does not output anything but comments if
994 // inner_type is not empty (see use_ert)
995 parse_text(p, os, outer_flags, outer, context);
998 context.check_end_layout(os);
1000 #ifdef PRESERVE_LAYOUT
1001 // LyX puts a % after the end of the minipage
1002 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1004 //handle_comment(os, "%dummy", parent_context);
1007 parent_context.new_paragraph(os);
1009 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1010 //handle_comment(os, "%dummy", parent_context);
1013 // We add a protected space if something real follows
1014 if (p.good() && p.next_token().cat() != catComment) {
1015 begin_inset(os, "space ~\n");
1024 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1025 Context & parent_context, string const & outer_type,
1026 string const & special)
1028 eat_whitespace(p, os, parent_context, false);
1029 if (flags & FLAG_ITEM) {
1031 if (p.next_token().cat() == catBegin)
1034 cerr << "Warning: Ignoring missing '{' after \\"
1035 << outer_type << '.' << endl;
1036 eat_whitespace(p, os, parent_context, false);
1039 unsigned int inner_flags = 0;
1041 if (outer_type == "minipage" || outer_type == "parbox") {
1042 p.skip_spaces(true);
1043 while (p.hasOpt()) {
1045 p.skip_spaces(true);
1048 p.skip_spaces(true);
1049 if (outer_type == "parbox") {
1051 if (p.next_token().cat() == catBegin)
1053 p.skip_spaces(true);
1056 if (outer_type == "shaded") {
1057 // These boxes never have an inner box
1059 } else if (p.next_token().asInput() == "\\parbox") {
1060 inner = p.get_token().cs();
1061 inner_flags = FLAG_ITEM;
1062 } else if (p.next_token().asInput() == "\\begin") {
1063 // Is this a minipage or shaded box?
1066 inner = p.getArg('{', '}');
1068 if (inner == "minipage" || inner == "shaded")
1069 inner_flags = FLAG_END;
1074 if (inner_flags == FLAG_END) {
1075 if (inner != "shaded")
1079 eat_whitespace(p, os, parent_context, false);
1081 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1082 outer_type, special, inner);
1084 if (inner_flags == FLAG_ITEM) {
1086 eat_whitespace(p, os, parent_context, false);
1088 parse_box(p, os, flags, inner_flags, outer, parent_context,
1089 outer_type, special, inner);
1094 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1096 parent_context.check_layout(os);
1097 begin_inset(os, "listings\n");
1098 os << "inline false\n"
1099 << "status collapsed\n";
1100 Context context(true, parent_context.textclass);
1101 context.layout = &parent_context.textclass.plainLayout();
1102 context.check_layout(os);
1103 string const s = p.verbatimEnvironment("lstlisting");
1104 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1106 os << "\n\\backslash\n";
1107 else if (*it == '\n') {
1108 // avoid adding an empty paragraph at the end
1110 context.new_paragraph(os);
1111 context.check_layout(os);
1116 context.check_end_layout(os);
1121 /// parse an unknown environment
1122 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1123 unsigned flags, bool outer,
1124 Context & parent_context)
1126 if (name == "tabbing")
1127 // We need to remember that we have to handle '\=' specially
1128 flags |= FLAG_TABBING;
1130 // We need to translate font changes and paragraphs inside the
1131 // environment to ERT if we have a non standard font.
1132 // Otherwise things like
1133 // \large\begin{foo}\huge bar\end{foo}
1135 bool const specialfont =
1136 (parent_context.font != parent_context.normalfont);
1137 bool const new_layout_allowed = parent_context.new_layout_allowed;
1139 parent_context.new_layout_allowed = false;
1140 handle_ert(os, "\\begin{" + name + "}", parent_context);
1141 parse_text_snippet(p, os, flags, outer, parent_context);
1142 handle_ert(os, "\\end{" + name + "}", parent_context);
1144 parent_context.new_layout_allowed = new_layout_allowed;
1148 void parse_environment(Parser & p, ostream & os, bool outer,
1149 string & last_env, bool & title_layout_found,
1150 Context & parent_context)
1152 Layout const * newlayout;
1153 InsetLayout const * newinsetlayout = 0;
1154 string const name = p.getArg('{', '}');
1155 const bool is_starred = suffixIs(name, '*');
1156 string const unstarred_name = rtrim(name, "*");
1157 active_environments.push_back(name);
1159 if (is_math_env(name)) {
1160 parent_context.check_layout(os);
1161 begin_inset(os, "Formula ");
1162 os << "\\begin{" << name << "}";
1163 parse_math(p, os, FLAG_END, MATH_MODE);
1164 os << "\\end{" << name << "}";
1166 if (is_display_math_env(name)) {
1167 // Prevent the conversion of a line break to a space
1168 // (bug 7668). This does not change the output, but
1169 // looks ugly in LyX.
1170 eat_whitespace(p, os, parent_context, false);
1174 else if (unstarred_name == "tabular" || name == "longtable") {
1175 eat_whitespace(p, os, parent_context, false);
1176 string width = "0pt";
1177 if (name == "tabular*") {
1178 width = lyx::translate_len(p.getArg('{', '}'));
1179 eat_whitespace(p, os, parent_context, false);
1181 parent_context.check_layout(os);
1182 begin_inset(os, "Tabular ");
1183 handle_tabular(p, os, name, width, parent_context);
1188 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1189 eat_whitespace(p, os, parent_context, false);
1190 parent_context.check_layout(os);
1191 begin_inset(os, "Float " + unstarred_name + "\n");
1192 // store the float type for subfloats
1193 // subfloats only work with figures and tables
1194 if (unstarred_name == "figure")
1195 float_type = unstarred_name;
1196 else if (unstarred_name == "table")
1197 float_type = unstarred_name;
1201 os << "placement " << p.getArg('[', ']') << '\n';
1202 os << "wide " << convert<string>(is_starred)
1203 << "\nsideways false"
1204 << "\nstatus open\n\n";
1205 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1207 // We don't need really a new paragraph, but
1208 // we must make sure that the next item gets a \begin_layout.
1209 parent_context.new_paragraph(os);
1211 // the float is parsed thus delete the type
1215 else if (unstarred_name == "sidewaysfigure"
1216 || unstarred_name == "sidewaystable") {
1217 eat_whitespace(p, os, parent_context, false);
1218 parent_context.check_layout(os);
1219 if (unstarred_name == "sidewaysfigure")
1220 begin_inset(os, "Float figure\n");
1222 begin_inset(os, "Float table\n");
1223 os << "wide " << convert<string>(is_starred)
1224 << "\nsideways true"
1225 << "\nstatus open\n\n";
1226 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1228 // We don't need really a new paragraph, but
1229 // we must make sure that the next item gets a \begin_layout.
1230 parent_context.new_paragraph(os);
1234 else if (name == "wrapfigure" || name == "wraptable") {
1235 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1236 eat_whitespace(p, os, parent_context, false);
1237 parent_context.check_layout(os);
1240 string overhang = "0col%";
1243 lines = p.getArg('[', ']');
1244 string const placement = p.getArg('{', '}');
1246 overhang = p.getArg('[', ']');
1247 string const width = p.getArg('{', '}');
1249 if (name == "wrapfigure")
1250 begin_inset(os, "Wrap figure\n");
1252 begin_inset(os, "Wrap table\n");
1253 os << "lines " << lines
1254 << "\nplacement " << placement
1255 << "\noverhang " << lyx::translate_len(overhang)
1256 << "\nwidth " << lyx::translate_len(width)
1257 << "\nstatus open\n\n";
1258 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1260 // We don't need really a new paragraph, but
1261 // we must make sure that the next item gets a \begin_layout.
1262 parent_context.new_paragraph(os);
1266 else if (name == "minipage") {
1267 eat_whitespace(p, os, parent_context, false);
1268 // Test whether this is an outer box of a shaded box
1270 // swallow arguments
1271 while (p.hasOpt()) {
1273 p.skip_spaces(true);
1276 p.skip_spaces(true);
1277 Token t = p.get_token();
1278 bool shaded = false;
1279 if (t.asInput() == "\\begin") {
1280 p.skip_spaces(true);
1281 if (p.getArg('{', '}') == "shaded")
1286 parse_outer_box(p, os, FLAG_END, outer,
1287 parent_context, name, "shaded");
1289 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1294 else if (name == "comment") {
1295 eat_whitespace(p, os, parent_context, false);
1296 parent_context.check_layout(os);
1297 begin_inset(os, "Note Comment\n");
1298 os << "status open\n";
1299 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1302 skip_braces(p); // eat {} that might by set by LyX behind comments
1305 else if (name == "lyxgreyedout") {
1306 eat_whitespace(p, os, parent_context, false);
1307 parent_context.check_layout(os);
1308 begin_inset(os, "Note Greyedout\n");
1309 os << "status open\n";
1310 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1313 if (!preamble.notefontcolor().empty())
1314 preamble.registerAutomaticallyLoadedPackage("color");
1317 else if (name == "framed" || name == "shaded") {
1318 eat_whitespace(p, os, parent_context, false);
1319 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1323 else if (name == "lstlisting") {
1324 eat_whitespace(p, os, parent_context, false);
1325 // FIXME handle listings with parameters
1326 // If this is added, don't forgot to handle the
1327 // automatic color package loading
1329 parse_unknown_environment(p, name, os, FLAG_END,
1330 outer, parent_context);
1332 parse_listings(p, os, parent_context);
1336 else if (!parent_context.new_layout_allowed)
1337 parse_unknown_environment(p, name, os, FLAG_END, outer,
1340 // Alignment and spacing settings
1341 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1342 // therefore are totally broken!
1343 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1344 // they are commands not environments. They are furthermore switches that
1345 // can be ended by another switches, but also by commands like \footnote or
1346 // \parbox. So the only safe way is to leave them untouched.
1347 else if (name == "center" || name == "centering" ||
1348 name == "flushleft" || name == "flushright" ||
1349 name == "singlespace" || name == "onehalfspace" ||
1350 name == "doublespace" || name == "spacing") {
1351 eat_whitespace(p, os, parent_context, false);
1352 // We must begin a new paragraph if not already done
1353 if (! parent_context.atParagraphStart()) {
1354 parent_context.check_end_layout(os);
1355 parent_context.new_paragraph(os);
1357 if (name == "flushleft")
1358 parent_context.add_extra_stuff("\\align left\n");
1359 else if (name == "flushright")
1360 parent_context.add_extra_stuff("\\align right\n");
1361 else if (name == "center" || name == "centering")
1362 parent_context.add_extra_stuff("\\align center\n");
1363 else if (name == "singlespace")
1364 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1365 else if (name == "onehalfspace")
1366 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1367 else if (name == "doublespace")
1368 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1369 else if (name == "spacing")
1370 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1371 parse_text(p, os, FLAG_END, outer, parent_context);
1372 // Just in case the environment is empty
1373 parent_context.extra_stuff.erase();
1374 // We must begin a new paragraph to reset the alignment
1375 parent_context.new_paragraph(os);
1379 // The single '=' is meant here.
1380 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1381 eat_whitespace(p, os, parent_context, false);
1382 Context context(true, parent_context.textclass, newlayout,
1383 parent_context.layout, parent_context.font);
1384 if (parent_context.deeper_paragraph) {
1385 // We are beginning a nested environment after a
1386 // deeper paragraph inside the outer list environment.
1387 // Therefore we don't need to output a "begin deeper".
1388 context.need_end_deeper = true;
1390 parent_context.check_end_layout(os);
1391 if (last_env == name) {
1392 // we need to output a separator since LyX would export
1393 // the two environments as one otherwise (bug 5716)
1394 docstring const sep = from_ascii("--Separator--");
1395 TeX2LyXDocClass const & textclass(parent_context.textclass);
1396 if (textclass.hasLayout(sep)) {
1397 Context newcontext(parent_context);
1398 newcontext.layout = &(textclass[sep]);
1399 newcontext.check_layout(os);
1400 newcontext.check_end_layout(os);
1402 parent_context.check_layout(os);
1403 begin_inset(os, "Note Note\n");
1404 os << "status closed\n";
1405 Context newcontext(true, textclass,
1406 &(textclass.defaultLayout()));
1407 newcontext.check_layout(os);
1408 newcontext.check_end_layout(os);
1410 parent_context.check_end_layout(os);
1413 switch (context.layout->latextype) {
1414 case LATEX_LIST_ENVIRONMENT:
1415 context.add_par_extra_stuff("\\labelwidthstring "
1416 + p.verbatim_item() + '\n');
1419 case LATEX_BIB_ENVIRONMENT:
1420 p.verbatim_item(); // swallow next arg
1426 context.check_deeper(os);
1427 // handle known optional and required arguments
1428 // layouts require all optional arguments before the required ones
1429 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1430 // It is impossible to place anything after the environment name,
1431 // but before the first \\item.
1432 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1433 bool need_layout = true;
1434 unsigned int optargs = 0;
1435 while (optargs < context.layout->optargs) {
1436 eat_whitespace(p, os, context, false);
1437 if (p.next_token().cat() == catEscape ||
1438 p.next_token().character() != '[')
1440 p.get_token(); // eat '['
1442 context.check_layout(os);
1443 need_layout = false;
1445 begin_inset(os, "Argument\n");
1446 os << "status collapsed\n\n";
1447 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1449 eat_whitespace(p, os, context, false);
1452 unsigned int reqargs = 0;
1453 while (reqargs < context.layout->reqargs) {
1454 eat_whitespace(p, os, context, false);
1455 if (p.next_token().cat() != catBegin)
1457 p.get_token(); // eat '{'
1459 context.check_layout(os);
1460 need_layout = false;
1462 begin_inset(os, "Argument\n");
1463 os << "status collapsed\n\n";
1464 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1466 eat_whitespace(p, os, context, false);
1470 parse_text(p, os, FLAG_END, outer, context);
1471 context.check_end_layout(os);
1472 if (parent_context.deeper_paragraph) {
1473 // We must suppress the "end deeper" because we
1474 // suppressed the "begin deeper" above.
1475 context.need_end_deeper = false;
1477 context.check_end_deeper(os);
1478 parent_context.new_paragraph(os);
1480 if (!title_layout_found)
1481 title_layout_found = newlayout->intitle;
1484 // The single '=' is meant here.
1485 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1486 eat_whitespace(p, os, parent_context, false);
1487 parent_context.check_layout(os);
1488 begin_inset(os, "Flex ");
1489 os << to_utf8(newinsetlayout->name()) << '\n'
1490 << "status collapsed\n";
1491 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1495 else if (name == "appendix") {
1496 // This is no good latex style, but it works and is used in some documents...
1497 eat_whitespace(p, os, parent_context, false);
1498 parent_context.check_end_layout(os);
1499 Context context(true, parent_context.textclass, parent_context.layout,
1500 parent_context.layout, parent_context.font);
1501 context.check_layout(os);
1502 os << "\\start_of_appendix\n";
1503 parse_text(p, os, FLAG_END, outer, context);
1504 context.check_end_layout(os);
1508 else if (known_environments.find(name) != known_environments.end()) {
1509 vector<ArgumentType> arguments = known_environments[name];
1510 // The last "argument" denotes wether we may translate the
1511 // environment contents to LyX
1512 // The default required if no argument is given makes us
1513 // compatible with the reLyXre environment.
1514 ArgumentType contents = arguments.empty() ?
1517 if (!arguments.empty())
1518 arguments.pop_back();
1519 // See comment in parse_unknown_environment()
1520 bool const specialfont =
1521 (parent_context.font != parent_context.normalfont);
1522 bool const new_layout_allowed =
1523 parent_context.new_layout_allowed;
1525 parent_context.new_layout_allowed = false;
1526 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1527 outer, parent_context);
1528 if (contents == verbatim)
1529 handle_ert(os, p.verbatimEnvironment(name),
1532 parse_text_snippet(p, os, FLAG_END, outer,
1534 handle_ert(os, "\\end{" + name + "}", parent_context);
1536 parent_context.new_layout_allowed = new_layout_allowed;
1540 parse_unknown_environment(p, name, os, FLAG_END, outer,
1544 active_environments.pop_back();
1548 /// parses a comment and outputs it to \p os.
1549 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1551 LASSERT(t.cat() == catComment, return);
1552 if (!t.cs().empty()) {
1553 context.check_layout(os);
1554 handle_comment(os, '%' + t.cs(), context);
1555 if (p.next_token().cat() == catNewline) {
1556 // A newline after a comment line starts a new
1558 if (context.new_layout_allowed) {
1559 if(!context.atParagraphStart())
1560 // Only start a new paragraph if not already
1561 // done (we might get called recursively)
1562 context.new_paragraph(os);
1564 handle_ert(os, "\n", context);
1565 eat_whitespace(p, os, context, true);
1568 // "%\n" combination
1575 * Reads spaces and comments until the first non-space, non-comment token.
1576 * New paragraphs (double newlines or \\par) are handled like simple spaces
1577 * if \p eatParagraph is true.
1578 * Spaces are skipped, but comments are written to \p os.
1580 void eat_whitespace(Parser & p, ostream & os, Context & context,
1584 Token const & t = p.get_token();
1585 if (t.cat() == catComment)
1586 parse_comment(p, os, t, context);
1587 else if ((! eatParagraph && p.isParagraph()) ||
1588 (t.cat() != catSpace && t.cat() != catNewline)) {
1597 * Set a font attribute, parse text and reset the font attribute.
1598 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1599 * \param currentvalue Current value of the attribute. Is set to the new
1600 * value during parsing.
1601 * \param newvalue New value of the attribute
1603 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1604 Context & context, string const & attribute,
1605 string & currentvalue, string const & newvalue)
1607 context.check_layout(os);
1608 string const oldvalue = currentvalue;
1609 currentvalue = newvalue;
1610 os << '\n' << attribute << ' ' << newvalue << "\n";
1611 parse_text_snippet(p, os, flags, outer, context);
1612 context.check_layout(os);
1613 os << '\n' << attribute << ' ' << oldvalue << "\n";
1614 currentvalue = oldvalue;
1618 /// get the arguments of a natbib or jurabib citation command
1619 void get_cite_arguments(Parser & p, bool natbibOrder,
1620 string & before, string & after)
1622 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1624 // text before the citation
1626 // text after the citation
1627 after = p.getFullOpt();
1629 if (!after.empty()) {
1630 before = p.getFullOpt();
1631 if (natbibOrder && !before.empty())
1632 swap(before, after);
1637 /// Convert filenames with TeX macros and/or quotes to something LyX
1639 string const normalize_filename(string const & name)
1641 Parser p(trim(name, "\""));
1644 Token const & t = p.get_token();
1645 if (t.cat() != catEscape)
1647 else if (t.cs() == "lyxdot") {
1648 // This is used by LyX for simple dots in relative
1652 } else if (t.cs() == "space") {
1662 /// Convert \p name from TeX convention (relative to master file) to LyX
1663 /// convention (relative to .lyx file) if it is relative
1664 void fix_relative_filename(string & name)
1666 if (FileName::isAbsolute(name))
1669 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1670 from_utf8(getParentFilePath())));
1674 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1675 void parse_noweb(Parser & p, ostream & os, Context & context)
1677 // assemble the rest of the keyword
1681 Token const & t = p.get_token();
1682 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1685 scrap = (p.good() && p.next_token().asInput() == "=");
1687 name += p.get_token().asInput();
1690 name += t.asInput();
1693 if (!scrap || !context.new_layout_allowed ||
1694 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1695 cerr << "Warning: Could not interpret '" << name
1696 << "'. Ignoring it." << endl;
1700 // We use new_paragraph instead of check_end_layout because the stuff
1701 // following the noweb chunk needs to start with a \begin_layout.
1702 // This may create a new paragraph even if there was none in the
1703 // noweb file, but the alternative is an invalid LyX file. Since
1704 // noweb code chunks are implemented with a layout style in LyX they
1705 // always must be in an own paragraph.
1706 context.new_paragraph(os);
1707 Context newcontext(true, context.textclass,
1708 &context.textclass[from_ascii("Scrap")]);
1709 newcontext.check_layout(os);
1712 Token const & t = p.get_token();
1713 // We abuse the parser a bit, because this is no TeX syntax
1715 if (t.cat() == catEscape)
1716 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1719 Context tmp(false, context.textclass,
1720 &context.textclass[from_ascii("Scrap")]);
1721 tmp.need_end_layout = true;
1722 tmp.check_layout(oss);
1723 os << subst(t.asInput(), "\n", oss.str());
1725 // The scrap chunk is ended by an @ at the beginning of a line.
1726 // After the @ the line may contain a comment and/or
1727 // whitespace, but nothing else.
1728 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1729 (p.next_token().cat() == catSpace ||
1730 p.next_token().cat() == catNewline ||
1731 p.next_token().cat() == catComment)) {
1732 while (p.good() && p.next_token().cat() == catSpace)
1733 os << p.get_token().asInput();
1734 if (p.next_token().cat() == catComment)
1735 // The comment includes a final '\n'
1736 os << p.get_token().asInput();
1738 if (p.next_token().cat() == catNewline)
1745 newcontext.check_end_layout(os);
1749 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1750 bool is_macro(Parser & p)
1752 Token first = p.curr_token();
1753 if (first.cat() != catEscape || !p.good())
1755 if (first.cs() == "def")
1757 if (first.cs() != "global" && first.cs() != "long")
1759 Token second = p.get_token();
1761 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1762 second.cat() == catNewline || second.cat() == catComment)) {
1763 second = p.get_token();
1766 bool secondvalid = second.cat() == catEscape;
1768 bool thirdvalid = false;
1769 if (p.good() && first.cs() == "global" && secondvalid &&
1770 second.cs() == "long") {
1771 third = p.get_token();
1773 while (p.good() && !p.isParagraph() &&
1774 (third.cat() == catSpace ||
1775 third.cat() == catNewline ||
1776 third.cat() == catComment)) {
1777 third = p.get_token();
1780 thirdvalid = third.cat() == catEscape;
1782 for (int i = 0; i < pos; ++i)
1787 return (first.cs() == "global" || first.cs() == "long") &&
1788 second.cs() == "def";
1789 return first.cs() == "global" && second.cs() == "long" &&
1790 third.cs() == "def";
1794 /// Parse a macro definition (assumes that is_macro() returned true)
1795 void parse_macro(Parser & p, ostream & os, Context & context)
1797 context.check_layout(os);
1798 Token first = p.curr_token();
1801 string command = first.asInput();
1802 if (first.cs() != "def") {
1804 eat_whitespace(p, os, context, false);
1805 second = p.curr_token();
1806 command += second.asInput();
1807 if (second.cs() != "def") {
1809 eat_whitespace(p, os, context, false);
1810 third = p.curr_token();
1811 command += third.asInput();
1814 eat_whitespace(p, os, context, false);
1815 string const name = p.get_token().cs();
1816 eat_whitespace(p, os, context, false);
1822 while (p.next_token().cat() != catBegin) {
1823 if (p.next_token().cat() == catParameter) {
1828 // followed by number?
1829 if (p.next_token().cat() == catOther) {
1830 char c = p.getChar();
1832 // number = current arity + 1?
1833 if (c == arity + '0' + 1)
1838 paramtext += p.get_token().cs();
1840 paramtext += p.get_token().cs();
1845 // only output simple (i.e. compatible) macro as FormulaMacros
1846 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1848 context.check_layout(os);
1849 begin_inset(os, "FormulaMacro");
1850 os << "\n\\def" << ert;
1853 handle_ert(os, command + ert, context);
1856 } // anonymous namespace
1859 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1862 Layout const * newlayout = 0;
1863 InsetLayout const * newinsetlayout = 0;
1864 // Store the latest bibliographystyle and nocite{*} option
1865 // (needed for bibtex inset)
1867 string bibliographystyle;
1868 bool const use_natbib = preamble.isPackageUsed("natbib");
1869 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1871 bool title_layout_found = false;
1873 Token const & t = p.get_token();
1876 debugToken(cerr, t, flags);
1879 if (flags & FLAG_ITEM) {
1880 if (t.cat() == catSpace)
1883 flags &= ~FLAG_ITEM;
1884 if (t.cat() == catBegin) {
1885 // skip the brace and collect everything to the next matching
1887 flags |= FLAG_BRACE_LAST;
1891 // handle only this single token, leave the loop if done
1892 flags |= FLAG_LEAVE;
1895 if (t.cat() != catEscape && t.character() == ']' &&
1896 (flags & FLAG_BRACK_LAST))
1898 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1901 // If there is anything between \end{env} and \begin{env} we
1902 // don't need to output a separator.
1903 if (t.cat() != catSpace && t.cat() != catNewline &&
1904 t.asInput() != "\\begin")
1910 if (t.cat() == catMath) {
1911 // we are inside some text mode thingy, so opening new math is allowed
1912 context.check_layout(os);
1913 begin_inset(os, "Formula ");
1914 Token const & n = p.get_token();
1915 bool const display(n.cat() == catMath && outer);
1917 // TeX's $$...$$ syntax for displayed math
1919 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1921 p.get_token(); // skip the second '$' token
1923 // simple $...$ stuff
1926 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1931 // Prevent the conversion of a line break to a
1932 // space (bug 7668). This does not change the
1933 // output, but looks ugly in LyX.
1934 eat_whitespace(p, os, context, false);
1938 else if (t.cat() == catSuper || t.cat() == catSub)
1939 cerr << "catcode " << t << " illegal in text mode\n";
1941 // Basic support for english quotes. This should be
1942 // extended to other quotes, but is not so easy (a
1943 // left english quote is the same as a right german
1945 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1946 context.check_layout(os);
1947 begin_inset(os, "Quotes ");
1953 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1954 context.check_layout(os);
1955 begin_inset(os, "Quotes ");
1962 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1963 context.check_layout(os);
1964 begin_inset(os, "Quotes ");
1971 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1972 context.check_layout(os);
1973 begin_inset(os, "Quotes ");
1980 else if (t.asInput() == "<"
1981 && p.next_token().asInput() == "<" && noweb_mode) {
1983 parse_noweb(p, os, context);
1986 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1987 check_space(p, os, context);
1989 else if (t.character() == '[' && noweb_mode &&
1990 p.next_token().character() == '[') {
1991 // These can contain underscores
1993 string const s = p.getFullOpt() + ']';
1994 if (p.next_token().character() == ']')
1997 cerr << "Warning: Inserting missing ']' in '"
1998 << s << "'." << endl;
1999 handle_ert(os, s, context);
2002 else if (t.cat() == catLetter) {
2003 context.check_layout(os);
2004 // Workaround for bug 4752.
2005 // FIXME: This whole code block needs to be removed
2006 // when the bug is fixed and tex2lyx produces
2007 // the updated file format.
2008 // The replacement algorithm in LyX is so stupid that
2009 // it even translates a phrase if it is part of a word.
2010 bool handled = false;
2011 for (int const * l = known_phrase_lengths; *l; ++l) {
2012 string phrase = t.cs();
2013 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2014 phrase += p.get_token().cs();
2015 if (is_known(phrase, known_coded_phrases)) {
2016 handle_ert(os, phrase, context);
2020 for (size_t i = 1; i < phrase.length(); ++i)
2028 else if (t.cat() == catOther ||
2029 t.cat() == catAlign ||
2030 t.cat() == catParameter) {
2031 // This translates "&" to "\\&" which may be wrong...
2032 context.check_layout(os);
2036 else if (p.isParagraph()) {
2037 if (context.new_layout_allowed)
2038 context.new_paragraph(os);
2040 handle_ert(os, "\\par ", context);
2041 eat_whitespace(p, os, context, true);
2044 else if (t.cat() == catActive) {
2045 context.check_layout(os);
2046 if (t.character() == '~') {
2047 if (context.layout->free_spacing)
2050 begin_inset(os, "space ~\n");
2057 else if (t.cat() == catBegin &&
2058 p.next_token().cat() == catEnd) {
2060 Token const prev = p.prev_token();
2062 if (p.next_token().character() == '`' ||
2063 (prev.character() == '-' &&
2064 p.next_token().character() == '-'))
2065 ; // ignore it in {}`` or -{}-
2067 handle_ert(os, "{}", context);
2071 else if (t.cat() == catBegin) {
2072 context.check_layout(os);
2073 // special handling of font attribute changes
2074 Token const prev = p.prev_token();
2075 Token const next = p.next_token();
2076 TeXFont const oldFont = context.font;
2077 if (next.character() == '[' ||
2078 next.character() == ']' ||
2079 next.character() == '*') {
2081 if (p.next_token().cat() == catEnd) {
2086 handle_ert(os, "{", context);
2087 parse_text_snippet(p, os,
2090 handle_ert(os, "}", context);
2092 } else if (! context.new_layout_allowed) {
2093 handle_ert(os, "{", context);
2094 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2096 handle_ert(os, "}", context);
2097 } else if (is_known(next.cs(), known_sizes)) {
2098 // next will change the size, so we must
2100 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2102 if (!context.atParagraphStart())
2104 << context.font.size << "\n";
2105 } else if (is_known(next.cs(), known_font_families)) {
2106 // next will change the font family, so we
2107 // must reset it here
2108 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2110 if (!context.atParagraphStart())
2112 << context.font.family << "\n";
2113 } else if (is_known(next.cs(), known_font_series)) {
2114 // next will change the font series, so we
2115 // must reset it here
2116 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2118 if (!context.atParagraphStart())
2120 << context.font.series << "\n";
2121 } else if (is_known(next.cs(), known_font_shapes)) {
2122 // next will change the font shape, so we
2123 // must reset it here
2124 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2126 if (!context.atParagraphStart())
2128 << context.font.shape << "\n";
2129 } else if (is_known(next.cs(), known_old_font_families) ||
2130 is_known(next.cs(), known_old_font_series) ||
2131 is_known(next.cs(), known_old_font_shapes)) {
2132 // next will change the font family, series
2133 // and shape, so we must reset it here
2134 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2136 if (!context.atParagraphStart())
2138 << context.font.family
2140 << context.font.series
2142 << context.font.shape << "\n";
2144 handle_ert(os, "{", context);
2145 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2147 handle_ert(os, "}", context);
2151 else if (t.cat() == catEnd) {
2152 if (flags & FLAG_BRACE_LAST) {
2155 cerr << "stray '}' in text\n";
2156 handle_ert(os, "}", context);
2159 else if (t.cat() == catComment)
2160 parse_comment(p, os, t, context);
2163 // control sequences
2166 else if (t.cs() == "(") {
2167 context.check_layout(os);
2168 begin_inset(os, "Formula");
2170 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2175 else if (t.cs() == "[") {
2176 context.check_layout(os);
2177 begin_inset(os, "Formula");
2179 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2182 // Prevent the conversion of a line break to a space
2183 // (bug 7668). This does not change the output, but
2184 // looks ugly in LyX.
2185 eat_whitespace(p, os, context, false);
2188 else if (t.cs() == "begin")
2189 parse_environment(p, os, outer, last_env,
2190 title_layout_found, context);
2192 else if (t.cs() == "end") {
2193 if (flags & FLAG_END) {
2194 // eat environment name
2195 string const name = p.getArg('{', '}');
2196 if (name != active_environment())
2197 cerr << "\\end{" + name + "} does not match \\begin{"
2198 + active_environment() + "}\n";
2201 p.error("found 'end' unexpectedly");
2204 else if (t.cs() == "item") {
2206 bool const optarg = p.hasOpt();
2208 // FIXME: This swallows comments, but we cannot use
2209 // eat_whitespace() since we must not output
2210 // anything before the item.
2211 s = p.getArg('[', ']');
2213 p.skip_spaces(false);
2215 context.check_layout(os);
2216 if (context.has_item) {
2217 // An item in an unknown list-like environment
2218 // FIXME: Do this in check_layout()!
2219 context.has_item = false;
2221 handle_ert(os, "\\item", context);
2223 handle_ert(os, "\\item ", context);
2226 if (context.layout->labeltype != LABEL_MANUAL) {
2227 // LyX does not support \item[\mybullet]
2228 // in itemize environments
2230 os << parse_text_snippet(p2,
2231 FLAG_BRACK_LAST, outer, context);
2232 } else if (!s.empty()) {
2233 // LyX adds braces around the argument,
2234 // so we need to remove them here.
2235 if (s.size() > 2 && s[0] == '{' &&
2236 s[s.size()-1] == '}')
2237 s = s.substr(1, s.size()-2);
2238 // If the argument contains a space we
2239 // must put it into ERT: Otherwise LyX
2240 // would misinterpret the space as
2241 // item delimiter (bug 7663)
2242 if (contains(s, ' ')) {
2243 handle_ert(os, s, context);
2246 os << parse_text_snippet(p2,
2250 // The space is needed to separate the
2251 // item from the rest of the sentence.
2253 eat_whitespace(p, os, context, false);
2258 else if (t.cs() == "bibitem") {
2260 context.check_layout(os);
2261 string label = convert_command_inset_arg(p.getArg('[', ']'));
2262 string key = convert_command_inset_arg(p.verbatim_item());
2263 if (contains(label, '\\') || contains(key, '\\')) {
2264 // LyX can't handle LaTeX commands in labels or keys
2265 handle_ert(os, t.asInput() + '[' + label +
2266 "]{" + p.verbatim_item() + '}',
2269 begin_command_inset(os, "bibitem", "bibitem");
2270 os << "label \"" << label << "\"\n"
2271 "key \"" << key << "\"\n";
2276 else if (is_macro(p))
2277 parse_macro(p, os, context);
2279 else if (t.cs() == "noindent") {
2281 context.add_par_extra_stuff("\\noindent\n");
2284 else if (t.cs() == "appendix") {
2285 context.add_par_extra_stuff("\\start_of_appendix\n");
2286 // We need to start a new paragraph. Otherwise the
2287 // appendix in 'bla\appendix\chapter{' would start
2289 context.new_paragraph(os);
2290 // We need to make sure that the paragraph is
2291 // generated even if it is empty. Otherwise the
2292 // appendix in '\par\appendix\par\chapter{' would
2294 context.check_layout(os);
2295 // FIXME: This is a hack to prevent paragraph
2296 // deletion if it is empty. Handle this better!
2298 "%dummy comment inserted by tex2lyx to "
2299 "ensure that this paragraph is not empty",
2301 // Both measures above may generate an additional
2302 // empty paragraph, but that does not hurt, because
2303 // whitespace does not matter here.
2304 eat_whitespace(p, os, context, true);
2307 // Must catch empty dates before findLayout is called below
2308 else if (t.cs() == "date") {
2309 string const date = p.verbatim_item();
2311 preamble.suppressDate(true);
2313 preamble.suppressDate(false);
2314 if (context.new_layout_allowed &&
2315 (newlayout = findLayout(context.textclass,
2318 output_command_layout(os, p, outer,
2319 context, newlayout);
2321 if (!title_layout_found)
2322 title_layout_found = newlayout->intitle;
2324 handle_ert(os, "\\date{" + date + '}',
2329 // Starred section headings
2330 // Must attempt to parse "Section*" before "Section".
2331 else if ((p.next_token().asInput() == "*") &&
2332 context.new_layout_allowed &&
2333 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2336 output_command_layout(os, p, outer, context, newlayout);
2338 if (!title_layout_found)
2339 title_layout_found = newlayout->intitle;
2342 // Section headings and the like
2343 else if (context.new_layout_allowed &&
2344 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2346 output_command_layout(os, p, outer, context, newlayout);
2348 if (!title_layout_found)
2349 title_layout_found = newlayout->intitle;
2352 else if (t.cs() == "caption") {
2354 context.check_layout(os);
2356 begin_inset(os, "Caption\n");
2357 Context newcontext(true, context.textclass);
2358 newcontext.font = context.font;
2359 newcontext.check_layout(os);
2360 if (p.next_token().cat() != catEscape &&
2361 p.next_token().character() == '[') {
2362 p.get_token(); // eat '['
2363 begin_inset(os, "Argument\n");
2364 os << "status collapsed\n";
2365 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2367 eat_whitespace(p, os, context, false);
2369 parse_text(p, os, FLAG_ITEM, outer, context);
2370 context.check_end_layout(os);
2371 // We don't need really a new paragraph, but
2372 // we must make sure that the next item gets a \begin_layout.
2373 context.new_paragraph(os);
2376 newcontext.check_end_layout(os);
2379 else if (t.cs() == "subfloat") {
2380 // the syntax is \subfloat[caption]{content}
2381 // if it is a table of figure depends on the surrounding float
2382 bool has_caption = false;
2384 // do nothing if there is no outer float
2385 if (!float_type.empty()) {
2386 context.check_layout(os);
2388 begin_inset(os, "Float " + float_type + "\n");
2390 << "\nsideways false"
2391 << "\nstatus collapsed\n\n";
2394 if (p.next_token().cat() != catEscape &&
2395 p.next_token().character() == '[') {
2396 p.get_token(); // eat '['
2397 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2401 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2402 // the caption comes always as the last
2404 // we must make sure that the caption gets a \begin_layout
2405 os << "\n\\begin_layout Plain Layout";
2407 begin_inset(os, "Caption\n");
2408 Context newcontext(true, context.textclass);
2409 newcontext.font = context.font;
2410 newcontext.check_layout(os);
2411 os << caption << "\n";
2412 newcontext.check_end_layout(os);
2413 // We don't need really a new paragraph, but
2414 // we must make sure that the next item gets a \begin_layout.
2415 //newcontext.new_paragraph(os);
2419 // We don't need really a new paragraph, but
2420 // we must make sure that the next item gets a \begin_layout.
2422 context.new_paragraph(os);
2425 context.check_end_layout(os);
2426 // close the layout we opened
2428 os << "\n\\end_layout\n";
2430 // if the float type is not supported or there is no surrounding float
2433 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2434 handle_ert(os, t.asInput() + '[' + opt_arg +
2435 "]{" + p.verbatim_item() + '}', context);
2437 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2441 else if (t.cs() == "includegraphics") {
2442 bool const clip = p.next_token().asInput() == "*";
2445 string const arg = p.getArg('[', ']');
2446 map<string, string> opts;
2447 vector<string> keys;
2448 split_map(arg, opts, keys);
2450 opts["clip"] = string();
2451 string name = normalize_filename(p.verbatim_item());
2453 string const path = getMasterFilePath();
2454 // We want to preserve relative / absolute filenames,
2455 // therefore path is only used for testing
2456 if (!makeAbsPath(name, path).exists()) {
2457 // The file extension is probably missing.
2458 // Now try to find it out.
2459 string const dvips_name =
2460 find_file(name, path,
2461 known_dvips_graphics_formats);
2462 string const pdftex_name =
2463 find_file(name, path,
2464 known_pdftex_graphics_formats);
2465 if (!dvips_name.empty()) {
2466 if (!pdftex_name.empty()) {
2467 cerr << "This file contains the "
2469 "\"\\includegraphics{"
2471 "However, files\n\""
2472 << dvips_name << "\" and\n\""
2473 << pdftex_name << "\"\n"
2474 "both exist, so I had to make a "
2475 "choice and took the first one.\n"
2476 "Please move the unwanted one "
2477 "someplace else and try again\n"
2478 "if my choice was wrong."
2482 } else if (!pdftex_name.empty()) {
2488 if (makeAbsPath(name, path).exists())
2489 fix_relative_filename(name);
2491 cerr << "Warning: Could not find graphics file '"
2492 << name << "'." << endl;
2494 context.check_layout(os);
2495 begin_inset(os, "Graphics ");
2496 os << "\n\tfilename " << name << '\n';
2497 if (opts.find("width") != opts.end())
2499 << translate_len(opts["width"]) << '\n';
2500 if (opts.find("height") != opts.end())
2502 << translate_len(opts["height"]) << '\n';
2503 if (opts.find("scale") != opts.end()) {
2504 istringstream iss(opts["scale"]);
2508 os << "\tscale " << val << '\n';
2510 if (opts.find("angle") != opts.end()) {
2511 os << "\trotateAngle "
2512 << opts["angle"] << '\n';
2513 vector<string>::const_iterator a =
2514 find(keys.begin(), keys.end(), "angle");
2515 vector<string>::const_iterator s =
2516 find(keys.begin(), keys.end(), "width");
2517 if (s == keys.end())
2518 s = find(keys.begin(), keys.end(), "height");
2519 if (s == keys.end())
2520 s = find(keys.begin(), keys.end(), "scale");
2521 if (s != keys.end() && distance(s, a) > 0)
2522 os << "\tscaleBeforeRotation\n";
2524 if (opts.find("origin") != opts.end()) {
2526 string const opt = opts["origin"];
2527 if (opt.find('l') != string::npos) ss << "left";
2528 if (opt.find('r') != string::npos) ss << "right";
2529 if (opt.find('c') != string::npos) ss << "center";
2530 if (opt.find('t') != string::npos) ss << "Top";
2531 if (opt.find('b') != string::npos) ss << "Bottom";
2532 if (opt.find('B') != string::npos) ss << "Baseline";
2533 if (!ss.str().empty())
2534 os << "\trotateOrigin " << ss.str() << '\n';
2536 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2538 if (opts.find("keepaspectratio") != opts.end())
2539 os << "\tkeepAspectRatio\n";
2540 if (opts.find("clip") != opts.end())
2542 if (opts.find("draft") != opts.end())
2544 if (opts.find("bb") != opts.end())
2545 os << "\tBoundingBox "
2546 << opts["bb"] << '\n';
2547 int numberOfbbOptions = 0;
2548 if (opts.find("bbllx") != opts.end())
2549 numberOfbbOptions++;
2550 if (opts.find("bblly") != opts.end())
2551 numberOfbbOptions++;
2552 if (opts.find("bburx") != opts.end())
2553 numberOfbbOptions++;
2554 if (opts.find("bbury") != opts.end())
2555 numberOfbbOptions++;
2556 if (numberOfbbOptions == 4)
2557 os << "\tBoundingBox "
2558 << opts["bbllx"] << " " << opts["bblly"] << " "
2559 << opts["bburx"] << " " << opts["bbury"] << '\n';
2560 else if (numberOfbbOptions > 0)
2561 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2562 numberOfbbOptions = 0;
2563 if (opts.find("natwidth") != opts.end())
2564 numberOfbbOptions++;
2565 if (opts.find("natheight") != opts.end())
2566 numberOfbbOptions++;
2567 if (numberOfbbOptions == 2)
2568 os << "\tBoundingBox 0bp 0bp "
2569 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2570 else if (numberOfbbOptions > 0)
2571 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2572 ostringstream special;
2573 if (opts.find("hiresbb") != opts.end())
2574 special << "hiresbb,";
2575 if (opts.find("trim") != opts.end())
2577 if (opts.find("viewport") != opts.end())
2578 special << "viewport=" << opts["viewport"] << ',';
2579 if (opts.find("totalheight") != opts.end())
2580 special << "totalheight=" << opts["totalheight"] << ',';
2581 if (opts.find("type") != opts.end())
2582 special << "type=" << opts["type"] << ',';
2583 if (opts.find("ext") != opts.end())
2584 special << "ext=" << opts["ext"] << ',';
2585 if (opts.find("read") != opts.end())
2586 special << "read=" << opts["read"] << ',';
2587 if (opts.find("command") != opts.end())
2588 special << "command=" << opts["command"] << ',';
2589 string s_special = special.str();
2590 if (!s_special.empty()) {
2591 // We had special arguments. Remove the trailing ','.
2592 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2594 // TODO: Handle the unknown settings better.
2595 // Warn about invalid options.
2596 // Check whether some option was given twice.
2600 else if (t.cs() == "footnote" ||
2601 (t.cs() == "thanks" && context.layout->intitle)) {
2603 context.check_layout(os);
2604 begin_inset(os, "Foot\n");
2605 os << "status collapsed\n\n";
2606 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2610 else if (t.cs() == "marginpar") {
2612 context.check_layout(os);
2613 begin_inset(os, "Marginal\n");
2614 os << "status collapsed\n\n";
2615 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2619 else if (t.cs() == "ensuremath") {
2621 context.check_layout(os);
2622 string const s = p.verbatim_item();
2623 //FIXME: this never triggers in UTF8
2624 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2627 handle_ert(os, "\\ensuremath{" + s + "}",
2631 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2632 if (title_layout_found) {
2634 skip_spaces_braces(p);
2636 handle_ert(os, t.asInput(), context);
2639 else if (t.cs() == "tableofcontents") {
2640 context.check_layout(os);
2641 begin_command_inset(os, "toc", "tableofcontents");
2643 skip_spaces_braces(p);
2646 else if (t.cs() == "listoffigures") {
2647 context.check_layout(os);
2648 begin_inset(os, "FloatList figure\n");
2650 skip_spaces_braces(p);
2653 else if (t.cs() == "listoftables") {
2654 context.check_layout(os);
2655 begin_inset(os, "FloatList table\n");
2657 skip_spaces_braces(p);
2660 else if (t.cs() == "listof") {
2661 p.skip_spaces(true);
2662 string const name = p.get_token().cs();
2663 if (context.textclass.floats().typeExist(name)) {
2664 context.check_layout(os);
2665 begin_inset(os, "FloatList ");
2668 p.get_token(); // swallow second arg
2670 handle_ert(os, "\\listof{" + name + "}", context);
2673 else if (t.cs() == "textrm")
2674 parse_text_attributes(p, os, FLAG_ITEM, outer,
2675 context, "\\family",
2676 context.font.family, "roman");
2678 else if (t.cs() == "textsf")
2679 parse_text_attributes(p, os, FLAG_ITEM, outer,
2680 context, "\\family",
2681 context.font.family, "sans");
2683 else if (t.cs() == "texttt")
2684 parse_text_attributes(p, os, FLAG_ITEM, outer,
2685 context, "\\family",
2686 context.font.family, "typewriter");
2688 else if (t.cs() == "textmd")
2689 parse_text_attributes(p, os, FLAG_ITEM, outer,
2690 context, "\\series",
2691 context.font.series, "medium");
2693 else if (t.cs() == "textbf")
2694 parse_text_attributes(p, os, FLAG_ITEM, outer,
2695 context, "\\series",
2696 context.font.series, "bold");
2698 else if (t.cs() == "textup")
2699 parse_text_attributes(p, os, FLAG_ITEM, outer,
2701 context.font.shape, "up");
2703 else if (t.cs() == "textit")
2704 parse_text_attributes(p, os, FLAG_ITEM, outer,
2706 context.font.shape, "italic");
2708 else if (t.cs() == "textsl")
2709 parse_text_attributes(p, os, FLAG_ITEM, outer,
2711 context.font.shape, "slanted");
2713 else if (t.cs() == "textsc")
2714 parse_text_attributes(p, os, FLAG_ITEM, outer,
2716 context.font.shape, "smallcaps");
2718 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2719 context.check_layout(os);
2720 TeXFont oldFont = context.font;
2721 context.font.init();
2722 context.font.size = oldFont.size;
2723 os << "\n\\family " << context.font.family << "\n";
2724 os << "\n\\series " << context.font.series << "\n";
2725 os << "\n\\shape " << context.font.shape << "\n";
2726 if (t.cs() == "textnormal") {
2727 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2728 output_font_change(os, context.font, oldFont);
2729 context.font = oldFont;
2731 eat_whitespace(p, os, context, false);
2734 else if (t.cs() == "textcolor") {
2735 // scheme is \textcolor{color name}{text}
2736 string const color = p.verbatim_item();
2737 // we only support the predefined colors of the color package
2738 if (color == "black" || color == "blue" || color == "cyan"
2739 || color == "green" || color == "magenta" || color == "red"
2740 || color == "white" || color == "yellow") {
2741 context.check_layout(os);
2742 os << "\n\\color " << color << "\n";
2743 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2744 context.check_layout(os);
2745 os << "\n\\color inherit\n";
2746 preamble.registerAutomaticallyLoadedPackage("color");
2748 // for custom defined colors
2749 handle_ert(os, t.asInput() + "{" + color + "}", context);
2752 else if (t.cs() == "underbar" || t.cs() == "uline") {
2753 // \underbar is not 100% correct (LyX outputs \uline
2754 // of ulem.sty). The difference is that \ulem allows
2755 // line breaks, and \underbar does not.
2756 // Do NOT handle \underline.
2757 // \underbar cuts through y, g, q, p etc.,
2758 // \underline does not.
2759 context.check_layout(os);
2760 os << "\n\\bar under\n";
2761 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2762 context.check_layout(os);
2763 os << "\n\\bar default\n";
2764 preamble.registerAutomaticallyLoadedPackage("ulem");
2767 else if (t.cs() == "sout") {
2768 context.check_layout(os);
2769 os << "\n\\strikeout on\n";
2770 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2771 context.check_layout(os);
2772 os << "\n\\strikeout default\n";
2773 preamble.registerAutomaticallyLoadedPackage("ulem");
2776 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2777 t.cs() == "emph" || t.cs() == "noun") {
2778 context.check_layout(os);
2779 os << "\n\\" << t.cs() << " on\n";
2780 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2781 context.check_layout(os);
2782 os << "\n\\" << t.cs() << " default\n";
2783 if (t.cs() == "uuline" || t.cs() == "uwave")
2784 preamble.registerAutomaticallyLoadedPackage("ulem");
2787 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2788 context.check_layout(os);
2789 string name = p.getArg('{', '}');
2790 string localtime = p.getArg('{', '}');
2791 preamble.registerAuthor(name);
2792 Author const & author = preamble.getAuthor(name);
2793 // from_ctime() will fail if LyX decides to output the
2794 // time in the text language. It might also use a wrong
2795 // time zone (if the original LyX document was exported
2796 // with a different time zone).
2797 time_t ptime = from_ctime(localtime);
2798 if (ptime == static_cast<time_t>(-1)) {
2799 cerr << "Warning: Could not parse time `" << localtime
2800 << "´ for change tracking, using current time instead.\n";
2801 ptime = current_time();
2803 if (t.cs() == "lyxadded")
2804 os << "\n\\change_inserted ";
2806 os << "\n\\change_deleted ";
2807 os << author.bufferId() << ' ' << ptime << '\n';
2808 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2809 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2810 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2811 LaTeXPackages::isAvailable("xcolor");
2812 // No need to test for luatex, since luatex comes in
2813 // two flavours (dvi and pdf), like latex, and those
2814 // are detected by pdflatex.
2815 if (pdflatex || xetex) {
2817 preamble.registerAutomaticallyLoadedPackage("ulem");
2818 preamble.registerAutomaticallyLoadedPackage("xcolor");
2819 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2823 preamble.registerAutomaticallyLoadedPackage("dvipost");
2824 } else if (xcolorulem) {
2825 preamble.registerAutomaticallyLoadedPackage("ulem");
2826 preamble.registerAutomaticallyLoadedPackage("xcolor");
2831 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2832 t.cs() == "vphantom") {
2833 context.check_layout(os);
2834 if (t.cs() == "phantom")
2835 begin_inset(os, "Phantom Phantom\n");
2836 if (t.cs() == "hphantom")
2837 begin_inset(os, "Phantom HPhantom\n");
2838 if (t.cs() == "vphantom")
2839 begin_inset(os, "Phantom VPhantom\n");
2840 os << "status open\n";
2841 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2846 else if (t.cs() == "href") {
2847 context.check_layout(os);
2848 string target = p.getArg('{', '}');
2849 string name = p.getArg('{', '}');
2851 size_t i = target.find(':');
2852 if (i != string::npos) {
2853 type = target.substr(0, i + 1);
2854 if (type == "mailto:" || type == "file:")
2855 target = target.substr(i + 1);
2856 // handle the case that name is equal to target, except of "http://"
2857 else if (target.substr(i + 3) == name && type == "http:")
2860 begin_command_inset(os, "href", "href");
2862 os << "name \"" << name << "\"\n";
2863 os << "target \"" << target << "\"\n";
2864 if (type == "mailto:" || type == "file:")
2865 os << "type \"" << type << "\"\n";
2867 skip_spaces_braces(p);
2870 else if (t.cs() == "lyxline") {
2871 // swallow size argument (it is not used anyway)
2873 if (!context.atParagraphStart()) {
2874 // so our line is in the middle of a paragraph
2875 // we need to add a new line, lest this line
2876 // follow the other content on that line and
2877 // run off the side of the page
2878 // FIXME: This may create an empty paragraph,
2879 // but without that it would not be
2880 // possible to set noindent below.
2881 // Fortunately LaTeX does not care
2882 // about the empty paragraph.
2883 context.new_paragraph(os);
2885 if (preamble.indentParagraphs()) {
2886 // we need to unindent, lest the line be too long
2887 context.add_par_extra_stuff("\\noindent\n");
2889 context.check_layout(os);
2890 begin_command_inset(os, "line", "rule");
2891 os << "offset \"0.5ex\"\n"
2892 "width \"100line%\"\n"
2897 else if (t.cs() == "rule") {
2898 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2899 string const width = p.getArg('{', '}');
2900 string const thickness = p.getArg('{', '}');
2901 context.check_layout(os);
2902 begin_command_inset(os, "line", "rule");
2903 if (!offset.empty())
2904 os << "offset \"" << translate_len(offset) << "\"\n";
2905 os << "width \"" << translate_len(width) << "\"\n"
2906 "height \"" << translate_len(thickness) << "\"\n";
2910 else if (is_known(t.cs(), known_phrases) ||
2911 (t.cs() == "protect" &&
2912 p.next_token().cat() == catEscape &&
2913 is_known(p.next_token().cs(), known_phrases))) {
2914 // LyX sometimes puts a \protect in front, so we have to ignore it
2915 // FIXME: This needs to be changed when bug 4752 is fixed.
2916 char const * const * where = is_known(
2917 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2919 context.check_layout(os);
2920 os << known_coded_phrases[where - known_phrases];
2921 skip_spaces_braces(p);
2924 else if (is_known(t.cs(), known_ref_commands)) {
2925 string const opt = p.getOpt();
2927 context.check_layout(os);
2928 char const * const * where = is_known(t.cs(),
2929 known_ref_commands);
2930 begin_command_inset(os, "ref",
2931 known_coded_ref_commands[where - known_ref_commands]);
2932 os << "reference \""
2933 << convert_command_inset_arg(p.verbatim_item())
2937 // LyX does not support optional arguments of ref commands
2938 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2939 p.verbatim_item() + "}", context);
2943 else if (use_natbib &&
2944 is_known(t.cs(), known_natbib_commands) &&
2945 ((t.cs() != "citefullauthor" &&
2946 t.cs() != "citeyear" &&
2947 t.cs() != "citeyearpar") ||
2948 p.next_token().asInput() != "*")) {
2949 context.check_layout(os);
2950 string command = t.cs();
2951 if (p.next_token().asInput() == "*") {
2955 if (command == "citefullauthor")
2956 // alternative name for "\\citeauthor*"
2957 command = "citeauthor*";
2959 // text before the citation
2961 // text after the citation
2963 get_cite_arguments(p, true, before, after);
2965 if (command == "cite") {
2966 // \cite without optional argument means
2967 // \citet, \cite with at least one optional
2968 // argument means \citep.
2969 if (before.empty() && after.empty())
2974 if (before.empty() && after == "[]")
2975 // avoid \citet[]{a}
2977 else if (before == "[]" && after == "[]") {
2978 // avoid \citet[][]{a}
2982 // remove the brackets around after and before
2983 if (!after.empty()) {
2985 after.erase(after.length() - 1, 1);
2986 after = convert_command_inset_arg(after);
2988 if (!before.empty()) {
2990 before.erase(before.length() - 1, 1);
2991 before = convert_command_inset_arg(before);
2993 begin_command_inset(os, "citation", command);
2994 os << "after " << '"' << after << '"' << "\n";
2995 os << "before " << '"' << before << '"' << "\n";
2997 << convert_command_inset_arg(p.verbatim_item())
3002 else if (use_jurabib &&
3003 is_known(t.cs(), known_jurabib_commands) &&
3004 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3005 context.check_layout(os);
3006 string command = t.cs();
3007 if (p.next_token().asInput() == "*") {
3011 char argumentOrder = '\0';
3012 vector<string> const options =
3013 preamble.getPackageOptions("jurabib");
3014 if (find(options.begin(), options.end(),
3015 "natbiborder") != options.end())
3016 argumentOrder = 'n';
3017 else if (find(options.begin(), options.end(),
3018 "jurabiborder") != options.end())
3019 argumentOrder = 'j';
3021 // text before the citation
3023 // text after the citation
3025 get_cite_arguments(p, argumentOrder != 'j', before, after);
3027 string const citation = p.verbatim_item();
3028 if (!before.empty() && argumentOrder == '\0') {
3029 cerr << "Warning: Assuming argument order "
3030 "of jurabib version 0.6 for\n'"
3031 << command << before << after << '{'
3032 << citation << "}'.\n"
3033 "Add 'jurabiborder' to the jurabib "
3034 "package options if you used an\n"
3035 "earlier jurabib version." << endl;
3037 if (!after.empty()) {
3039 after.erase(after.length() - 1, 1);
3041 if (!before.empty()) {
3043 before.erase(before.length() - 1, 1);
3045 begin_command_inset(os, "citation", command);
3046 os << "after " << '"' << after << '"' << "\n";
3047 os << "before " << '"' << before << '"' << "\n";
3048 os << "key " << '"' << citation << '"' << "\n";
3052 else if (t.cs() == "cite"
3053 || t.cs() == "nocite") {
3054 context.check_layout(os);
3055 string after = convert_command_inset_arg(p.getArg('[', ']'));
3056 string key = convert_command_inset_arg(p.verbatim_item());
3057 // store the case that it is "\nocite{*}" to use it later for
3060 begin_command_inset(os, "citation", t.cs());
3061 os << "after " << '"' << after << '"' << "\n";
3062 os << "key " << '"' << key << '"' << "\n";
3064 } else if (t.cs() == "nocite")
3068 else if (t.cs() == "index") {
3069 context.check_layout(os);
3070 begin_inset(os, "Index idx\n");
3071 os << "status collapsed\n";
3072 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3076 else if (t.cs() == "nomenclature") {
3077 context.check_layout(os);
3078 begin_command_inset(os, "nomenclature", "nomenclature");
3079 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3080 if (!prefix.empty())
3081 os << "prefix " << '"' << prefix << '"' << "\n";
3082 os << "symbol " << '"'
3083 << convert_command_inset_arg(p.verbatim_item());
3084 os << "\"\ndescription \""
3085 << convert_command_inset_arg(p.verbatim_item())
3090 else if (t.cs() == "label") {
3091 context.check_layout(os);
3092 begin_command_inset(os, "label", "label");
3094 << convert_command_inset_arg(p.verbatim_item())
3099 else if (t.cs() == "printindex") {
3100 context.check_layout(os);
3101 begin_command_inset(os, "index_print", "printindex");
3102 os << "type \"idx\"\n";
3104 skip_spaces_braces(p);
3107 else if (t.cs() == "printnomenclature") {
3109 string width_type = "";
3110 context.check_layout(os);
3111 begin_command_inset(os, "nomencl_print", "printnomenclature");
3112 // case of a custom width
3114 width = p.getArg('[', ']');
3115 width = translate_len(width);
3116 width_type = "custom";
3118 // case of no custom width
3119 // the case of no custom width but the width set
3120 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3121 // because the user could have set anything, not only the width
3122 // of the longest label (which would be width_type = "auto")
3123 string label = convert_command_inset_arg(p.getArg('{', '}'));
3124 if (label.empty() && width_type.empty())
3125 width_type = "none";
3126 os << "set_width \"" << width_type << "\"\n";
3127 if (width_type == "custom")
3128 os << "width \"" << width << '\"';
3130 skip_spaces_braces(p);
3133 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3134 context.check_layout(os);
3135 begin_inset(os, "script ");
3136 os << t.cs().substr(4) << '\n';
3137 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3139 if (t.cs() == "textsubscript")
3140 preamble.registerAutomaticallyLoadedPackage("subscript");
3143 else if (is_known(t.cs(), known_quotes)) {
3144 char const * const * where = is_known(t.cs(), known_quotes);
3145 context.check_layout(os);
3146 begin_inset(os, "Quotes ");
3147 os << known_coded_quotes[where - known_quotes];
3149 // LyX adds {} after the quote, so we have to eat
3150 // spaces here if there are any before a possible
3152 eat_whitespace(p, os, context, false);
3156 else if (is_known(t.cs(), known_sizes) &&
3157 context.new_layout_allowed) {
3158 char const * const * where = is_known(t.cs(), known_sizes);
3159 context.check_layout(os);
3160 TeXFont const oldFont = context.font;
3161 context.font.size = known_coded_sizes[where - known_sizes];
3162 output_font_change(os, oldFont, context.font);
3163 eat_whitespace(p, os, context, false);
3166 else if (is_known(t.cs(), known_font_families) &&
3167 context.new_layout_allowed) {
3168 char const * const * where =
3169 is_known(t.cs(), known_font_families);
3170 context.check_layout(os);
3171 TeXFont const oldFont = context.font;
3172 context.font.family =
3173 known_coded_font_families[where - known_font_families];
3174 output_font_change(os, oldFont, context.font);
3175 eat_whitespace(p, os, context, false);
3178 else if (is_known(t.cs(), known_font_series) &&
3179 context.new_layout_allowed) {
3180 char const * const * where =
3181 is_known(t.cs(), known_font_series);
3182 context.check_layout(os);
3183 TeXFont const oldFont = context.font;
3184 context.font.series =
3185 known_coded_font_series[where - known_font_series];
3186 output_font_change(os, oldFont, context.font);
3187 eat_whitespace(p, os, context, false);
3190 else if (is_known(t.cs(), known_font_shapes) &&
3191 context.new_layout_allowed) {
3192 char const * const * where =
3193 is_known(t.cs(), known_font_shapes);
3194 context.check_layout(os);
3195 TeXFont const oldFont = context.font;
3196 context.font.shape =
3197 known_coded_font_shapes[where - known_font_shapes];
3198 output_font_change(os, oldFont, context.font);
3199 eat_whitespace(p, os, context, false);
3201 else if (is_known(t.cs(), known_old_font_families) &&
3202 context.new_layout_allowed) {
3203 char const * const * where =
3204 is_known(t.cs(), known_old_font_families);
3205 context.check_layout(os);
3206 TeXFont const oldFont = context.font;
3207 context.font.init();
3208 context.font.size = oldFont.size;
3209 context.font.family =
3210 known_coded_font_families[where - known_old_font_families];
3211 output_font_change(os, oldFont, context.font);
3212 eat_whitespace(p, os, context, false);
3215 else if (is_known(t.cs(), known_old_font_series) &&
3216 context.new_layout_allowed) {
3217 char const * const * where =
3218 is_known(t.cs(), known_old_font_series);
3219 context.check_layout(os);
3220 TeXFont const oldFont = context.font;
3221 context.font.init();
3222 context.font.size = oldFont.size;
3223 context.font.series =
3224 known_coded_font_series[where - known_old_font_series];
3225 output_font_change(os, oldFont, context.font);
3226 eat_whitespace(p, os, context, false);
3229 else if (is_known(t.cs(), known_old_font_shapes) &&
3230 context.new_layout_allowed) {
3231 char const * const * where =
3232 is_known(t.cs(), known_old_font_shapes);
3233 context.check_layout(os);
3234 TeXFont const oldFont = context.font;
3235 context.font.init();
3236 context.font.size = oldFont.size;
3237 context.font.shape =
3238 known_coded_font_shapes[where - known_old_font_shapes];
3239 output_font_change(os, oldFont, context.font);
3240 eat_whitespace(p, os, context, false);
3243 else if (t.cs() == "selectlanguage") {
3244 context.check_layout(os);
3245 // save the language for the case that a
3246 // \foreignlanguage is used
3248 context.font.language = babel2lyx(p.verbatim_item());
3249 os << "\n\\lang " << context.font.language << "\n";
3252 else if (t.cs() == "foreignlanguage") {
3253 string const lang = babel2lyx(p.verbatim_item());
3254 parse_text_attributes(p, os, FLAG_ITEM, outer,
3256 context.font.language, lang);
3259 else if (t.cs() == "inputencoding") {
3260 // nothing to write here
3261 string const enc = subst(p.verbatim_item(), "\n", " ");
3265 else if (t.cs() == "ldots") {
3266 context.check_layout(os);
3267 os << "\\SpecialChar \\ldots{}\n";
3268 skip_spaces_braces(p);
3271 else if (t.cs() == "lyxarrow") {
3272 context.check_layout(os);
3273 os << "\\SpecialChar \\menuseparator\n";
3274 skip_spaces_braces(p);
3277 else if (t.cs() == "textcompwordmark") {
3278 context.check_layout(os);
3279 os << "\\SpecialChar \\textcompwordmark{}\n";
3280 skip_spaces_braces(p);
3283 else if (t.cs() == "slash") {
3284 context.check_layout(os);
3285 os << "\\SpecialChar \\slash{}\n";
3286 skip_spaces_braces(p);
3289 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3290 context.check_layout(os);
3291 os << "\\SpecialChar \\nobreakdash-\n";
3295 else if (t.cs() == "textquotedbl") {
3296 context.check_layout(os);
3301 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3302 context.check_layout(os);
3303 os << "\\SpecialChar \\@.\n";
3307 else if (t.cs() == "-") {
3308 context.check_layout(os);
3309 os << "\\SpecialChar \\-\n";
3312 else if (t.cs() == "textasciitilde") {
3313 context.check_layout(os);
3315 skip_spaces_braces(p);
3318 else if (t.cs() == "textasciicircum") {
3319 context.check_layout(os);
3321 skip_spaces_braces(p);
3324 else if (t.cs() == "textbackslash") {
3325 context.check_layout(os);
3326 os << "\n\\backslash\n";
3327 skip_spaces_braces(p);
3330 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3331 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3333 context.check_layout(os);
3337 else if (t.cs() == "char") {
3338 context.check_layout(os);
3339 if (p.next_token().character() == '`') {
3341 if (p.next_token().cs() == "\"") {
3346 handle_ert(os, "\\char`", context);
3349 handle_ert(os, "\\char", context);
3353 else if (t.cs() == "verb") {
3354 context.check_layout(os);
3355 char const delimiter = p.next_token().character();
3356 string const arg = p.getArg(delimiter, delimiter);
3358 oss << "\\verb" << delimiter << arg << delimiter;
3359 handle_ert(os, oss.str(), context);
3362 // Problem: \= creates a tabstop inside the tabbing environment
3363 // and else an accent. In the latter case we really would want
3364 // \={o} instead of \= o.
3365 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3366 handle_ert(os, t.asInput(), context);
3368 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3369 else if (t.cs().size() == 1
3370 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3371 context.check_layout(os);
3372 // try to see whether the string is in unicodesymbols
3374 string command = t.asInput() + "{"
3375 + trimSpaceAndEol(p.verbatim_item())
3377 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3380 cerr << "When parsing " << command
3381 << ", result is " << to_utf8(s)
3382 << "+" << to_utf8(rem) << endl;
3385 // we did not find a non-ert version
3386 handle_ert(os, command, context);
3389 else if (t.cs() == "\\") {
3390 context.check_layout(os);
3392 handle_ert(os, "\\\\" + p.getOpt(), context);
3393 else if (p.next_token().asInput() == "*") {
3395 // getOpt() eats the following space if there
3396 // is no optional argument, but that is OK
3397 // here since it has no effect in the output.
3398 handle_ert(os, "\\\\*" + p.getOpt(), context);
3401 begin_inset(os, "Newline newline");
3406 else if (t.cs() == "newline" ||
3407 (t.cs() == "linebreak" && !p.hasOpt())) {
3408 context.check_layout(os);
3409 begin_inset(os, "Newline ");
3412 skip_spaces_braces(p);
3415 else if (t.cs() == "input" || t.cs() == "include"
3416 || t.cs() == "verbatiminput") {
3417 string name = t.cs();
3418 if (t.cs() == "verbatiminput"
3419 && p.next_token().asInput() == "*")
3420 name += p.get_token().asInput();
3421 context.check_layout(os);
3422 string filename(normalize_filename(p.getArg('{', '}')));
3423 string const path = getMasterFilePath();
3424 // We want to preserve relative / absolute filenames,
3425 // therefore path is only used for testing
3426 if ((t.cs() == "include" || t.cs() == "input") &&
3427 !makeAbsPath(filename, path).exists()) {
3428 // The file extension is probably missing.
3429 // Now try to find it out.
3430 string const tex_name =
3431 find_file(filename, path,
3432 known_tex_extensions);
3433 if (!tex_name.empty())
3434 filename = tex_name;
3436 bool external = false;
3438 if (makeAbsPath(filename, path).exists()) {
3439 string const abstexname =
3440 makeAbsPath(filename, path).absFileName();
3441 string const abslyxname =
3442 changeExtension(abstexname, ".lyx");
3443 string const absfigname =
3444 changeExtension(abstexname, ".fig");
3445 fix_relative_filename(filename);
3446 string const lyxname =
3447 changeExtension(filename, ".lyx");
3449 external = FileName(absfigname).exists();
3450 if (t.cs() == "input") {
3451 string const ext = getExtension(abstexname);
3453 // Combined PS/LaTeX:
3454 // x.eps, x.pstex_t (old xfig)
3455 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3456 FileName const absepsname(
3457 changeExtension(abstexname, ".eps"));
3458 FileName const abspstexname(
3459 changeExtension(abstexname, ".pstex"));
3460 bool const xfigeps =
3461 (absepsname.exists() ||
3462 abspstexname.exists()) &&
3465 // Combined PDF/LaTeX:
3466 // x.pdf, x.pdftex_t (old xfig)
3467 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3468 FileName const abspdfname(
3469 changeExtension(abstexname, ".pdf"));
3470 bool const xfigpdf =
3471 abspdfname.exists() &&
3472 (ext == "pdftex_t" || ext == "pdf_t");
3476 // Combined PS/PDF/LaTeX:
3477 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3478 string const absbase2(
3479 removeExtension(abstexname) + "_pspdftex");
3480 FileName const abseps2name(
3481 addExtension(absbase2, ".eps"));
3482 FileName const abspdf2name(
3483 addExtension(absbase2, ".pdf"));
3484 bool const xfigboth =
3485 abspdf2name.exists() &&
3486 abseps2name.exists() && ext == "pspdftex";
3488 xfig = xfigpdf || xfigeps || xfigboth;
3489 external = external && xfig;
3492 outname = changeExtension(filename, ".fig");
3494 // Don't try to convert, the result
3495 // would be full of ERT.
3497 } else if (t.cs() != "verbatiminput" &&
3498 tex2lyx(abstexname, FileName(abslyxname),
3505 cerr << "Warning: Could not find included file '"
3506 << filename << "'." << endl;
3510 begin_inset(os, "External\n");
3511 os << "\ttemplate XFig\n"
3512 << "\tfilename " << outname << '\n';
3514 begin_command_inset(os, "include", name);
3515 os << "preview false\n"
3516 "filename \"" << outname << "\"\n";
3521 else if (t.cs() == "bibliographystyle") {
3522 // store new bibliographystyle
3523 bibliographystyle = p.verbatim_item();
3524 // If any other command than \bibliography and
3525 // \nocite{*} follows, we need to output the style
3526 // (because it might be used by that command).
3527 // Otherwise, it will automatically be output by LyX.
3530 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3531 if (t2.cat() == catBegin)
3533 if (t2.cat() != catEscape)
3535 if (t2.cs() == "nocite") {
3536 if (p.getArg('{', '}') == "*")
3538 } else if (t2.cs() == "bibliography")
3545 "\\bibliographystyle{" + bibliographystyle + '}',
3550 else if (t.cs() == "bibliography") {
3551 context.check_layout(os);
3552 begin_command_inset(os, "bibtex", "bibtex");
3553 if (!btprint.empty()) {
3554 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3555 // clear the string because the next BibTeX inset can be without the
3556 // \nocite{*} option
3559 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3560 // Do we have a bibliographystyle set?
3561 if (!bibliographystyle.empty())
3562 os << "options " << '"' << bibliographystyle << '"' << "\n";
3566 else if (t.cs() == "parbox") {
3567 // Test whether this is an outer box of a shaded box
3569 // swallow arguments
3570 while (p.hasOpt()) {
3572 p.skip_spaces(true);
3575 p.skip_spaces(true);
3577 if (p.next_token().cat() == catBegin)
3579 p.skip_spaces(true);
3580 Token to = p.get_token();
3581 bool shaded = false;
3582 if (to.asInput() == "\\begin") {
3583 p.skip_spaces(true);
3584 if (p.getArg('{', '}') == "shaded")
3589 parse_outer_box(p, os, FLAG_ITEM, outer,
3590 context, "parbox", "shaded");
3592 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3596 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3597 t.cs() == "shadowbox" || t.cs() == "doublebox")
3598 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3600 else if (t.cs() == "framebox") {
3601 string special = p.getFullOpt();
3602 special += p.getOpt();
3603 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3606 //\makebox() is part of the picture environment and different from \makebox{}
3607 //\makebox{} will be parsed by parse_box
3608 else if (t.cs() == "makebox") {
3609 string arg = t.asInput();
3610 if (p.next_token().character() == '(') {
3611 //the syntax is: \makebox(x,y)[position]{content}
3612 arg += p.getFullParentheseArg();
3613 arg += p.getFullOpt();
3614 eat_whitespace(p, os, context, false);
3615 handle_ert(os, arg + '{', context);
3616 eat_whitespace(p, os, context, false);
3617 parse_text(p, os, FLAG_ITEM, outer, context);
3618 handle_ert(os, "}", context);
3620 //the syntax is: \makebox[width][position]{content}
3621 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3625 else if (t.cs() == "smallskip" ||
3626 t.cs() == "medskip" ||
3627 t.cs() == "bigskip" ||
3628 t.cs() == "vfill") {
3629 context.check_layout(os);
3630 begin_inset(os, "VSpace ");
3633 skip_spaces_braces(p);
3636 else if (is_known(t.cs(), known_spaces)) {
3637 char const * const * where = is_known(t.cs(), known_spaces);
3638 context.check_layout(os);
3639 begin_inset(os, "space ");
3640 os << '\\' << known_coded_spaces[where - known_spaces]
3643 // LaTeX swallows whitespace after all spaces except
3644 // "\\,". We have to do that here, too, because LyX
3645 // adds "{}" which would make the spaces significant.
3647 eat_whitespace(p, os, context, false);
3648 // LyX adds "{}" after all spaces except "\\ " and
3649 // "\\,", so we have to remove "{}".
3650 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3651 // remove the braces after "\\,", too.
3656 else if (t.cs() == "newpage" ||
3657 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3658 t.cs() == "clearpage" ||
3659 t.cs() == "cleardoublepage") {
3660 context.check_layout(os);
3661 begin_inset(os, "Newpage ");
3664 skip_spaces_braces(p);
3667 else if (t.cs() == "DeclareRobustCommand" ||
3668 t.cs() == "DeclareRobustCommandx" ||
3669 t.cs() == "newcommand" ||
3670 t.cs() == "newcommandx" ||
3671 t.cs() == "providecommand" ||
3672 t.cs() == "providecommandx" ||
3673 t.cs() == "renewcommand" ||
3674 t.cs() == "renewcommandx") {
3675 // DeclareRobustCommand, DeclareRobustCommandx,
3676 // providecommand and providecommandx could be handled
3677 // by parse_command(), but we need to call
3678 // add_known_command() here.
3679 string name = t.asInput();
3680 if (p.next_token().asInput() == "*") {
3681 // Starred form. Eat '*'
3685 string const command = p.verbatim_item();
3686 string const opt1 = p.getFullOpt();
3687 string const opt2 = p.getFullOpt();
3688 add_known_command(command, opt1, !opt2.empty());
3689 string const ert = name + '{' + command + '}' +
3691 '{' + p.verbatim_item() + '}';
3693 if (t.cs() == "DeclareRobustCommand" ||
3694 t.cs() == "DeclareRobustCommandx" ||
3695 t.cs() == "providecommand" ||
3696 t.cs() == "providecommandx" ||
3697 name[name.length()-1] == '*')
3698 handle_ert(os, ert, context);
3700 context.check_layout(os);
3701 begin_inset(os, "FormulaMacro");
3707 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3708 // let could be handled by parse_command(),
3709 // but we need to call add_known_command() here.
3710 string ert = t.asInput();
3713 if (p.next_token().cat() == catBegin) {
3714 name = p.verbatim_item();
3715 ert += '{' + name + '}';
3717 name = p.verbatim_item();
3722 if (p.next_token().cat() == catBegin) {
3723 command = p.verbatim_item();
3724 ert += '{' + command + '}';
3726 command = p.verbatim_item();
3729 // If command is known, make name known too, to parse
3730 // its arguments correctly. For this reason we also
3731 // have commands in syntax.default that are hardcoded.
3732 CommandMap::iterator it = known_commands.find(command);
3733 if (it != known_commands.end())
3734 known_commands[t.asInput()] = it->second;
3735 handle_ert(os, ert, context);
3738 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3739 bool starred = false;
3740 if (p.next_token().asInput() == "*") {
3744 string name = t.asInput();
3745 string const length = p.verbatim_item();
3748 bool valid = splitLatexLength(length, valstring, unit);
3749 bool known_hspace = false;
3750 bool known_vspace = false;
3751 bool known_unit = false;
3754 istringstream iss(valstring);
3757 if (t.cs()[0] == 'h') {
3758 if (unit == "\\fill") {
3763 known_hspace = true;
3766 if (unit == "\\smallskipamount") {
3768 known_vspace = true;
3769 } else if (unit == "\\medskipamount") {
3771 known_vspace = true;
3772 } else if (unit == "\\bigskipamount") {
3774 known_vspace = true;
3775 } else if (unit == "\\fill") {
3777 known_vspace = true;
3781 if (!known_hspace && !known_vspace) {
3782 switch (unitFromString(unit)) {
3803 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3804 // Literal horizontal length or known variable
3805 context.check_layout(os);
3806 begin_inset(os, "space ");
3814 if (known_unit && !known_hspace)
3816 << translate_len(length);
3818 } else if (known_unit || known_vspace) {
3819 // Literal vertical length or known variable
3820 context.check_layout(os);
3821 begin_inset(os, "VSpace ");
3829 // LyX can't handle other length variables in Inset VSpace/space
3834 handle_ert(os, name + '{' + unit + '}', context);
3835 else if (value == -1.0)
3836 handle_ert(os, name + "{-" + unit + '}', context);
3838 handle_ert(os, name + '{' + valstring + unit + '}', context);
3840 handle_ert(os, name + '{' + length + '}', context);
3844 // The single '=' is meant here.
3845 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3847 context.check_layout(os);
3848 begin_inset(os, "Flex ");
3849 os << to_utf8(newinsetlayout->name()) << '\n'
3850 << "status collapsed\n";
3851 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3856 // try to see whether the string is in unicodesymbols
3857 // Only use text mode commands, since we are in text mode here,
3858 // and math commands may be invalid (bug 6797)
3860 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3861 rem, Encodings::TEXT_CMD);
3864 cerr << "When parsing " << t.cs()
3865 << ", result is " << to_utf8(s)
3866 << "+" << to_utf8(rem) << endl;
3867 context.check_layout(os);
3869 skip_spaces_braces(p);
3871 //cerr << "#: " << t << " mode: " << mode << endl;
3872 // heuristic: read up to next non-nested space
3874 string s = t.asInput();
3875 string z = p.verbatim_item();
3876 while (p.good() && z != " " && z.size()) {
3877 //cerr << "read: " << z << endl;
3879 z = p.verbatim_item();
3881 cerr << "found ERT: " << s << endl;
3882 handle_ert(os, s + ' ', context);
3885 string name = t.asInput();
3886 if (p.next_token().asInput() == "*") {
3887 // Starred commands like \vspace*{}
3888 p.get_token(); // Eat '*'
3891 if (!parse_command(name, p, os, outer, context))
3892 handle_ert(os, name, context);
3896 if (flags & FLAG_LEAVE) {
3897 flags &= ~FLAG_LEAVE;