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 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1191 eat_whitespace(p, os, parent_context, false);
1192 parent_context.check_layout(os);
1193 begin_inset(os, "Float " + unstarred_name + "\n");
1194 // store the float type for subfloats
1195 // subfloats only work with figures and tables
1196 if (unstarred_name == "figure")
1197 float_type = unstarred_name;
1198 else if (unstarred_name == "table")
1199 float_type = unstarred_name;
1203 os << "placement " << opt << '\n';
1204 os << "wide " << convert<string>(is_starred)
1205 << "\nsideways false"
1206 << "\nstatus open\n\n";
1207 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1209 // We don't need really a new paragraph, but
1210 // we must make sure that the next item gets a \begin_layout.
1211 parent_context.new_paragraph(os);
1213 // the float is parsed thus delete the type
1217 else if (unstarred_name == "sidewaysfigure"
1218 || unstarred_name == "sidewaystable") {
1219 eat_whitespace(p, os, parent_context, false);
1220 parent_context.check_layout(os);
1221 if (unstarred_name == "sidewaysfigure")
1222 begin_inset(os, "Float figure\n");
1224 begin_inset(os, "Float table\n");
1225 os << "wide " << convert<string>(is_starred)
1226 << "\nsideways true"
1227 << "\nstatus open\n\n";
1228 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1230 // We don't need really a new paragraph, but
1231 // we must make sure that the next item gets a \begin_layout.
1232 parent_context.new_paragraph(os);
1236 else if (name == "wrapfigure" || name == "wraptable") {
1237 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1238 eat_whitespace(p, os, parent_context, false);
1239 parent_context.check_layout(os);
1242 string overhang = "0col%";
1245 lines = p.getArg('[', ']');
1246 string const placement = p.getArg('{', '}');
1248 overhang = p.getArg('[', ']');
1249 string const width = p.getArg('{', '}');
1251 if (name == "wrapfigure")
1252 begin_inset(os, "Wrap figure\n");
1254 begin_inset(os, "Wrap table\n");
1255 os << "lines " << lines
1256 << "\nplacement " << placement
1257 << "\noverhang " << lyx::translate_len(overhang)
1258 << "\nwidth " << lyx::translate_len(width)
1259 << "\nstatus open\n\n";
1260 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1262 // We don't need really a new paragraph, but
1263 // we must make sure that the next item gets a \begin_layout.
1264 parent_context.new_paragraph(os);
1268 else if (name == "minipage") {
1269 eat_whitespace(p, os, parent_context, false);
1270 // Test whether this is an outer box of a shaded box
1272 // swallow arguments
1273 while (p.hasOpt()) {
1275 p.skip_spaces(true);
1278 p.skip_spaces(true);
1279 Token t = p.get_token();
1280 bool shaded = false;
1281 if (t.asInput() == "\\begin") {
1282 p.skip_spaces(true);
1283 if (p.getArg('{', '}') == "shaded")
1288 parse_outer_box(p, os, FLAG_END, outer,
1289 parent_context, name, "shaded");
1291 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1296 else if (name == "comment") {
1297 eat_whitespace(p, os, parent_context, false);
1298 parent_context.check_layout(os);
1299 begin_inset(os, "Note Comment\n");
1300 os << "status open\n";
1301 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1304 skip_braces(p); // eat {} that might by set by LyX behind comments
1307 else if (name == "lyxgreyedout") {
1308 eat_whitespace(p, os, parent_context, false);
1309 parent_context.check_layout(os);
1310 begin_inset(os, "Note Greyedout\n");
1311 os << "status open\n";
1312 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1315 if (!preamble.notefontcolor().empty())
1316 preamble.registerAutomaticallyLoadedPackage("color");
1319 else if (name == "framed" || name == "shaded") {
1320 eat_whitespace(p, os, parent_context, false);
1321 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1325 else if (name == "lstlisting") {
1326 eat_whitespace(p, os, parent_context, false);
1327 // FIXME handle listings with parameters
1328 // If this is added, don't forgot to handle the
1329 // automatic color package loading
1331 parse_unknown_environment(p, name, os, FLAG_END,
1332 outer, parent_context);
1334 parse_listings(p, os, parent_context);
1338 else if (!parent_context.new_layout_allowed)
1339 parse_unknown_environment(p, name, os, FLAG_END, outer,
1342 // Alignment and spacing settings
1343 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1344 // therefore are totally broken!
1345 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1346 // they are commands not environments. They are furthermore switches that
1347 // can be ended by another switches, but also by commands like \footnote or
1348 // \parbox. So the only safe way is to leave them untouched.
1349 else if (name == "center" || name == "centering" ||
1350 name == "flushleft" || name == "flushright" ||
1351 name == "singlespace" || name == "onehalfspace" ||
1352 name == "doublespace" || name == "spacing") {
1353 eat_whitespace(p, os, parent_context, false);
1354 // We must begin a new paragraph if not already done
1355 if (! parent_context.atParagraphStart()) {
1356 parent_context.check_end_layout(os);
1357 parent_context.new_paragraph(os);
1359 if (name == "flushleft")
1360 parent_context.add_extra_stuff("\\align left\n");
1361 else if (name == "flushright")
1362 parent_context.add_extra_stuff("\\align right\n");
1363 else if (name == "center" || name == "centering")
1364 parent_context.add_extra_stuff("\\align center\n");
1365 else if (name == "singlespace")
1366 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1367 else if (name == "onehalfspace")
1368 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1369 else if (name == "doublespace")
1370 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1371 else if (name == "spacing")
1372 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1373 parse_text(p, os, FLAG_END, outer, parent_context);
1374 // Just in case the environment is empty
1375 parent_context.extra_stuff.erase();
1376 // We must begin a new paragraph to reset the alignment
1377 parent_context.new_paragraph(os);
1381 // The single '=' is meant here.
1382 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1383 eat_whitespace(p, os, parent_context, false);
1384 Context context(true, parent_context.textclass, newlayout,
1385 parent_context.layout, parent_context.font);
1386 if (parent_context.deeper_paragraph) {
1387 // We are beginning a nested environment after a
1388 // deeper paragraph inside the outer list environment.
1389 // Therefore we don't need to output a "begin deeper".
1390 context.need_end_deeper = true;
1392 parent_context.check_end_layout(os);
1393 if (last_env == name) {
1394 // we need to output a separator since LyX would export
1395 // the two environments as one otherwise (bug 5716)
1396 docstring const sep = from_ascii("--Separator--");
1397 TeX2LyXDocClass const & textclass(parent_context.textclass);
1398 if (textclass.hasLayout(sep)) {
1399 Context newcontext(parent_context);
1400 newcontext.layout = &(textclass[sep]);
1401 newcontext.check_layout(os);
1402 newcontext.check_end_layout(os);
1404 parent_context.check_layout(os);
1405 begin_inset(os, "Note Note\n");
1406 os << "status closed\n";
1407 Context newcontext(true, textclass,
1408 &(textclass.defaultLayout()));
1409 newcontext.check_layout(os);
1410 newcontext.check_end_layout(os);
1412 parent_context.check_end_layout(os);
1415 switch (context.layout->latextype) {
1416 case LATEX_LIST_ENVIRONMENT:
1417 context.add_par_extra_stuff("\\labelwidthstring "
1418 + p.verbatim_item() + '\n');
1421 case LATEX_BIB_ENVIRONMENT:
1422 p.verbatim_item(); // swallow next arg
1428 context.check_deeper(os);
1429 // handle known optional and required arguments
1430 // layouts require all optional arguments before the required ones
1431 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1432 // It is impossible to place anything after the environment name,
1433 // but before the first \\item.
1434 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1435 bool need_layout = true;
1436 unsigned int optargs = 0;
1437 while (optargs < context.layout->optargs) {
1438 eat_whitespace(p, os, context, false);
1439 if (p.next_token().cat() == catEscape ||
1440 p.next_token().character() != '[')
1442 p.get_token(); // eat '['
1444 context.check_layout(os);
1445 need_layout = false;
1447 begin_inset(os, "Argument\n");
1448 os << "status collapsed\n\n";
1449 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1451 eat_whitespace(p, os, context, false);
1454 unsigned int reqargs = 0;
1455 while (reqargs < context.layout->reqargs) {
1456 eat_whitespace(p, os, context, false);
1457 if (p.next_token().cat() != catBegin)
1459 p.get_token(); // eat '{'
1461 context.check_layout(os);
1462 need_layout = false;
1464 begin_inset(os, "Argument\n");
1465 os << "status collapsed\n\n";
1466 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1468 eat_whitespace(p, os, context, false);
1472 parse_text(p, os, FLAG_END, outer, context);
1473 context.check_end_layout(os);
1474 if (parent_context.deeper_paragraph) {
1475 // We must suppress the "end deeper" because we
1476 // suppressed the "begin deeper" above.
1477 context.need_end_deeper = false;
1479 context.check_end_deeper(os);
1480 parent_context.new_paragraph(os);
1482 if (!title_layout_found)
1483 title_layout_found = newlayout->intitle;
1486 // The single '=' is meant here.
1487 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1488 eat_whitespace(p, os, parent_context, false);
1489 parent_context.check_layout(os);
1490 begin_inset(os, "Flex ");
1491 os << to_utf8(newinsetlayout->name()) << '\n'
1492 << "status collapsed\n";
1493 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1497 else if (name == "appendix") {
1498 // This is no good latex style, but it works and is used in some documents...
1499 eat_whitespace(p, os, parent_context, false);
1500 parent_context.check_end_layout(os);
1501 Context context(true, parent_context.textclass, parent_context.layout,
1502 parent_context.layout, parent_context.font);
1503 context.check_layout(os);
1504 os << "\\start_of_appendix\n";
1505 parse_text(p, os, FLAG_END, outer, context);
1506 context.check_end_layout(os);
1510 else if (known_environments.find(name) != known_environments.end()) {
1511 vector<ArgumentType> arguments = known_environments[name];
1512 // The last "argument" denotes wether we may translate the
1513 // environment contents to LyX
1514 // The default required if no argument is given makes us
1515 // compatible with the reLyXre environment.
1516 ArgumentType contents = arguments.empty() ?
1519 if (!arguments.empty())
1520 arguments.pop_back();
1521 // See comment in parse_unknown_environment()
1522 bool const specialfont =
1523 (parent_context.font != parent_context.normalfont);
1524 bool const new_layout_allowed =
1525 parent_context.new_layout_allowed;
1527 parent_context.new_layout_allowed = false;
1528 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1529 outer, parent_context);
1530 if (contents == verbatim)
1531 handle_ert(os, p.verbatimEnvironment(name),
1534 parse_text_snippet(p, os, FLAG_END, outer,
1536 handle_ert(os, "\\end{" + name + "}", parent_context);
1538 parent_context.new_layout_allowed = new_layout_allowed;
1542 parse_unknown_environment(p, name, os, FLAG_END, outer,
1546 active_environments.pop_back();
1550 /// parses a comment and outputs it to \p os.
1551 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1553 LASSERT(t.cat() == catComment, return);
1554 if (!t.cs().empty()) {
1555 context.check_layout(os);
1556 handle_comment(os, '%' + t.cs(), context);
1557 if (p.next_token().cat() == catNewline) {
1558 // A newline after a comment line starts a new
1560 if (context.new_layout_allowed) {
1561 if(!context.atParagraphStart())
1562 // Only start a new paragraph if not already
1563 // done (we might get called recursively)
1564 context.new_paragraph(os);
1566 handle_ert(os, "\n", context);
1567 eat_whitespace(p, os, context, true);
1570 // "%\n" combination
1577 * Reads spaces and comments until the first non-space, non-comment token.
1578 * New paragraphs (double newlines or \\par) are handled like simple spaces
1579 * if \p eatParagraph is true.
1580 * Spaces are skipped, but comments are written to \p os.
1582 void eat_whitespace(Parser & p, ostream & os, Context & context,
1586 Token const & t = p.get_token();
1587 if (t.cat() == catComment)
1588 parse_comment(p, os, t, context);
1589 else if ((! eatParagraph && p.isParagraph()) ||
1590 (t.cat() != catSpace && t.cat() != catNewline)) {
1599 * Set a font attribute, parse text and reset the font attribute.
1600 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1601 * \param currentvalue Current value of the attribute. Is set to the new
1602 * value during parsing.
1603 * \param newvalue New value of the attribute
1605 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1606 Context & context, string const & attribute,
1607 string & currentvalue, string const & newvalue)
1609 context.check_layout(os);
1610 string const oldvalue = currentvalue;
1611 currentvalue = newvalue;
1612 os << '\n' << attribute << ' ' << newvalue << "\n";
1613 parse_text_snippet(p, os, flags, outer, context);
1614 context.check_layout(os);
1615 os << '\n' << attribute << ' ' << oldvalue << "\n";
1616 currentvalue = oldvalue;
1620 /// get the arguments of a natbib or jurabib citation command
1621 void get_cite_arguments(Parser & p, bool natbibOrder,
1622 string & before, string & after)
1624 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1626 // text before the citation
1628 // text after the citation
1629 after = p.getFullOpt();
1631 if (!after.empty()) {
1632 before = p.getFullOpt();
1633 if (natbibOrder && !before.empty())
1634 swap(before, after);
1639 /// Convert filenames with TeX macros and/or quotes to something LyX
1641 string const normalize_filename(string const & name)
1643 Parser p(trim(name, "\""));
1646 Token const & t = p.get_token();
1647 if (t.cat() != catEscape)
1649 else if (t.cs() == "lyxdot") {
1650 // This is used by LyX for simple dots in relative
1654 } else if (t.cs() == "space") {
1664 /// Convert \p name from TeX convention (relative to master file) to LyX
1665 /// convention (relative to .lyx file) if it is relative
1666 void fix_relative_filename(string & name)
1668 if (FileName::isAbsolute(name))
1671 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1672 from_utf8(getParentFilePath())));
1676 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1677 void parse_noweb(Parser & p, ostream & os, Context & context)
1679 // assemble the rest of the keyword
1683 Token const & t = p.get_token();
1684 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1687 scrap = (p.good() && p.next_token().asInput() == "=");
1689 name += p.get_token().asInput();
1692 name += t.asInput();
1695 if (!scrap || !context.new_layout_allowed ||
1696 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1697 cerr << "Warning: Could not interpret '" << name
1698 << "'. Ignoring it." << endl;
1702 // We use new_paragraph instead of check_end_layout because the stuff
1703 // following the noweb chunk needs to start with a \begin_layout.
1704 // This may create a new paragraph even if there was none in the
1705 // noweb file, but the alternative is an invalid LyX file. Since
1706 // noweb code chunks are implemented with a layout style in LyX they
1707 // always must be in an own paragraph.
1708 context.new_paragraph(os);
1709 Context newcontext(true, context.textclass,
1710 &context.textclass[from_ascii("Scrap")]);
1711 newcontext.check_layout(os);
1714 Token const & t = p.get_token();
1715 // We abuse the parser a bit, because this is no TeX syntax
1717 if (t.cat() == catEscape)
1718 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1721 Context tmp(false, context.textclass,
1722 &context.textclass[from_ascii("Scrap")]);
1723 tmp.need_end_layout = true;
1724 tmp.check_layout(oss);
1725 os << subst(t.asInput(), "\n", oss.str());
1727 // The scrap chunk is ended by an @ at the beginning of a line.
1728 // After the @ the line may contain a comment and/or
1729 // whitespace, but nothing else.
1730 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1731 (p.next_token().cat() == catSpace ||
1732 p.next_token().cat() == catNewline ||
1733 p.next_token().cat() == catComment)) {
1734 while (p.good() && p.next_token().cat() == catSpace)
1735 os << p.get_token().asInput();
1736 if (p.next_token().cat() == catComment)
1737 // The comment includes a final '\n'
1738 os << p.get_token().asInput();
1740 if (p.next_token().cat() == catNewline)
1747 newcontext.check_end_layout(os);
1751 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1752 bool is_macro(Parser & p)
1754 Token first = p.curr_token();
1755 if (first.cat() != catEscape || !p.good())
1757 if (first.cs() == "def")
1759 if (first.cs() != "global" && first.cs() != "long")
1761 Token second = p.get_token();
1763 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1764 second.cat() == catNewline || second.cat() == catComment)) {
1765 second = p.get_token();
1768 bool secondvalid = second.cat() == catEscape;
1770 bool thirdvalid = false;
1771 if (p.good() && first.cs() == "global" && secondvalid &&
1772 second.cs() == "long") {
1773 third = p.get_token();
1775 while (p.good() && !p.isParagraph() &&
1776 (third.cat() == catSpace ||
1777 third.cat() == catNewline ||
1778 third.cat() == catComment)) {
1779 third = p.get_token();
1782 thirdvalid = third.cat() == catEscape;
1784 for (int i = 0; i < pos; ++i)
1789 return (first.cs() == "global" || first.cs() == "long") &&
1790 second.cs() == "def";
1791 return first.cs() == "global" && second.cs() == "long" &&
1792 third.cs() == "def";
1796 /// Parse a macro definition (assumes that is_macro() returned true)
1797 void parse_macro(Parser & p, ostream & os, Context & context)
1799 context.check_layout(os);
1800 Token first = p.curr_token();
1803 string command = first.asInput();
1804 if (first.cs() != "def") {
1806 eat_whitespace(p, os, context, false);
1807 second = p.curr_token();
1808 command += second.asInput();
1809 if (second.cs() != "def") {
1811 eat_whitespace(p, os, context, false);
1812 third = p.curr_token();
1813 command += third.asInput();
1816 eat_whitespace(p, os, context, false);
1817 string const name = p.get_token().cs();
1818 eat_whitespace(p, os, context, false);
1824 while (p.next_token().cat() != catBegin) {
1825 if (p.next_token().cat() == catParameter) {
1830 // followed by number?
1831 if (p.next_token().cat() == catOther) {
1832 char c = p.getChar();
1834 // number = current arity + 1?
1835 if (c == arity + '0' + 1)
1840 paramtext += p.get_token().cs();
1842 paramtext += p.get_token().cs();
1847 // only output simple (i.e. compatible) macro as FormulaMacros
1848 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1850 context.check_layout(os);
1851 begin_inset(os, "FormulaMacro");
1852 os << "\n\\def" << ert;
1855 handle_ert(os, command + ert, context);
1858 } // anonymous namespace
1861 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1864 Layout const * newlayout = 0;
1865 InsetLayout const * newinsetlayout = 0;
1866 // Store the latest bibliographystyle and nocite{*} option
1867 // (needed for bibtex inset)
1869 string bibliographystyle;
1870 bool const use_natbib = preamble.isPackageUsed("natbib");
1871 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1873 bool title_layout_found = false;
1875 Token const & t = p.get_token();
1878 debugToken(cerr, t, flags);
1881 if (flags & FLAG_ITEM) {
1882 if (t.cat() == catSpace)
1885 flags &= ~FLAG_ITEM;
1886 if (t.cat() == catBegin) {
1887 // skip the brace and collect everything to the next matching
1889 flags |= FLAG_BRACE_LAST;
1893 // handle only this single token, leave the loop if done
1894 flags |= FLAG_LEAVE;
1897 if (t.cat() != catEscape && t.character() == ']' &&
1898 (flags & FLAG_BRACK_LAST))
1900 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1903 // If there is anything between \end{env} and \begin{env} we
1904 // don't need to output a separator.
1905 if (t.cat() != catSpace && t.cat() != catNewline &&
1906 t.asInput() != "\\begin")
1912 if (t.cat() == catMath) {
1913 // we are inside some text mode thingy, so opening new math is allowed
1914 context.check_layout(os);
1915 begin_inset(os, "Formula ");
1916 Token const & n = p.get_token();
1917 bool const display(n.cat() == catMath && outer);
1919 // TeX's $$...$$ syntax for displayed math
1921 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1923 p.get_token(); // skip the second '$' token
1925 // simple $...$ stuff
1928 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1933 // Prevent the conversion of a line break to a
1934 // space (bug 7668). This does not change the
1935 // output, but looks ugly in LyX.
1936 eat_whitespace(p, os, context, false);
1940 else if (t.cat() == catSuper || t.cat() == catSub)
1941 cerr << "catcode " << t << " illegal in text mode\n";
1943 // Basic support for english quotes. This should be
1944 // extended to other quotes, but is not so easy (a
1945 // left english quote is the same as a right german
1947 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1948 context.check_layout(os);
1949 begin_inset(os, "Quotes ");
1955 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1956 context.check_layout(os);
1957 begin_inset(os, "Quotes ");
1964 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1965 context.check_layout(os);
1966 begin_inset(os, "Quotes ");
1973 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1974 context.check_layout(os);
1975 begin_inset(os, "Quotes ");
1982 else if (t.asInput() == "<"
1983 && p.next_token().asInput() == "<" && noweb_mode) {
1985 parse_noweb(p, os, context);
1988 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1989 check_space(p, os, context);
1991 else if (t.character() == '[' && noweb_mode &&
1992 p.next_token().character() == '[') {
1993 // These can contain underscores
1995 string const s = p.getFullOpt() + ']';
1996 if (p.next_token().character() == ']')
1999 cerr << "Warning: Inserting missing ']' in '"
2000 << s << "'." << endl;
2001 handle_ert(os, s, context);
2004 else if (t.cat() == catLetter) {
2005 context.check_layout(os);
2006 // Workaround for bug 4752.
2007 // FIXME: This whole code block needs to be removed
2008 // when the bug is fixed and tex2lyx produces
2009 // the updated file format.
2010 // The replacement algorithm in LyX is so stupid that
2011 // it even translates a phrase if it is part of a word.
2012 bool handled = false;
2013 for (int const * l = known_phrase_lengths; *l; ++l) {
2014 string phrase = t.cs();
2015 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2016 phrase += p.get_token().cs();
2017 if (is_known(phrase, known_coded_phrases)) {
2018 handle_ert(os, phrase, context);
2022 for (size_t i = 1; i < phrase.length(); ++i)
2030 else if (t.cat() == catOther ||
2031 t.cat() == catAlign ||
2032 t.cat() == catParameter) {
2033 // This translates "&" to "\\&" which may be wrong...
2034 context.check_layout(os);
2038 else if (p.isParagraph()) {
2039 if (context.new_layout_allowed)
2040 context.new_paragraph(os);
2042 handle_ert(os, "\\par ", context);
2043 eat_whitespace(p, os, context, true);
2046 else if (t.cat() == catActive) {
2047 context.check_layout(os);
2048 if (t.character() == '~') {
2049 if (context.layout->free_spacing)
2052 begin_inset(os, "space ~\n");
2059 else if (t.cat() == catBegin &&
2060 p.next_token().cat() == catEnd) {
2062 Token const prev = p.prev_token();
2064 if (p.next_token().character() == '`' ||
2065 (prev.character() == '-' &&
2066 p.next_token().character() == '-'))
2067 ; // ignore it in {}`` or -{}-
2069 handle_ert(os, "{}", context);
2073 else if (t.cat() == catBegin) {
2074 context.check_layout(os);
2075 // special handling of font attribute changes
2076 Token const prev = p.prev_token();
2077 Token const next = p.next_token();
2078 TeXFont const oldFont = context.font;
2079 if (next.character() == '[' ||
2080 next.character() == ']' ||
2081 next.character() == '*') {
2083 if (p.next_token().cat() == catEnd) {
2088 handle_ert(os, "{", context);
2089 parse_text_snippet(p, os,
2092 handle_ert(os, "}", context);
2094 } else if (! context.new_layout_allowed) {
2095 handle_ert(os, "{", context);
2096 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2098 handle_ert(os, "}", context);
2099 } else if (is_known(next.cs(), known_sizes)) {
2100 // next will change the size, so we must
2102 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2104 if (!context.atParagraphStart())
2106 << context.font.size << "\n";
2107 } else if (is_known(next.cs(), known_font_families)) {
2108 // next will change the font family, so we
2109 // must reset it here
2110 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2112 if (!context.atParagraphStart())
2114 << context.font.family << "\n";
2115 } else if (is_known(next.cs(), known_font_series)) {
2116 // next will change the font series, so we
2117 // must reset it here
2118 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2120 if (!context.atParagraphStart())
2122 << context.font.series << "\n";
2123 } else if (is_known(next.cs(), known_font_shapes)) {
2124 // next will change the font shape, so we
2125 // must reset it here
2126 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2128 if (!context.atParagraphStart())
2130 << context.font.shape << "\n";
2131 } else if (is_known(next.cs(), known_old_font_families) ||
2132 is_known(next.cs(), known_old_font_series) ||
2133 is_known(next.cs(), known_old_font_shapes)) {
2134 // next will change the font family, series
2135 // and shape, so we must reset it here
2136 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2138 if (!context.atParagraphStart())
2140 << context.font.family
2142 << context.font.series
2144 << context.font.shape << "\n";
2146 handle_ert(os, "{", context);
2147 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2149 handle_ert(os, "}", context);
2153 else if (t.cat() == catEnd) {
2154 if (flags & FLAG_BRACE_LAST) {
2157 cerr << "stray '}' in text\n";
2158 handle_ert(os, "}", context);
2161 else if (t.cat() == catComment)
2162 parse_comment(p, os, t, context);
2165 // control sequences
2168 else if (t.cs() == "(") {
2169 context.check_layout(os);
2170 begin_inset(os, "Formula");
2172 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2177 else if (t.cs() == "[") {
2178 context.check_layout(os);
2179 begin_inset(os, "Formula");
2181 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2184 // Prevent the conversion of a line break to a space
2185 // (bug 7668). This does not change the output, but
2186 // looks ugly in LyX.
2187 eat_whitespace(p, os, context, false);
2190 else if (t.cs() == "begin")
2191 parse_environment(p, os, outer, last_env,
2192 title_layout_found, context);
2194 else if (t.cs() == "end") {
2195 if (flags & FLAG_END) {
2196 // eat environment name
2197 string const name = p.getArg('{', '}');
2198 if (name != active_environment())
2199 cerr << "\\end{" + name + "} does not match \\begin{"
2200 + active_environment() + "}\n";
2203 p.error("found 'end' unexpectedly");
2206 else if (t.cs() == "item") {
2208 bool const optarg = p.hasOpt();
2210 // FIXME: This swallows comments, but we cannot use
2211 // eat_whitespace() since we must not output
2212 // anything before the item.
2213 s = p.getArg('[', ']');
2215 p.skip_spaces(false);
2217 context.check_layout(os);
2218 if (context.has_item) {
2219 // An item in an unknown list-like environment
2220 // FIXME: Do this in check_layout()!
2221 context.has_item = false;
2223 handle_ert(os, "\\item", context);
2225 handle_ert(os, "\\item ", context);
2228 if (context.layout->labeltype != LABEL_MANUAL) {
2229 // LyX does not support \item[\mybullet]
2230 // in itemize environments
2232 os << parse_text_snippet(p2,
2233 FLAG_BRACK_LAST, outer, context);
2234 } else if (!s.empty()) {
2235 // LyX adds braces around the argument,
2236 // so we need to remove them here.
2237 if (s.size() > 2 && s[0] == '{' &&
2238 s[s.size()-1] == '}')
2239 s = s.substr(1, s.size()-2);
2240 // If the argument contains a space we
2241 // must put it into ERT: Otherwise LyX
2242 // would misinterpret the space as
2243 // item delimiter (bug 7663)
2244 if (contains(s, ' ')) {
2245 handle_ert(os, s, context);
2248 os << parse_text_snippet(p2,
2252 // The space is needed to separate the
2253 // item from the rest of the sentence.
2255 eat_whitespace(p, os, context, false);
2260 else if (t.cs() == "bibitem") {
2262 context.check_layout(os);
2263 string label = convert_command_inset_arg(p.getArg('[', ']'));
2264 string key = convert_command_inset_arg(p.verbatim_item());
2265 if (contains(label, '\\') || contains(key, '\\')) {
2266 // LyX can't handle LaTeX commands in labels or keys
2267 handle_ert(os, t.asInput() + '[' + label +
2268 "]{" + p.verbatim_item() + '}',
2271 begin_command_inset(os, "bibitem", "bibitem");
2272 os << "label \"" << label << "\"\n"
2273 "key \"" << key << "\"\n";
2278 else if (is_macro(p))
2279 parse_macro(p, os, context);
2281 else if (t.cs() == "noindent") {
2283 context.add_par_extra_stuff("\\noindent\n");
2286 else if (t.cs() == "appendix") {
2287 context.add_par_extra_stuff("\\start_of_appendix\n");
2288 // We need to start a new paragraph. Otherwise the
2289 // appendix in 'bla\appendix\chapter{' would start
2291 context.new_paragraph(os);
2292 // We need to make sure that the paragraph is
2293 // generated even if it is empty. Otherwise the
2294 // appendix in '\par\appendix\par\chapter{' would
2296 context.check_layout(os);
2297 // FIXME: This is a hack to prevent paragraph
2298 // deletion if it is empty. Handle this better!
2300 "%dummy comment inserted by tex2lyx to "
2301 "ensure that this paragraph is not empty",
2303 // Both measures above may generate an additional
2304 // empty paragraph, but that does not hurt, because
2305 // whitespace does not matter here.
2306 eat_whitespace(p, os, context, true);
2309 // Must catch empty dates before findLayout is called below
2310 else if (t.cs() == "date") {
2311 string const date = p.verbatim_item();
2313 preamble.suppressDate(true);
2315 preamble.suppressDate(false);
2316 if (context.new_layout_allowed &&
2317 (newlayout = findLayout(context.textclass,
2320 output_command_layout(os, p, outer,
2321 context, newlayout);
2323 if (!title_layout_found)
2324 title_layout_found = newlayout->intitle;
2326 handle_ert(os, "\\date{" + date + '}',
2331 // Starred section headings
2332 // Must attempt to parse "Section*" before "Section".
2333 else if ((p.next_token().asInput() == "*") &&
2334 context.new_layout_allowed &&
2335 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2338 output_command_layout(os, p, outer, context, newlayout);
2340 if (!title_layout_found)
2341 title_layout_found = newlayout->intitle;
2344 // Section headings and the like
2345 else if (context.new_layout_allowed &&
2346 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2348 output_command_layout(os, p, outer, context, newlayout);
2350 if (!title_layout_found)
2351 title_layout_found = newlayout->intitle;
2354 else if (t.cs() == "caption") {
2356 context.check_layout(os);
2358 begin_inset(os, "Caption\n");
2359 Context newcontext(true, context.textclass);
2360 newcontext.font = context.font;
2361 newcontext.check_layout(os);
2362 if (p.next_token().cat() != catEscape &&
2363 p.next_token().character() == '[') {
2364 p.get_token(); // eat '['
2365 begin_inset(os, "Argument\n");
2366 os << "status collapsed\n";
2367 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2369 eat_whitespace(p, os, context, false);
2371 parse_text(p, os, FLAG_ITEM, outer, context);
2372 context.check_end_layout(os);
2373 // We don't need really a new paragraph, but
2374 // we must make sure that the next item gets a \begin_layout.
2375 context.new_paragraph(os);
2378 newcontext.check_end_layout(os);
2381 else if (t.cs() == "subfloat") {
2382 // the syntax is \subfloat[caption]{content}
2383 // if it is a table of figure depends on the surrounding float
2384 bool has_caption = false;
2386 // do nothing if there is no outer float
2387 if (!float_type.empty()) {
2388 context.check_layout(os);
2390 begin_inset(os, "Float " + float_type + "\n");
2392 << "\nsideways false"
2393 << "\nstatus collapsed\n\n";
2396 if (p.next_token().cat() != catEscape &&
2397 p.next_token().character() == '[') {
2398 p.get_token(); // eat '['
2399 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2403 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2404 // the caption comes always as the last
2406 // we must make sure that the caption gets a \begin_layout
2407 os << "\n\\begin_layout Plain Layout";
2409 begin_inset(os, "Caption\n");
2410 Context newcontext(true, context.textclass);
2411 newcontext.font = context.font;
2412 newcontext.check_layout(os);
2413 os << caption << "\n";
2414 newcontext.check_end_layout(os);
2415 // We don't need really a new paragraph, but
2416 // we must make sure that the next item gets a \begin_layout.
2417 //newcontext.new_paragraph(os);
2421 // We don't need really a new paragraph, but
2422 // we must make sure that the next item gets a \begin_layout.
2424 context.new_paragraph(os);
2427 context.check_end_layout(os);
2428 // close the layout we opened
2430 os << "\n\\end_layout\n";
2432 // if the float type is not supported or there is no surrounding float
2435 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2436 handle_ert(os, t.asInput() + '[' + opt_arg +
2437 "]{" + p.verbatim_item() + '}', context);
2439 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2443 else if (t.cs() == "includegraphics") {
2444 bool const clip = p.next_token().asInput() == "*";
2447 string const arg = p.getArg('[', ']');
2448 map<string, string> opts;
2449 vector<string> keys;
2450 split_map(arg, opts, keys);
2452 opts["clip"] = string();
2453 string name = normalize_filename(p.verbatim_item());
2455 string const path = getMasterFilePath();
2456 // We want to preserve relative / absolute filenames,
2457 // therefore path is only used for testing
2458 if (!makeAbsPath(name, path).exists()) {
2459 // The file extension is probably missing.
2460 // Now try to find it out.
2461 string const dvips_name =
2462 find_file(name, path,
2463 known_dvips_graphics_formats);
2464 string const pdftex_name =
2465 find_file(name, path,
2466 known_pdftex_graphics_formats);
2467 if (!dvips_name.empty()) {
2468 if (!pdftex_name.empty()) {
2469 cerr << "This file contains the "
2471 "\"\\includegraphics{"
2473 "However, files\n\""
2474 << dvips_name << "\" and\n\""
2475 << pdftex_name << "\"\n"
2476 "both exist, so I had to make a "
2477 "choice and took the first one.\n"
2478 "Please move the unwanted one "
2479 "someplace else and try again\n"
2480 "if my choice was wrong."
2484 } else if (!pdftex_name.empty()) {
2490 if (makeAbsPath(name, path).exists())
2491 fix_relative_filename(name);
2493 cerr << "Warning: Could not find graphics file '"
2494 << name << "'." << endl;
2496 context.check_layout(os);
2497 begin_inset(os, "Graphics ");
2498 os << "\n\tfilename " << name << '\n';
2499 if (opts.find("width") != opts.end())
2501 << translate_len(opts["width"]) << '\n';
2502 if (opts.find("height") != opts.end())
2504 << translate_len(opts["height"]) << '\n';
2505 if (opts.find("scale") != opts.end()) {
2506 istringstream iss(opts["scale"]);
2510 os << "\tscale " << val << '\n';
2512 if (opts.find("angle") != opts.end()) {
2513 os << "\trotateAngle "
2514 << opts["angle"] << '\n';
2515 vector<string>::const_iterator a =
2516 find(keys.begin(), keys.end(), "angle");
2517 vector<string>::const_iterator s =
2518 find(keys.begin(), keys.end(), "width");
2519 if (s == keys.end())
2520 s = find(keys.begin(), keys.end(), "height");
2521 if (s == keys.end())
2522 s = find(keys.begin(), keys.end(), "scale");
2523 if (s != keys.end() && distance(s, a) > 0)
2524 os << "\tscaleBeforeRotation\n";
2526 if (opts.find("origin") != opts.end()) {
2528 string const opt = opts["origin"];
2529 if (opt.find('l') != string::npos) ss << "left";
2530 if (opt.find('r') != string::npos) ss << "right";
2531 if (opt.find('c') != string::npos) ss << "center";
2532 if (opt.find('t') != string::npos) ss << "Top";
2533 if (opt.find('b') != string::npos) ss << "Bottom";
2534 if (opt.find('B') != string::npos) ss << "Baseline";
2535 if (!ss.str().empty())
2536 os << "\trotateOrigin " << ss.str() << '\n';
2538 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2540 if (opts.find("keepaspectratio") != opts.end())
2541 os << "\tkeepAspectRatio\n";
2542 if (opts.find("clip") != opts.end())
2544 if (opts.find("draft") != opts.end())
2546 if (opts.find("bb") != opts.end())
2547 os << "\tBoundingBox "
2548 << opts["bb"] << '\n';
2549 int numberOfbbOptions = 0;
2550 if (opts.find("bbllx") != opts.end())
2551 numberOfbbOptions++;
2552 if (opts.find("bblly") != opts.end())
2553 numberOfbbOptions++;
2554 if (opts.find("bburx") != opts.end())
2555 numberOfbbOptions++;
2556 if (opts.find("bbury") != opts.end())
2557 numberOfbbOptions++;
2558 if (numberOfbbOptions == 4)
2559 os << "\tBoundingBox "
2560 << opts["bbllx"] << " " << opts["bblly"] << " "
2561 << opts["bburx"] << " " << opts["bbury"] << '\n';
2562 else if (numberOfbbOptions > 0)
2563 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2564 numberOfbbOptions = 0;
2565 if (opts.find("natwidth") != opts.end())
2566 numberOfbbOptions++;
2567 if (opts.find("natheight") != opts.end())
2568 numberOfbbOptions++;
2569 if (numberOfbbOptions == 2)
2570 os << "\tBoundingBox 0bp 0bp "
2571 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2572 else if (numberOfbbOptions > 0)
2573 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2574 ostringstream special;
2575 if (opts.find("hiresbb") != opts.end())
2576 special << "hiresbb,";
2577 if (opts.find("trim") != opts.end())
2579 if (opts.find("viewport") != opts.end())
2580 special << "viewport=" << opts["viewport"] << ',';
2581 if (opts.find("totalheight") != opts.end())
2582 special << "totalheight=" << opts["totalheight"] << ',';
2583 if (opts.find("type") != opts.end())
2584 special << "type=" << opts["type"] << ',';
2585 if (opts.find("ext") != opts.end())
2586 special << "ext=" << opts["ext"] << ',';
2587 if (opts.find("read") != opts.end())
2588 special << "read=" << opts["read"] << ',';
2589 if (opts.find("command") != opts.end())
2590 special << "command=" << opts["command"] << ',';
2591 string s_special = special.str();
2592 if (!s_special.empty()) {
2593 // We had special arguments. Remove the trailing ','.
2594 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2596 // TODO: Handle the unknown settings better.
2597 // Warn about invalid options.
2598 // Check whether some option was given twice.
2602 else if (t.cs() == "footnote" ||
2603 (t.cs() == "thanks" && context.layout->intitle)) {
2605 context.check_layout(os);
2606 begin_inset(os, "Foot\n");
2607 os << "status collapsed\n\n";
2608 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2612 else if (t.cs() == "marginpar") {
2614 context.check_layout(os);
2615 begin_inset(os, "Marginal\n");
2616 os << "status collapsed\n\n";
2617 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2621 else if (t.cs() == "ensuremath") {
2623 context.check_layout(os);
2624 string const s = p.verbatim_item();
2625 //FIXME: this never triggers in UTF8
2626 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2629 handle_ert(os, "\\ensuremath{" + s + "}",
2633 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2634 if (title_layout_found) {
2636 skip_spaces_braces(p);
2638 handle_ert(os, t.asInput(), context);
2641 else if (t.cs() == "tableofcontents") {
2642 context.check_layout(os);
2643 begin_command_inset(os, "toc", "tableofcontents");
2645 skip_spaces_braces(p);
2648 else if (t.cs() == "listoffigures") {
2649 context.check_layout(os);
2650 begin_inset(os, "FloatList figure\n");
2652 skip_spaces_braces(p);
2655 else if (t.cs() == "listoftables") {
2656 context.check_layout(os);
2657 begin_inset(os, "FloatList table\n");
2659 skip_spaces_braces(p);
2662 else if (t.cs() == "listof") {
2663 p.skip_spaces(true);
2664 string const name = p.get_token().cs();
2665 if (context.textclass.floats().typeExist(name)) {
2666 context.check_layout(os);
2667 begin_inset(os, "FloatList ");
2670 p.get_token(); // swallow second arg
2672 handle_ert(os, "\\listof{" + name + "}", context);
2675 else if (t.cs() == "textrm")
2676 parse_text_attributes(p, os, FLAG_ITEM, outer,
2677 context, "\\family",
2678 context.font.family, "roman");
2680 else if (t.cs() == "textsf")
2681 parse_text_attributes(p, os, FLAG_ITEM, outer,
2682 context, "\\family",
2683 context.font.family, "sans");
2685 else if (t.cs() == "texttt")
2686 parse_text_attributes(p, os, FLAG_ITEM, outer,
2687 context, "\\family",
2688 context.font.family, "typewriter");
2690 else if (t.cs() == "textmd")
2691 parse_text_attributes(p, os, FLAG_ITEM, outer,
2692 context, "\\series",
2693 context.font.series, "medium");
2695 else if (t.cs() == "textbf")
2696 parse_text_attributes(p, os, FLAG_ITEM, outer,
2697 context, "\\series",
2698 context.font.series, "bold");
2700 else if (t.cs() == "textup")
2701 parse_text_attributes(p, os, FLAG_ITEM, outer,
2703 context.font.shape, "up");
2705 else if (t.cs() == "textit")
2706 parse_text_attributes(p, os, FLAG_ITEM, outer,
2708 context.font.shape, "italic");
2710 else if (t.cs() == "textsl")
2711 parse_text_attributes(p, os, FLAG_ITEM, outer,
2713 context.font.shape, "slanted");
2715 else if (t.cs() == "textsc")
2716 parse_text_attributes(p, os, FLAG_ITEM, outer,
2718 context.font.shape, "smallcaps");
2720 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2721 context.check_layout(os);
2722 TeXFont oldFont = context.font;
2723 context.font.init();
2724 context.font.size = oldFont.size;
2725 os << "\n\\family " << context.font.family << "\n";
2726 os << "\n\\series " << context.font.series << "\n";
2727 os << "\n\\shape " << context.font.shape << "\n";
2728 if (t.cs() == "textnormal") {
2729 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2730 output_font_change(os, context.font, oldFont);
2731 context.font = oldFont;
2733 eat_whitespace(p, os, context, false);
2736 else if (t.cs() == "textcolor") {
2737 // scheme is \textcolor{color name}{text}
2738 string const color = p.verbatim_item();
2739 // we only support the predefined colors of the color package
2740 if (color == "black" || color == "blue" || color == "cyan"
2741 || color == "green" || color == "magenta" || color == "red"
2742 || color == "white" || color == "yellow") {
2743 context.check_layout(os);
2744 os << "\n\\color " << color << "\n";
2745 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2746 context.check_layout(os);
2747 os << "\n\\color inherit\n";
2748 preamble.registerAutomaticallyLoadedPackage("color");
2750 // for custom defined colors
2751 handle_ert(os, t.asInput() + "{" + color + "}", context);
2754 else if (t.cs() == "underbar" || t.cs() == "uline") {
2755 // \underbar is not 100% correct (LyX outputs \uline
2756 // of ulem.sty). The difference is that \ulem allows
2757 // line breaks, and \underbar does not.
2758 // Do NOT handle \underline.
2759 // \underbar cuts through y, g, q, p etc.,
2760 // \underline does not.
2761 context.check_layout(os);
2762 os << "\n\\bar under\n";
2763 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2764 context.check_layout(os);
2765 os << "\n\\bar default\n";
2766 preamble.registerAutomaticallyLoadedPackage("ulem");
2769 else if (t.cs() == "sout") {
2770 context.check_layout(os);
2771 os << "\n\\strikeout on\n";
2772 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2773 context.check_layout(os);
2774 os << "\n\\strikeout default\n";
2775 preamble.registerAutomaticallyLoadedPackage("ulem");
2778 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2779 t.cs() == "emph" || t.cs() == "noun") {
2780 context.check_layout(os);
2781 os << "\n\\" << t.cs() << " on\n";
2782 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2783 context.check_layout(os);
2784 os << "\n\\" << t.cs() << " default\n";
2785 if (t.cs() == "uuline" || t.cs() == "uwave")
2786 preamble.registerAutomaticallyLoadedPackage("ulem");
2789 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2790 context.check_layout(os);
2791 string name = p.getArg('{', '}');
2792 string localtime = p.getArg('{', '}');
2793 preamble.registerAuthor(name);
2794 Author const & author = preamble.getAuthor(name);
2795 // from_ctime() will fail if LyX decides to output the
2796 // time in the text language. It might also use a wrong
2797 // time zone (if the original LyX document was exported
2798 // with a different time zone).
2799 time_t ptime = from_ctime(localtime);
2800 if (ptime == static_cast<time_t>(-1)) {
2801 cerr << "Warning: Could not parse time `" << localtime
2802 << "´ for change tracking, using current time instead.\n";
2803 ptime = current_time();
2805 if (t.cs() == "lyxadded")
2806 os << "\n\\change_inserted ";
2808 os << "\n\\change_deleted ";
2809 os << author.bufferId() << ' ' << ptime << '\n';
2810 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2811 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2812 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2813 LaTeXPackages::isAvailable("xcolor");
2814 // No need to test for luatex, since luatex comes in
2815 // two flavours (dvi and pdf), like latex, and those
2816 // are detected by pdflatex.
2817 if (pdflatex || xetex) {
2819 preamble.registerAutomaticallyLoadedPackage("ulem");
2820 preamble.registerAutomaticallyLoadedPackage("xcolor");
2821 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2825 preamble.registerAutomaticallyLoadedPackage("dvipost");
2826 } else if (xcolorulem) {
2827 preamble.registerAutomaticallyLoadedPackage("ulem");
2828 preamble.registerAutomaticallyLoadedPackage("xcolor");
2833 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2834 t.cs() == "vphantom") {
2835 context.check_layout(os);
2836 if (t.cs() == "phantom")
2837 begin_inset(os, "Phantom Phantom\n");
2838 if (t.cs() == "hphantom")
2839 begin_inset(os, "Phantom HPhantom\n");
2840 if (t.cs() == "vphantom")
2841 begin_inset(os, "Phantom VPhantom\n");
2842 os << "status open\n";
2843 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2848 else if (t.cs() == "href") {
2849 context.check_layout(os);
2850 string target = p.getArg('{', '}');
2851 string name = p.getArg('{', '}');
2853 size_t i = target.find(':');
2854 if (i != string::npos) {
2855 type = target.substr(0, i + 1);
2856 if (type == "mailto:" || type == "file:")
2857 target = target.substr(i + 1);
2858 // handle the case that name is equal to target, except of "http://"
2859 else if (target.substr(i + 3) == name && type == "http:")
2862 begin_command_inset(os, "href", "href");
2864 os << "name \"" << name << "\"\n";
2865 os << "target \"" << target << "\"\n";
2866 if (type == "mailto:" || type == "file:")
2867 os << "type \"" << type << "\"\n";
2869 skip_spaces_braces(p);
2872 else if (t.cs() == "lyxline") {
2873 // swallow size argument (it is not used anyway)
2875 if (!context.atParagraphStart()) {
2876 // so our line is in the middle of a paragraph
2877 // we need to add a new line, lest this line
2878 // follow the other content on that line and
2879 // run off the side of the page
2880 // FIXME: This may create an empty paragraph,
2881 // but without that it would not be
2882 // possible to set noindent below.
2883 // Fortunately LaTeX does not care
2884 // about the empty paragraph.
2885 context.new_paragraph(os);
2887 if (preamble.indentParagraphs()) {
2888 // we need to unindent, lest the line be too long
2889 context.add_par_extra_stuff("\\noindent\n");
2891 context.check_layout(os);
2892 begin_command_inset(os, "line", "rule");
2893 os << "offset \"0.5ex\"\n"
2894 "width \"100line%\"\n"
2899 else if (t.cs() == "rule") {
2900 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2901 string const width = p.getArg('{', '}');
2902 string const thickness = p.getArg('{', '}');
2903 context.check_layout(os);
2904 begin_command_inset(os, "line", "rule");
2905 if (!offset.empty())
2906 os << "offset \"" << translate_len(offset) << "\"\n";
2907 os << "width \"" << translate_len(width) << "\"\n"
2908 "height \"" << translate_len(thickness) << "\"\n";
2912 else if (is_known(t.cs(), known_phrases) ||
2913 (t.cs() == "protect" &&
2914 p.next_token().cat() == catEscape &&
2915 is_known(p.next_token().cs(), known_phrases))) {
2916 // LyX sometimes puts a \protect in front, so we have to ignore it
2917 // FIXME: This needs to be changed when bug 4752 is fixed.
2918 char const * const * where = is_known(
2919 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2921 context.check_layout(os);
2922 os << known_coded_phrases[where - known_phrases];
2923 skip_spaces_braces(p);
2926 else if (is_known(t.cs(), known_ref_commands)) {
2927 string const opt = p.getOpt();
2929 context.check_layout(os);
2930 char const * const * where = is_known(t.cs(),
2931 known_ref_commands);
2932 begin_command_inset(os, "ref",
2933 known_coded_ref_commands[where - known_ref_commands]);
2934 os << "reference \""
2935 << convert_command_inset_arg(p.verbatim_item())
2939 // LyX does not support optional arguments of ref commands
2940 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2941 p.verbatim_item() + "}", context);
2945 else if (use_natbib &&
2946 is_known(t.cs(), known_natbib_commands) &&
2947 ((t.cs() != "citefullauthor" &&
2948 t.cs() != "citeyear" &&
2949 t.cs() != "citeyearpar") ||
2950 p.next_token().asInput() != "*")) {
2951 context.check_layout(os);
2952 string command = t.cs();
2953 if (p.next_token().asInput() == "*") {
2957 if (command == "citefullauthor")
2958 // alternative name for "\\citeauthor*"
2959 command = "citeauthor*";
2961 // text before the citation
2963 // text after the citation
2965 get_cite_arguments(p, true, before, after);
2967 if (command == "cite") {
2968 // \cite without optional argument means
2969 // \citet, \cite with at least one optional
2970 // argument means \citep.
2971 if (before.empty() && after.empty())
2976 if (before.empty() && after == "[]")
2977 // avoid \citet[]{a}
2979 else if (before == "[]" && after == "[]") {
2980 // avoid \citet[][]{a}
2984 // remove the brackets around after and before
2985 if (!after.empty()) {
2987 after.erase(after.length() - 1, 1);
2988 after = convert_command_inset_arg(after);
2990 if (!before.empty()) {
2992 before.erase(before.length() - 1, 1);
2993 before = convert_command_inset_arg(before);
2995 begin_command_inset(os, "citation", command);
2996 os << "after " << '"' << after << '"' << "\n";
2997 os << "before " << '"' << before << '"' << "\n";
2999 << convert_command_inset_arg(p.verbatim_item())
3004 else if (use_jurabib &&
3005 is_known(t.cs(), known_jurabib_commands) &&
3006 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3007 context.check_layout(os);
3008 string command = t.cs();
3009 if (p.next_token().asInput() == "*") {
3013 char argumentOrder = '\0';
3014 vector<string> const options =
3015 preamble.getPackageOptions("jurabib");
3016 if (find(options.begin(), options.end(),
3017 "natbiborder") != options.end())
3018 argumentOrder = 'n';
3019 else if (find(options.begin(), options.end(),
3020 "jurabiborder") != options.end())
3021 argumentOrder = 'j';
3023 // text before the citation
3025 // text after the citation
3027 get_cite_arguments(p, argumentOrder != 'j', before, after);
3029 string const citation = p.verbatim_item();
3030 if (!before.empty() && argumentOrder == '\0') {
3031 cerr << "Warning: Assuming argument order "
3032 "of jurabib version 0.6 for\n'"
3033 << command << before << after << '{'
3034 << citation << "}'.\n"
3035 "Add 'jurabiborder' to the jurabib "
3036 "package options if you used an\n"
3037 "earlier jurabib version." << endl;
3039 if (!after.empty()) {
3041 after.erase(after.length() - 1, 1);
3043 if (!before.empty()) {
3045 before.erase(before.length() - 1, 1);
3047 begin_command_inset(os, "citation", command);
3048 os << "after " << '"' << after << '"' << "\n";
3049 os << "before " << '"' << before << '"' << "\n";
3050 os << "key " << '"' << citation << '"' << "\n";
3054 else if (t.cs() == "cite"
3055 || t.cs() == "nocite") {
3056 context.check_layout(os);
3057 string after = convert_command_inset_arg(p.getArg('[', ']'));
3058 string key = convert_command_inset_arg(p.verbatim_item());
3059 // store the case that it is "\nocite{*}" to use it later for
3062 begin_command_inset(os, "citation", t.cs());
3063 os << "after " << '"' << after << '"' << "\n";
3064 os << "key " << '"' << key << '"' << "\n";
3066 } else if (t.cs() == "nocite")
3070 else if (t.cs() == "index") {
3071 context.check_layout(os);
3072 begin_inset(os, "Index idx\n");
3073 os << "status collapsed\n";
3074 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3078 else if (t.cs() == "nomenclature") {
3079 context.check_layout(os);
3080 begin_command_inset(os, "nomenclature", "nomenclature");
3081 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3082 if (!prefix.empty())
3083 os << "prefix " << '"' << prefix << '"' << "\n";
3084 os << "symbol " << '"'
3085 << convert_command_inset_arg(p.verbatim_item());
3086 os << "\"\ndescription \""
3087 << convert_command_inset_arg(p.verbatim_item())
3092 else if (t.cs() == "label") {
3093 context.check_layout(os);
3094 begin_command_inset(os, "label", "label");
3096 << convert_command_inset_arg(p.verbatim_item())
3101 else if (t.cs() == "printindex") {
3102 context.check_layout(os);
3103 begin_command_inset(os, "index_print", "printindex");
3104 os << "type \"idx\"\n";
3106 skip_spaces_braces(p);
3109 else if (t.cs() == "printnomenclature") {
3111 string width_type = "";
3112 context.check_layout(os);
3113 begin_command_inset(os, "nomencl_print", "printnomenclature");
3114 // case of a custom width
3116 width = p.getArg('[', ']');
3117 width = translate_len(width);
3118 width_type = "custom";
3120 // case of no custom width
3121 // the case of no custom width but the width set
3122 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3123 // because the user could have set anything, not only the width
3124 // of the longest label (which would be width_type = "auto")
3125 string label = convert_command_inset_arg(p.getArg('{', '}'));
3126 if (label.empty() && width_type.empty())
3127 width_type = "none";
3128 os << "set_width \"" << width_type << "\"\n";
3129 if (width_type == "custom")
3130 os << "width \"" << width << '\"';
3132 skip_spaces_braces(p);
3135 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3136 context.check_layout(os);
3137 begin_inset(os, "script ");
3138 os << t.cs().substr(4) << '\n';
3139 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3141 if (t.cs() == "textsubscript")
3142 preamble.registerAutomaticallyLoadedPackage("subscript");
3145 else if (is_known(t.cs(), known_quotes)) {
3146 char const * const * where = is_known(t.cs(), known_quotes);
3147 context.check_layout(os);
3148 begin_inset(os, "Quotes ");
3149 os << known_coded_quotes[where - known_quotes];
3151 // LyX adds {} after the quote, so we have to eat
3152 // spaces here if there are any before a possible
3154 eat_whitespace(p, os, context, false);
3158 else if (is_known(t.cs(), known_sizes) &&
3159 context.new_layout_allowed) {
3160 char const * const * where = is_known(t.cs(), known_sizes);
3161 context.check_layout(os);
3162 TeXFont const oldFont = context.font;
3163 context.font.size = known_coded_sizes[where - known_sizes];
3164 output_font_change(os, oldFont, context.font);
3165 eat_whitespace(p, os, context, false);
3168 else if (is_known(t.cs(), known_font_families) &&
3169 context.new_layout_allowed) {
3170 char const * const * where =
3171 is_known(t.cs(), known_font_families);
3172 context.check_layout(os);
3173 TeXFont const oldFont = context.font;
3174 context.font.family =
3175 known_coded_font_families[where - known_font_families];
3176 output_font_change(os, oldFont, context.font);
3177 eat_whitespace(p, os, context, false);
3180 else if (is_known(t.cs(), known_font_series) &&
3181 context.new_layout_allowed) {
3182 char const * const * where =
3183 is_known(t.cs(), known_font_series);
3184 context.check_layout(os);
3185 TeXFont const oldFont = context.font;
3186 context.font.series =
3187 known_coded_font_series[where - known_font_series];
3188 output_font_change(os, oldFont, context.font);
3189 eat_whitespace(p, os, context, false);
3192 else if (is_known(t.cs(), known_font_shapes) &&
3193 context.new_layout_allowed) {
3194 char const * const * where =
3195 is_known(t.cs(), known_font_shapes);
3196 context.check_layout(os);
3197 TeXFont const oldFont = context.font;
3198 context.font.shape =
3199 known_coded_font_shapes[where - known_font_shapes];
3200 output_font_change(os, oldFont, context.font);
3201 eat_whitespace(p, os, context, false);
3203 else if (is_known(t.cs(), known_old_font_families) &&
3204 context.new_layout_allowed) {
3205 char const * const * where =
3206 is_known(t.cs(), known_old_font_families);
3207 context.check_layout(os);
3208 TeXFont const oldFont = context.font;
3209 context.font.init();
3210 context.font.size = oldFont.size;
3211 context.font.family =
3212 known_coded_font_families[where - known_old_font_families];
3213 output_font_change(os, oldFont, context.font);
3214 eat_whitespace(p, os, context, false);
3217 else if (is_known(t.cs(), known_old_font_series) &&
3218 context.new_layout_allowed) {
3219 char const * const * where =
3220 is_known(t.cs(), known_old_font_series);
3221 context.check_layout(os);
3222 TeXFont const oldFont = context.font;
3223 context.font.init();
3224 context.font.size = oldFont.size;
3225 context.font.series =
3226 known_coded_font_series[where - known_old_font_series];
3227 output_font_change(os, oldFont, context.font);
3228 eat_whitespace(p, os, context, false);
3231 else if (is_known(t.cs(), known_old_font_shapes) &&
3232 context.new_layout_allowed) {
3233 char const * const * where =
3234 is_known(t.cs(), known_old_font_shapes);
3235 context.check_layout(os);
3236 TeXFont const oldFont = context.font;
3237 context.font.init();
3238 context.font.size = oldFont.size;
3239 context.font.shape =
3240 known_coded_font_shapes[where - known_old_font_shapes];
3241 output_font_change(os, oldFont, context.font);
3242 eat_whitespace(p, os, context, false);
3245 else if (t.cs() == "selectlanguage") {
3246 context.check_layout(os);
3247 // save the language for the case that a
3248 // \foreignlanguage is used
3250 context.font.language = babel2lyx(p.verbatim_item());
3251 os << "\n\\lang " << context.font.language << "\n";
3254 else if (t.cs() == "foreignlanguage") {
3255 string const lang = babel2lyx(p.verbatim_item());
3256 parse_text_attributes(p, os, FLAG_ITEM, outer,
3258 context.font.language, lang);
3261 else if (t.cs() == "inputencoding") {
3262 // nothing to write here
3263 string const enc = subst(p.verbatim_item(), "\n", " ");
3267 else if (t.cs() == "ldots") {
3268 context.check_layout(os);
3269 os << "\\SpecialChar \\ldots{}\n";
3270 skip_spaces_braces(p);
3273 else if (t.cs() == "lyxarrow") {
3274 context.check_layout(os);
3275 os << "\\SpecialChar \\menuseparator\n";
3276 skip_spaces_braces(p);
3279 else if (t.cs() == "textcompwordmark") {
3280 context.check_layout(os);
3281 os << "\\SpecialChar \\textcompwordmark{}\n";
3282 skip_spaces_braces(p);
3285 else if (t.cs() == "slash") {
3286 context.check_layout(os);
3287 os << "\\SpecialChar \\slash{}\n";
3288 skip_spaces_braces(p);
3291 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3292 context.check_layout(os);
3293 os << "\\SpecialChar \\nobreakdash-\n";
3297 else if (t.cs() == "textquotedbl") {
3298 context.check_layout(os);
3303 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3304 context.check_layout(os);
3305 os << "\\SpecialChar \\@.\n";
3309 else if (t.cs() == "-") {
3310 context.check_layout(os);
3311 os << "\\SpecialChar \\-\n";
3314 else if (t.cs() == "textasciitilde") {
3315 context.check_layout(os);
3317 skip_spaces_braces(p);
3320 else if (t.cs() == "textasciicircum") {
3321 context.check_layout(os);
3323 skip_spaces_braces(p);
3326 else if (t.cs() == "textbackslash") {
3327 context.check_layout(os);
3328 os << "\n\\backslash\n";
3329 skip_spaces_braces(p);
3332 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3333 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3335 context.check_layout(os);
3339 else if (t.cs() == "char") {
3340 context.check_layout(os);
3341 if (p.next_token().character() == '`') {
3343 if (p.next_token().cs() == "\"") {
3348 handle_ert(os, "\\char`", context);
3351 handle_ert(os, "\\char", context);
3355 else if (t.cs() == "verb") {
3356 context.check_layout(os);
3357 char const delimiter = p.next_token().character();
3358 string const arg = p.getArg(delimiter, delimiter);
3360 oss << "\\verb" << delimiter << arg << delimiter;
3361 handle_ert(os, oss.str(), context);
3364 // Problem: \= creates a tabstop inside the tabbing environment
3365 // and else an accent. In the latter case we really would want
3366 // \={o} instead of \= o.
3367 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3368 handle_ert(os, t.asInput(), context);
3370 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3371 else if (t.cs().size() == 1
3372 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3373 context.check_layout(os);
3374 // try to see whether the string is in unicodesymbols
3376 string command = t.asInput() + "{"
3377 + trimSpaceAndEol(p.verbatim_item())
3379 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3382 cerr << "When parsing " << command
3383 << ", result is " << to_utf8(s)
3384 << "+" << to_utf8(rem) << endl;
3387 // we did not find a non-ert version
3388 handle_ert(os, command, context);
3391 else if (t.cs() == "\\") {
3392 context.check_layout(os);
3394 handle_ert(os, "\\\\" + p.getOpt(), context);
3395 else if (p.next_token().asInput() == "*") {
3397 // getOpt() eats the following space if there
3398 // is no optional argument, but that is OK
3399 // here since it has no effect in the output.
3400 handle_ert(os, "\\\\*" + p.getOpt(), context);
3403 begin_inset(os, "Newline newline");
3408 else if (t.cs() == "newline" ||
3409 (t.cs() == "linebreak" && !p.hasOpt())) {
3410 context.check_layout(os);
3411 begin_inset(os, "Newline ");
3414 skip_spaces_braces(p);
3417 else if (t.cs() == "input" || t.cs() == "include"
3418 || t.cs() == "verbatiminput") {
3419 string name = t.cs();
3420 if (t.cs() == "verbatiminput"
3421 && p.next_token().asInput() == "*")
3422 name += p.get_token().asInput();
3423 context.check_layout(os);
3424 string filename(normalize_filename(p.getArg('{', '}')));
3425 string const path = getMasterFilePath();
3426 // We want to preserve relative / absolute filenames,
3427 // therefore path is only used for testing
3428 if ((t.cs() == "include" || t.cs() == "input") &&
3429 !makeAbsPath(filename, path).exists()) {
3430 // The file extension is probably missing.
3431 // Now try to find it out.
3432 string const tex_name =
3433 find_file(filename, path,
3434 known_tex_extensions);
3435 if (!tex_name.empty())
3436 filename = tex_name;
3438 bool external = false;
3440 if (makeAbsPath(filename, path).exists()) {
3441 string const abstexname =
3442 makeAbsPath(filename, path).absFileName();
3443 string const abslyxname =
3444 changeExtension(abstexname, ".lyx");
3445 string const absfigname =
3446 changeExtension(abstexname, ".fig");
3447 fix_relative_filename(filename);
3448 string const lyxname =
3449 changeExtension(filename, ".lyx");
3451 external = FileName(absfigname).exists();
3452 if (t.cs() == "input") {
3453 string const ext = getExtension(abstexname);
3455 // Combined PS/LaTeX:
3456 // x.eps, x.pstex_t (old xfig)
3457 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3458 FileName const absepsname(
3459 changeExtension(abstexname, ".eps"));
3460 FileName const abspstexname(
3461 changeExtension(abstexname, ".pstex"));
3462 bool const xfigeps =
3463 (absepsname.exists() ||
3464 abspstexname.exists()) &&
3467 // Combined PDF/LaTeX:
3468 // x.pdf, x.pdftex_t (old xfig)
3469 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3470 FileName const abspdfname(
3471 changeExtension(abstexname, ".pdf"));
3472 bool const xfigpdf =
3473 abspdfname.exists() &&
3474 (ext == "pdftex_t" || ext == "pdf_t");
3478 // Combined PS/PDF/LaTeX:
3479 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3480 string const absbase2(
3481 removeExtension(abstexname) + "_pspdftex");
3482 FileName const abseps2name(
3483 addExtension(absbase2, ".eps"));
3484 FileName const abspdf2name(
3485 addExtension(absbase2, ".pdf"));
3486 bool const xfigboth =
3487 abspdf2name.exists() &&
3488 abseps2name.exists() && ext == "pspdftex";
3490 xfig = xfigpdf || xfigeps || xfigboth;
3491 external = external && xfig;
3494 outname = changeExtension(filename, ".fig");
3496 // Don't try to convert, the result
3497 // would be full of ERT.
3499 } else if (t.cs() != "verbatiminput" &&
3500 tex2lyx(abstexname, FileName(abslyxname),
3507 cerr << "Warning: Could not find included file '"
3508 << filename << "'." << endl;
3512 begin_inset(os, "External\n");
3513 os << "\ttemplate XFig\n"
3514 << "\tfilename " << outname << '\n';
3516 begin_command_inset(os, "include", name);
3517 os << "preview false\n"
3518 "filename \"" << outname << "\"\n";
3523 else if (t.cs() == "bibliographystyle") {
3524 // store new bibliographystyle
3525 bibliographystyle = p.verbatim_item();
3526 // If any other command than \bibliography and
3527 // \nocite{*} follows, we need to output the style
3528 // (because it might be used by that command).
3529 // Otherwise, it will automatically be output by LyX.
3532 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3533 if (t2.cat() == catBegin)
3535 if (t2.cat() != catEscape)
3537 if (t2.cs() == "nocite") {
3538 if (p.getArg('{', '}') == "*")
3540 } else if (t2.cs() == "bibliography")
3547 "\\bibliographystyle{" + bibliographystyle + '}',
3552 else if (t.cs() == "bibliography") {
3553 context.check_layout(os);
3554 begin_command_inset(os, "bibtex", "bibtex");
3555 if (!btprint.empty()) {
3556 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3557 // clear the string because the next BibTeX inset can be without the
3558 // \nocite{*} option
3561 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3562 // Do we have a bibliographystyle set?
3563 if (!bibliographystyle.empty())
3564 os << "options " << '"' << bibliographystyle << '"' << "\n";
3568 else if (t.cs() == "parbox") {
3569 // Test whether this is an outer box of a shaded box
3571 // swallow arguments
3572 while (p.hasOpt()) {
3574 p.skip_spaces(true);
3577 p.skip_spaces(true);
3579 if (p.next_token().cat() == catBegin)
3581 p.skip_spaces(true);
3582 Token to = p.get_token();
3583 bool shaded = false;
3584 if (to.asInput() == "\\begin") {
3585 p.skip_spaces(true);
3586 if (p.getArg('{', '}') == "shaded")
3591 parse_outer_box(p, os, FLAG_ITEM, outer,
3592 context, "parbox", "shaded");
3594 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3598 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3599 t.cs() == "shadowbox" || t.cs() == "doublebox")
3600 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3602 else if (t.cs() == "framebox") {
3603 string special = p.getFullOpt();
3604 special += p.getOpt();
3605 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3608 //\makebox() is part of the picture environment and different from \makebox{}
3609 //\makebox{} will be parsed by parse_box
3610 else if (t.cs() == "makebox") {
3611 string arg = t.asInput();
3612 if (p.next_token().character() == '(') {
3613 //the syntax is: \makebox(x,y)[position]{content}
3614 arg += p.getFullParentheseArg();
3615 arg += p.getFullOpt();
3616 eat_whitespace(p, os, context, false);
3617 handle_ert(os, arg + '{', context);
3618 eat_whitespace(p, os, context, false);
3619 parse_text(p, os, FLAG_ITEM, outer, context);
3620 handle_ert(os, "}", context);
3622 //the syntax is: \makebox[width][position]{content}
3623 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3627 else if (t.cs() == "smallskip" ||
3628 t.cs() == "medskip" ||
3629 t.cs() == "bigskip" ||
3630 t.cs() == "vfill") {
3631 context.check_layout(os);
3632 begin_inset(os, "VSpace ");
3635 skip_spaces_braces(p);
3638 else if (is_known(t.cs(), known_spaces)) {
3639 char const * const * where = is_known(t.cs(), known_spaces);
3640 context.check_layout(os);
3641 begin_inset(os, "space ");
3642 os << '\\' << known_coded_spaces[where - known_spaces]
3645 // LaTeX swallows whitespace after all spaces except
3646 // "\\,". We have to do that here, too, because LyX
3647 // adds "{}" which would make the spaces significant.
3649 eat_whitespace(p, os, context, false);
3650 // LyX adds "{}" after all spaces except "\\ " and
3651 // "\\,", so we have to remove "{}".
3652 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3653 // remove the braces after "\\,", too.
3658 else if (t.cs() == "newpage" ||
3659 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3660 t.cs() == "clearpage" ||
3661 t.cs() == "cleardoublepage") {
3662 context.check_layout(os);
3663 begin_inset(os, "Newpage ");
3666 skip_spaces_braces(p);
3669 else if (t.cs() == "DeclareRobustCommand" ||
3670 t.cs() == "DeclareRobustCommandx" ||
3671 t.cs() == "newcommand" ||
3672 t.cs() == "newcommandx" ||
3673 t.cs() == "providecommand" ||
3674 t.cs() == "providecommandx" ||
3675 t.cs() == "renewcommand" ||
3676 t.cs() == "renewcommandx") {
3677 // DeclareRobustCommand, DeclareRobustCommandx,
3678 // providecommand and providecommandx could be handled
3679 // by parse_command(), but we need to call
3680 // add_known_command() here.
3681 string name = t.asInput();
3682 if (p.next_token().asInput() == "*") {
3683 // Starred form. Eat '*'
3687 string const command = p.verbatim_item();
3688 string const opt1 = p.getFullOpt();
3689 string const opt2 = p.getFullOpt();
3690 add_known_command(command, opt1, !opt2.empty());
3691 string const ert = name + '{' + command + '}' +
3693 '{' + p.verbatim_item() + '}';
3695 if (t.cs() == "DeclareRobustCommand" ||
3696 t.cs() == "DeclareRobustCommandx" ||
3697 t.cs() == "providecommand" ||
3698 t.cs() == "providecommandx" ||
3699 name[name.length()-1] == '*')
3700 handle_ert(os, ert, context);
3702 context.check_layout(os);
3703 begin_inset(os, "FormulaMacro");
3709 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3710 // let could be handled by parse_command(),
3711 // but we need to call add_known_command() here.
3712 string ert = t.asInput();
3715 if (p.next_token().cat() == catBegin) {
3716 name = p.verbatim_item();
3717 ert += '{' + name + '}';
3719 name = p.verbatim_item();
3724 if (p.next_token().cat() == catBegin) {
3725 command = p.verbatim_item();
3726 ert += '{' + command + '}';
3728 command = p.verbatim_item();
3731 // If command is known, make name known too, to parse
3732 // its arguments correctly. For this reason we also
3733 // have commands in syntax.default that are hardcoded.
3734 CommandMap::iterator it = known_commands.find(command);
3735 if (it != known_commands.end())
3736 known_commands[t.asInput()] = it->second;
3737 handle_ert(os, ert, context);
3740 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3741 bool starred = false;
3742 if (p.next_token().asInput() == "*") {
3746 string name = t.asInput();
3747 string const length = p.verbatim_item();
3750 bool valid = splitLatexLength(length, valstring, unit);
3751 bool known_hspace = false;
3752 bool known_vspace = false;
3753 bool known_unit = false;
3756 istringstream iss(valstring);
3759 if (t.cs()[0] == 'h') {
3760 if (unit == "\\fill") {
3765 known_hspace = true;
3768 if (unit == "\\smallskipamount") {
3770 known_vspace = true;
3771 } else if (unit == "\\medskipamount") {
3773 known_vspace = true;
3774 } else if (unit == "\\bigskipamount") {
3776 known_vspace = true;
3777 } else if (unit == "\\fill") {
3779 known_vspace = true;
3783 if (!known_hspace && !known_vspace) {
3784 switch (unitFromString(unit)) {
3805 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3806 // Literal horizontal length or known variable
3807 context.check_layout(os);
3808 begin_inset(os, "space ");
3816 if (known_unit && !known_hspace)
3818 << translate_len(length);
3820 } else if (known_unit || known_vspace) {
3821 // Literal vertical length or known variable
3822 context.check_layout(os);
3823 begin_inset(os, "VSpace ");
3831 // LyX can't handle other length variables in Inset VSpace/space
3836 handle_ert(os, name + '{' + unit + '}', context);
3837 else if (value == -1.0)
3838 handle_ert(os, name + "{-" + unit + '}', context);
3840 handle_ert(os, name + '{' + valstring + unit + '}', context);
3842 handle_ert(os, name + '{' + length + '}', context);
3846 // The single '=' is meant here.
3847 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3849 context.check_layout(os);
3850 begin_inset(os, "Flex ");
3851 os << to_utf8(newinsetlayout->name()) << '\n'
3852 << "status collapsed\n";
3853 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3858 // try to see whether the string is in unicodesymbols
3859 // Only use text mode commands, since we are in text mode here,
3860 // and math commands may be invalid (bug 6797)
3862 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3863 rem, Encodings::TEXT_CMD);
3866 cerr << "When parsing " << t.cs()
3867 << ", result is " << to_utf8(s)
3868 << "+" << to_utf8(rem) << endl;
3869 context.check_layout(os);
3871 skip_spaces_braces(p);
3873 //cerr << "#: " << t << " mode: " << mode << endl;
3874 // heuristic: read up to next non-nested space
3876 string s = t.asInput();
3877 string z = p.verbatim_item();
3878 while (p.good() && z != " " && z.size()) {
3879 //cerr << "read: " << z << endl;
3881 z = p.verbatim_item();
3883 cerr << "found ERT: " << s << endl;
3884 handle_ert(os, s + ' ', context);
3887 string name = t.asInput();
3888 if (p.next_token().asInput() == "*") {
3889 // Starred commands like \vspace*{}
3890 p.get_token(); // Eat '*'
3893 if (!parse_command(name, p, os, outer, context))
3894 handle_ert(os, name, context);
3898 if (flags & FLAG_LEAVE) {
3899 flags &= ~FLAG_LEAVE;