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();
900 parse_text(p, os, outer_flags, outer, parent_context);
901 if (outer_flags & FLAG_END)
902 handle_ert(os, "\\end{" + outer_type + '}',
904 else if (inner_type.empty() && outer_type == "framebox")
905 // in this case it is already closed later
908 handle_ert(os, "}", parent_context);
911 // LyX does not like empty positions, so we have
912 // to set them to the LaTeX default values here.
913 if (position.empty())
915 if (inner_pos.empty())
916 inner_pos = position;
917 parent_context.check_layout(os);
918 begin_inset(os, "Box ");
919 if (outer_type == "framed")
921 else if (outer_type == "framebox")
923 else if (outer_type == "shadowbox")
925 else if ((outer_type == "shaded" && inner_type.empty()) ||
926 (outer_type == "minipage" && inner_type == "shaded") ||
927 (outer_type == "parbox" && inner_type == "shaded")) {
929 preamble.registerAutomaticallyLoadedPackage("color");
930 } else if (outer_type == "doublebox")
932 else if (outer_type.empty())
935 os << outer_type << '\n';
936 os << "position \"" << position << "\"\n";
937 os << "hor_pos \"" << hor_pos << "\"\n";
938 os << "has_inner_box " << !inner_type.empty() << "\n";
939 os << "inner_pos \"" << inner_pos << "\"\n";
940 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
942 os << "use_makebox " << (inner_type == "makebox") << '\n';
943 os << "width \"" << width_value << width_unit << "\"\n";
944 os << "special \"" << width_special << "\"\n";
945 os << "height \"" << height_value << height_unit << "\"\n";
946 os << "height_special \"" << height_special << "\"\n";
947 os << "status open\n\n";
949 // Unfortunately we can't use parse_text_in_inset:
950 // InsetBox::forcePlainLayout() is hard coded and does not
951 // use the inset layout. Apart from that do we call parse_text
952 // up to two times, but need only one check_end_layout.
953 bool const forcePlainLayout =
954 (!inner_type.empty() || inner_type == "makebox") &&
955 outer_type != "shaded" && outer_type != "framed";
956 Context context(true, parent_context.textclass);
957 if (forcePlainLayout)
958 context.layout = &context.textclass.plainLayout();
960 context.font = parent_context.font;
962 // If we have no inner box the contents will be read with the outer box
963 if (!inner_type.empty())
964 parse_text(p, os, inner_flags, outer, context);
966 // Ensure that the end of the outer box is parsed correctly:
967 // The opening brace has been eaten by parse_outer_box()
968 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
969 outer_flags &= ~FLAG_ITEM;
970 outer_flags |= FLAG_BRACE_LAST;
973 // Find end of outer box, output contents if inner_type is
974 // empty and output possible comments
975 if (!outer_type.empty()) {
976 // If we already read the inner box we have to pop
978 if (!inner_type.empty() && (inner_flags & FLAG_END))
979 active_environments.pop_back();
980 // This does not output anything but comments if
981 // inner_type is not empty (see use_ert)
982 parse_text(p, os, outer_flags, outer, context);
985 context.check_end_layout(os);
987 #ifdef PRESERVE_LAYOUT
988 // LyX puts a % after the end of the minipage
989 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
991 //handle_comment(os, "%dummy", parent_context);
994 parent_context.new_paragraph(os);
996 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
997 //handle_comment(os, "%dummy", parent_context);
1000 // We add a protected space if something real follows
1001 if (p.good() && p.next_token().cat() != catComment) {
1002 begin_inset(os, "space ~\n");
1011 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1012 Context & parent_context, string const & outer_type,
1013 string const & special)
1015 eat_whitespace(p, os, parent_context, false);
1016 if (flags & FLAG_ITEM) {
1018 if (p.next_token().cat() == catBegin)
1021 cerr << "Warning: Ignoring missing '{' after \\"
1022 << outer_type << '.' << endl;
1023 eat_whitespace(p, os, parent_context, false);
1026 unsigned int inner_flags = 0;
1028 if (outer_type == "minipage" || outer_type == "parbox") {
1029 p.skip_spaces(true);
1030 while (p.hasOpt()) {
1032 p.skip_spaces(true);
1035 p.skip_spaces(true);
1036 if (outer_type == "parbox") {
1038 if (p.next_token().cat() == catBegin)
1040 p.skip_spaces(true);
1043 if (outer_type == "shaded") {
1044 // These boxes never have an inner box
1046 } else if (p.next_token().asInput() == "\\parbox") {
1047 inner = p.get_token().cs();
1048 inner_flags = FLAG_ITEM;
1049 } else if (p.next_token().asInput() == "\\begin") {
1050 // Is this a minipage or shaded box?
1053 inner = p.getArg('{', '}');
1055 if (inner == "minipage" || inner == "shaded")
1056 inner_flags = FLAG_END;
1061 if (inner_flags == FLAG_END) {
1062 if (inner != "shaded")
1066 eat_whitespace(p, os, parent_context, false);
1068 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1069 outer_type, special, inner);
1071 if (inner_flags == FLAG_ITEM) {
1073 eat_whitespace(p, os, parent_context, false);
1075 parse_box(p, os, flags, inner_flags, outer, parent_context,
1076 outer_type, special, inner);
1081 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1083 parent_context.check_layout(os);
1084 begin_inset(os, "listings\n");
1085 os << "inline false\n"
1086 << "status collapsed\n";
1087 Context context(true, parent_context.textclass);
1088 context.layout = &parent_context.textclass.plainLayout();
1089 context.check_layout(os);
1090 string const s = p.verbatimEnvironment("lstlisting");
1091 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1093 os << "\n\\backslash\n";
1094 else if (*it == '\n') {
1095 // avoid adding an empty paragraph at the end
1097 context.new_paragraph(os);
1098 context.check_layout(os);
1103 context.check_end_layout(os);
1108 /// parse an unknown environment
1109 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1110 unsigned flags, bool outer,
1111 Context & parent_context)
1113 if (name == "tabbing")
1114 // We need to remember that we have to handle '\=' specially
1115 flags |= FLAG_TABBING;
1117 // We need to translate font changes and paragraphs inside the
1118 // environment to ERT if we have a non standard font.
1119 // Otherwise things like
1120 // \large\begin{foo}\huge bar\end{foo}
1122 bool const specialfont =
1123 (parent_context.font != parent_context.normalfont);
1124 bool const new_layout_allowed = parent_context.new_layout_allowed;
1126 parent_context.new_layout_allowed = false;
1127 handle_ert(os, "\\begin{" + name + "}", parent_context);
1128 parse_text_snippet(p, os, flags, outer, parent_context);
1129 handle_ert(os, "\\end{" + name + "}", parent_context);
1131 parent_context.new_layout_allowed = new_layout_allowed;
1135 void parse_environment(Parser & p, ostream & os, bool outer,
1136 string & last_env, bool & title_layout_found,
1137 Context & parent_context)
1139 Layout const * newlayout;
1140 InsetLayout const * newinsetlayout = 0;
1141 string const name = p.getArg('{', '}');
1142 const bool is_starred = suffixIs(name, '*');
1143 string const unstarred_name = rtrim(name, "*");
1144 active_environments.push_back(name);
1146 if (is_math_env(name)) {
1147 parent_context.check_layout(os);
1148 begin_inset(os, "Formula ");
1149 os << "\\begin{" << name << "}";
1150 parse_math(p, os, FLAG_END, MATH_MODE);
1151 os << "\\end{" << name << "}";
1155 else if (unstarred_name == "tabular" || name == "longtable") {
1156 eat_whitespace(p, os, parent_context, false);
1157 string width = "0pt";
1158 if (name == "tabular*") {
1159 width = lyx::translate_len(p.getArg('{', '}'));
1160 eat_whitespace(p, os, parent_context, false);
1162 parent_context.check_layout(os);
1163 begin_inset(os, "Tabular ");
1164 handle_tabular(p, os, name, width, parent_context);
1169 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1170 eat_whitespace(p, os, parent_context, false);
1171 parent_context.check_layout(os);
1172 begin_inset(os, "Float " + unstarred_name + "\n");
1173 // store the float type for subfloats
1174 // subfloats only work with figures and tables
1175 if (unstarred_name == "figure")
1176 float_type = unstarred_name;
1177 else if (unstarred_name == "table")
1178 float_type = unstarred_name;
1182 os << "placement " << p.getArg('[', ']') << '\n';
1183 os << "wide " << convert<string>(is_starred)
1184 << "\nsideways false"
1185 << "\nstatus open\n\n";
1186 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1188 // We don't need really a new paragraph, but
1189 // we must make sure that the next item gets a \begin_layout.
1190 parent_context.new_paragraph(os);
1192 // the float is parsed thus delete the type
1196 else if (unstarred_name == "sidewaysfigure"
1197 || unstarred_name == "sidewaystable") {
1198 eat_whitespace(p, os, parent_context, false);
1199 parent_context.check_layout(os);
1200 if (unstarred_name == "sidewaysfigure")
1201 begin_inset(os, "Float figure\n");
1203 begin_inset(os, "Float table\n");
1204 os << "wide " << convert<string>(is_starred)
1205 << "\nsideways true"
1206 << "\nstatus open\n\n";
1207 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1209 // We don't need really a new paragraph, but
1210 // we must make sure that the next item gets a \begin_layout.
1211 parent_context.new_paragraph(os);
1215 else if (name == "wrapfigure" || name == "wraptable") {
1216 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1217 eat_whitespace(p, os, parent_context, false);
1218 parent_context.check_layout(os);
1221 string overhang = "0col%";
1224 lines = p.getArg('[', ']');
1225 string const placement = p.getArg('{', '}');
1227 overhang = p.getArg('[', ']');
1228 string const width = p.getArg('{', '}');
1230 if (name == "wrapfigure")
1231 begin_inset(os, "Wrap figure\n");
1233 begin_inset(os, "Wrap table\n");
1234 os << "lines " << lines
1235 << "\nplacement " << placement
1236 << "\noverhang " << lyx::translate_len(overhang)
1237 << "\nwidth " << lyx::translate_len(width)
1238 << "\nstatus open\n\n";
1239 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1241 // We don't need really a new paragraph, but
1242 // we must make sure that the next item gets a \begin_layout.
1243 parent_context.new_paragraph(os);
1247 else if (name == "minipage") {
1248 eat_whitespace(p, os, parent_context, false);
1249 // Test whether this is an outer box of a shaded box
1251 // swallow arguments
1252 while (p.hasOpt()) {
1254 p.skip_spaces(true);
1257 p.skip_spaces(true);
1258 Token t = p.get_token();
1259 bool shaded = false;
1260 if (t.asInput() == "\\begin") {
1261 p.skip_spaces(true);
1262 if (p.getArg('{', '}') == "shaded")
1267 parse_outer_box(p, os, FLAG_END, outer,
1268 parent_context, name, "shaded");
1270 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1275 else if (name == "comment") {
1276 eat_whitespace(p, os, parent_context, false);
1277 parent_context.check_layout(os);
1278 begin_inset(os, "Note Comment\n");
1279 os << "status open\n";
1280 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1283 skip_braces(p); // eat {} that might by set by LyX behind comments
1286 else if (name == "lyxgreyedout") {
1287 eat_whitespace(p, os, parent_context, false);
1288 parent_context.check_layout(os);
1289 begin_inset(os, "Note Greyedout\n");
1290 os << "status open\n";
1291 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1294 if (!preamble.notefontcolor().empty())
1295 preamble.registerAutomaticallyLoadedPackage("color");
1298 else if (name == "framed" || name == "shaded") {
1299 eat_whitespace(p, os, parent_context, false);
1300 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1304 else if (name == "lstlisting") {
1305 eat_whitespace(p, os, parent_context, false);
1306 // FIXME handle listings with parameters
1307 // If this is added, don't forgot to handle the
1308 // automatic color package loading
1310 parse_unknown_environment(p, name, os, FLAG_END,
1311 outer, parent_context);
1313 parse_listings(p, os, parent_context);
1317 else if (!parent_context.new_layout_allowed)
1318 parse_unknown_environment(p, name, os, FLAG_END, outer,
1321 // Alignment and spacing settings
1322 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1323 // therefore are totally broken!
1324 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1325 // they are commands not environments. They are furthermore switches that
1326 // can be ended by another switches, but also by commands like \footnote or
1327 // \parbox. So the only safe way is to leave them untouched.
1328 else if (name == "center" || name == "centering" ||
1329 name == "flushleft" || name == "flushright" ||
1330 name == "singlespace" || name == "onehalfspace" ||
1331 name == "doublespace" || name == "spacing") {
1332 eat_whitespace(p, os, parent_context, false);
1333 // We must begin a new paragraph if not already done
1334 if (! parent_context.atParagraphStart()) {
1335 parent_context.check_end_layout(os);
1336 parent_context.new_paragraph(os);
1338 if (name == "flushleft")
1339 parent_context.add_extra_stuff("\\align left\n");
1340 else if (name == "flushright")
1341 parent_context.add_extra_stuff("\\align right\n");
1342 else if (name == "center" || name == "centering")
1343 parent_context.add_extra_stuff("\\align center\n");
1344 else if (name == "singlespace")
1345 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1346 else if (name == "onehalfspace")
1347 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1348 else if (name == "doublespace")
1349 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1350 else if (name == "spacing")
1351 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1352 parse_text(p, os, FLAG_END, outer, parent_context);
1353 // Just in case the environment is empty
1354 parent_context.extra_stuff.erase();
1355 // We must begin a new paragraph to reset the alignment
1356 parent_context.new_paragraph(os);
1360 // The single '=' is meant here.
1361 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1362 eat_whitespace(p, os, parent_context, false);
1363 Context context(true, parent_context.textclass, newlayout,
1364 parent_context.layout, parent_context.font);
1365 if (parent_context.deeper_paragraph) {
1366 // We are beginning a nested environment after a
1367 // deeper paragraph inside the outer list environment.
1368 // Therefore we don't need to output a "begin deeper".
1369 context.need_end_deeper = true;
1371 parent_context.check_end_layout(os);
1372 if (last_env == name) {
1373 // we need to output a separator since LyX would export
1374 // the two environments as one otherwise (bug 5716)
1375 docstring const sep = from_ascii("--Separator--");
1376 TeX2LyXDocClass const & textclass(parent_context.textclass);
1377 if (textclass.hasLayout(sep)) {
1378 Context newcontext(parent_context);
1379 newcontext.layout = &(textclass[sep]);
1380 newcontext.check_layout(os);
1381 newcontext.check_end_layout(os);
1383 parent_context.check_layout(os);
1384 begin_inset(os, "Note Note\n");
1385 os << "status closed\n";
1386 Context newcontext(true, textclass,
1387 &(textclass.defaultLayout()));
1388 newcontext.check_layout(os);
1389 newcontext.check_end_layout(os);
1391 parent_context.check_end_layout(os);
1394 switch (context.layout->latextype) {
1395 case LATEX_LIST_ENVIRONMENT:
1396 context.add_par_extra_stuff("\\labelwidthstring "
1397 + p.verbatim_item() + '\n');
1400 case LATEX_BIB_ENVIRONMENT:
1401 p.verbatim_item(); // swallow next arg
1407 context.check_deeper(os);
1408 // handle known optional and required arguments
1409 // layouts require all optional arguments before the required ones
1410 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1411 // It is impossible to place anything after the environment name,
1412 // but before the first \\item.
1413 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1414 bool need_layout = true;
1415 unsigned int optargs = 0;
1416 while (optargs < context.layout->optargs) {
1417 eat_whitespace(p, os, context, false);
1418 if (p.next_token().cat() == catEscape ||
1419 p.next_token().character() != '[')
1421 p.get_token(); // eat '['
1423 context.check_layout(os);
1424 need_layout = false;
1426 begin_inset(os, "Argument\n");
1427 os << "status collapsed\n\n";
1428 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1430 eat_whitespace(p, os, context, false);
1433 unsigned int reqargs = 0;
1434 while (reqargs < context.layout->reqargs) {
1435 eat_whitespace(p, os, context, false);
1436 if (p.next_token().cat() != catBegin)
1438 p.get_token(); // eat '{'
1440 context.check_layout(os);
1441 need_layout = false;
1443 begin_inset(os, "Argument\n");
1444 os << "status collapsed\n\n";
1445 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1447 eat_whitespace(p, os, context, false);
1451 parse_text(p, os, FLAG_END, outer, context);
1452 context.check_end_layout(os);
1453 if (parent_context.deeper_paragraph) {
1454 // We must suppress the "end deeper" because we
1455 // suppressed the "begin deeper" above.
1456 context.need_end_deeper = false;
1458 context.check_end_deeper(os);
1459 parent_context.new_paragraph(os);
1461 if (!title_layout_found)
1462 title_layout_found = newlayout->intitle;
1465 // The single '=' is meant here.
1466 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1467 eat_whitespace(p, os, parent_context, false);
1468 parent_context.check_layout(os);
1469 begin_inset(os, "Flex ");
1470 os << to_utf8(newinsetlayout->name()) << '\n'
1471 << "status collapsed\n";
1472 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1476 else if (name == "appendix") {
1477 // This is no good latex style, but it works and is used in some documents...
1478 eat_whitespace(p, os, parent_context, false);
1479 parent_context.check_end_layout(os);
1480 Context context(true, parent_context.textclass, parent_context.layout,
1481 parent_context.layout, parent_context.font);
1482 context.check_layout(os);
1483 os << "\\start_of_appendix\n";
1484 parse_text(p, os, FLAG_END, outer, context);
1485 context.check_end_layout(os);
1489 else if (known_environments.find(name) != known_environments.end()) {
1490 vector<ArgumentType> arguments = known_environments[name];
1491 // The last "argument" denotes wether we may translate the
1492 // environment contents to LyX
1493 // The default required if no argument is given makes us
1494 // compatible with the reLyXre environment.
1495 ArgumentType contents = arguments.empty() ?
1498 if (!arguments.empty())
1499 arguments.pop_back();
1500 // See comment in parse_unknown_environment()
1501 bool const specialfont =
1502 (parent_context.font != parent_context.normalfont);
1503 bool const new_layout_allowed =
1504 parent_context.new_layout_allowed;
1506 parent_context.new_layout_allowed = false;
1507 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1508 outer, parent_context);
1509 if (contents == verbatim)
1510 handle_ert(os, p.verbatimEnvironment(name),
1513 parse_text_snippet(p, os, FLAG_END, outer,
1515 handle_ert(os, "\\end{" + name + "}", parent_context);
1517 parent_context.new_layout_allowed = new_layout_allowed;
1521 parse_unknown_environment(p, name, os, FLAG_END, outer,
1525 active_environments.pop_back();
1529 /// parses a comment and outputs it to \p os.
1530 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1532 LASSERT(t.cat() == catComment, return);
1533 if (!t.cs().empty()) {
1534 context.check_layout(os);
1535 handle_comment(os, '%' + t.cs(), context);
1536 if (p.next_token().cat() == catNewline) {
1537 // A newline after a comment line starts a new
1539 if (context.new_layout_allowed) {
1540 if(!context.atParagraphStart())
1541 // Only start a new paragraph if not already
1542 // done (we might get called recursively)
1543 context.new_paragraph(os);
1545 handle_ert(os, "\n", context);
1546 eat_whitespace(p, os, context, true);
1549 // "%\n" combination
1556 * Reads spaces and comments until the first non-space, non-comment token.
1557 * New paragraphs (double newlines or \\par) are handled like simple spaces
1558 * if \p eatParagraph is true.
1559 * Spaces are skipped, but comments are written to \p os.
1561 void eat_whitespace(Parser & p, ostream & os, Context & context,
1565 Token const & t = p.get_token();
1566 if (t.cat() == catComment)
1567 parse_comment(p, os, t, context);
1568 else if ((! eatParagraph && p.isParagraph()) ||
1569 (t.cat() != catSpace && t.cat() != catNewline)) {
1578 * Set a font attribute, parse text and reset the font attribute.
1579 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1580 * \param currentvalue Current value of the attribute. Is set to the new
1581 * value during parsing.
1582 * \param newvalue New value of the attribute
1584 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1585 Context & context, string const & attribute,
1586 string & currentvalue, string const & newvalue)
1588 context.check_layout(os);
1589 string const oldvalue = currentvalue;
1590 currentvalue = newvalue;
1591 os << '\n' << attribute << ' ' << newvalue << "\n";
1592 parse_text_snippet(p, os, flags, outer, context);
1593 context.check_layout(os);
1594 os << '\n' << attribute << ' ' << oldvalue << "\n";
1595 currentvalue = oldvalue;
1599 /// get the arguments of a natbib or jurabib citation command
1600 void get_cite_arguments(Parser & p, bool natbibOrder,
1601 string & before, string & after)
1603 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1605 // text before the citation
1607 // text after the citation
1608 after = p.getFullOpt();
1610 if (!after.empty()) {
1611 before = p.getFullOpt();
1612 if (natbibOrder && !before.empty())
1613 swap(before, after);
1618 /// Convert filenames with TeX macros and/or quotes to something LyX
1620 string const normalize_filename(string const & name)
1622 Parser p(trim(name, "\""));
1625 Token const & t = p.get_token();
1626 if (t.cat() != catEscape)
1628 else if (t.cs() == "lyxdot") {
1629 // This is used by LyX for simple dots in relative
1633 } else if (t.cs() == "space") {
1643 /// Convert \p name from TeX convention (relative to master file) to LyX
1644 /// convention (relative to .lyx file) if it is relative
1645 void fix_relative_filename(string & name)
1647 if (FileName::isAbsolute(name))
1650 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1651 from_utf8(getParentFilePath())));
1655 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1656 void parse_noweb(Parser & p, ostream & os, Context & context)
1658 // assemble the rest of the keyword
1662 Token const & t = p.get_token();
1663 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1666 scrap = (p.good() && p.next_token().asInput() == "=");
1668 name += p.get_token().asInput();
1671 name += t.asInput();
1674 if (!scrap || !context.new_layout_allowed ||
1675 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1676 cerr << "Warning: Could not interpret '" << name
1677 << "'. Ignoring it." << endl;
1681 // We use new_paragraph instead of check_end_layout because the stuff
1682 // following the noweb chunk needs to start with a \begin_layout.
1683 // This may create a new paragraph even if there was none in the
1684 // noweb file, but the alternative is an invalid LyX file. Since
1685 // noweb code chunks are implemented with a layout style in LyX they
1686 // always must be in an own paragraph.
1687 context.new_paragraph(os);
1688 Context newcontext(true, context.textclass,
1689 &context.textclass[from_ascii("Scrap")]);
1690 newcontext.check_layout(os);
1693 Token const & t = p.get_token();
1694 // We abuse the parser a bit, because this is no TeX syntax
1696 if (t.cat() == catEscape)
1697 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1700 Context tmp(false, context.textclass,
1701 &context.textclass[from_ascii("Scrap")]);
1702 tmp.need_end_layout = true;
1703 tmp.check_layout(oss);
1704 os << subst(t.asInput(), "\n", oss.str());
1706 // The scrap chunk is ended by an @ at the beginning of a line.
1707 // After the @ the line may contain a comment and/or
1708 // whitespace, but nothing else.
1709 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1710 (p.next_token().cat() == catSpace ||
1711 p.next_token().cat() == catNewline ||
1712 p.next_token().cat() == catComment)) {
1713 while (p.good() && p.next_token().cat() == catSpace)
1714 os << p.get_token().asInput();
1715 if (p.next_token().cat() == catComment)
1716 // The comment includes a final '\n'
1717 os << p.get_token().asInput();
1719 if (p.next_token().cat() == catNewline)
1726 newcontext.check_end_layout(os);
1730 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1731 bool is_macro(Parser & p)
1733 Token first = p.curr_token();
1734 if (first.cat() != catEscape || !p.good())
1736 if (first.cs() == "def")
1738 if (first.cs() != "global" && first.cs() != "long")
1740 Token second = p.get_token();
1742 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1743 second.cat() == catNewline || second.cat() == catComment)) {
1744 second = p.get_token();
1747 bool secondvalid = second.cat() == catEscape;
1749 bool thirdvalid = false;
1750 if (p.good() && first.cs() == "global" && secondvalid &&
1751 second.cs() == "long") {
1752 third = p.get_token();
1754 while (p.good() && !p.isParagraph() &&
1755 (third.cat() == catSpace ||
1756 third.cat() == catNewline ||
1757 third.cat() == catComment)) {
1758 third = p.get_token();
1761 thirdvalid = third.cat() == catEscape;
1763 for (int i = 0; i < pos; ++i)
1768 return (first.cs() == "global" || first.cs() == "long") &&
1769 second.cs() == "def";
1770 return first.cs() == "global" && second.cs() == "long" &&
1771 third.cs() == "def";
1775 /// Parse a macro definition (assumes that is_macro() returned true)
1776 void parse_macro(Parser & p, ostream & os, Context & context)
1778 context.check_layout(os);
1779 Token first = p.curr_token();
1782 string command = first.asInput();
1783 if (first.cs() != "def") {
1785 eat_whitespace(p, os, context, false);
1786 second = p.curr_token();
1787 command += second.asInput();
1788 if (second.cs() != "def") {
1790 eat_whitespace(p, os, context, false);
1791 third = p.curr_token();
1792 command += third.asInput();
1795 eat_whitespace(p, os, context, false);
1796 string const name = p.get_token().cs();
1797 eat_whitespace(p, os, context, false);
1803 while (p.next_token().cat() != catBegin) {
1804 if (p.next_token().cat() == catParameter) {
1809 // followed by number?
1810 if (p.next_token().cat() == catOther) {
1811 char c = p.getChar();
1813 // number = current arity + 1?
1814 if (c == arity + '0' + 1)
1819 paramtext += p.get_token().cs();
1821 paramtext += p.get_token().cs();
1826 // only output simple (i.e. compatible) macro as FormulaMacros
1827 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1829 context.check_layout(os);
1830 begin_inset(os, "FormulaMacro");
1831 os << "\n\\def" << ert;
1834 handle_ert(os, command + ert, context);
1837 } // anonymous namespace
1840 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1843 Layout const * newlayout = 0;
1844 InsetLayout const * newinsetlayout = 0;
1845 // Store the latest bibliographystyle and nocite{*} option
1846 // (needed for bibtex inset)
1848 string bibliographystyle;
1849 bool const use_natbib = preamble.isPackageUsed("natbib");
1850 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1852 bool title_layout_found = false;
1854 Token const & t = p.get_token();
1857 debugToken(cerr, t, flags);
1860 if (flags & FLAG_ITEM) {
1861 if (t.cat() == catSpace)
1864 flags &= ~FLAG_ITEM;
1865 if (t.cat() == catBegin) {
1866 // skip the brace and collect everything to the next matching
1868 flags |= FLAG_BRACE_LAST;
1872 // handle only this single token, leave the loop if done
1873 flags |= FLAG_LEAVE;
1876 if (t.cat() != catEscape && t.character() == ']' &&
1877 (flags & FLAG_BRACK_LAST))
1879 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1882 // If there is anything between \end{env} and \begin{env} we
1883 // don't need to output a separator.
1884 if (t.cat() != catSpace && t.cat() != catNewline &&
1885 t.asInput() != "\\begin")
1891 if (t.cat() == catMath) {
1892 // we are inside some text mode thingy, so opening new math is allowed
1893 context.check_layout(os);
1894 begin_inset(os, "Formula ");
1895 Token const & n = p.get_token();
1896 if (n.cat() == catMath && outer) {
1897 // TeX's $$...$$ syntax for displayed math
1899 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1901 p.get_token(); // skip the second '$' token
1903 // simple $...$ stuff
1906 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1912 else if (t.cat() == catSuper || t.cat() == catSub)
1913 cerr << "catcode " << t << " illegal in text mode\n";
1915 // Basic support for english quotes. This should be
1916 // extended to other quotes, but is not so easy (a
1917 // left english quote is the same as a right german
1919 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1920 context.check_layout(os);
1921 begin_inset(os, "Quotes ");
1927 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1928 context.check_layout(os);
1929 begin_inset(os, "Quotes ");
1936 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1937 context.check_layout(os);
1938 begin_inset(os, "Quotes ");
1945 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1946 context.check_layout(os);
1947 begin_inset(os, "Quotes ");
1954 else if (t.asInput() == "<"
1955 && p.next_token().asInput() == "<" && noweb_mode) {
1957 parse_noweb(p, os, context);
1960 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1961 check_space(p, os, context);
1963 else if (t.character() == '[' && noweb_mode &&
1964 p.next_token().character() == '[') {
1965 // These can contain underscores
1967 string const s = p.getFullOpt() + ']';
1968 if (p.next_token().character() == ']')
1971 cerr << "Warning: Inserting missing ']' in '"
1972 << s << "'." << endl;
1973 handle_ert(os, s, context);
1976 else if (t.cat() == catLetter) {
1977 context.check_layout(os);
1978 // Workaround for bug 4752.
1979 // FIXME: This whole code block needs to be removed
1980 // when the bug is fixed and tex2lyx produces
1981 // the updated file format.
1982 // The replacement algorithm in LyX is so stupid that
1983 // it even translates a phrase if it is part of a word.
1984 bool handled = false;
1985 for (int const * l = known_phrase_lengths; *l; ++l) {
1986 string phrase = t.cs();
1987 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1988 phrase += p.get_token().cs();
1989 if (is_known(phrase, known_coded_phrases)) {
1990 handle_ert(os, phrase, context);
1994 for (size_t i = 1; i < phrase.length(); ++i)
2002 else if (t.cat() == catOther ||
2003 t.cat() == catAlign ||
2004 t.cat() == catParameter) {
2005 // This translates "&" to "\\&" which may be wrong...
2006 context.check_layout(os);
2010 else if (p.isParagraph()) {
2011 if (context.new_layout_allowed)
2012 context.new_paragraph(os);
2014 handle_ert(os, "\\par ", context);
2015 eat_whitespace(p, os, context, true);
2018 else if (t.cat() == catActive) {
2019 context.check_layout(os);
2020 if (t.character() == '~') {
2021 if (context.layout->free_spacing)
2024 begin_inset(os, "space ~\n");
2031 else if (t.cat() == catBegin &&
2032 p.next_token().cat() == catEnd) {
2034 Token const prev = p.prev_token();
2036 if (p.next_token().character() == '`' ||
2037 (prev.character() == '-' &&
2038 p.next_token().character() == '-'))
2039 ; // ignore it in {}`` or -{}-
2041 handle_ert(os, "{}", context);
2045 else if (t.cat() == catBegin) {
2046 context.check_layout(os);
2047 // special handling of font attribute changes
2048 Token const prev = p.prev_token();
2049 Token const next = p.next_token();
2050 TeXFont const oldFont = context.font;
2051 if (next.character() == '[' ||
2052 next.character() == ']' ||
2053 next.character() == '*') {
2055 if (p.next_token().cat() == catEnd) {
2060 handle_ert(os, "{", context);
2061 parse_text_snippet(p, os,
2064 handle_ert(os, "}", context);
2066 } else if (! context.new_layout_allowed) {
2067 handle_ert(os, "{", context);
2068 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2070 handle_ert(os, "}", context);
2071 } else if (is_known(next.cs(), known_sizes)) {
2072 // next will change the size, so we must
2074 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2076 if (!context.atParagraphStart())
2078 << context.font.size << "\n";
2079 } else if (is_known(next.cs(), known_font_families)) {
2080 // next will change the font family, so we
2081 // must reset it here
2082 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2084 if (!context.atParagraphStart())
2086 << context.font.family << "\n";
2087 } else if (is_known(next.cs(), known_font_series)) {
2088 // next will change the font series, so we
2089 // must reset it here
2090 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2092 if (!context.atParagraphStart())
2094 << context.font.series << "\n";
2095 } else if (is_known(next.cs(), known_font_shapes)) {
2096 // next will change the font shape, so we
2097 // must reset it here
2098 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2100 if (!context.atParagraphStart())
2102 << context.font.shape << "\n";
2103 } else if (is_known(next.cs(), known_old_font_families) ||
2104 is_known(next.cs(), known_old_font_series) ||
2105 is_known(next.cs(), known_old_font_shapes)) {
2106 // next will change the font family, series
2107 // and shape, so we must reset it here
2108 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2110 if (!context.atParagraphStart())
2112 << context.font.family
2114 << context.font.series
2116 << context.font.shape << "\n";
2118 handle_ert(os, "{", context);
2119 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2121 handle_ert(os, "}", context);
2125 else if (t.cat() == catEnd) {
2126 if (flags & FLAG_BRACE_LAST) {
2129 cerr << "stray '}' in text\n";
2130 handle_ert(os, "}", context);
2133 else if (t.cat() == catComment)
2134 parse_comment(p, os, t, context);
2137 // control sequences
2140 else if (t.cs() == "(") {
2141 context.check_layout(os);
2142 begin_inset(os, "Formula");
2144 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2149 else if (t.cs() == "[") {
2150 context.check_layout(os);
2151 begin_inset(os, "Formula");
2153 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2158 else if (t.cs() == "begin")
2159 parse_environment(p, os, outer, last_env,
2160 title_layout_found, context);
2162 else if (t.cs() == "end") {
2163 if (flags & FLAG_END) {
2164 // eat environment name
2165 string const name = p.getArg('{', '}');
2166 if (name != active_environment())
2167 cerr << "\\end{" + name + "} does not match \\begin{"
2168 + active_environment() + "}\n";
2171 p.error("found 'end' unexpectedly");
2174 else if (t.cs() == "item") {
2177 bool optarg = false;
2178 if (p.next_token().cat() != catEscape &&
2179 p.next_token().character() == '[') {
2180 p.get_token(); // eat '['
2181 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2186 context.check_layout(os);
2187 if (context.has_item) {
2188 // An item in an unknown list-like environment
2189 // FIXME: Do this in check_layout()!
2190 context.has_item = false;
2192 handle_ert(os, "\\item", context);
2194 handle_ert(os, "\\item ", context);
2197 if (context.layout->labeltype != LABEL_MANUAL) {
2198 // LyX does not support \item[\mybullet]
2199 // in itemize environments
2200 handle_ert(os, "[", context);
2202 handle_ert(os, "]", context);
2203 } else if (!s.empty()) {
2204 // The space is needed to separate the
2205 // item from the rest of the sentence.
2207 eat_whitespace(p, os, context, false);
2212 else if (t.cs() == "bibitem") {
2214 context.check_layout(os);
2215 string label = convert_command_inset_arg(p.getArg('[', ']'));
2216 string key = convert_command_inset_arg(p.verbatim_item());
2217 if (contains(label, '\\') || contains(key, '\\')) {
2218 // LyX can't handle LaTeX commands in labels or keys
2219 handle_ert(os, t.asInput() + '[' + label +
2220 "]{" + p.verbatim_item() + '}',
2223 begin_command_inset(os, "bibitem", "bibitem");
2224 os << "label \"" << label << "\"\n"
2225 "key \"" << key << "\"\n";
2230 else if (is_macro(p))
2231 parse_macro(p, os, context);
2233 else if (t.cs() == "noindent") {
2235 context.add_par_extra_stuff("\\noindent\n");
2238 else if (t.cs() == "appendix") {
2239 context.add_par_extra_stuff("\\start_of_appendix\n");
2240 // We need to start a new paragraph. Otherwise the
2241 // appendix in 'bla\appendix\chapter{' would start
2243 context.new_paragraph(os);
2244 // We need to make sure that the paragraph is
2245 // generated even if it is empty. Otherwise the
2246 // appendix in '\par\appendix\par\chapter{' would
2248 context.check_layout(os);
2249 // FIXME: This is a hack to prevent paragraph
2250 // deletion if it is empty. Handle this better!
2252 "%dummy comment inserted by tex2lyx to "
2253 "ensure that this paragraph is not empty",
2255 // Both measures above may generate an additional
2256 // empty paragraph, but that does not hurt, because
2257 // whitespace does not matter here.
2258 eat_whitespace(p, os, context, true);
2261 // Must catch empty dates before findLayout is called below
2262 else if (t.cs() == "date") {
2263 string const date = p.verbatim_item();
2265 preamble.suppressDate(true);
2267 preamble.suppressDate(false);
2268 if (context.new_layout_allowed &&
2269 (newlayout = findLayout(context.textclass,
2272 output_command_layout(os, p, outer,
2273 context, newlayout);
2275 if (!title_layout_found)
2276 title_layout_found = newlayout->intitle;
2278 handle_ert(os, "\\date{" + date + '}',
2283 // Starred section headings
2284 // Must attempt to parse "Section*" before "Section".
2285 else if ((p.next_token().asInput() == "*") &&
2286 context.new_layout_allowed &&
2287 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2290 output_command_layout(os, p, outer, context, newlayout);
2292 if (!title_layout_found)
2293 title_layout_found = newlayout->intitle;
2296 // Section headings and the like
2297 else if (context.new_layout_allowed &&
2298 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2300 output_command_layout(os, p, outer, context, newlayout);
2302 if (!title_layout_found)
2303 title_layout_found = newlayout->intitle;
2306 else if (t.cs() == "caption") {
2308 context.check_layout(os);
2310 begin_inset(os, "Caption\n");
2311 Context newcontext(true, context.textclass);
2312 newcontext.font = context.font;
2313 newcontext.check_layout(os);
2314 if (p.next_token().cat() != catEscape &&
2315 p.next_token().character() == '[') {
2316 p.get_token(); // eat '['
2317 begin_inset(os, "Argument\n");
2318 os << "status collapsed\n";
2319 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2321 eat_whitespace(p, os, context, false);
2323 parse_text(p, os, FLAG_ITEM, outer, context);
2324 context.check_end_layout(os);
2325 // We don't need really a new paragraph, but
2326 // we must make sure that the next item gets a \begin_layout.
2327 context.new_paragraph(os);
2330 newcontext.check_end_layout(os);
2333 else if (t.cs() == "subfloat") {
2334 // the syntax is \subfloat[caption]{content}
2335 // if it is a table of figure depends on the surrounding float
2336 bool has_caption = false;
2338 // do nothing if there is no outer float
2339 if (!float_type.empty()) {
2340 context.check_layout(os);
2342 begin_inset(os, "Float " + float_type + "\n");
2344 << "\nsideways false"
2345 << "\nstatus collapsed\n\n";
2348 if (p.next_token().cat() != catEscape &&
2349 p.next_token().character() == '[') {
2350 p.get_token(); // eat '['
2351 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2355 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2356 // the caption comes always as the last
2358 // we must make sure that the caption gets a \begin_layout
2359 os << "\n\\begin_layout Plain Layout";
2361 begin_inset(os, "Caption\n");
2362 Context newcontext(true, context.textclass);
2363 newcontext.font = context.font;
2364 newcontext.check_layout(os);
2365 os << caption << "\n";
2366 newcontext.check_end_layout(os);
2367 // We don't need really a new paragraph, but
2368 // we must make sure that the next item gets a \begin_layout.
2369 //newcontext.new_paragraph(os);
2373 // We don't need really a new paragraph, but
2374 // we must make sure that the next item gets a \begin_layout.
2376 context.new_paragraph(os);
2379 context.check_end_layout(os);
2380 // close the layout we opened
2382 os << "\n\\end_layout\n";
2384 // if the float type is not supported or there is no surrounding float
2387 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2388 handle_ert(os, t.asInput() + '[' + opt_arg +
2389 "]{" + p.verbatim_item() + '}', context);
2391 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2395 else if (t.cs() == "includegraphics") {
2396 bool const clip = p.next_token().asInput() == "*";
2399 string const arg = p.getArg('[', ']');
2400 map<string, string> opts;
2401 vector<string> keys;
2402 split_map(arg, opts, keys);
2404 opts["clip"] = string();
2405 string name = normalize_filename(p.verbatim_item());
2407 string const path = getMasterFilePath();
2408 // We want to preserve relative / absolute filenames,
2409 // therefore path is only used for testing
2410 if (!makeAbsPath(name, path).exists()) {
2411 // The file extension is probably missing.
2412 // Now try to find it out.
2413 string const dvips_name =
2414 find_file(name, path,
2415 known_dvips_graphics_formats);
2416 string const pdftex_name =
2417 find_file(name, path,
2418 known_pdftex_graphics_formats);
2419 if (!dvips_name.empty()) {
2420 if (!pdftex_name.empty()) {
2421 cerr << "This file contains the "
2423 "\"\\includegraphics{"
2425 "However, files\n\""
2426 << dvips_name << "\" and\n\""
2427 << pdftex_name << "\"\n"
2428 "both exist, so I had to make a "
2429 "choice and took the first one.\n"
2430 "Please move the unwanted one "
2431 "someplace else and try again\n"
2432 "if my choice was wrong."
2436 } else if (!pdftex_name.empty()) {
2442 if (makeAbsPath(name, path).exists())
2443 fix_relative_filename(name);
2445 cerr << "Warning: Could not find graphics file '"
2446 << name << "'." << endl;
2448 context.check_layout(os);
2449 begin_inset(os, "Graphics ");
2450 os << "\n\tfilename " << name << '\n';
2451 if (opts.find("width") != opts.end())
2453 << translate_len(opts["width"]) << '\n';
2454 if (opts.find("height") != opts.end())
2456 << translate_len(opts["height"]) << '\n';
2457 if (opts.find("scale") != opts.end()) {
2458 istringstream iss(opts["scale"]);
2462 os << "\tscale " << val << '\n';
2464 if (opts.find("angle") != opts.end()) {
2465 os << "\trotateAngle "
2466 << opts["angle"] << '\n';
2467 vector<string>::const_iterator a =
2468 find(keys.begin(), keys.end(), "angle");
2469 vector<string>::const_iterator s =
2470 find(keys.begin(), keys.end(), "width");
2471 if (s == keys.end())
2472 s = find(keys.begin(), keys.end(), "height");
2473 if (s == keys.end())
2474 s = find(keys.begin(), keys.end(), "scale");
2475 if (s != keys.end() && distance(s, a) > 0)
2476 os << "\tscaleBeforeRotation\n";
2478 if (opts.find("origin") != opts.end()) {
2480 string const opt = opts["origin"];
2481 if (opt.find('l') != string::npos) ss << "left";
2482 if (opt.find('r') != string::npos) ss << "right";
2483 if (opt.find('c') != string::npos) ss << "center";
2484 if (opt.find('t') != string::npos) ss << "Top";
2485 if (opt.find('b') != string::npos) ss << "Bottom";
2486 if (opt.find('B') != string::npos) ss << "Baseline";
2487 if (!ss.str().empty())
2488 os << "\trotateOrigin " << ss.str() << '\n';
2490 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2492 if (opts.find("keepaspectratio") != opts.end())
2493 os << "\tkeepAspectRatio\n";
2494 if (opts.find("clip") != opts.end())
2496 if (opts.find("draft") != opts.end())
2498 if (opts.find("bb") != opts.end())
2499 os << "\tBoundingBox "
2500 << opts["bb"] << '\n';
2501 int numberOfbbOptions = 0;
2502 if (opts.find("bbllx") != opts.end())
2503 numberOfbbOptions++;
2504 if (opts.find("bblly") != opts.end())
2505 numberOfbbOptions++;
2506 if (opts.find("bburx") != opts.end())
2507 numberOfbbOptions++;
2508 if (opts.find("bbury") != opts.end())
2509 numberOfbbOptions++;
2510 if (numberOfbbOptions == 4)
2511 os << "\tBoundingBox "
2512 << opts["bbllx"] << " " << opts["bblly"] << " "
2513 << opts["bburx"] << " " << opts["bbury"] << '\n';
2514 else if (numberOfbbOptions > 0)
2515 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2516 numberOfbbOptions = 0;
2517 if (opts.find("natwidth") != opts.end())
2518 numberOfbbOptions++;
2519 if (opts.find("natheight") != opts.end())
2520 numberOfbbOptions++;
2521 if (numberOfbbOptions == 2)
2522 os << "\tBoundingBox 0bp 0bp "
2523 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2524 else if (numberOfbbOptions > 0)
2525 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2526 ostringstream special;
2527 if (opts.find("hiresbb") != opts.end())
2528 special << "hiresbb,";
2529 if (opts.find("trim") != opts.end())
2531 if (opts.find("viewport") != opts.end())
2532 special << "viewport=" << opts["viewport"] << ',';
2533 if (opts.find("totalheight") != opts.end())
2534 special << "totalheight=" << opts["totalheight"] << ',';
2535 if (opts.find("type") != opts.end())
2536 special << "type=" << opts["type"] << ',';
2537 if (opts.find("ext") != opts.end())
2538 special << "ext=" << opts["ext"] << ',';
2539 if (opts.find("read") != opts.end())
2540 special << "read=" << opts["read"] << ',';
2541 if (opts.find("command") != opts.end())
2542 special << "command=" << opts["command"] << ',';
2543 string s_special = special.str();
2544 if (!s_special.empty()) {
2545 // We had special arguments. Remove the trailing ','.
2546 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2548 // TODO: Handle the unknown settings better.
2549 // Warn about invalid options.
2550 // Check whether some option was given twice.
2554 else if (t.cs() == "footnote" ||
2555 (t.cs() == "thanks" && context.layout->intitle)) {
2557 context.check_layout(os);
2558 begin_inset(os, "Foot\n");
2559 os << "status collapsed\n\n";
2560 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2564 else if (t.cs() == "marginpar") {
2566 context.check_layout(os);
2567 begin_inset(os, "Marginal\n");
2568 os << "status collapsed\n\n";
2569 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2573 else if (t.cs() == "ensuremath") {
2575 context.check_layout(os);
2576 string const s = p.verbatim_item();
2577 //FIXME: this never triggers in UTF8
2578 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2581 handle_ert(os, "\\ensuremath{" + s + "}",
2585 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2586 if (title_layout_found) {
2588 skip_spaces_braces(p);
2590 handle_ert(os, t.asInput(), context);
2593 else if (t.cs() == "tableofcontents") {
2594 context.check_layout(os);
2595 begin_command_inset(os, "toc", "tableofcontents");
2597 skip_spaces_braces(p);
2600 else if (t.cs() == "listoffigures") {
2601 context.check_layout(os);
2602 begin_inset(os, "FloatList figure\n");
2604 skip_spaces_braces(p);
2607 else if (t.cs() == "listoftables") {
2608 context.check_layout(os);
2609 begin_inset(os, "FloatList table\n");
2611 skip_spaces_braces(p);
2614 else if (t.cs() == "listof") {
2615 p.skip_spaces(true);
2616 string const name = p.get_token().cs();
2617 if (context.textclass.floats().typeExist(name)) {
2618 context.check_layout(os);
2619 begin_inset(os, "FloatList ");
2622 p.get_token(); // swallow second arg
2624 handle_ert(os, "\\listof{" + name + "}", context);
2627 else if (t.cs() == "textrm")
2628 parse_text_attributes(p, os, FLAG_ITEM, outer,
2629 context, "\\family",
2630 context.font.family, "roman");
2632 else if (t.cs() == "textsf")
2633 parse_text_attributes(p, os, FLAG_ITEM, outer,
2634 context, "\\family",
2635 context.font.family, "sans");
2637 else if (t.cs() == "texttt")
2638 parse_text_attributes(p, os, FLAG_ITEM, outer,
2639 context, "\\family",
2640 context.font.family, "typewriter");
2642 else if (t.cs() == "textmd")
2643 parse_text_attributes(p, os, FLAG_ITEM, outer,
2644 context, "\\series",
2645 context.font.series, "medium");
2647 else if (t.cs() == "textbf")
2648 parse_text_attributes(p, os, FLAG_ITEM, outer,
2649 context, "\\series",
2650 context.font.series, "bold");
2652 else if (t.cs() == "textup")
2653 parse_text_attributes(p, os, FLAG_ITEM, outer,
2655 context.font.shape, "up");
2657 else if (t.cs() == "textit")
2658 parse_text_attributes(p, os, FLAG_ITEM, outer,
2660 context.font.shape, "italic");
2662 else if (t.cs() == "textsl")
2663 parse_text_attributes(p, os, FLAG_ITEM, outer,
2665 context.font.shape, "slanted");
2667 else if (t.cs() == "textsc")
2668 parse_text_attributes(p, os, FLAG_ITEM, outer,
2670 context.font.shape, "smallcaps");
2672 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2673 context.check_layout(os);
2674 TeXFont oldFont = context.font;
2675 context.font.init();
2676 context.font.size = oldFont.size;
2677 os << "\n\\family " << context.font.family << "\n";
2678 os << "\n\\series " << context.font.series << "\n";
2679 os << "\n\\shape " << context.font.shape << "\n";
2680 if (t.cs() == "textnormal") {
2681 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2682 output_font_change(os, context.font, oldFont);
2683 context.font = oldFont;
2685 eat_whitespace(p, os, context, false);
2688 else if (t.cs() == "textcolor") {
2689 // scheme is \textcolor{color name}{text}
2690 string const color = p.verbatim_item();
2691 // we only support the predefined colors of the color package
2692 if (color == "black" || color == "blue" || color == "cyan"
2693 || color == "green" || color == "magenta" || color == "red"
2694 || color == "white" || color == "yellow") {
2695 context.check_layout(os);
2696 os << "\n\\color " << color << "\n";
2697 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2698 context.check_layout(os);
2699 os << "\n\\color inherit\n";
2700 preamble.registerAutomaticallyLoadedPackage("color");
2702 // for custom defined colors
2703 handle_ert(os, t.asInput() + "{" + color + "}", context);
2706 else if (t.cs() == "underbar" || t.cs() == "uline") {
2707 // \underbar is not 100% correct (LyX outputs \uline
2708 // of ulem.sty). The difference is that \ulem allows
2709 // line breaks, and \underbar does not.
2710 // Do NOT handle \underline.
2711 // \underbar cuts through y, g, q, p etc.,
2712 // \underline does not.
2713 context.check_layout(os);
2714 os << "\n\\bar under\n";
2715 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2716 context.check_layout(os);
2717 os << "\n\\bar default\n";
2718 preamble.registerAutomaticallyLoadedPackage("ulem");
2721 else if (t.cs() == "sout") {
2722 context.check_layout(os);
2723 os << "\n\\strikeout on\n";
2724 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2725 context.check_layout(os);
2726 os << "\n\\strikeout default\n";
2727 preamble.registerAutomaticallyLoadedPackage("ulem");
2730 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2731 t.cs() == "emph" || t.cs() == "noun") {
2732 context.check_layout(os);
2733 os << "\n\\" << t.cs() << " on\n";
2734 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2735 context.check_layout(os);
2736 os << "\n\\" << t.cs() << " default\n";
2737 if (t.cs() == "uuline" || t.cs() == "uwave")
2738 preamble.registerAutomaticallyLoadedPackage("ulem");
2741 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2742 context.check_layout(os);
2743 string name = p.getArg('{', '}');
2744 string localtime = p.getArg('{', '}');
2745 preamble.registerAuthor(name);
2746 Author const & author = preamble.getAuthor(name);
2747 // from_ctime() will fail if LyX decides to output the
2748 // time in the text language. It might also use a wrong
2749 // time zone (if the original LyX document was exported
2750 // with a different time zone).
2751 time_t ptime = from_ctime(localtime);
2752 if (ptime == static_cast<time_t>(-1)) {
2753 cerr << "Warning: Could not parse time `" << localtime
2754 << "´ for change tracking, using current time instead.\n";
2755 ptime = current_time();
2757 if (t.cs() == "lyxadded")
2758 os << "\n\\change_inserted ";
2760 os << "\n\\change_deleted ";
2761 os << author.bufferId() << ' ' << ptime << '\n';
2762 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2763 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2764 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2765 LaTeXPackages::isAvailable("xcolor");
2766 // No need to test for luatex, since luatex comes in
2767 // two flavours (dvi and pdf), like latex, and those
2768 // are detected by pdflatex.
2769 if (pdflatex || xetex) {
2771 preamble.registerAutomaticallyLoadedPackage("ulem");
2772 preamble.registerAutomaticallyLoadedPackage("xcolor");
2773 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2777 preamble.registerAutomaticallyLoadedPackage("dvipost");
2778 } else if (xcolorulem) {
2779 preamble.registerAutomaticallyLoadedPackage("ulem");
2780 preamble.registerAutomaticallyLoadedPackage("xcolor");
2785 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2786 t.cs() == "vphantom") {
2787 context.check_layout(os);
2788 if (t.cs() == "phantom")
2789 begin_inset(os, "Phantom Phantom\n");
2790 if (t.cs() == "hphantom")
2791 begin_inset(os, "Phantom HPhantom\n");
2792 if (t.cs() == "vphantom")
2793 begin_inset(os, "Phantom VPhantom\n");
2794 os << "status open\n";
2795 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2800 else if (t.cs() == "href") {
2801 context.check_layout(os);
2802 string target = p.getArg('{', '}');
2803 string name = p.getArg('{', '}');
2805 size_t i = target.find(':');
2806 if (i != string::npos) {
2807 type = target.substr(0, i + 1);
2808 if (type == "mailto:" || type == "file:")
2809 target = target.substr(i + 1);
2810 // handle the case that name is equal to target, except of "http://"
2811 else if (target.substr(i + 3) == name && type == "http:")
2814 begin_command_inset(os, "href", "href");
2816 os << "name \"" << name << "\"\n";
2817 os << "target \"" << target << "\"\n";
2818 if (type == "mailto:" || type == "file:")
2819 os << "type \"" << type << "\"\n";
2821 skip_spaces_braces(p);
2824 else if (t.cs() == "lyxline") {
2825 // swallow size argument (it is not used anyway)
2827 if (!context.atParagraphStart()) {
2828 // so our line is in the middle of a paragraph
2829 // we need to add a new line, lest this line
2830 // follow the other content on that line and
2831 // run off the side of the page
2832 // FIXME: This may create an empty paragraph,
2833 // but without that it would not be
2834 // possible to set noindent below.
2835 // Fortunately LaTeX does not care
2836 // about the empty paragraph.
2837 context.new_paragraph(os);
2839 if (preamble.indentParagraphs()) {
2840 // we need to unindent, lest the line be too long
2841 context.add_par_extra_stuff("\\noindent\n");
2843 context.check_layout(os);
2844 begin_command_inset(os, "line", "rule");
2845 os << "offset \"0.5ex\"\n"
2846 "width \"100line%\"\n"
2851 else if (t.cs() == "rule") {
2852 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2853 string const width = p.getArg('{', '}');
2854 string const thickness = p.getArg('{', '}');
2855 context.check_layout(os);
2856 begin_command_inset(os, "line", "rule");
2857 if (!offset.empty())
2858 os << "offset \"" << translate_len(offset) << "\"\n";
2859 os << "width \"" << translate_len(width) << "\"\n"
2860 "height \"" << translate_len(thickness) << "\"\n";
2864 else if (is_known(t.cs(), known_phrases) ||
2865 (t.cs() == "protect" &&
2866 p.next_token().cat() == catEscape &&
2867 is_known(p.next_token().cs(), known_phrases))) {
2868 // LyX sometimes puts a \protect in front, so we have to ignore it
2869 // FIXME: This needs to be changed when bug 4752 is fixed.
2870 char const * const * where = is_known(
2871 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2873 context.check_layout(os);
2874 os << known_coded_phrases[where - known_phrases];
2875 skip_spaces_braces(p);
2878 else if (is_known(t.cs(), known_ref_commands)) {
2879 string const opt = p.getOpt();
2881 context.check_layout(os);
2882 char const * const * where = is_known(t.cs(),
2883 known_ref_commands);
2884 begin_command_inset(os, "ref",
2885 known_coded_ref_commands[where - known_ref_commands]);
2886 os << "reference \""
2887 << convert_command_inset_arg(p.verbatim_item())
2891 // LyX does not support optional arguments of ref commands
2892 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2893 p.verbatim_item() + "}", context);
2897 else if (use_natbib &&
2898 is_known(t.cs(), known_natbib_commands) &&
2899 ((t.cs() != "citefullauthor" &&
2900 t.cs() != "citeyear" &&
2901 t.cs() != "citeyearpar") ||
2902 p.next_token().asInput() != "*")) {
2903 context.check_layout(os);
2904 string command = t.cs();
2905 if (p.next_token().asInput() == "*") {
2909 if (command == "citefullauthor")
2910 // alternative name for "\\citeauthor*"
2911 command = "citeauthor*";
2913 // text before the citation
2915 // text after the citation
2917 get_cite_arguments(p, true, before, after);
2919 if (command == "cite") {
2920 // \cite without optional argument means
2921 // \citet, \cite with at least one optional
2922 // argument means \citep.
2923 if (before.empty() && after.empty())
2928 if (before.empty() && after == "[]")
2929 // avoid \citet[]{a}
2931 else if (before == "[]" && after == "[]") {
2932 // avoid \citet[][]{a}
2936 // remove the brackets around after and before
2937 if (!after.empty()) {
2939 after.erase(after.length() - 1, 1);
2940 after = convert_command_inset_arg(after);
2942 if (!before.empty()) {
2944 before.erase(before.length() - 1, 1);
2945 before = convert_command_inset_arg(before);
2947 begin_command_inset(os, "citation", command);
2948 os << "after " << '"' << after << '"' << "\n";
2949 os << "before " << '"' << before << '"' << "\n";
2951 << convert_command_inset_arg(p.verbatim_item())
2956 else if (use_jurabib &&
2957 is_known(t.cs(), known_jurabib_commands) &&
2958 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2959 context.check_layout(os);
2960 string command = t.cs();
2961 if (p.next_token().asInput() == "*") {
2965 char argumentOrder = '\0';
2966 vector<string> const options =
2967 preamble.getPackageOptions("jurabib");
2968 if (find(options.begin(), options.end(),
2969 "natbiborder") != options.end())
2970 argumentOrder = 'n';
2971 else if (find(options.begin(), options.end(),
2972 "jurabiborder") != options.end())
2973 argumentOrder = 'j';
2975 // text before the citation
2977 // text after the citation
2979 get_cite_arguments(p, argumentOrder != 'j', before, after);
2981 string const citation = p.verbatim_item();
2982 if (!before.empty() && argumentOrder == '\0') {
2983 cerr << "Warning: Assuming argument order "
2984 "of jurabib version 0.6 for\n'"
2985 << command << before << after << '{'
2986 << citation << "}'.\n"
2987 "Add 'jurabiborder' to the jurabib "
2988 "package options if you used an\n"
2989 "earlier jurabib version." << endl;
2991 if (!after.empty()) {
2993 after.erase(after.length() - 1, 1);
2995 if (!before.empty()) {
2997 before.erase(before.length() - 1, 1);
2999 begin_command_inset(os, "citation", command);
3000 os << "after " << '"' << after << '"' << "\n";
3001 os << "before " << '"' << before << '"' << "\n";
3002 os << "key " << '"' << citation << '"' << "\n";
3006 else if (t.cs() == "cite"
3007 || t.cs() == "nocite") {
3008 context.check_layout(os);
3009 string after = convert_command_inset_arg(p.getArg('[', ']'));
3010 string key = convert_command_inset_arg(p.verbatim_item());
3011 // store the case that it is "\nocite{*}" to use it later for
3014 begin_command_inset(os, "citation", t.cs());
3015 os << "after " << '"' << after << '"' << "\n";
3016 os << "key " << '"' << key << '"' << "\n";
3018 } else if (t.cs() == "nocite")
3022 else if (t.cs() == "index") {
3023 context.check_layout(os);
3024 begin_inset(os, "Index idx\n");
3025 os << "status collapsed\n";
3026 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3030 else if (t.cs() == "nomenclature") {
3031 context.check_layout(os);
3032 begin_command_inset(os, "nomenclature", "nomenclature");
3033 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3034 if (!prefix.empty())
3035 os << "prefix " << '"' << prefix << '"' << "\n";
3036 os << "symbol " << '"'
3037 << convert_command_inset_arg(p.verbatim_item());
3038 os << "\"\ndescription \""
3039 << convert_command_inset_arg(p.verbatim_item())
3044 else if (t.cs() == "label") {
3045 context.check_layout(os);
3046 begin_command_inset(os, "label", "label");
3048 << convert_command_inset_arg(p.verbatim_item())
3053 else if (t.cs() == "printindex") {
3054 context.check_layout(os);
3055 begin_command_inset(os, "index_print", "printindex");
3056 os << "type \"idx\"\n";
3058 skip_spaces_braces(p);
3061 else if (t.cs() == "printnomenclature") {
3063 string width_type = "";
3064 context.check_layout(os);
3065 begin_command_inset(os, "nomencl_print", "printnomenclature");
3066 // case of a custom width
3068 width = p.getArg('[', ']');
3069 width = translate_len(width);
3070 width_type = "custom";
3072 // case of no custom width
3073 // the case of no custom width but the width set
3074 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3075 // because the user could have set anything, not only the width
3076 // of the longest label (which would be width_type = "auto")
3077 string label = convert_command_inset_arg(p.getArg('{', '}'));
3078 if (label.empty() && width_type.empty())
3079 width_type = "none";
3080 os << "set_width \"" << width_type << "\"\n";
3081 if (width_type == "custom")
3082 os << "width \"" << width << '\"';
3084 skip_spaces_braces(p);
3087 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3088 context.check_layout(os);
3089 begin_inset(os, "script ");
3090 os << t.cs().substr(4) << '\n';
3091 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3093 if (t.cs() == "textsubscript")
3094 preamble.registerAutomaticallyLoadedPackage("subscript");
3097 else if (is_known(t.cs(), known_quotes)) {
3098 char const * const * where = is_known(t.cs(), known_quotes);
3099 context.check_layout(os);
3100 begin_inset(os, "Quotes ");
3101 os << known_coded_quotes[where - known_quotes];
3103 // LyX adds {} after the quote, so we have to eat
3104 // spaces here if there are any before a possible
3106 eat_whitespace(p, os, context, false);
3110 else if (is_known(t.cs(), known_sizes) &&
3111 context.new_layout_allowed) {
3112 char const * const * where = is_known(t.cs(), known_sizes);
3113 context.check_layout(os);
3114 TeXFont const oldFont = context.font;
3115 context.font.size = known_coded_sizes[where - known_sizes];
3116 output_font_change(os, oldFont, context.font);
3117 eat_whitespace(p, os, context, false);
3120 else if (is_known(t.cs(), known_font_families) &&
3121 context.new_layout_allowed) {
3122 char const * const * where =
3123 is_known(t.cs(), known_font_families);
3124 context.check_layout(os);
3125 TeXFont const oldFont = context.font;
3126 context.font.family =
3127 known_coded_font_families[where - known_font_families];
3128 output_font_change(os, oldFont, context.font);
3129 eat_whitespace(p, os, context, false);
3132 else if (is_known(t.cs(), known_font_series) &&
3133 context.new_layout_allowed) {
3134 char const * const * where =
3135 is_known(t.cs(), known_font_series);
3136 context.check_layout(os);
3137 TeXFont const oldFont = context.font;
3138 context.font.series =
3139 known_coded_font_series[where - known_font_series];
3140 output_font_change(os, oldFont, context.font);
3141 eat_whitespace(p, os, context, false);
3144 else if (is_known(t.cs(), known_font_shapes) &&
3145 context.new_layout_allowed) {
3146 char const * const * where =
3147 is_known(t.cs(), known_font_shapes);
3148 context.check_layout(os);
3149 TeXFont const oldFont = context.font;
3150 context.font.shape =
3151 known_coded_font_shapes[where - known_font_shapes];
3152 output_font_change(os, oldFont, context.font);
3153 eat_whitespace(p, os, context, false);
3155 else if (is_known(t.cs(), known_old_font_families) &&
3156 context.new_layout_allowed) {
3157 char const * const * where =
3158 is_known(t.cs(), known_old_font_families);
3159 context.check_layout(os);
3160 TeXFont const oldFont = context.font;
3161 context.font.init();
3162 context.font.size = oldFont.size;
3163 context.font.family =
3164 known_coded_font_families[where - known_old_font_families];
3165 output_font_change(os, oldFont, context.font);
3166 eat_whitespace(p, os, context, false);
3169 else if (is_known(t.cs(), known_old_font_series) &&
3170 context.new_layout_allowed) {
3171 char const * const * where =
3172 is_known(t.cs(), known_old_font_series);
3173 context.check_layout(os);
3174 TeXFont const oldFont = context.font;
3175 context.font.init();
3176 context.font.size = oldFont.size;
3177 context.font.series =
3178 known_coded_font_series[where - known_old_font_series];
3179 output_font_change(os, oldFont, context.font);
3180 eat_whitespace(p, os, context, false);
3183 else if (is_known(t.cs(), known_old_font_shapes) &&
3184 context.new_layout_allowed) {
3185 char const * const * where =
3186 is_known(t.cs(), known_old_font_shapes);
3187 context.check_layout(os);
3188 TeXFont const oldFont = context.font;
3189 context.font.init();
3190 context.font.size = oldFont.size;
3191 context.font.shape =
3192 known_coded_font_shapes[where - known_old_font_shapes];
3193 output_font_change(os, oldFont, context.font);
3194 eat_whitespace(p, os, context, false);
3197 else if (t.cs() == "selectlanguage") {
3198 context.check_layout(os);
3199 // save the language for the case that a
3200 // \foreignlanguage is used
3202 context.font.language = babel2lyx(p.verbatim_item());
3203 os << "\n\\lang " << context.font.language << "\n";
3206 else if (t.cs() == "foreignlanguage") {
3207 string const lang = babel2lyx(p.verbatim_item());
3208 parse_text_attributes(p, os, FLAG_ITEM, outer,
3210 context.font.language, lang);
3213 else if (t.cs() == "inputencoding") {
3214 // nothing to write here
3215 string const enc = subst(p.verbatim_item(), "\n", " ");
3219 else if (t.cs() == "ldots") {
3220 context.check_layout(os);
3221 os << "\\SpecialChar \\ldots{}\n";
3222 skip_spaces_braces(p);
3225 else if (t.cs() == "lyxarrow") {
3226 context.check_layout(os);
3227 os << "\\SpecialChar \\menuseparator\n";
3228 skip_spaces_braces(p);
3231 else if (t.cs() == "textcompwordmark") {
3232 context.check_layout(os);
3233 os << "\\SpecialChar \\textcompwordmark{}\n";
3234 skip_spaces_braces(p);
3237 else if (t.cs() == "slash") {
3238 context.check_layout(os);
3239 os << "\\SpecialChar \\slash{}\n";
3240 skip_spaces_braces(p);
3243 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3244 context.check_layout(os);
3245 os << "\\SpecialChar \\nobreakdash-\n";
3249 else if (t.cs() == "textquotedbl") {
3250 context.check_layout(os);
3255 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3256 context.check_layout(os);
3257 os << "\\SpecialChar \\@.\n";
3261 else if (t.cs() == "-") {
3262 context.check_layout(os);
3263 os << "\\SpecialChar \\-\n";
3266 else if (t.cs() == "textasciitilde") {
3267 context.check_layout(os);
3269 skip_spaces_braces(p);
3272 else if (t.cs() == "textasciicircum") {
3273 context.check_layout(os);
3275 skip_spaces_braces(p);
3278 else if (t.cs() == "textbackslash") {
3279 context.check_layout(os);
3280 os << "\n\\backslash\n";
3281 skip_spaces_braces(p);
3284 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3285 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3287 context.check_layout(os);
3291 else if (t.cs() == "char") {
3292 context.check_layout(os);
3293 if (p.next_token().character() == '`') {
3295 if (p.next_token().cs() == "\"") {
3300 handle_ert(os, "\\char`", context);
3303 handle_ert(os, "\\char", context);
3307 else if (t.cs() == "verb") {
3308 context.check_layout(os);
3309 char const delimiter = p.next_token().character();
3310 string const arg = p.getArg(delimiter, delimiter);
3312 oss << "\\verb" << delimiter << arg << delimiter;
3313 handle_ert(os, oss.str(), context);
3316 // Problem: \= creates a tabstop inside the tabbing environment
3317 // and else an accent. In the latter case we really would want
3318 // \={o} instead of \= o.
3319 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3320 handle_ert(os, t.asInput(), context);
3322 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3323 else if (t.cs().size() == 1
3324 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3325 context.check_layout(os);
3326 // try to see whether the string is in unicodesymbols
3328 string command = t.asInput() + "{"
3329 + trimSpaceAndEol(p.verbatim_item())
3331 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3334 cerr << "When parsing " << command
3335 << ", result is " << to_utf8(s)
3336 << "+" << to_utf8(rem) << endl;
3339 // we did not find a non-ert version
3340 handle_ert(os, command, context);
3343 else if (t.cs() == "\\") {
3344 context.check_layout(os);
3346 handle_ert(os, "\\\\" + p.getOpt(), context);
3347 else if (p.next_token().asInput() == "*") {
3349 // getOpt() eats the following space if there
3350 // is no optional argument, but that is OK
3351 // here since it has no effect in the output.
3352 handle_ert(os, "\\\\*" + p.getOpt(), context);
3355 begin_inset(os, "Newline newline");
3360 else if (t.cs() == "newline" ||
3361 (t.cs() == "linebreak" && !p.hasOpt())) {
3362 context.check_layout(os);
3363 begin_inset(os, "Newline ");
3366 skip_spaces_braces(p);
3369 else if (t.cs() == "input" || t.cs() == "include"
3370 || t.cs() == "verbatiminput") {
3371 string name = t.cs();
3372 if (t.cs() == "verbatiminput"
3373 && p.next_token().asInput() == "*")
3374 name += p.get_token().asInput();
3375 context.check_layout(os);
3376 string filename(normalize_filename(p.getArg('{', '}')));
3377 string const path = getMasterFilePath();
3378 // We want to preserve relative / absolute filenames,
3379 // therefore path is only used for testing
3380 if ((t.cs() == "include" || t.cs() == "input") &&
3381 !makeAbsPath(filename, path).exists()) {
3382 // The file extension is probably missing.
3383 // Now try to find it out.
3384 string const tex_name =
3385 find_file(filename, path,
3386 known_tex_extensions);
3387 if (!tex_name.empty())
3388 filename = tex_name;
3390 bool external = false;
3392 if (makeAbsPath(filename, path).exists()) {
3393 string const abstexname =
3394 makeAbsPath(filename, path).absFileName();
3395 string const abslyxname =
3396 changeExtension(abstexname, ".lyx");
3397 string const absfigname =
3398 changeExtension(abstexname, ".fig");
3399 fix_relative_filename(filename);
3400 string const lyxname =
3401 changeExtension(filename, ".lyx");
3403 external = FileName(absfigname).exists();
3404 if (t.cs() == "input") {
3405 string const ext = getExtension(abstexname);
3407 // Combined PS/LaTeX:
3408 // x.eps, x.pstex_t (old xfig)
3409 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3410 FileName const absepsname(
3411 changeExtension(abstexname, ".eps"));
3412 FileName const abspstexname(
3413 changeExtension(abstexname, ".pstex"));
3414 bool const xfigeps =
3415 (absepsname.exists() ||
3416 abspstexname.exists()) &&
3419 // Combined PDF/LaTeX:
3420 // x.pdf, x.pdftex_t (old xfig)
3421 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3422 FileName const abspdfname(
3423 changeExtension(abstexname, ".pdf"));
3424 bool const xfigpdf =
3425 abspdfname.exists() &&
3426 (ext == "pdftex_t" || ext == "pdf_t");
3430 // Combined PS/PDF/LaTeX:
3431 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3432 string const absbase2(
3433 removeExtension(abstexname) + "_pspdftex");
3434 FileName const abseps2name(
3435 addExtension(absbase2, ".eps"));
3436 FileName const abspdf2name(
3437 addExtension(absbase2, ".pdf"));
3438 bool const xfigboth =
3439 abspdf2name.exists() &&
3440 abseps2name.exists() && ext == "pspdftex";
3442 xfig = xfigpdf || xfigeps || xfigboth;
3443 external = external && xfig;
3446 outname = changeExtension(filename, ".fig");
3448 // Don't try to convert, the result
3449 // would be full of ERT.
3451 } else if (t.cs() != "verbatiminput" &&
3452 tex2lyx(abstexname, FileName(abslyxname),
3459 cerr << "Warning: Could not find included file '"
3460 << filename << "'." << endl;
3464 begin_inset(os, "External\n");
3465 os << "\ttemplate XFig\n"
3466 << "\tfilename " << outname << '\n';
3468 begin_command_inset(os, "include", name);
3469 os << "preview false\n"
3470 "filename \"" << outname << "\"\n";
3475 else if (t.cs() == "bibliographystyle") {
3476 // store new bibliographystyle
3477 bibliographystyle = p.verbatim_item();
3478 // If any other command than \bibliography and
3479 // \nocite{*} follows, we need to output the style
3480 // (because it might be used by that command).
3481 // Otherwise, it will automatically be output by LyX.
3484 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3485 if (t2.cat() == catBegin)
3487 if (t2.cat() != catEscape)
3489 if (t2.cs() == "nocite") {
3490 if (p.getArg('{', '}') == "*")
3492 } else if (t2.cs() == "bibliography")
3499 "\\bibliographystyle{" + bibliographystyle + '}',
3504 else if (t.cs() == "bibliography") {
3505 context.check_layout(os);
3506 begin_command_inset(os, "bibtex", "bibtex");
3507 if (!btprint.empty()) {
3508 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3509 // clear the string because the next BibTeX inset can be without the
3510 // \nocite{*} option
3513 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3514 // Do we have a bibliographystyle set?
3515 if (!bibliographystyle.empty())
3516 os << "options " << '"' << bibliographystyle << '"' << "\n";
3520 else if (t.cs() == "parbox") {
3521 // Test whether this is an outer box of a shaded box
3523 // swallow arguments
3524 while (p.hasOpt()) {
3526 p.skip_spaces(true);
3529 p.skip_spaces(true);
3531 if (p.next_token().cat() == catBegin)
3533 p.skip_spaces(true);
3534 Token to = p.get_token();
3535 bool shaded = false;
3536 if (to.asInput() == "\\begin") {
3537 p.skip_spaces(true);
3538 if (p.getArg('{', '}') == "shaded")
3543 parse_outer_box(p, os, FLAG_ITEM, outer,
3544 context, "parbox", "shaded");
3546 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3550 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3551 t.cs() == "shadowbox" || t.cs() == "doublebox")
3552 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3554 else if (t.cs() == "framebox") {
3555 string special = p.getFullOpt();
3556 special += p.getOpt();
3557 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3560 //\makebox() is part of the picture environment and different from \makebox{}
3561 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3562 else if (t.cs() == "makebox") {
3563 string arg = t.asInput();
3564 if (p.next_token().character() == '(') {
3565 //the syntax is: \makebox(x,y)[position]{content}
3566 arg += p.getFullParentheseArg();
3567 arg += p.getFullOpt();
3568 handle_ert(os, arg + p.get_token().asInput(), context);
3570 //the syntax is: \makebox[width][position]{content}
3571 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3575 else if (t.cs() == "smallskip" ||
3576 t.cs() == "medskip" ||
3577 t.cs() == "bigskip" ||
3578 t.cs() == "vfill") {
3579 context.check_layout(os);
3580 begin_inset(os, "VSpace ");
3583 skip_spaces_braces(p);
3586 else if (is_known(t.cs(), known_spaces)) {
3587 char const * const * where = is_known(t.cs(), known_spaces);
3588 context.check_layout(os);
3589 begin_inset(os, "space ");
3590 os << '\\' << known_coded_spaces[where - known_spaces]
3593 // LaTeX swallows whitespace after all spaces except
3594 // "\\,". We have to do that here, too, because LyX
3595 // adds "{}" which would make the spaces significant.
3597 eat_whitespace(p, os, context, false);
3598 // LyX adds "{}" after all spaces except "\\ " and
3599 // "\\,", so we have to remove "{}".
3600 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3601 // remove the braces after "\\,", too.
3606 else if (t.cs() == "newpage" ||
3607 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3608 t.cs() == "clearpage" ||
3609 t.cs() == "cleardoublepage") {
3610 context.check_layout(os);
3611 begin_inset(os, "Newpage ");
3614 skip_spaces_braces(p);
3617 else if (t.cs() == "DeclareRobustCommand" ||
3618 t.cs() == "DeclareRobustCommandx" ||
3619 t.cs() == "newcommand" ||
3620 t.cs() == "newcommandx" ||
3621 t.cs() == "providecommand" ||
3622 t.cs() == "providecommandx" ||
3623 t.cs() == "renewcommand" ||
3624 t.cs() == "renewcommandx") {
3625 // DeclareRobustCommand, DeclareRobustCommandx,
3626 // providecommand and providecommandx could be handled
3627 // by parse_command(), but we need to call
3628 // add_known_command() here.
3629 string name = t.asInput();
3630 if (p.next_token().asInput() == "*") {
3631 // Starred form. Eat '*'
3635 string const command = p.verbatim_item();
3636 string const opt1 = p.getFullOpt();
3637 string const opt2 = p.getFullOpt();
3638 add_known_command(command, opt1, !opt2.empty());
3639 string const ert = name + '{' + command + '}' +
3641 '{' + p.verbatim_item() + '}';
3643 if (t.cs() == "DeclareRobustCommand" ||
3644 t.cs() == "DeclareRobustCommandx" ||
3645 t.cs() == "providecommand" ||
3646 t.cs() == "providecommandx" ||
3647 name[name.length()-1] == '*')
3648 handle_ert(os, ert, context);
3650 context.check_layout(os);
3651 begin_inset(os, "FormulaMacro");
3657 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3658 // let could be handled by parse_command(),
3659 // but we need to call add_known_command() here.
3660 string ert = t.asInput();
3663 if (p.next_token().cat() == catBegin) {
3664 name = p.verbatim_item();
3665 ert += '{' + name + '}';
3667 name = p.verbatim_item();
3672 if (p.next_token().cat() == catBegin) {
3673 command = p.verbatim_item();
3674 ert += '{' + command + '}';
3676 command = p.verbatim_item();
3679 // If command is known, make name known too, to parse
3680 // its arguments correctly. For this reason we also
3681 // have commands in syntax.default that are hardcoded.
3682 CommandMap::iterator it = known_commands.find(command);
3683 if (it != known_commands.end())
3684 known_commands[t.asInput()] = it->second;
3685 handle_ert(os, ert, context);
3688 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3689 bool starred = false;
3690 if (p.next_token().asInput() == "*") {
3694 string name = t.asInput();
3695 string const length = p.verbatim_item();
3698 bool valid = splitLatexLength(length, valstring, unit);
3699 bool known_hspace = false;
3700 bool known_vspace = false;
3701 bool known_unit = false;
3704 istringstream iss(valstring);
3707 if (t.cs()[0] == 'h') {
3708 if (unit == "\\fill") {
3713 known_hspace = true;
3716 if (unit == "\\smallskipamount") {
3718 known_vspace = true;
3719 } else if (unit == "\\medskipamount") {
3721 known_vspace = true;
3722 } else if (unit == "\\bigskipamount") {
3724 known_vspace = true;
3725 } else if (unit == "\\fill") {
3727 known_vspace = true;
3731 if (!known_hspace && !known_vspace) {
3732 switch (unitFromString(unit)) {
3753 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3754 // Literal horizontal length or known variable
3755 context.check_layout(os);
3756 begin_inset(os, "space ");
3764 if (known_unit && !known_hspace)
3766 << translate_len(length);
3768 } else if (known_unit || known_vspace) {
3769 // Literal vertical length or known variable
3770 context.check_layout(os);
3771 begin_inset(os, "VSpace ");
3779 // LyX can't handle other length variables in Inset VSpace/space
3784 handle_ert(os, name + '{' + unit + '}', context);
3785 else if (value == -1.0)
3786 handle_ert(os, name + "{-" + unit + '}', context);
3788 handle_ert(os, name + '{' + valstring + unit + '}', context);
3790 handle_ert(os, name + '{' + length + '}', context);
3794 // The single '=' is meant here.
3795 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3797 context.check_layout(os);
3798 begin_inset(os, "Flex ");
3799 os << to_utf8(newinsetlayout->name()) << '\n'
3800 << "status collapsed\n";
3801 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3806 // try to see whether the string is in unicodesymbols
3807 // Only use text mode commands, since we are in text mode here,
3808 // and math commands may be invalid (bug 6797)
3810 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3811 rem, Encodings::TEXT_CMD);
3814 cerr << "When parsing " << t.cs()
3815 << ", result is " << to_utf8(s)
3816 << "+" << to_utf8(rem) << endl;
3817 context.check_layout(os);
3819 skip_spaces_braces(p);
3821 //cerr << "#: " << t << " mode: " << mode << endl;
3822 // heuristic: read up to next non-nested space
3824 string s = t.asInput();
3825 string z = p.verbatim_item();
3826 while (p.good() && z != " " && z.size()) {
3827 //cerr << "read: " << z << endl;
3829 z = p.verbatim_item();
3831 cerr << "found ERT: " << s << endl;
3832 handle_ert(os, s + ' ', context);
3835 string name = t.asInput();
3836 if (p.next_token().asInput() == "*") {
3837 // Starred commands like \vspace*{}
3838 p.get_token(); // Eat '*'
3841 if (!parse_command(name, p, os, outer, context))
3842 handle_ert(os, name, context);
3846 if (flags & FLAG_LEAVE) {
3847 flags &= ~FLAG_LEAVE;