2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "support/lassert.h"
28 #include "support/convert.h"
29 #include "support/FileName.h"
30 #include "support/filetools.h"
31 #include "support/lstrings.h"
32 #include "support/lyxtime.h"
41 using namespace lyx::support;
46 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
47 Context const & context, InsetLayout const * layout)
49 bool const forcePlainLayout =
50 layout ? layout->forcePlainLayout() : false;
51 Context newcontext(true, context.textclass);
53 newcontext.layout = &context.textclass.plainLayout();
55 newcontext.font = context.font;
56 parse_text(p, os, flags, outer, newcontext);
57 newcontext.check_end_layout(os);
63 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
64 Context const & context, string const & name)
66 InsetLayout const * layout = 0;
67 DocumentClass::InsetLayouts::const_iterator it =
68 context.textclass.insetLayouts().find(from_ascii(name));
69 if (it != context.textclass.insetLayouts().end())
70 layout = &(it->second);
71 parse_text_in_inset(p, os, flags, outer, context, layout);
74 /// parses a paragraph snippet, useful for example for \\emph{...}
75 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
78 Context newcontext(context);
79 // Don't inherit the paragraph-level extra stuff
80 newcontext.par_extra_stuff.clear();
81 parse_text(p, os, flags, outer, newcontext);
82 // Make sure that we don't create invalid .lyx files
83 context.need_layout = newcontext.need_layout;
84 context.need_end_layout = newcontext.need_end_layout;
89 * Thin wrapper around parse_text_snippet() using a string.
91 * We completely ignore \c context.need_layout and \c context.need_end_layout,
92 * because our return value is not used directly (otherwise the stream version
93 * of parse_text_snippet() could be used). That means that the caller needs
94 * to do layout management manually.
95 * This is intended to parse text that does not create any layout changes.
97 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
100 Context newcontext(context);
101 newcontext.need_layout = false;
102 newcontext.need_end_layout = false;
103 newcontext.new_layout_allowed = false;
104 // Avoid warning by Context::~Context()
105 newcontext.par_extra_stuff.clear();
107 parse_text_snippet(p, os, flags, outer, newcontext);
112 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
113 "vpageref", "prettyref", "eqref", 0 };
115 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
116 "vpageref", "formatted", "eqref", 0 };
120 * The starred forms are also known except for "citefullauthor",
121 * "citeyear" and "citeyearpar".
123 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
124 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
125 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
129 * No starred form other than "cite*" known.
131 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
132 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
133 // jurabib commands not (yet) supported by LyX:
135 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
136 // "footciteauthor", "footciteyear", "footciteyearpar",
137 "citefield", "citetitle", 0 };
139 /// LaTeX names for quotes
140 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
141 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
142 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
143 "guilsinglleft", "frq", "guilsinglright", 0};
145 /// the same as known_quotes with .lyx names
146 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
147 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
148 "gld", "grd", "gls", "ers", "fls",
149 "fls", "frs", "frs", 0};
151 /// LaTeX names for font sizes
152 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
153 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
155 /// the same as known_sizes with .lyx names
156 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
157 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
159 /// LaTeX 2.09 names for font families
160 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
162 /// LaTeX names for font families
163 char const * const known_font_families[] = { "rmfamily", "sffamily",
166 /// the same as known_old_font_families and known_font_families with .lyx names
167 char const * const known_coded_font_families[] = { "roman", "sans",
170 /// LaTeX 2.09 names for font series
171 char const * const known_old_font_series[] = { "bf", 0};
173 /// LaTeX names for font series
174 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
176 /// the same as known_old_font_series and known_font_series with .lyx names
177 char const * const known_coded_font_series[] = { "bold", "medium", 0};
179 /// LaTeX 2.09 names for font shapes
180 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
182 /// LaTeX names for font shapes
183 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
186 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
187 char const * const known_coded_font_shapes[] = { "italic", "slanted",
188 "smallcaps", "up", 0};
191 * Graphics file extensions known by the dvips driver of the graphics package.
192 * These extensions are used to complete the filename of an included
193 * graphics file if it does not contain an extension.
194 * The order must be the same that latex uses to find a file, because we
195 * will use the first extension that matches.
196 * This is only an approximation for the common cases. If we would want to
197 * do it right in all cases, we would need to know which graphics driver is
198 * used and know the extensions of every driver of the graphics package.
200 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
201 "ps.gz", "eps.Z", "ps.Z", 0};
204 * Graphics file extensions known by the pdftex driver of the graphics package.
205 * \sa known_dvips_graphics_formats
207 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
211 * Known file extensions for TeX files as used by \\include.
213 char const * const known_tex_extensions[] = {"tex", 0};
215 /// spaces known by InsetSpace
216 char const * const known_spaces[] = { " ", "space", ",",
217 "thinspace", "quad", "qquad", "enspace", "enskip",
218 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
219 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
220 "upbracefill", "downbracefill", 0};
222 /// the same as known_spaces with .lyx names
223 char const * const known_coded_spaces[] = { "space{}", "space{}",
224 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
225 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
226 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
227 "upbracefill{}", "downbracefill{}", 0};
229 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
230 /// them in ERT. "LaTeXe" must come before "LaTeX"!
231 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
232 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
233 int const known_phrase_lengths[] = {3, 5, 7, 0};
235 // string to store the float type to be able to determine the type of subfloats
236 string float_type = "";
239 /// splits "x=z, y=b" into a map and an ordered keyword vector
240 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
245 keys.resize(v.size());
246 for (size_t i = 0; i < v.size(); ++i) {
247 size_t const pos = v[i].find('=');
248 string const index = trimSpaceAndEol(v[i].substr(0, pos));
249 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
257 * Split a LaTeX length into value and unit.
258 * The latter can be a real unit like "pt", or a latex length variable
259 * like "\textwidth". The unit may contain additional stuff like glue
260 * lengths, but we don't care, because such lengths are ERT anyway.
261 * \returns true if \p value and \p unit are valid.
263 bool splitLatexLength(string const & len, string & value, string & unit)
267 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
268 //'4,5' is a valid LaTeX length number. Change it to '4.5'
269 string const length = subst(len, ',', '.');
270 if (i == string::npos)
273 if (len[0] == '\\') {
274 // We had something like \textwidth without a factor
280 value = trimSpaceAndEol(string(length, 0, i));
284 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
285 if (contains(len, '\\'))
286 unit = trimSpaceAndEol(string(len, i));
288 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
293 /// A simple function to translate a latex length to something LyX can
294 /// understand. Not perfect, but rather best-effort.
295 bool translate_len(string const & length, string & valstring, string & unit)
297 if (!splitLatexLength(length, valstring, unit))
299 // LyX uses percent values
301 istringstream iss(valstring);
306 string const percentval = oss.str();
308 if (unit.empty() || unit[0] != '\\')
310 string::size_type const i = unit.find(' ');
311 string const endlen = (i == string::npos) ? string() : string(unit, i);
312 if (unit == "\\textwidth") {
313 valstring = percentval;
314 unit = "text%" + endlen;
315 } else if (unit == "\\columnwidth") {
316 valstring = percentval;
317 unit = "col%" + endlen;
318 } else if (unit == "\\paperwidth") {
319 valstring = percentval;
320 unit = "page%" + endlen;
321 } else if (unit == "\\linewidth") {
322 valstring = percentval;
323 unit = "line%" + endlen;
324 } else if (unit == "\\paperheight") {
325 valstring = percentval;
326 unit = "pheight%" + endlen;
327 } else if (unit == "\\textheight") {
328 valstring = percentval;
329 unit = "theight%" + endlen;
337 string translate_len(string const & length)
341 if (translate_len(length, value, unit))
343 // If the input is invalid, return what we have.
351 * Translates a LaTeX length into \p value, \p unit and
352 * \p special parts suitable for a box inset.
353 * The difference from translate_len() is that a box inset knows about
354 * some special "units" that are stored in \p special.
356 void translate_box_len(string const & length, string & value, string & unit, string & special)
358 if (translate_len(length, value, unit)) {
359 if (unit == "\\height" || unit == "\\depth" ||
360 unit == "\\totalheight" || unit == "\\width") {
361 special = unit.substr(1);
362 // The unit is not used, but LyX requires a dummy setting
375 * Find a file with basename \p name in path \p path and an extension
378 string find_file(string const & name, string const & path,
379 char const * const * extensions)
381 for (char const * const * what = extensions; *what; ++what) {
382 string const trial = addExtension(name, *what);
383 if (makeAbsPath(trial, path).exists())
390 void begin_inset(ostream & os, string const & name)
392 os << "\n\\begin_inset " << name;
396 void begin_command_inset(ostream & os, string const & name,
397 string const & latexname)
399 begin_inset(os, "CommandInset ");
400 os << name << "\nLatexCommand " << latexname << '\n';
404 void end_inset(ostream & os)
406 os << "\n\\end_inset\n\n";
410 bool skip_braces(Parser & p)
412 if (p.next_token().cat() != catBegin)
415 if (p.next_token().cat() == catEnd) {
424 /// replace LaTeX commands in \p s from the unicodesymbols file with their
426 docstring convert_unicodesymbols(docstring s)
429 for (size_t i = 0; i < s.size();) {
436 docstring parsed = encodings.fromLaTeXCommand(s, rem,
437 Encodings::TEXT_CMD);
440 if (s.empty() || s[0] != '\\')
449 /// try to convert \p s to a valid InsetCommand argument
450 string convert_command_inset_arg(string s)
453 // since we don't know the input encoding we can't use from_utf8
454 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
455 // LyX cannot handle newlines in a latex command
456 return subst(s, "\n", " ");
460 void handle_backslash(ostream & os, string const & s)
462 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
464 os << "\n\\backslash\n";
471 void handle_ert(ostream & os, string const & s, Context & context)
473 // We must have a valid layout before outputting the ERT inset.
474 context.check_layout(os);
475 Context newcontext(true, context.textclass);
476 begin_inset(os, "ERT");
477 os << "\nstatus collapsed\n";
478 newcontext.check_layout(os);
479 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
481 os << "\n\\backslash\n";
482 else if (*it == '\n') {
483 newcontext.new_paragraph(os);
484 newcontext.check_layout(os);
488 newcontext.check_end_layout(os);
493 void handle_comment(ostream & os, string const & s, Context & context)
495 // TODO: Handle this better
496 Context newcontext(true, context.textclass);
497 begin_inset(os, "ERT");
498 os << "\nstatus collapsed\n";
499 newcontext.check_layout(os);
500 handle_backslash(os, s);
501 // make sure that our comment is the last thing on the line
502 newcontext.new_paragraph(os);
503 newcontext.check_layout(os);
504 newcontext.check_end_layout(os);
509 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
511 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
514 if (checkModule(name, command))
515 return findLayoutWithoutModule(textclass, name, command);
520 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
522 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
525 if (checkModule(name, command))
526 return findInsetLayoutWithoutModule(textclass, name, command);
531 void eat_whitespace(Parser &, ostream &, Context &, bool);
535 * Skips whitespace and braces.
536 * This should be called after a command has been parsed that is not put into
537 * ERT, and where LyX adds "{}" if needed.
539 void skip_spaces_braces(Parser & p, bool keepws = false)
541 /* The following four examples produce the same typeset output and
542 should be handled by this function:
550 // Unfortunately we need to skip comments, too.
551 // We can't use eat_whitespace since writing them after the {}
552 // results in different output in some cases.
553 bool const skipped_spaces = p.skip_spaces(true);
554 bool const skipped_braces = skip_braces(p);
555 if (keepws && skipped_spaces && !skipped_braces)
556 // put back the space (it is better handled by check_space)
557 p.unskip_spaces(true);
561 void output_command_layout(ostream & os, Parser & p, bool outer,
562 Context & parent_context,
563 Layout const * newlayout)
565 TeXFont const oldFont = parent_context.font;
566 // save the current font size
567 string const size = oldFont.size;
568 // reset the font size to default, because the font size switches
569 // don't affect section headings and the like
570 parent_context.font.size = Context::normalfont.size;
571 // we only need to write the font change if we have an open layout
572 if (!parent_context.atParagraphStart())
573 output_font_change(os, oldFont, parent_context.font);
574 parent_context.check_end_layout(os);
575 Context context(true, parent_context.textclass, newlayout,
576 parent_context.layout, parent_context.font);
577 if (parent_context.deeper_paragraph) {
578 // We are beginning a nested environment after a
579 // deeper paragraph inside the outer list environment.
580 // Therefore we don't need to output a "begin deeper".
581 context.need_end_deeper = true;
583 context.check_deeper(os);
584 context.check_layout(os);
585 unsigned int optargs = 0;
586 while (optargs < context.layout->optargs) {
587 eat_whitespace(p, os, context, false);
588 if (p.next_token().cat() == catEscape ||
589 p.next_token().character() != '[')
591 p.get_token(); // eat '['
592 begin_inset(os, "Argument\n");
593 os << "status collapsed\n\n";
594 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
596 eat_whitespace(p, os, context, false);
599 unsigned int reqargs = 0;
600 while (reqargs < context.layout->reqargs) {
601 eat_whitespace(p, os, context, false);
602 if (p.next_token().cat() != catBegin)
604 p.get_token(); // eat '{'
605 begin_inset(os, "Argument\n");
606 os << "status collapsed\n\n";
607 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
609 eat_whitespace(p, os, context, false);
612 parse_text(p, os, FLAG_ITEM, outer, context);
613 context.check_end_layout(os);
614 if (parent_context.deeper_paragraph) {
615 // We must suppress the "end deeper" because we
616 // suppressed the "begin deeper" above.
617 context.need_end_deeper = false;
619 context.check_end_deeper(os);
620 // We don't need really a new paragraph, but
621 // we must make sure that the next item gets a \begin_layout.
622 parent_context.new_paragraph(os);
623 // Set the font size to the original value. No need to output it here
624 // (Context::begin_layout() will do that if needed)
625 parent_context.font.size = size;
630 * Output a space if necessary.
631 * This function gets called for every whitespace token.
633 * We have three cases here:
634 * 1. A space must be suppressed. Example: The lyxcode case below
635 * 2. A space may be suppressed. Example: Spaces before "\par"
636 * 3. A space must not be suppressed. Example: A space between two words
638 * We currently handle only 1. and 3 and from 2. only the case of
639 * spaces before newlines as a side effect.
641 * 2. could be used to suppress as many spaces as possible. This has two effects:
642 * - Reimporting LyX generated LaTeX files changes almost no whitespace
643 * - Superflous whitespace from non LyX generated LaTeX files is removed.
644 * The drawback is that the logic inside the function becomes
645 * complicated, and that is the reason why it is not implemented.
647 void check_space(Parser & p, ostream & os, Context & context)
649 Token const next = p.next_token();
650 Token const curr = p.curr_token();
651 // A space before a single newline and vice versa must be ignored
652 // LyX emits a newline before \end{lyxcode}.
653 // This newline must be ignored,
654 // otherwise LyX will add an additional protected space.
655 if (next.cat() == catSpace ||
656 next.cat() == catNewline ||
657 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
660 context.check_layout(os);
666 * Parse all arguments of \p command
668 void parse_arguments(string const & command,
669 vector<ArgumentType> const & template_arguments,
670 Parser & p, ostream & os, bool outer, Context & context)
672 string ert = command;
673 size_t no_arguments = template_arguments.size();
674 for (size_t i = 0; i < no_arguments; ++i) {
675 switch (template_arguments[i]) {
677 // This argument contains regular LaTeX
678 handle_ert(os, ert + '{', context);
679 eat_whitespace(p, os, context, false);
680 parse_text(p, os, FLAG_ITEM, outer, context);
684 // This argument consists only of a single item.
685 // The presence of '{' or not must be preserved.
687 if (p.next_token().cat() == catBegin)
688 ert += '{' + p.verbatim_item() + '}';
690 ert += p.verbatim_item();
693 // This argument may contain special characters
694 ert += '{' + p.verbatim_item() + '}';
697 // true because we must not eat whitespace
698 // if an optional arg follows we must not strip the
699 // brackets from this one
700 if (i < no_arguments - 1 &&
701 template_arguments[i+1] == optional)
702 ert += p.getFullOpt(true);
704 ert += p.getOpt(true);
708 handle_ert(os, ert, context);
713 * Check whether \p command is a known command. If yes,
714 * handle the command with all arguments.
715 * \return true if the command was parsed, false otherwise.
717 bool parse_command(string const & command, Parser & p, ostream & os,
718 bool outer, Context & context)
720 if (known_commands.find(command) != known_commands.end()) {
721 parse_arguments(command, known_commands[command], p, os,
729 /// Parses a minipage or parbox
730 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
731 unsigned inner_flags, bool outer, Context & parent_context,
732 string const & outer_type, string const & special,
733 string const & inner_type)
737 string hor_pos = "c";
738 // We need to set the height to the LaTeX default of 1\\totalheight
739 // for the case when no height argument is given
740 string height_value = "1";
741 string height_unit = "in";
742 string height_special = "totalheight";
747 string width_special = "none";
748 if (!inner_type.empty() && p.hasOpt()) {
749 if (inner_type != "makebox")
750 position = p.getArg('[', ']');
752 latex_width = p.getArg('[', ']');
753 translate_box_len(latex_width, width_value, width_unit, width_special);
756 if (position != "t" && position != "c" && position != "b") {
757 cerr << "invalid position " << position << " for "
758 << inner_type << endl;
762 if (inner_type != "makebox") {
763 latex_height = p.getArg('[', ']');
764 translate_box_len(latex_height, height_value, height_unit, height_special);
766 hor_pos = p.getArg('[', ']');
769 inner_pos = p.getArg('[', ']');
770 if (inner_pos != "c" && inner_pos != "t" &&
771 inner_pos != "b" && inner_pos != "s") {
772 cerr << "invalid inner_pos "
773 << inner_pos << " for "
774 << inner_type << endl;
775 inner_pos = position;
780 if (inner_type.empty()) {
781 if (special.empty() && outer_type != "framebox")
782 latex_width = "1\\columnwidth";
785 latex_width = p2.getArg('[', ']');
786 string const opt = p2.getArg('[', ']');
789 if (hor_pos != "l" && hor_pos != "c" &&
791 cerr << "invalid hor_pos " << hor_pos
792 << " for " << outer_type << endl;
797 } else if (inner_type != "makebox")
798 latex_width = p.verbatim_item();
799 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
800 // as this is LyX's standard for such cases (except for makebox)
801 // \framebox is more special and handled below
802 if (latex_width.empty() && inner_type != "makebox"
803 && outer_type != "framebox")
804 latex_width = "1\\columnwidth";
806 translate_len(latex_width, width_value, width_unit);
808 bool shadedparbox = false;
809 if (inner_type == "shaded") {
810 eat_whitespace(p, os, parent_context, false);
811 if (outer_type == "parbox") {
813 if (p.next_token().cat() == catBegin)
815 eat_whitespace(p, os, parent_context, false);
821 // If we already read the inner box we have to push the inner env
822 if (!outer_type.empty() && !inner_type.empty() &&
823 (inner_flags & FLAG_END))
824 active_environments.push_back(inner_type);
825 // LyX can't handle length variables
826 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
827 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
828 // Look whether there is some content after the end of the
829 // inner box, but before the end of the outer box.
830 // If yes, we need to output ERT.
832 if (inner_flags & FLAG_END)
833 p.verbatimEnvironment(inner_type);
837 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
838 if ((outer_env && p.next_token().asInput() != "\\end") ||
839 (!outer_env && p.next_token().cat() != catEnd)) {
840 // something is between the end of the inner box and
841 // the end of the outer box, so we need to use ERT.
846 // if only \makebox{content} was used we can set its width to 1\width
847 // because this identic and also identic to \mbox
848 // this doesn't work for \framebox{content}, thus we have to use ERT for this
849 if (latex_width.empty() && inner_type == "makebox") {
852 width_special = "width";
853 } else if (latex_width.empty() && outer_type == "framebox") {
858 if (!outer_type.empty()) {
859 if (outer_flags & FLAG_END)
860 ss << "\\begin{" << outer_type << '}';
862 ss << '\\' << outer_type << '{';
863 if (!special.empty())
867 if (!inner_type.empty()) {
868 if (inner_type != "shaded") {
869 if (inner_flags & FLAG_END)
870 ss << "\\begin{" << inner_type << '}';
872 ss << '\\' << inner_type;
874 if (!position.empty())
875 ss << '[' << position << ']';
876 if (!latex_height.empty())
877 ss << '[' << latex_height << ']';
878 if (!inner_pos.empty())
879 ss << '[' << inner_pos << ']';
880 ss << '{' << latex_width << '}';
881 if (!(inner_flags & FLAG_END))
884 if (inner_type == "shaded")
885 ss << "\\begin{shaded}";
886 handle_ert(os, ss.str(), parent_context);
887 if (!inner_type.empty()) {
888 parse_text(p, os, inner_flags, outer, parent_context);
889 if (inner_flags & FLAG_END)
890 handle_ert(os, "\\end{" + inner_type + '}',
893 handle_ert(os, "}", parent_context);
895 if (!outer_type.empty()) {
896 // If we already read the inner box we have to pop
898 if (!inner_type.empty() && (inner_flags & FLAG_END))
899 active_environments.pop_back();
901 // Ensure that the end of the outer box is parsed correctly:
902 // The opening brace has been eaten by parse_outer_box()
903 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
904 outer_flags &= ~FLAG_ITEM;
905 outer_flags |= FLAG_BRACE_LAST;
907 parse_text(p, os, outer_flags, outer, parent_context);
908 if (outer_flags & FLAG_END)
909 handle_ert(os, "\\end{" + outer_type + '}',
911 else if (inner_type.empty() && outer_type == "framebox")
912 // in this case it is already closed later
915 handle_ert(os, "}", parent_context);
918 // LyX does not like empty positions, so we have
919 // to set them to the LaTeX default values here.
920 if (position.empty())
922 if (inner_pos.empty())
923 inner_pos = position;
924 parent_context.check_layout(os);
925 begin_inset(os, "Box ");
926 if (outer_type == "framed")
928 else if (outer_type == "framebox")
930 else if (outer_type == "shadowbox")
932 else if ((outer_type == "shaded" && inner_type.empty()) ||
933 (outer_type == "minipage" && inner_type == "shaded") ||
934 (outer_type == "parbox" && inner_type == "shaded")) {
936 preamble.registerAutomaticallyLoadedPackage("color");
937 } else if (outer_type == "doublebox")
939 else if (outer_type.empty())
942 os << outer_type << '\n';
943 os << "position \"" << position << "\"\n";
944 os << "hor_pos \"" << hor_pos << "\"\n";
945 os << "has_inner_box " << !inner_type.empty() << "\n";
946 os << "inner_pos \"" << inner_pos << "\"\n";
947 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
949 os << "use_makebox " << (inner_type == "makebox") << '\n';
950 os << "width \"" << width_value << width_unit << "\"\n";
951 os << "special \"" << width_special << "\"\n";
952 os << "height \"" << height_value << height_unit << "\"\n";
953 os << "height_special \"" << height_special << "\"\n";
954 os << "status open\n\n";
956 // Unfortunately we can't use parse_text_in_inset:
957 // InsetBox::forcePlainLayout() is hard coded and does not
958 // use the inset layout. Apart from that do we call parse_text
959 // up to two times, but need only one check_end_layout.
960 bool const forcePlainLayout =
961 (!inner_type.empty() || inner_type == "makebox") &&
962 outer_type != "shaded" && outer_type != "framed";
963 Context context(true, parent_context.textclass);
964 if (forcePlainLayout)
965 context.layout = &context.textclass.plainLayout();
967 context.font = parent_context.font;
969 // If we have no inner box the contents will be read with the outer box
970 if (!inner_type.empty())
971 parse_text(p, os, inner_flags, outer, context);
973 // Ensure that the end of the outer box is parsed correctly:
974 // The opening brace has been eaten by parse_outer_box()
975 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
976 outer_flags &= ~FLAG_ITEM;
977 outer_flags |= FLAG_BRACE_LAST;
980 // Find end of outer box, output contents if inner_type is
981 // empty and output possible comments
982 if (!outer_type.empty()) {
983 // If we already read the inner box we have to pop
985 if (!inner_type.empty() && (inner_flags & FLAG_END))
986 active_environments.pop_back();
987 // This does not output anything but comments if
988 // inner_type is not empty (see use_ert)
989 parse_text(p, os, outer_flags, outer, context);
992 context.check_end_layout(os);
994 #ifdef PRESERVE_LAYOUT
995 // LyX puts a % after the end of the minipage
996 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
998 //handle_comment(os, "%dummy", parent_context);
1001 parent_context.new_paragraph(os);
1003 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1004 //handle_comment(os, "%dummy", parent_context);
1007 // We add a protected space if something real follows
1008 if (p.good() && p.next_token().cat() != catComment) {
1009 begin_inset(os, "space ~\n");
1018 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1019 Context & parent_context, string const & outer_type,
1020 string const & special)
1022 eat_whitespace(p, os, parent_context, false);
1023 if (flags & FLAG_ITEM) {
1025 if (p.next_token().cat() == catBegin)
1028 cerr << "Warning: Ignoring missing '{' after \\"
1029 << outer_type << '.' << endl;
1030 eat_whitespace(p, os, parent_context, false);
1033 unsigned int inner_flags = 0;
1035 if (outer_type == "minipage" || outer_type == "parbox") {
1036 p.skip_spaces(true);
1037 while (p.hasOpt()) {
1039 p.skip_spaces(true);
1042 p.skip_spaces(true);
1043 if (outer_type == "parbox") {
1045 if (p.next_token().cat() == catBegin)
1047 p.skip_spaces(true);
1050 if (outer_type == "shaded") {
1051 // These boxes never have an inner box
1053 } else if (p.next_token().asInput() == "\\parbox") {
1054 inner = p.get_token().cs();
1055 inner_flags = FLAG_ITEM;
1056 } else if (p.next_token().asInput() == "\\begin") {
1057 // Is this a minipage or shaded box?
1060 inner = p.getArg('{', '}');
1062 if (inner == "minipage" || inner == "shaded")
1063 inner_flags = FLAG_END;
1068 if (inner_flags == FLAG_END) {
1069 if (inner != "shaded")
1073 eat_whitespace(p, os, parent_context, false);
1075 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1076 outer_type, special, inner);
1078 if (inner_flags == FLAG_ITEM) {
1080 eat_whitespace(p, os, parent_context, false);
1082 parse_box(p, os, flags, inner_flags, outer, parent_context,
1083 outer_type, special, inner);
1088 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1090 parent_context.check_layout(os);
1091 begin_inset(os, "listings\n");
1092 os << "inline false\n"
1093 << "status collapsed\n";
1094 Context context(true, parent_context.textclass);
1095 context.layout = &parent_context.textclass.plainLayout();
1096 context.check_layout(os);
1097 string const s = p.verbatimEnvironment("lstlisting");
1098 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1100 os << "\n\\backslash\n";
1101 else if (*it == '\n') {
1102 // avoid adding an empty paragraph at the end
1104 context.new_paragraph(os);
1105 context.check_layout(os);
1110 context.check_end_layout(os);
1115 /// parse an unknown environment
1116 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1117 unsigned flags, bool outer,
1118 Context & parent_context)
1120 if (name == "tabbing")
1121 // We need to remember that we have to handle '\=' specially
1122 flags |= FLAG_TABBING;
1124 // We need to translate font changes and paragraphs inside the
1125 // environment to ERT if we have a non standard font.
1126 // Otherwise things like
1127 // \large\begin{foo}\huge bar\end{foo}
1129 bool const specialfont =
1130 (parent_context.font != parent_context.normalfont);
1131 bool const new_layout_allowed = parent_context.new_layout_allowed;
1133 parent_context.new_layout_allowed = false;
1134 handle_ert(os, "\\begin{" + name + "}", parent_context);
1135 parse_text_snippet(p, os, flags, outer, parent_context);
1136 handle_ert(os, "\\end{" + name + "}", parent_context);
1138 parent_context.new_layout_allowed = new_layout_allowed;
1142 void parse_environment(Parser & p, ostream & os, bool outer,
1143 string & last_env, bool & title_layout_found,
1144 Context & parent_context)
1146 Layout const * newlayout;
1147 InsetLayout const * newinsetlayout = 0;
1148 string const name = p.getArg('{', '}');
1149 const bool is_starred = suffixIs(name, '*');
1150 string const unstarred_name = rtrim(name, "*");
1151 active_environments.push_back(name);
1153 if (is_math_env(name)) {
1154 parent_context.check_layout(os);
1155 begin_inset(os, "Formula ");
1156 os << "\\begin{" << name << "}";
1157 parse_math(p, os, FLAG_END, MATH_MODE);
1158 os << "\\end{" << name << "}";
1162 else if (unstarred_name == "tabular" || name == "longtable") {
1163 eat_whitespace(p, os, parent_context, false);
1164 string width = "0pt";
1165 if (name == "tabular*") {
1166 width = lyx::translate_len(p.getArg('{', '}'));
1167 eat_whitespace(p, os, parent_context, false);
1169 parent_context.check_layout(os);
1170 begin_inset(os, "Tabular ");
1171 handle_tabular(p, os, name, width, parent_context);
1176 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1177 eat_whitespace(p, os, parent_context, false);
1178 parent_context.check_layout(os);
1179 begin_inset(os, "Float " + unstarred_name + "\n");
1180 // store the float type for subfloats
1181 // subfloats only work with figures and tables
1182 if (unstarred_name == "figure")
1183 float_type = unstarred_name;
1184 else if (unstarred_name == "table")
1185 float_type = unstarred_name;
1189 os << "placement " << p.getArg('[', ']') << '\n';
1190 os << "wide " << convert<string>(is_starred)
1191 << "\nsideways false"
1192 << "\nstatus open\n\n";
1193 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1195 // We don't need really a new paragraph, but
1196 // we must make sure that the next item gets a \begin_layout.
1197 parent_context.new_paragraph(os);
1199 // the float is parsed thus delete the type
1203 else if (unstarred_name == "sidewaysfigure"
1204 || unstarred_name == "sidewaystable") {
1205 eat_whitespace(p, os, parent_context, false);
1206 parent_context.check_layout(os);
1207 if (unstarred_name == "sidewaysfigure")
1208 begin_inset(os, "Float figure\n");
1210 begin_inset(os, "Float table\n");
1211 os << "wide " << convert<string>(is_starred)
1212 << "\nsideways true"
1213 << "\nstatus open\n\n";
1214 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1216 // We don't need really a new paragraph, but
1217 // we must make sure that the next item gets a \begin_layout.
1218 parent_context.new_paragraph(os);
1222 else if (name == "wrapfigure" || name == "wraptable") {
1223 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1224 eat_whitespace(p, os, parent_context, false);
1225 parent_context.check_layout(os);
1228 string overhang = "0col%";
1231 lines = p.getArg('[', ']');
1232 string const placement = p.getArg('{', '}');
1234 overhang = p.getArg('[', ']');
1235 string const width = p.getArg('{', '}');
1237 if (name == "wrapfigure")
1238 begin_inset(os, "Wrap figure\n");
1240 begin_inset(os, "Wrap table\n");
1241 os << "lines " << lines
1242 << "\nplacement " << placement
1243 << "\noverhang " << lyx::translate_len(overhang)
1244 << "\nwidth " << lyx::translate_len(width)
1245 << "\nstatus open\n\n";
1246 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1248 // We don't need really a new paragraph, but
1249 // we must make sure that the next item gets a \begin_layout.
1250 parent_context.new_paragraph(os);
1254 else if (name == "minipage") {
1255 eat_whitespace(p, os, parent_context, false);
1256 // Test whether this is an outer box of a shaded box
1258 // swallow arguments
1259 while (p.hasOpt()) {
1261 p.skip_spaces(true);
1264 p.skip_spaces(true);
1265 Token t = p.get_token();
1266 bool shaded = false;
1267 if (t.asInput() == "\\begin") {
1268 p.skip_spaces(true);
1269 if (p.getArg('{', '}') == "shaded")
1274 parse_outer_box(p, os, FLAG_END, outer,
1275 parent_context, name, "shaded");
1277 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1282 else if (name == "comment") {
1283 eat_whitespace(p, os, parent_context, false);
1284 parent_context.check_layout(os);
1285 begin_inset(os, "Note Comment\n");
1286 os << "status open\n";
1287 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1290 skip_braces(p); // eat {} that might by set by LyX behind comments
1293 else if (name == "lyxgreyedout") {
1294 eat_whitespace(p, os, parent_context, false);
1295 parent_context.check_layout(os);
1296 begin_inset(os, "Note Greyedout\n");
1297 os << "status open\n";
1298 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1301 if (!preamble.notefontcolor().empty())
1302 preamble.registerAutomaticallyLoadedPackage("color");
1305 else if (name == "framed" || name == "shaded") {
1306 eat_whitespace(p, os, parent_context, false);
1307 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1311 else if (name == "lstlisting") {
1312 eat_whitespace(p, os, parent_context, false);
1313 // FIXME handle listings with parameters
1314 // If this is added, don't forgot to handle the
1315 // automatic color package loading
1317 parse_unknown_environment(p, name, os, FLAG_END,
1318 outer, parent_context);
1320 parse_listings(p, os, parent_context);
1324 else if (!parent_context.new_layout_allowed)
1325 parse_unknown_environment(p, name, os, FLAG_END, outer,
1328 // Alignment and spacing settings
1329 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1330 // therefore are totally broken!
1331 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1332 // they are commands not environments. They are furthermore switches that
1333 // can be ended by another switches, but also by commands like \footnote or
1334 // \parbox. So the only safe way is to leave them untouched.
1335 else if (name == "center" || name == "centering" ||
1336 name == "flushleft" || name == "flushright" ||
1337 name == "singlespace" || name == "onehalfspace" ||
1338 name == "doublespace" || name == "spacing") {
1339 eat_whitespace(p, os, parent_context, false);
1340 // We must begin a new paragraph if not already done
1341 if (! parent_context.atParagraphStart()) {
1342 parent_context.check_end_layout(os);
1343 parent_context.new_paragraph(os);
1345 if (name == "flushleft")
1346 parent_context.add_extra_stuff("\\align left\n");
1347 else if (name == "flushright")
1348 parent_context.add_extra_stuff("\\align right\n");
1349 else if (name == "center" || name == "centering")
1350 parent_context.add_extra_stuff("\\align center\n");
1351 else if (name == "singlespace")
1352 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1353 else if (name == "onehalfspace")
1354 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1355 else if (name == "doublespace")
1356 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1357 else if (name == "spacing")
1358 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1359 parse_text(p, os, FLAG_END, outer, parent_context);
1360 // Just in case the environment is empty
1361 parent_context.extra_stuff.erase();
1362 // We must begin a new paragraph to reset the alignment
1363 parent_context.new_paragraph(os);
1367 // The single '=' is meant here.
1368 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1369 eat_whitespace(p, os, parent_context, false);
1370 Context context(true, parent_context.textclass, newlayout,
1371 parent_context.layout, parent_context.font);
1372 if (parent_context.deeper_paragraph) {
1373 // We are beginning a nested environment after a
1374 // deeper paragraph inside the outer list environment.
1375 // Therefore we don't need to output a "begin deeper".
1376 context.need_end_deeper = true;
1378 parent_context.check_end_layout(os);
1379 if (last_env == name) {
1380 // we need to output a separator since LyX would export
1381 // the two environments as one otherwise (bug 5716)
1382 docstring const sep = from_ascii("--Separator--");
1383 TeX2LyXDocClass const & textclass(parent_context.textclass);
1384 if (textclass.hasLayout(sep)) {
1385 Context newcontext(parent_context);
1386 newcontext.layout = &(textclass[sep]);
1387 newcontext.check_layout(os);
1388 newcontext.check_end_layout(os);
1390 parent_context.check_layout(os);
1391 begin_inset(os, "Note Note\n");
1392 os << "status closed\n";
1393 Context newcontext(true, textclass,
1394 &(textclass.defaultLayout()));
1395 newcontext.check_layout(os);
1396 newcontext.check_end_layout(os);
1398 parent_context.check_end_layout(os);
1401 switch (context.layout->latextype) {
1402 case LATEX_LIST_ENVIRONMENT:
1403 context.add_par_extra_stuff("\\labelwidthstring "
1404 + p.verbatim_item() + '\n');
1407 case LATEX_BIB_ENVIRONMENT:
1408 p.verbatim_item(); // swallow next arg
1414 context.check_deeper(os);
1415 // handle known optional and required arguments
1416 // layouts require all optional arguments before the required ones
1417 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1418 // It is impossible to place anything after the environment name,
1419 // but before the first \\item.
1420 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1421 bool need_layout = true;
1422 unsigned int optargs = 0;
1423 while (optargs < context.layout->optargs) {
1424 eat_whitespace(p, os, context, false);
1425 if (p.next_token().cat() == catEscape ||
1426 p.next_token().character() != '[')
1428 p.get_token(); // eat '['
1430 context.check_layout(os);
1431 need_layout = false;
1433 begin_inset(os, "Argument\n");
1434 os << "status collapsed\n\n";
1435 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1437 eat_whitespace(p, os, context, false);
1440 unsigned int reqargs = 0;
1441 while (reqargs < context.layout->reqargs) {
1442 eat_whitespace(p, os, context, false);
1443 if (p.next_token().cat() != catBegin)
1445 p.get_token(); // eat '{'
1447 context.check_layout(os);
1448 need_layout = false;
1450 begin_inset(os, "Argument\n");
1451 os << "status collapsed\n\n";
1452 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1454 eat_whitespace(p, os, context, false);
1458 parse_text(p, os, FLAG_END, outer, context);
1459 context.check_end_layout(os);
1460 if (parent_context.deeper_paragraph) {
1461 // We must suppress the "end deeper" because we
1462 // suppressed the "begin deeper" above.
1463 context.need_end_deeper = false;
1465 context.check_end_deeper(os);
1466 parent_context.new_paragraph(os);
1468 if (!title_layout_found)
1469 title_layout_found = newlayout->intitle;
1472 // The single '=' is meant here.
1473 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1474 eat_whitespace(p, os, parent_context, false);
1475 parent_context.check_layout(os);
1476 begin_inset(os, "Flex ");
1477 os << to_utf8(newinsetlayout->name()) << '\n'
1478 << "status collapsed\n";
1479 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1483 else if (name == "appendix") {
1484 // This is no good latex style, but it works and is used in some documents...
1485 eat_whitespace(p, os, parent_context, false);
1486 parent_context.check_end_layout(os);
1487 Context context(true, parent_context.textclass, parent_context.layout,
1488 parent_context.layout, parent_context.font);
1489 context.check_layout(os);
1490 os << "\\start_of_appendix\n";
1491 parse_text(p, os, FLAG_END, outer, context);
1492 context.check_end_layout(os);
1496 else if (known_environments.find(name) != known_environments.end()) {
1497 vector<ArgumentType> arguments = known_environments[name];
1498 // The last "argument" denotes wether we may translate the
1499 // environment contents to LyX
1500 // The default required if no argument is given makes us
1501 // compatible with the reLyXre environment.
1502 ArgumentType contents = arguments.empty() ?
1505 if (!arguments.empty())
1506 arguments.pop_back();
1507 // See comment in parse_unknown_environment()
1508 bool const specialfont =
1509 (parent_context.font != parent_context.normalfont);
1510 bool const new_layout_allowed =
1511 parent_context.new_layout_allowed;
1513 parent_context.new_layout_allowed = false;
1514 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1515 outer, parent_context);
1516 if (contents == verbatim)
1517 handle_ert(os, p.verbatimEnvironment(name),
1520 parse_text_snippet(p, os, FLAG_END, outer,
1522 handle_ert(os, "\\end{" + name + "}", parent_context);
1524 parent_context.new_layout_allowed = new_layout_allowed;
1528 parse_unknown_environment(p, name, os, FLAG_END, outer,
1532 active_environments.pop_back();
1536 /// parses a comment and outputs it to \p os.
1537 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1539 LASSERT(t.cat() == catComment, return);
1540 if (!t.cs().empty()) {
1541 context.check_layout(os);
1542 handle_comment(os, '%' + t.cs(), context);
1543 if (p.next_token().cat() == catNewline) {
1544 // A newline after a comment line starts a new
1546 if (context.new_layout_allowed) {
1547 if(!context.atParagraphStart())
1548 // Only start a new paragraph if not already
1549 // done (we might get called recursively)
1550 context.new_paragraph(os);
1552 handle_ert(os, "\n", context);
1553 eat_whitespace(p, os, context, true);
1556 // "%\n" combination
1563 * Reads spaces and comments until the first non-space, non-comment token.
1564 * New paragraphs (double newlines or \\par) are handled like simple spaces
1565 * if \p eatParagraph is true.
1566 * Spaces are skipped, but comments are written to \p os.
1568 void eat_whitespace(Parser & p, ostream & os, Context & context,
1572 Token const & t = p.get_token();
1573 if (t.cat() == catComment)
1574 parse_comment(p, os, t, context);
1575 else if ((! eatParagraph && p.isParagraph()) ||
1576 (t.cat() != catSpace && t.cat() != catNewline)) {
1585 * Set a font attribute, parse text and reset the font attribute.
1586 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1587 * \param currentvalue Current value of the attribute. Is set to the new
1588 * value during parsing.
1589 * \param newvalue New value of the attribute
1591 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1592 Context & context, string const & attribute,
1593 string & currentvalue, string const & newvalue)
1595 context.check_layout(os);
1596 string const oldvalue = currentvalue;
1597 currentvalue = newvalue;
1598 os << '\n' << attribute << ' ' << newvalue << "\n";
1599 parse_text_snippet(p, os, flags, outer, context);
1600 context.check_layout(os);
1601 os << '\n' << attribute << ' ' << oldvalue << "\n";
1602 currentvalue = oldvalue;
1606 /// get the arguments of a natbib or jurabib citation command
1607 void get_cite_arguments(Parser & p, bool natbibOrder,
1608 string & before, string & after)
1610 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1612 // text before the citation
1614 // text after the citation
1615 after = p.getFullOpt();
1617 if (!after.empty()) {
1618 before = p.getFullOpt();
1619 if (natbibOrder && !before.empty())
1620 swap(before, after);
1625 /// Convert filenames with TeX macros and/or quotes to something LyX
1627 string const normalize_filename(string const & name)
1629 Parser p(trim(name, "\""));
1632 Token const & t = p.get_token();
1633 if (t.cat() != catEscape)
1635 else if (t.cs() == "lyxdot") {
1636 // This is used by LyX for simple dots in relative
1640 } else if (t.cs() == "space") {
1650 /// Convert \p name from TeX convention (relative to master file) to LyX
1651 /// convention (relative to .lyx file) if it is relative
1652 void fix_relative_filename(string & name)
1654 if (FileName::isAbsolute(name))
1657 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1658 from_utf8(getParentFilePath())));
1662 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1663 void parse_noweb(Parser & p, ostream & os, Context & context)
1665 // assemble the rest of the keyword
1669 Token const & t = p.get_token();
1670 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1673 scrap = (p.good() && p.next_token().asInput() == "=");
1675 name += p.get_token().asInput();
1678 name += t.asInput();
1681 if (!scrap || !context.new_layout_allowed ||
1682 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1683 cerr << "Warning: Could not interpret '" << name
1684 << "'. Ignoring it." << endl;
1688 // We use new_paragraph instead of check_end_layout because the stuff
1689 // following the noweb chunk needs to start with a \begin_layout.
1690 // This may create a new paragraph even if there was none in the
1691 // noweb file, but the alternative is an invalid LyX file. Since
1692 // noweb code chunks are implemented with a layout style in LyX they
1693 // always must be in an own paragraph.
1694 context.new_paragraph(os);
1695 Context newcontext(true, context.textclass,
1696 &context.textclass[from_ascii("Scrap")]);
1697 newcontext.check_layout(os);
1700 Token const & t = p.get_token();
1701 // We abuse the parser a bit, because this is no TeX syntax
1703 if (t.cat() == catEscape)
1704 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1707 Context tmp(false, context.textclass,
1708 &context.textclass[from_ascii("Scrap")]);
1709 tmp.need_end_layout = true;
1710 tmp.check_layout(oss);
1711 os << subst(t.asInput(), "\n", oss.str());
1713 // The scrap chunk is ended by an @ at the beginning of a line.
1714 // After the @ the line may contain a comment and/or
1715 // whitespace, but nothing else.
1716 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1717 (p.next_token().cat() == catSpace ||
1718 p.next_token().cat() == catNewline ||
1719 p.next_token().cat() == catComment)) {
1720 while (p.good() && p.next_token().cat() == catSpace)
1721 os << p.get_token().asInput();
1722 if (p.next_token().cat() == catComment)
1723 // The comment includes a final '\n'
1724 os << p.get_token().asInput();
1726 if (p.next_token().cat() == catNewline)
1733 newcontext.check_end_layout(os);
1737 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1738 bool is_macro(Parser & p)
1740 Token first = p.curr_token();
1741 if (first.cat() != catEscape || !p.good())
1743 if (first.cs() == "def")
1745 if (first.cs() != "global" && first.cs() != "long")
1747 Token second = p.get_token();
1749 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1750 second.cat() == catNewline || second.cat() == catComment)) {
1751 second = p.get_token();
1754 bool secondvalid = second.cat() == catEscape;
1756 bool thirdvalid = false;
1757 if (p.good() && first.cs() == "global" && secondvalid &&
1758 second.cs() == "long") {
1759 third = p.get_token();
1761 while (p.good() && !p.isParagraph() &&
1762 (third.cat() == catSpace ||
1763 third.cat() == catNewline ||
1764 third.cat() == catComment)) {
1765 third = p.get_token();
1768 thirdvalid = third.cat() == catEscape;
1770 for (int i = 0; i < pos; ++i)
1775 return (first.cs() == "global" || first.cs() == "long") &&
1776 second.cs() == "def";
1777 return first.cs() == "global" && second.cs() == "long" &&
1778 third.cs() == "def";
1782 /// Parse a macro definition (assumes that is_macro() returned true)
1783 void parse_macro(Parser & p, ostream & os, Context & context)
1785 context.check_layout(os);
1786 Token first = p.curr_token();
1789 string command = first.asInput();
1790 if (first.cs() != "def") {
1792 eat_whitespace(p, os, context, false);
1793 second = p.curr_token();
1794 command += second.asInput();
1795 if (second.cs() != "def") {
1797 eat_whitespace(p, os, context, false);
1798 third = p.curr_token();
1799 command += third.asInput();
1802 eat_whitespace(p, os, context, false);
1803 string const name = p.get_token().cs();
1804 eat_whitespace(p, os, context, false);
1810 while (p.next_token().cat() != catBegin) {
1811 if (p.next_token().cat() == catParameter) {
1816 // followed by number?
1817 if (p.next_token().cat() == catOther) {
1818 char c = p.getChar();
1820 // number = current arity + 1?
1821 if (c == arity + '0' + 1)
1826 paramtext += p.get_token().cs();
1828 paramtext += p.get_token().cs();
1833 // only output simple (i.e. compatible) macro as FormulaMacros
1834 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1836 context.check_layout(os);
1837 begin_inset(os, "FormulaMacro");
1838 os << "\n\\def" << ert;
1841 handle_ert(os, command + ert, context);
1844 } // anonymous namespace
1847 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1850 Layout const * newlayout = 0;
1851 InsetLayout const * newinsetlayout = 0;
1852 // Store the latest bibliographystyle and nocite{*} option
1853 // (needed for bibtex inset)
1855 string bibliographystyle;
1856 bool const use_natbib = preamble.isPackageUsed("natbib");
1857 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1859 bool title_layout_found = false;
1861 Token const & t = p.get_token();
1864 debugToken(cerr, t, flags);
1867 if (flags & FLAG_ITEM) {
1868 if (t.cat() == catSpace)
1871 flags &= ~FLAG_ITEM;
1872 if (t.cat() == catBegin) {
1873 // skip the brace and collect everything to the next matching
1875 flags |= FLAG_BRACE_LAST;
1879 // handle only this single token, leave the loop if done
1880 flags |= FLAG_LEAVE;
1883 if (t.cat() != catEscape && t.character() == ']' &&
1884 (flags & FLAG_BRACK_LAST))
1886 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1889 // If there is anything between \end{env} and \begin{env} we
1890 // don't need to output a separator.
1891 if (t.cat() != catSpace && t.cat() != catNewline &&
1892 t.asInput() != "\\begin")
1898 if (t.cat() == catMath) {
1899 // we are inside some text mode thingy, so opening new math is allowed
1900 context.check_layout(os);
1901 begin_inset(os, "Formula ");
1902 Token const & n = p.get_token();
1903 if (n.cat() == catMath && outer) {
1904 // TeX's $$...$$ syntax for displayed math
1906 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1908 p.get_token(); // skip the second '$' token
1910 // simple $...$ stuff
1913 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1919 else if (t.cat() == catSuper || t.cat() == catSub)
1920 cerr << "catcode " << t << " illegal in text mode\n";
1922 // Basic support for english quotes. This should be
1923 // extended to other quotes, but is not so easy (a
1924 // left english quote is the same as a right german
1926 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1927 context.check_layout(os);
1928 begin_inset(os, "Quotes ");
1934 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1935 context.check_layout(os);
1936 begin_inset(os, "Quotes ");
1943 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1944 context.check_layout(os);
1945 begin_inset(os, "Quotes ");
1952 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1953 context.check_layout(os);
1954 begin_inset(os, "Quotes ");
1961 else if (t.asInput() == "<"
1962 && p.next_token().asInput() == "<" && noweb_mode) {
1964 parse_noweb(p, os, context);
1967 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1968 check_space(p, os, context);
1970 else if (t.character() == '[' && noweb_mode &&
1971 p.next_token().character() == '[') {
1972 // These can contain underscores
1974 string const s = p.getFullOpt() + ']';
1975 if (p.next_token().character() == ']')
1978 cerr << "Warning: Inserting missing ']' in '"
1979 << s << "'." << endl;
1980 handle_ert(os, s, context);
1983 else if (t.cat() == catLetter) {
1984 context.check_layout(os);
1985 // Workaround for bug 4752.
1986 // FIXME: This whole code block needs to be removed
1987 // when the bug is fixed and tex2lyx produces
1988 // the updated file format.
1989 // The replacement algorithm in LyX is so stupid that
1990 // it even translates a phrase if it is part of a word.
1991 bool handled = false;
1992 for (int const * l = known_phrase_lengths; *l; ++l) {
1993 string phrase = t.cs();
1994 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1995 phrase += p.get_token().cs();
1996 if (is_known(phrase, known_coded_phrases)) {
1997 handle_ert(os, phrase, context);
2001 for (size_t i = 1; i < phrase.length(); ++i)
2009 else if (t.cat() == catOther ||
2010 t.cat() == catAlign ||
2011 t.cat() == catParameter) {
2012 // This translates "&" to "\\&" which may be wrong...
2013 context.check_layout(os);
2017 else if (p.isParagraph()) {
2018 if (context.new_layout_allowed)
2019 context.new_paragraph(os);
2021 handle_ert(os, "\\par ", context);
2022 eat_whitespace(p, os, context, true);
2025 else if (t.cat() == catActive) {
2026 context.check_layout(os);
2027 if (t.character() == '~') {
2028 if (context.layout->free_spacing)
2031 begin_inset(os, "space ~\n");
2038 else if (t.cat() == catBegin &&
2039 p.next_token().cat() == catEnd) {
2041 Token const prev = p.prev_token();
2043 if (p.next_token().character() == '`' ||
2044 (prev.character() == '-' &&
2045 p.next_token().character() == '-'))
2046 ; // ignore it in {}`` or -{}-
2048 handle_ert(os, "{}", context);
2052 else if (t.cat() == catBegin) {
2053 context.check_layout(os);
2054 // special handling of font attribute changes
2055 Token const prev = p.prev_token();
2056 Token const next = p.next_token();
2057 TeXFont const oldFont = context.font;
2058 if (next.character() == '[' ||
2059 next.character() == ']' ||
2060 next.character() == '*') {
2062 if (p.next_token().cat() == catEnd) {
2067 handle_ert(os, "{", context);
2068 parse_text_snippet(p, os,
2071 handle_ert(os, "}", context);
2073 } else if (! context.new_layout_allowed) {
2074 handle_ert(os, "{", context);
2075 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2077 handle_ert(os, "}", context);
2078 } else if (is_known(next.cs(), known_sizes)) {
2079 // next will change the size, so we must
2081 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2083 if (!context.atParagraphStart())
2085 << context.font.size << "\n";
2086 } else if (is_known(next.cs(), known_font_families)) {
2087 // next will change the font family, so we
2088 // must reset it here
2089 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2091 if (!context.atParagraphStart())
2093 << context.font.family << "\n";
2094 } else if (is_known(next.cs(), known_font_series)) {
2095 // next will change the font series, so we
2096 // must reset it here
2097 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2099 if (!context.atParagraphStart())
2101 << context.font.series << "\n";
2102 } else if (is_known(next.cs(), known_font_shapes)) {
2103 // next will change the font shape, so we
2104 // must reset it here
2105 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2107 if (!context.atParagraphStart())
2109 << context.font.shape << "\n";
2110 } else if (is_known(next.cs(), known_old_font_families) ||
2111 is_known(next.cs(), known_old_font_series) ||
2112 is_known(next.cs(), known_old_font_shapes)) {
2113 // next will change the font family, series
2114 // and shape, so we must reset it here
2115 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2117 if (!context.atParagraphStart())
2119 << context.font.family
2121 << context.font.series
2123 << context.font.shape << "\n";
2125 handle_ert(os, "{", context);
2126 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2128 handle_ert(os, "}", context);
2132 else if (t.cat() == catEnd) {
2133 if (flags & FLAG_BRACE_LAST) {
2136 cerr << "stray '}' in text\n";
2137 handle_ert(os, "}", context);
2140 else if (t.cat() == catComment)
2141 parse_comment(p, os, t, context);
2144 // control sequences
2147 else if (t.cs() == "(") {
2148 context.check_layout(os);
2149 begin_inset(os, "Formula");
2151 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2156 else if (t.cs() == "[") {
2157 context.check_layout(os);
2158 begin_inset(os, "Formula");
2160 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2165 else if (t.cs() == "begin")
2166 parse_environment(p, os, outer, last_env,
2167 title_layout_found, context);
2169 else if (t.cs() == "end") {
2170 if (flags & FLAG_END) {
2171 // eat environment name
2172 string const name = p.getArg('{', '}');
2173 if (name != active_environment())
2174 cerr << "\\end{" + name + "} does not match \\begin{"
2175 + active_environment() + "}\n";
2178 p.error("found 'end' unexpectedly");
2181 else if (t.cs() == "item") {
2184 bool optarg = false;
2185 if (p.next_token().cat() != catEscape &&
2186 p.next_token().character() == '[') {
2187 p.get_token(); // eat '['
2188 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2193 context.check_layout(os);
2194 if (context.has_item) {
2195 // An item in an unknown list-like environment
2196 // FIXME: Do this in check_layout()!
2197 context.has_item = false;
2199 handle_ert(os, "\\item", context);
2201 handle_ert(os, "\\item ", context);
2204 if (context.layout->labeltype != LABEL_MANUAL) {
2205 // LyX does not support \item[\mybullet]
2206 // in itemize environments
2207 handle_ert(os, "[", context);
2209 handle_ert(os, "]", context);
2210 } else if (!s.empty()) {
2211 // The space is needed to separate the
2212 // item from the rest of the sentence.
2214 eat_whitespace(p, os, context, false);
2219 else if (t.cs() == "bibitem") {
2221 context.check_layout(os);
2222 string label = convert_command_inset_arg(p.getArg('[', ']'));
2223 string key = convert_command_inset_arg(p.verbatim_item());
2224 if (contains(label, '\\') || contains(key, '\\')) {
2225 // LyX can't handle LaTeX commands in labels or keys
2226 handle_ert(os, t.asInput() + '[' + label +
2227 "]{" + p.verbatim_item() + '}',
2230 begin_command_inset(os, "bibitem", "bibitem");
2231 os << "label \"" << label << "\"\n"
2232 "key \"" << key << "\"\n";
2237 else if (is_macro(p))
2238 parse_macro(p, os, context);
2240 else if (t.cs() == "noindent") {
2242 context.add_par_extra_stuff("\\noindent\n");
2245 else if (t.cs() == "appendix") {
2246 context.add_par_extra_stuff("\\start_of_appendix\n");
2247 // We need to start a new paragraph. Otherwise the
2248 // appendix in 'bla\appendix\chapter{' would start
2250 context.new_paragraph(os);
2251 // We need to make sure that the paragraph is
2252 // generated even if it is empty. Otherwise the
2253 // appendix in '\par\appendix\par\chapter{' would
2255 context.check_layout(os);
2256 // FIXME: This is a hack to prevent paragraph
2257 // deletion if it is empty. Handle this better!
2259 "%dummy comment inserted by tex2lyx to "
2260 "ensure that this paragraph is not empty",
2262 // Both measures above may generate an additional
2263 // empty paragraph, but that does not hurt, because
2264 // whitespace does not matter here.
2265 eat_whitespace(p, os, context, true);
2268 // Must catch empty dates before findLayout is called below
2269 else if (t.cs() == "date") {
2270 string const date = p.verbatim_item();
2272 preamble.suppressDate(true);
2274 preamble.suppressDate(false);
2275 if (context.new_layout_allowed &&
2276 (newlayout = findLayout(context.textclass,
2279 output_command_layout(os, p, outer,
2280 context, newlayout);
2282 if (!title_layout_found)
2283 title_layout_found = newlayout->intitle;
2285 handle_ert(os, "\\date{" + date + '}',
2290 // Starred section headings
2291 // Must attempt to parse "Section*" before "Section".
2292 else if ((p.next_token().asInput() == "*") &&
2293 context.new_layout_allowed &&
2294 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2297 output_command_layout(os, p, outer, context, newlayout);
2299 if (!title_layout_found)
2300 title_layout_found = newlayout->intitle;
2303 // Section headings and the like
2304 else if (context.new_layout_allowed &&
2305 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2307 output_command_layout(os, p, outer, context, newlayout);
2309 if (!title_layout_found)
2310 title_layout_found = newlayout->intitle;
2313 else if (t.cs() == "caption") {
2315 context.check_layout(os);
2317 begin_inset(os, "Caption\n");
2318 Context newcontext(true, context.textclass);
2319 newcontext.font = context.font;
2320 newcontext.check_layout(os);
2321 if (p.next_token().cat() != catEscape &&
2322 p.next_token().character() == '[') {
2323 p.get_token(); // eat '['
2324 begin_inset(os, "Argument\n");
2325 os << "status collapsed\n";
2326 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2328 eat_whitespace(p, os, context, false);
2330 parse_text(p, os, FLAG_ITEM, outer, context);
2331 context.check_end_layout(os);
2332 // We don't need really a new paragraph, but
2333 // we must make sure that the next item gets a \begin_layout.
2334 context.new_paragraph(os);
2337 newcontext.check_end_layout(os);
2340 else if (t.cs() == "subfloat") {
2341 // the syntax is \subfloat[caption]{content}
2342 // if it is a table of figure depends on the surrounding float
2343 bool has_caption = false;
2345 // do nothing if there is no outer float
2346 if (!float_type.empty()) {
2347 context.check_layout(os);
2349 begin_inset(os, "Float " + float_type + "\n");
2351 << "\nsideways false"
2352 << "\nstatus collapsed\n\n";
2355 if (p.next_token().cat() != catEscape &&
2356 p.next_token().character() == '[') {
2357 p.get_token(); // eat '['
2358 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2362 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2363 // the caption comes always as the last
2365 // we must make sure that the caption gets a \begin_layout
2366 os << "\n\\begin_layout Plain Layout";
2368 begin_inset(os, "Caption\n");
2369 Context newcontext(true, context.textclass);
2370 newcontext.font = context.font;
2371 newcontext.check_layout(os);
2372 os << caption << "\n";
2373 newcontext.check_end_layout(os);
2374 // We don't need really a new paragraph, but
2375 // we must make sure that the next item gets a \begin_layout.
2376 //newcontext.new_paragraph(os);
2380 // We don't need really a new paragraph, but
2381 // we must make sure that the next item gets a \begin_layout.
2383 context.new_paragraph(os);
2386 context.check_end_layout(os);
2387 // close the layout we opened
2389 os << "\n\\end_layout\n";
2391 // if the float type is not supported or there is no surrounding float
2394 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2395 handle_ert(os, t.asInput() + '[' + opt_arg +
2396 "]{" + p.verbatim_item() + '}', context);
2398 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2402 else if (t.cs() == "includegraphics") {
2403 bool const clip = p.next_token().asInput() == "*";
2406 string const arg = p.getArg('[', ']');
2407 map<string, string> opts;
2408 vector<string> keys;
2409 split_map(arg, opts, keys);
2411 opts["clip"] = string();
2412 string name = normalize_filename(p.verbatim_item());
2414 string const path = getMasterFilePath();
2415 // We want to preserve relative / absolute filenames,
2416 // therefore path is only used for testing
2417 if (!makeAbsPath(name, path).exists()) {
2418 // The file extension is probably missing.
2419 // Now try to find it out.
2420 string const dvips_name =
2421 find_file(name, path,
2422 known_dvips_graphics_formats);
2423 string const pdftex_name =
2424 find_file(name, path,
2425 known_pdftex_graphics_formats);
2426 if (!dvips_name.empty()) {
2427 if (!pdftex_name.empty()) {
2428 cerr << "This file contains the "
2430 "\"\\includegraphics{"
2432 "However, files\n\""
2433 << dvips_name << "\" and\n\""
2434 << pdftex_name << "\"\n"
2435 "both exist, so I had to make a "
2436 "choice and took the first one.\n"
2437 "Please move the unwanted one "
2438 "someplace else and try again\n"
2439 "if my choice was wrong."
2443 } else if (!pdftex_name.empty()) {
2449 if (makeAbsPath(name, path).exists())
2450 fix_relative_filename(name);
2452 cerr << "Warning: Could not find graphics file '"
2453 << name << "'." << endl;
2455 context.check_layout(os);
2456 begin_inset(os, "Graphics ");
2457 os << "\n\tfilename " << name << '\n';
2458 if (opts.find("width") != opts.end())
2460 << translate_len(opts["width"]) << '\n';
2461 if (opts.find("height") != opts.end())
2463 << translate_len(opts["height"]) << '\n';
2464 if (opts.find("scale") != opts.end()) {
2465 istringstream iss(opts["scale"]);
2469 os << "\tscale " << val << '\n';
2471 if (opts.find("angle") != opts.end()) {
2472 os << "\trotateAngle "
2473 << opts["angle"] << '\n';
2474 vector<string>::const_iterator a =
2475 find(keys.begin(), keys.end(), "angle");
2476 vector<string>::const_iterator s =
2477 find(keys.begin(), keys.end(), "width");
2478 if (s == keys.end())
2479 s = find(keys.begin(), keys.end(), "height");
2480 if (s == keys.end())
2481 s = find(keys.begin(), keys.end(), "scale");
2482 if (s != keys.end() && distance(s, a) > 0)
2483 os << "\tscaleBeforeRotation\n";
2485 if (opts.find("origin") != opts.end()) {
2487 string const opt = opts["origin"];
2488 if (opt.find('l') != string::npos) ss << "left";
2489 if (opt.find('r') != string::npos) ss << "right";
2490 if (opt.find('c') != string::npos) ss << "center";
2491 if (opt.find('t') != string::npos) ss << "Top";
2492 if (opt.find('b') != string::npos) ss << "Bottom";
2493 if (opt.find('B') != string::npos) ss << "Baseline";
2494 if (!ss.str().empty())
2495 os << "\trotateOrigin " << ss.str() << '\n';
2497 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2499 if (opts.find("keepaspectratio") != opts.end())
2500 os << "\tkeepAspectRatio\n";
2501 if (opts.find("clip") != opts.end())
2503 if (opts.find("draft") != opts.end())
2505 if (opts.find("bb") != opts.end())
2506 os << "\tBoundingBox "
2507 << opts["bb"] << '\n';
2508 int numberOfbbOptions = 0;
2509 if (opts.find("bbllx") != opts.end())
2510 numberOfbbOptions++;
2511 if (opts.find("bblly") != opts.end())
2512 numberOfbbOptions++;
2513 if (opts.find("bburx") != opts.end())
2514 numberOfbbOptions++;
2515 if (opts.find("bbury") != opts.end())
2516 numberOfbbOptions++;
2517 if (numberOfbbOptions == 4)
2518 os << "\tBoundingBox "
2519 << opts["bbllx"] << " " << opts["bblly"] << " "
2520 << opts["bburx"] << " " << opts["bbury"] << '\n';
2521 else if (numberOfbbOptions > 0)
2522 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2523 numberOfbbOptions = 0;
2524 if (opts.find("natwidth") != opts.end())
2525 numberOfbbOptions++;
2526 if (opts.find("natheight") != opts.end())
2527 numberOfbbOptions++;
2528 if (numberOfbbOptions == 2)
2529 os << "\tBoundingBox 0bp 0bp "
2530 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2531 else if (numberOfbbOptions > 0)
2532 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2533 ostringstream special;
2534 if (opts.find("hiresbb") != opts.end())
2535 special << "hiresbb,";
2536 if (opts.find("trim") != opts.end())
2538 if (opts.find("viewport") != opts.end())
2539 special << "viewport=" << opts["viewport"] << ',';
2540 if (opts.find("totalheight") != opts.end())
2541 special << "totalheight=" << opts["totalheight"] << ',';
2542 if (opts.find("type") != opts.end())
2543 special << "type=" << opts["type"] << ',';
2544 if (opts.find("ext") != opts.end())
2545 special << "ext=" << opts["ext"] << ',';
2546 if (opts.find("read") != opts.end())
2547 special << "read=" << opts["read"] << ',';
2548 if (opts.find("command") != opts.end())
2549 special << "command=" << opts["command"] << ',';
2550 string s_special = special.str();
2551 if (!s_special.empty()) {
2552 // We had special arguments. Remove the trailing ','.
2553 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2555 // TODO: Handle the unknown settings better.
2556 // Warn about invalid options.
2557 // Check whether some option was given twice.
2561 else if (t.cs() == "footnote" ||
2562 (t.cs() == "thanks" && context.layout->intitle)) {
2564 context.check_layout(os);
2565 begin_inset(os, "Foot\n");
2566 os << "status collapsed\n\n";
2567 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2571 else if (t.cs() == "marginpar") {
2573 context.check_layout(os);
2574 begin_inset(os, "Marginal\n");
2575 os << "status collapsed\n\n";
2576 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2580 else if (t.cs() == "ensuremath") {
2582 context.check_layout(os);
2583 string const s = p.verbatim_item();
2584 //FIXME: this never triggers in UTF8
2585 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2588 handle_ert(os, "\\ensuremath{" + s + "}",
2592 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2593 if (title_layout_found) {
2595 skip_spaces_braces(p);
2597 handle_ert(os, t.asInput(), context);
2600 else if (t.cs() == "tableofcontents") {
2601 context.check_layout(os);
2602 begin_command_inset(os, "toc", "tableofcontents");
2604 skip_spaces_braces(p);
2607 else if (t.cs() == "listoffigures") {
2608 context.check_layout(os);
2609 begin_inset(os, "FloatList figure\n");
2611 skip_spaces_braces(p);
2614 else if (t.cs() == "listoftables") {
2615 context.check_layout(os);
2616 begin_inset(os, "FloatList table\n");
2618 skip_spaces_braces(p);
2621 else if (t.cs() == "listof") {
2622 p.skip_spaces(true);
2623 string const name = p.get_token().cs();
2624 if (context.textclass.floats().typeExist(name)) {
2625 context.check_layout(os);
2626 begin_inset(os, "FloatList ");
2629 p.get_token(); // swallow second arg
2631 handle_ert(os, "\\listof{" + name + "}", context);
2634 else if (t.cs() == "textrm")
2635 parse_text_attributes(p, os, FLAG_ITEM, outer,
2636 context, "\\family",
2637 context.font.family, "roman");
2639 else if (t.cs() == "textsf")
2640 parse_text_attributes(p, os, FLAG_ITEM, outer,
2641 context, "\\family",
2642 context.font.family, "sans");
2644 else if (t.cs() == "texttt")
2645 parse_text_attributes(p, os, FLAG_ITEM, outer,
2646 context, "\\family",
2647 context.font.family, "typewriter");
2649 else if (t.cs() == "textmd")
2650 parse_text_attributes(p, os, FLAG_ITEM, outer,
2651 context, "\\series",
2652 context.font.series, "medium");
2654 else if (t.cs() == "textbf")
2655 parse_text_attributes(p, os, FLAG_ITEM, outer,
2656 context, "\\series",
2657 context.font.series, "bold");
2659 else if (t.cs() == "textup")
2660 parse_text_attributes(p, os, FLAG_ITEM, outer,
2662 context.font.shape, "up");
2664 else if (t.cs() == "textit")
2665 parse_text_attributes(p, os, FLAG_ITEM, outer,
2667 context.font.shape, "italic");
2669 else if (t.cs() == "textsl")
2670 parse_text_attributes(p, os, FLAG_ITEM, outer,
2672 context.font.shape, "slanted");
2674 else if (t.cs() == "textsc")
2675 parse_text_attributes(p, os, FLAG_ITEM, outer,
2677 context.font.shape, "smallcaps");
2679 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2680 context.check_layout(os);
2681 TeXFont oldFont = context.font;
2682 context.font.init();
2683 context.font.size = oldFont.size;
2684 os << "\n\\family " << context.font.family << "\n";
2685 os << "\n\\series " << context.font.series << "\n";
2686 os << "\n\\shape " << context.font.shape << "\n";
2687 if (t.cs() == "textnormal") {
2688 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2689 output_font_change(os, context.font, oldFont);
2690 context.font = oldFont;
2692 eat_whitespace(p, os, context, false);
2695 else if (t.cs() == "textcolor") {
2696 // scheme is \textcolor{color name}{text}
2697 string const color = p.verbatim_item();
2698 // we only support the predefined colors of the color package
2699 if (color == "black" || color == "blue" || color == "cyan"
2700 || color == "green" || color == "magenta" || color == "red"
2701 || color == "white" || color == "yellow") {
2702 context.check_layout(os);
2703 os << "\n\\color " << color << "\n";
2704 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2705 context.check_layout(os);
2706 os << "\n\\color inherit\n";
2707 preamble.registerAutomaticallyLoadedPackage("color");
2709 // for custom defined colors
2710 handle_ert(os, t.asInput() + "{" + color + "}", context);
2713 else if (t.cs() == "underbar" || t.cs() == "uline") {
2714 // \underbar is not 100% correct (LyX outputs \uline
2715 // of ulem.sty). The difference is that \ulem allows
2716 // line breaks, and \underbar does not.
2717 // Do NOT handle \underline.
2718 // \underbar cuts through y, g, q, p etc.,
2719 // \underline does not.
2720 context.check_layout(os);
2721 os << "\n\\bar under\n";
2722 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2723 context.check_layout(os);
2724 os << "\n\\bar default\n";
2725 preamble.registerAutomaticallyLoadedPackage("ulem");
2728 else if (t.cs() == "sout") {
2729 context.check_layout(os);
2730 os << "\n\\strikeout on\n";
2731 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2732 context.check_layout(os);
2733 os << "\n\\strikeout default\n";
2734 preamble.registerAutomaticallyLoadedPackage("ulem");
2737 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2738 t.cs() == "emph" || t.cs() == "noun") {
2739 context.check_layout(os);
2740 os << "\n\\" << t.cs() << " on\n";
2741 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2742 context.check_layout(os);
2743 os << "\n\\" << t.cs() << " default\n";
2744 if (t.cs() == "uuline" || t.cs() == "uwave")
2745 preamble.registerAutomaticallyLoadedPackage("ulem");
2748 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2749 context.check_layout(os);
2750 string name = p.getArg('{', '}');
2751 string localtime = p.getArg('{', '}');
2752 preamble.registerAuthor(name);
2753 Author const & author = preamble.getAuthor(name);
2754 // from_ctime() will fail if LyX decides to output the
2755 // time in the text language. It might also use a wrong
2756 // time zone (if the original LyX document was exported
2757 // with a different time zone).
2758 time_t ptime = from_ctime(localtime);
2759 if (ptime == static_cast<time_t>(-1)) {
2760 cerr << "Warning: Could not parse time `" << localtime
2761 << "´ for change tracking, using current time instead.\n";
2762 ptime = current_time();
2764 if (t.cs() == "lyxadded")
2765 os << "\n\\change_inserted ";
2767 os << "\n\\change_deleted ";
2768 os << author.bufferId() << ' ' << ptime << '\n';
2769 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2770 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2771 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2772 LaTeXPackages::isAvailable("xcolor");
2773 // No need to test for luatex, since luatex comes in
2774 // two flavours (dvi and pdf), like latex, and those
2775 // are detected by pdflatex.
2776 if (pdflatex || xetex) {
2778 preamble.registerAutomaticallyLoadedPackage("ulem");
2779 preamble.registerAutomaticallyLoadedPackage("xcolor");
2780 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2784 preamble.registerAutomaticallyLoadedPackage("dvipost");
2785 } else if (xcolorulem) {
2786 preamble.registerAutomaticallyLoadedPackage("ulem");
2787 preamble.registerAutomaticallyLoadedPackage("xcolor");
2792 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2793 t.cs() == "vphantom") {
2794 context.check_layout(os);
2795 if (t.cs() == "phantom")
2796 begin_inset(os, "Phantom Phantom\n");
2797 if (t.cs() == "hphantom")
2798 begin_inset(os, "Phantom HPhantom\n");
2799 if (t.cs() == "vphantom")
2800 begin_inset(os, "Phantom VPhantom\n");
2801 os << "status open\n";
2802 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2807 else if (t.cs() == "href") {
2808 context.check_layout(os);
2809 string target = p.getArg('{', '}');
2810 string name = p.getArg('{', '}');
2812 size_t i = target.find(':');
2813 if (i != string::npos) {
2814 type = target.substr(0, i + 1);
2815 if (type == "mailto:" || type == "file:")
2816 target = target.substr(i + 1);
2817 // handle the case that name is equal to target, except of "http://"
2818 else if (target.substr(i + 3) == name && type == "http:")
2821 begin_command_inset(os, "href", "href");
2823 os << "name \"" << name << "\"\n";
2824 os << "target \"" << target << "\"\n";
2825 if (type == "mailto:" || type == "file:")
2826 os << "type \"" << type << "\"\n";
2828 skip_spaces_braces(p);
2831 else if (t.cs() == "lyxline") {
2832 // swallow size argument (it is not used anyway)
2834 if (!context.atParagraphStart()) {
2835 // so our line is in the middle of a paragraph
2836 // we need to add a new line, lest this line
2837 // follow the other content on that line and
2838 // run off the side of the page
2839 // FIXME: This may create an empty paragraph,
2840 // but without that it would not be
2841 // possible to set noindent below.
2842 // Fortunately LaTeX does not care
2843 // about the empty paragraph.
2844 context.new_paragraph(os);
2846 if (preamble.indentParagraphs()) {
2847 // we need to unindent, lest the line be too long
2848 context.add_par_extra_stuff("\\noindent\n");
2850 context.check_layout(os);
2851 begin_command_inset(os, "line", "rule");
2852 os << "offset \"0.5ex\"\n"
2853 "width \"100line%\"\n"
2858 else if (t.cs() == "rule") {
2859 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2860 string const width = p.getArg('{', '}');
2861 string const thickness = p.getArg('{', '}');
2862 context.check_layout(os);
2863 begin_command_inset(os, "line", "rule");
2864 if (!offset.empty())
2865 os << "offset \"" << translate_len(offset) << "\"\n";
2866 os << "width \"" << translate_len(width) << "\"\n"
2867 "height \"" << translate_len(thickness) << "\"\n";
2871 else if (is_known(t.cs(), known_phrases) ||
2872 (t.cs() == "protect" &&
2873 p.next_token().cat() == catEscape &&
2874 is_known(p.next_token().cs(), known_phrases))) {
2875 // LyX sometimes puts a \protect in front, so we have to ignore it
2876 // FIXME: This needs to be changed when bug 4752 is fixed.
2877 char const * const * where = is_known(
2878 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2880 context.check_layout(os);
2881 os << known_coded_phrases[where - known_phrases];
2882 skip_spaces_braces(p);
2885 else if (is_known(t.cs(), known_ref_commands)) {
2886 string const opt = p.getOpt();
2888 context.check_layout(os);
2889 char const * const * where = is_known(t.cs(),
2890 known_ref_commands);
2891 begin_command_inset(os, "ref",
2892 known_coded_ref_commands[where - known_ref_commands]);
2893 os << "reference \""
2894 << convert_command_inset_arg(p.verbatim_item())
2898 // LyX does not support optional arguments of ref commands
2899 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2900 p.verbatim_item() + "}", context);
2904 else if (use_natbib &&
2905 is_known(t.cs(), known_natbib_commands) &&
2906 ((t.cs() != "citefullauthor" &&
2907 t.cs() != "citeyear" &&
2908 t.cs() != "citeyearpar") ||
2909 p.next_token().asInput() != "*")) {
2910 context.check_layout(os);
2911 string command = t.cs();
2912 if (p.next_token().asInput() == "*") {
2916 if (command == "citefullauthor")
2917 // alternative name for "\\citeauthor*"
2918 command = "citeauthor*";
2920 // text before the citation
2922 // text after the citation
2924 get_cite_arguments(p, true, before, after);
2926 if (command == "cite") {
2927 // \cite without optional argument means
2928 // \citet, \cite with at least one optional
2929 // argument means \citep.
2930 if (before.empty() && after.empty())
2935 if (before.empty() && after == "[]")
2936 // avoid \citet[]{a}
2938 else if (before == "[]" && after == "[]") {
2939 // avoid \citet[][]{a}
2943 // remove the brackets around after and before
2944 if (!after.empty()) {
2946 after.erase(after.length() - 1, 1);
2947 after = convert_command_inset_arg(after);
2949 if (!before.empty()) {
2951 before.erase(before.length() - 1, 1);
2952 before = convert_command_inset_arg(before);
2954 begin_command_inset(os, "citation", command);
2955 os << "after " << '"' << after << '"' << "\n";
2956 os << "before " << '"' << before << '"' << "\n";
2958 << convert_command_inset_arg(p.verbatim_item())
2963 else if (use_jurabib &&
2964 is_known(t.cs(), known_jurabib_commands) &&
2965 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2966 context.check_layout(os);
2967 string command = t.cs();
2968 if (p.next_token().asInput() == "*") {
2972 char argumentOrder = '\0';
2973 vector<string> const options =
2974 preamble.getPackageOptions("jurabib");
2975 if (find(options.begin(), options.end(),
2976 "natbiborder") != options.end())
2977 argumentOrder = 'n';
2978 else if (find(options.begin(), options.end(),
2979 "jurabiborder") != options.end())
2980 argumentOrder = 'j';
2982 // text before the citation
2984 // text after the citation
2986 get_cite_arguments(p, argumentOrder != 'j', before, after);
2988 string const citation = p.verbatim_item();
2989 if (!before.empty() && argumentOrder == '\0') {
2990 cerr << "Warning: Assuming argument order "
2991 "of jurabib version 0.6 for\n'"
2992 << command << before << after << '{'
2993 << citation << "}'.\n"
2994 "Add 'jurabiborder' to the jurabib "
2995 "package options if you used an\n"
2996 "earlier jurabib version." << endl;
2998 if (!after.empty()) {
3000 after.erase(after.length() - 1, 1);
3002 if (!before.empty()) {
3004 before.erase(before.length() - 1, 1);
3006 begin_command_inset(os, "citation", command);
3007 os << "after " << '"' << after << '"' << "\n";
3008 os << "before " << '"' << before << '"' << "\n";
3009 os << "key " << '"' << citation << '"' << "\n";
3013 else if (t.cs() == "cite"
3014 || t.cs() == "nocite") {
3015 context.check_layout(os);
3016 string after = convert_command_inset_arg(p.getArg('[', ']'));
3017 string key = convert_command_inset_arg(p.verbatim_item());
3018 // store the case that it is "\nocite{*}" to use it later for
3021 begin_command_inset(os, "citation", t.cs());
3022 os << "after " << '"' << after << '"' << "\n";
3023 os << "key " << '"' << key << '"' << "\n";
3025 } else if (t.cs() == "nocite")
3029 else if (t.cs() == "index") {
3030 context.check_layout(os);
3031 begin_inset(os, "Index idx\n");
3032 os << "status collapsed\n";
3033 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3037 else if (t.cs() == "nomenclature") {
3038 context.check_layout(os);
3039 begin_command_inset(os, "nomenclature", "nomenclature");
3040 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3041 if (!prefix.empty())
3042 os << "prefix " << '"' << prefix << '"' << "\n";
3043 os << "symbol " << '"'
3044 << convert_command_inset_arg(p.verbatim_item());
3045 os << "\"\ndescription \""
3046 << convert_command_inset_arg(p.verbatim_item())
3051 else if (t.cs() == "label") {
3052 context.check_layout(os);
3053 begin_command_inset(os, "label", "label");
3055 << convert_command_inset_arg(p.verbatim_item())
3060 else if (t.cs() == "printindex") {
3061 context.check_layout(os);
3062 begin_command_inset(os, "index_print", "printindex");
3063 os << "type \"idx\"\n";
3065 skip_spaces_braces(p);
3068 else if (t.cs() == "printnomenclature") {
3070 string width_type = "";
3071 context.check_layout(os);
3072 begin_command_inset(os, "nomencl_print", "printnomenclature");
3073 // case of a custom width
3075 width = p.getArg('[', ']');
3076 width = translate_len(width);
3077 width_type = "custom";
3079 // case of no custom width
3080 // the case of no custom width but the width set
3081 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3082 // because the user could have set anything, not only the width
3083 // of the longest label (which would be width_type = "auto")
3084 string label = convert_command_inset_arg(p.getArg('{', '}'));
3085 if (label.empty() && width_type.empty())
3086 width_type = "none";
3087 os << "set_width \"" << width_type << "\"\n";
3088 if (width_type == "custom")
3089 os << "width \"" << width << '\"';
3091 skip_spaces_braces(p);
3094 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3095 context.check_layout(os);
3096 begin_inset(os, "script ");
3097 os << t.cs().substr(4) << '\n';
3098 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3100 if (t.cs() == "textsubscript")
3101 preamble.registerAutomaticallyLoadedPackage("subscript");
3104 else if (is_known(t.cs(), known_quotes)) {
3105 char const * const * where = is_known(t.cs(), known_quotes);
3106 context.check_layout(os);
3107 begin_inset(os, "Quotes ");
3108 os << known_coded_quotes[where - known_quotes];
3110 // LyX adds {} after the quote, so we have to eat
3111 // spaces here if there are any before a possible
3113 eat_whitespace(p, os, context, false);
3117 else if (is_known(t.cs(), known_sizes) &&
3118 context.new_layout_allowed) {
3119 char const * const * where = is_known(t.cs(), known_sizes);
3120 context.check_layout(os);
3121 TeXFont const oldFont = context.font;
3122 context.font.size = known_coded_sizes[where - known_sizes];
3123 output_font_change(os, oldFont, context.font);
3124 eat_whitespace(p, os, context, false);
3127 else if (is_known(t.cs(), known_font_families) &&
3128 context.new_layout_allowed) {
3129 char const * const * where =
3130 is_known(t.cs(), known_font_families);
3131 context.check_layout(os);
3132 TeXFont const oldFont = context.font;
3133 context.font.family =
3134 known_coded_font_families[where - known_font_families];
3135 output_font_change(os, oldFont, context.font);
3136 eat_whitespace(p, os, context, false);
3139 else if (is_known(t.cs(), known_font_series) &&
3140 context.new_layout_allowed) {
3141 char const * const * where =
3142 is_known(t.cs(), known_font_series);
3143 context.check_layout(os);
3144 TeXFont const oldFont = context.font;
3145 context.font.series =
3146 known_coded_font_series[where - known_font_series];
3147 output_font_change(os, oldFont, context.font);
3148 eat_whitespace(p, os, context, false);
3151 else if (is_known(t.cs(), known_font_shapes) &&
3152 context.new_layout_allowed) {
3153 char const * const * where =
3154 is_known(t.cs(), known_font_shapes);
3155 context.check_layout(os);
3156 TeXFont const oldFont = context.font;
3157 context.font.shape =
3158 known_coded_font_shapes[where - known_font_shapes];
3159 output_font_change(os, oldFont, context.font);
3160 eat_whitespace(p, os, context, false);
3162 else if (is_known(t.cs(), known_old_font_families) &&
3163 context.new_layout_allowed) {
3164 char const * const * where =
3165 is_known(t.cs(), known_old_font_families);
3166 context.check_layout(os);
3167 TeXFont const oldFont = context.font;
3168 context.font.init();
3169 context.font.size = oldFont.size;
3170 context.font.family =
3171 known_coded_font_families[where - known_old_font_families];
3172 output_font_change(os, oldFont, context.font);
3173 eat_whitespace(p, os, context, false);
3176 else if (is_known(t.cs(), known_old_font_series) &&
3177 context.new_layout_allowed) {
3178 char const * const * where =
3179 is_known(t.cs(), known_old_font_series);
3180 context.check_layout(os);
3181 TeXFont const oldFont = context.font;
3182 context.font.init();
3183 context.font.size = oldFont.size;
3184 context.font.series =
3185 known_coded_font_series[where - known_old_font_series];
3186 output_font_change(os, oldFont, context.font);
3187 eat_whitespace(p, os, context, false);
3190 else if (is_known(t.cs(), known_old_font_shapes) &&
3191 context.new_layout_allowed) {
3192 char const * const * where =
3193 is_known(t.cs(), known_old_font_shapes);
3194 context.check_layout(os);
3195 TeXFont const oldFont = context.font;
3196 context.font.init();
3197 context.font.size = oldFont.size;
3198 context.font.shape =
3199 known_coded_font_shapes[where - known_old_font_shapes];
3200 output_font_change(os, oldFont, context.font);
3201 eat_whitespace(p, os, context, false);
3204 else if (t.cs() == "selectlanguage") {
3205 context.check_layout(os);
3206 // save the language for the case that a
3207 // \foreignlanguage is used
3209 context.font.language = babel2lyx(p.verbatim_item());
3210 os << "\n\\lang " << context.font.language << "\n";
3213 else if (t.cs() == "foreignlanguage") {
3214 string const lang = babel2lyx(p.verbatim_item());
3215 parse_text_attributes(p, os, FLAG_ITEM, outer,
3217 context.font.language, lang);
3220 else if (t.cs() == "inputencoding") {
3221 // nothing to write here
3222 string const enc = subst(p.verbatim_item(), "\n", " ");
3226 else if (t.cs() == "ldots") {
3227 context.check_layout(os);
3228 os << "\\SpecialChar \\ldots{}\n";
3229 skip_spaces_braces(p);
3232 else if (t.cs() == "lyxarrow") {
3233 context.check_layout(os);
3234 os << "\\SpecialChar \\menuseparator\n";
3235 skip_spaces_braces(p);
3238 else if (t.cs() == "textcompwordmark") {
3239 context.check_layout(os);
3240 os << "\\SpecialChar \\textcompwordmark{}\n";
3241 skip_spaces_braces(p);
3244 else if (t.cs() == "slash") {
3245 context.check_layout(os);
3246 os << "\\SpecialChar \\slash{}\n";
3247 skip_spaces_braces(p);
3250 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3251 context.check_layout(os);
3252 os << "\\SpecialChar \\nobreakdash-\n";
3256 else if (t.cs() == "textquotedbl") {
3257 context.check_layout(os);
3262 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3263 context.check_layout(os);
3264 os << "\\SpecialChar \\@.\n";
3268 else if (t.cs() == "-") {
3269 context.check_layout(os);
3270 os << "\\SpecialChar \\-\n";
3273 else if (t.cs() == "textasciitilde") {
3274 context.check_layout(os);
3276 skip_spaces_braces(p);
3279 else if (t.cs() == "textasciicircum") {
3280 context.check_layout(os);
3282 skip_spaces_braces(p);
3285 else if (t.cs() == "textbackslash") {
3286 context.check_layout(os);
3287 os << "\n\\backslash\n";
3288 skip_spaces_braces(p);
3291 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3292 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3294 context.check_layout(os);
3298 else if (t.cs() == "char") {
3299 context.check_layout(os);
3300 if (p.next_token().character() == '`') {
3302 if (p.next_token().cs() == "\"") {
3307 handle_ert(os, "\\char`", context);
3310 handle_ert(os, "\\char", context);
3314 else if (t.cs() == "verb") {
3315 context.check_layout(os);
3316 char const delimiter = p.next_token().character();
3317 string const arg = p.getArg(delimiter, delimiter);
3319 oss << "\\verb" << delimiter << arg << delimiter;
3320 handle_ert(os, oss.str(), context);
3323 // Problem: \= creates a tabstop inside the tabbing environment
3324 // and else an accent. In the latter case we really would want
3325 // \={o} instead of \= o.
3326 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3327 handle_ert(os, t.asInput(), context);
3329 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3330 else if (t.cs().size() == 1
3331 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3332 context.check_layout(os);
3333 // try to see whether the string is in unicodesymbols
3335 string command = t.asInput() + "{"
3336 + trimSpaceAndEol(p.verbatim_item())
3338 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3341 cerr << "When parsing " << command
3342 << ", result is " << to_utf8(s)
3343 << "+" << to_utf8(rem) << endl;
3346 // we did not find a non-ert version
3347 handle_ert(os, command, context);
3350 else if (t.cs() == "\\") {
3351 context.check_layout(os);
3353 handle_ert(os, "\\\\" + p.getOpt(), context);
3354 else if (p.next_token().asInput() == "*") {
3356 // getOpt() eats the following space if there
3357 // is no optional argument, but that is OK
3358 // here since it has no effect in the output.
3359 handle_ert(os, "\\\\*" + p.getOpt(), context);
3362 begin_inset(os, "Newline newline");
3367 else if (t.cs() == "newline" ||
3368 (t.cs() == "linebreak" && !p.hasOpt())) {
3369 context.check_layout(os);
3370 begin_inset(os, "Newline ");
3373 skip_spaces_braces(p);
3376 else if (t.cs() == "input" || t.cs() == "include"
3377 || t.cs() == "verbatiminput") {
3378 string name = t.cs();
3379 if (t.cs() == "verbatiminput"
3380 && p.next_token().asInput() == "*")
3381 name += p.get_token().asInput();
3382 context.check_layout(os);
3383 string filename(normalize_filename(p.getArg('{', '}')));
3384 string const path = getMasterFilePath();
3385 // We want to preserve relative / absolute filenames,
3386 // therefore path is only used for testing
3387 if ((t.cs() == "include" || t.cs() == "input") &&
3388 !makeAbsPath(filename, path).exists()) {
3389 // The file extension is probably missing.
3390 // Now try to find it out.
3391 string const tex_name =
3392 find_file(filename, path,
3393 known_tex_extensions);
3394 if (!tex_name.empty())
3395 filename = tex_name;
3397 bool external = false;
3399 if (makeAbsPath(filename, path).exists()) {
3400 string const abstexname =
3401 makeAbsPath(filename, path).absFileName();
3402 string const abslyxname =
3403 changeExtension(abstexname, ".lyx");
3404 string const absfigname =
3405 changeExtension(abstexname, ".fig");
3406 fix_relative_filename(filename);
3407 string const lyxname =
3408 changeExtension(filename, ".lyx");
3410 external = FileName(absfigname).exists();
3411 if (t.cs() == "input") {
3412 string const ext = getExtension(abstexname);
3414 // Combined PS/LaTeX:
3415 // x.eps, x.pstex_t (old xfig)
3416 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3417 FileName const absepsname(
3418 changeExtension(abstexname, ".eps"));
3419 FileName const abspstexname(
3420 changeExtension(abstexname, ".pstex"));
3421 bool const xfigeps =
3422 (absepsname.exists() ||
3423 abspstexname.exists()) &&
3426 // Combined PDF/LaTeX:
3427 // x.pdf, x.pdftex_t (old xfig)
3428 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3429 FileName const abspdfname(
3430 changeExtension(abstexname, ".pdf"));
3431 bool const xfigpdf =
3432 abspdfname.exists() &&
3433 (ext == "pdftex_t" || ext == "pdf_t");
3437 // Combined PS/PDF/LaTeX:
3438 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3439 string const absbase2(
3440 removeExtension(abstexname) + "_pspdftex");
3441 FileName const abseps2name(
3442 addExtension(absbase2, ".eps"));
3443 FileName const abspdf2name(
3444 addExtension(absbase2, ".pdf"));
3445 bool const xfigboth =
3446 abspdf2name.exists() &&
3447 abseps2name.exists() && ext == "pspdftex";
3449 xfig = xfigpdf || xfigeps || xfigboth;
3450 external = external && xfig;
3453 outname = changeExtension(filename, ".fig");
3455 // Don't try to convert, the result
3456 // would be full of ERT.
3458 } else if (t.cs() != "verbatiminput" &&
3459 tex2lyx(abstexname, FileName(abslyxname),
3466 cerr << "Warning: Could not find included file '"
3467 << filename << "'." << endl;
3471 begin_inset(os, "External\n");
3472 os << "\ttemplate XFig\n"
3473 << "\tfilename " << outname << '\n';
3475 begin_command_inset(os, "include", name);
3476 os << "preview false\n"
3477 "filename \"" << outname << "\"\n";
3482 else if (t.cs() == "bibliographystyle") {
3483 // store new bibliographystyle
3484 bibliographystyle = p.verbatim_item();
3485 // If any other command than \bibliography and
3486 // \nocite{*} follows, we need to output the style
3487 // (because it might be used by that command).
3488 // Otherwise, it will automatically be output by LyX.
3491 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3492 if (t2.cat() == catBegin)
3494 if (t2.cat() != catEscape)
3496 if (t2.cs() == "nocite") {
3497 if (p.getArg('{', '}') == "*")
3499 } else if (t2.cs() == "bibliography")
3506 "\\bibliographystyle{" + bibliographystyle + '}',
3511 else if (t.cs() == "bibliography") {
3512 context.check_layout(os);
3513 begin_command_inset(os, "bibtex", "bibtex");
3514 if (!btprint.empty()) {
3515 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3516 // clear the string because the next BibTeX inset can be without the
3517 // \nocite{*} option
3520 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3521 // Do we have a bibliographystyle set?
3522 if (!bibliographystyle.empty())
3523 os << "options " << '"' << bibliographystyle << '"' << "\n";
3527 else if (t.cs() == "parbox") {
3528 // Test whether this is an outer box of a shaded box
3530 // swallow arguments
3531 while (p.hasOpt()) {
3533 p.skip_spaces(true);
3536 p.skip_spaces(true);
3538 if (p.next_token().cat() == catBegin)
3540 p.skip_spaces(true);
3541 Token to = p.get_token();
3542 bool shaded = false;
3543 if (to.asInput() == "\\begin") {
3544 p.skip_spaces(true);
3545 if (p.getArg('{', '}') == "shaded")
3550 parse_outer_box(p, os, FLAG_ITEM, outer,
3551 context, "parbox", "shaded");
3553 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3557 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3558 t.cs() == "shadowbox" || t.cs() == "doublebox")
3559 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3561 else if (t.cs() == "framebox") {
3562 string special = p.getFullOpt();
3563 special += p.getOpt();
3564 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3567 //\makebox() is part of the picture environment and different from \makebox{}
3568 //\makebox{} will be parsed by parse_box
3569 else if (t.cs() == "makebox") {
3570 string arg = t.asInput();
3571 if (p.next_token().character() == '(') {
3572 //the syntax is: \makebox(x,y)[position]{content}
3573 arg += p.getFullParentheseArg();
3574 arg += p.getFullOpt();
3575 eat_whitespace(p, os, context, false);
3576 handle_ert(os, arg + '{', context);
3577 eat_whitespace(p, os, context, false);
3578 parse_text(p, os, FLAG_ITEM, outer, context);
3579 handle_ert(os, "}", context);
3581 //the syntax is: \makebox[width][position]{content}
3582 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3586 else if (t.cs() == "smallskip" ||
3587 t.cs() == "medskip" ||
3588 t.cs() == "bigskip" ||
3589 t.cs() == "vfill") {
3590 context.check_layout(os);
3591 begin_inset(os, "VSpace ");
3594 skip_spaces_braces(p);
3597 else if (is_known(t.cs(), known_spaces)) {
3598 char const * const * where = is_known(t.cs(), known_spaces);
3599 context.check_layout(os);
3600 begin_inset(os, "space ");
3601 os << '\\' << known_coded_spaces[where - known_spaces]
3604 // LaTeX swallows whitespace after all spaces except
3605 // "\\,". We have to do that here, too, because LyX
3606 // adds "{}" which would make the spaces significant.
3608 eat_whitespace(p, os, context, false);
3609 // LyX adds "{}" after all spaces except "\\ " and
3610 // "\\,", so we have to remove "{}".
3611 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3612 // remove the braces after "\\,", too.
3617 else if (t.cs() == "newpage" ||
3618 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3619 t.cs() == "clearpage" ||
3620 t.cs() == "cleardoublepage") {
3621 context.check_layout(os);
3622 begin_inset(os, "Newpage ");
3625 skip_spaces_braces(p);
3628 else if (t.cs() == "DeclareRobustCommand" ||
3629 t.cs() == "DeclareRobustCommandx" ||
3630 t.cs() == "newcommand" ||
3631 t.cs() == "newcommandx" ||
3632 t.cs() == "providecommand" ||
3633 t.cs() == "providecommandx" ||
3634 t.cs() == "renewcommand" ||
3635 t.cs() == "renewcommandx") {
3636 // DeclareRobustCommand, DeclareRobustCommandx,
3637 // providecommand and providecommandx could be handled
3638 // by parse_command(), but we need to call
3639 // add_known_command() here.
3640 string name = t.asInput();
3641 if (p.next_token().asInput() == "*") {
3642 // Starred form. Eat '*'
3646 string const command = p.verbatim_item();
3647 string const opt1 = p.getFullOpt();
3648 string const opt2 = p.getFullOpt();
3649 add_known_command(command, opt1, !opt2.empty());
3650 string const ert = name + '{' + command + '}' +
3652 '{' + p.verbatim_item() + '}';
3654 if (t.cs() == "DeclareRobustCommand" ||
3655 t.cs() == "DeclareRobustCommandx" ||
3656 t.cs() == "providecommand" ||
3657 t.cs() == "providecommandx" ||
3658 name[name.length()-1] == '*')
3659 handle_ert(os, ert, context);
3661 context.check_layout(os);
3662 begin_inset(os, "FormulaMacro");
3668 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3669 // let could be handled by parse_command(),
3670 // but we need to call add_known_command() here.
3671 string ert = t.asInput();
3674 if (p.next_token().cat() == catBegin) {
3675 name = p.verbatim_item();
3676 ert += '{' + name + '}';
3678 name = p.verbatim_item();
3683 if (p.next_token().cat() == catBegin) {
3684 command = p.verbatim_item();
3685 ert += '{' + command + '}';
3687 command = p.verbatim_item();
3690 // If command is known, make name known too, to parse
3691 // its arguments correctly. For this reason we also
3692 // have commands in syntax.default that are hardcoded.
3693 CommandMap::iterator it = known_commands.find(command);
3694 if (it != known_commands.end())
3695 known_commands[t.asInput()] = it->second;
3696 handle_ert(os, ert, context);
3699 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3700 bool starred = false;
3701 if (p.next_token().asInput() == "*") {
3705 string name = t.asInput();
3706 string const length = p.verbatim_item();
3709 bool valid = splitLatexLength(length, valstring, unit);
3710 bool known_hspace = false;
3711 bool known_vspace = false;
3712 bool known_unit = false;
3715 istringstream iss(valstring);
3718 if (t.cs()[0] == 'h') {
3719 if (unit == "\\fill") {
3724 known_hspace = true;
3727 if (unit == "\\smallskipamount") {
3729 known_vspace = true;
3730 } else if (unit == "\\medskipamount") {
3732 known_vspace = true;
3733 } else if (unit == "\\bigskipamount") {
3735 known_vspace = true;
3736 } else if (unit == "\\fill") {
3738 known_vspace = true;
3742 if (!known_hspace && !known_vspace) {
3743 switch (unitFromString(unit)) {
3764 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3765 // Literal horizontal length or known variable
3766 context.check_layout(os);
3767 begin_inset(os, "space ");
3775 if (known_unit && !known_hspace)
3777 << translate_len(length);
3779 } else if (known_unit || known_vspace) {
3780 // Literal vertical length or known variable
3781 context.check_layout(os);
3782 begin_inset(os, "VSpace ");
3790 // LyX can't handle other length variables in Inset VSpace/space
3795 handle_ert(os, name + '{' + unit + '}', context);
3796 else if (value == -1.0)
3797 handle_ert(os, name + "{-" + unit + '}', context);
3799 handle_ert(os, name + '{' + valstring + unit + '}', context);
3801 handle_ert(os, name + '{' + length + '}', context);
3805 // The single '=' is meant here.
3806 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3808 context.check_layout(os);
3809 begin_inset(os, "Flex ");
3810 os << to_utf8(newinsetlayout->name()) << '\n'
3811 << "status collapsed\n";
3812 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3817 // try to see whether the string is in unicodesymbols
3818 // Only use text mode commands, since we are in text mode here,
3819 // and math commands may be invalid (bug 6797)
3821 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3822 rem, Encodings::TEXT_CMD);
3825 cerr << "When parsing " << t.cs()
3826 << ", result is " << to_utf8(s)
3827 << "+" << to_utf8(rem) << endl;
3828 context.check_layout(os);
3830 skip_spaces_braces(p);
3832 //cerr << "#: " << t << " mode: " << mode << endl;
3833 // heuristic: read up to next non-nested space
3835 string s = t.asInput();
3836 string z = p.verbatim_item();
3837 while (p.good() && z != " " && z.size()) {
3838 //cerr << "read: " << z << endl;
3840 z = p.verbatim_item();
3842 cerr << "found ERT: " << s << endl;
3843 handle_ert(os, s + ' ', context);
3846 string name = t.asInput();
3847 if (p.next_token().asInput() == "*") {
3848 // Starred commands like \vspace*{}
3849 p.get_token(); // Eat '*'
3852 if (!parse_command(name, p, os, outer, context))
3853 handle_ert(os, name, context);
3857 if (flags & FLAG_LEAVE) {
3858 flags &= ~FLAG_LEAVE;