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 (name == "tabular" || name == "longtable") {
1156 eat_whitespace(p, os, parent_context, false);
1157 parent_context.check_layout(os);
1158 begin_inset(os, "Tabular ");
1159 handle_tabular(p, os, name == "longtable", parent_context);
1164 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1165 eat_whitespace(p, os, parent_context, false);
1166 parent_context.check_layout(os);
1167 begin_inset(os, "Float " + unstarred_name + "\n");
1168 // store the float type for subfloats
1169 // subfloats only work with figures and tables
1170 if (unstarred_name == "figure")
1171 float_type = unstarred_name;
1172 else if (unstarred_name == "table")
1173 float_type = unstarred_name;
1177 os << "placement " << p.getArg('[', ']') << '\n';
1178 os << "wide " << convert<string>(is_starred)
1179 << "\nsideways false"
1180 << "\nstatus open\n\n";
1181 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1183 // We don't need really a new paragraph, but
1184 // we must make sure that the next item gets a \begin_layout.
1185 parent_context.new_paragraph(os);
1187 // the float is parsed thus delete the type
1191 else if (unstarred_name == "sidewaysfigure"
1192 || unstarred_name == "sidewaystable") {
1193 eat_whitespace(p, os, parent_context, false);
1194 parent_context.check_layout(os);
1195 if (unstarred_name == "sidewaysfigure")
1196 begin_inset(os, "Float figure\n");
1198 begin_inset(os, "Float table\n");
1199 os << "wide " << convert<string>(is_starred)
1200 << "\nsideways true"
1201 << "\nstatus open\n\n";
1202 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1204 // We don't need really a new paragraph, but
1205 // we must make sure that the next item gets a \begin_layout.
1206 parent_context.new_paragraph(os);
1210 else if (name == "wrapfigure" || name == "wraptable") {
1211 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1212 eat_whitespace(p, os, parent_context, false);
1213 parent_context.check_layout(os);
1216 string overhang = "0col%";
1219 lines = p.getArg('[', ']');
1220 string const placement = p.getArg('{', '}');
1222 overhang = p.getArg('[', ']');
1223 string const width = p.getArg('{', '}');
1225 if (name == "wrapfigure")
1226 begin_inset(os, "Wrap figure\n");
1228 begin_inset(os, "Wrap table\n");
1229 os << "lines " << lines
1230 << "\nplacement " << placement
1231 << "\noverhang " << lyx::translate_len(overhang)
1232 << "\nwidth " << lyx::translate_len(width)
1233 << "\nstatus open\n\n";
1234 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1236 // We don't need really a new paragraph, but
1237 // we must make sure that the next item gets a \begin_layout.
1238 parent_context.new_paragraph(os);
1242 else if (name == "minipage") {
1243 eat_whitespace(p, os, parent_context, false);
1244 // Test whether this is an outer box of a shaded box
1246 // swallow arguments
1247 while (p.hasOpt()) {
1249 p.skip_spaces(true);
1252 p.skip_spaces(true);
1253 Token t = p.get_token();
1254 bool shaded = false;
1255 if (t.asInput() == "\\begin") {
1256 p.skip_spaces(true);
1257 if (p.getArg('{', '}') == "shaded")
1262 parse_outer_box(p, os, FLAG_END, outer,
1263 parent_context, name, "shaded");
1265 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1270 else if (name == "comment") {
1271 eat_whitespace(p, os, parent_context, false);
1272 parent_context.check_layout(os);
1273 begin_inset(os, "Note Comment\n");
1274 os << "status open\n";
1275 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1278 skip_braces(p); // eat {} that might by set by LyX behind comments
1281 else if (name == "lyxgreyedout") {
1282 eat_whitespace(p, os, parent_context, false);
1283 parent_context.check_layout(os);
1284 begin_inset(os, "Note Greyedout\n");
1285 os << "status open\n";
1286 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1289 if (!preamble.notefontcolor().empty())
1290 preamble.registerAutomaticallyLoadedPackage("color");
1293 else if (name == "framed" || name == "shaded") {
1294 eat_whitespace(p, os, parent_context, false);
1295 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1299 else if (name == "lstlisting") {
1300 eat_whitespace(p, os, parent_context, false);
1301 // FIXME handle listings with parameters
1302 // If this is added, don't forgot to handle the
1303 // automatic color package loading
1305 parse_unknown_environment(p, name, os, FLAG_END,
1306 outer, parent_context);
1308 parse_listings(p, os, parent_context);
1312 else if (!parent_context.new_layout_allowed)
1313 parse_unknown_environment(p, name, os, FLAG_END, outer,
1316 // Alignment and spacing settings
1317 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1318 // therefore are totally broken!
1319 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1320 // they are commands not environments. They are furthermore switches that
1321 // can be ended by another switches, but also by commands like \footnote or
1322 // \parbox. So the only safe way is to leave them untouched.
1323 else if (name == "center" || name == "centering" ||
1324 name == "flushleft" || name == "flushright" ||
1325 name == "singlespace" || name == "onehalfspace" ||
1326 name == "doublespace" || name == "spacing") {
1327 eat_whitespace(p, os, parent_context, false);
1328 // We must begin a new paragraph if not already done
1329 if (! parent_context.atParagraphStart()) {
1330 parent_context.check_end_layout(os);
1331 parent_context.new_paragraph(os);
1333 if (name == "flushleft")
1334 parent_context.add_extra_stuff("\\align left\n");
1335 else if (name == "flushright")
1336 parent_context.add_extra_stuff("\\align right\n");
1337 else if (name == "center" || name == "centering")
1338 parent_context.add_extra_stuff("\\align center\n");
1339 else if (name == "singlespace")
1340 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1341 else if (name == "onehalfspace")
1342 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1343 else if (name == "doublespace")
1344 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1345 else if (name == "spacing")
1346 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1347 parse_text(p, os, FLAG_END, outer, parent_context);
1348 // Just in case the environment is empty
1349 parent_context.extra_stuff.erase();
1350 // We must begin a new paragraph to reset the alignment
1351 parent_context.new_paragraph(os);
1355 // The single '=' is meant here.
1356 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1357 eat_whitespace(p, os, parent_context, false);
1358 Context context(true, parent_context.textclass, newlayout,
1359 parent_context.layout, parent_context.font);
1360 if (parent_context.deeper_paragraph) {
1361 // We are beginning a nested environment after a
1362 // deeper paragraph inside the outer list environment.
1363 // Therefore we don't need to output a "begin deeper".
1364 context.need_end_deeper = true;
1366 parent_context.check_end_layout(os);
1367 if (last_env == name) {
1368 // we need to output a separator since LyX would export
1369 // the two environments as one otherwise (bug 5716)
1370 docstring const sep = from_ascii("--Separator--");
1371 TeX2LyXDocClass const & textclass(parent_context.textclass);
1372 if (textclass.hasLayout(sep)) {
1373 Context newcontext(parent_context);
1374 newcontext.layout = &(textclass[sep]);
1375 newcontext.check_layout(os);
1376 newcontext.check_end_layout(os);
1378 parent_context.check_layout(os);
1379 begin_inset(os, "Note Note\n");
1380 os << "status closed\n";
1381 Context newcontext(true, textclass,
1382 &(textclass.defaultLayout()));
1383 newcontext.check_layout(os);
1384 newcontext.check_end_layout(os);
1386 parent_context.check_end_layout(os);
1389 switch (context.layout->latextype) {
1390 case LATEX_LIST_ENVIRONMENT:
1391 context.add_par_extra_stuff("\\labelwidthstring "
1392 + p.verbatim_item() + '\n');
1395 case LATEX_BIB_ENVIRONMENT:
1396 p.verbatim_item(); // swallow next arg
1402 context.check_deeper(os);
1403 // handle known optional and required arguments
1404 // layouts require all optional arguments before the required ones
1405 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1406 // It is impossible to place anything after the environment name,
1407 // but before the first \\item.
1408 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1409 bool need_layout = true;
1410 unsigned int optargs = 0;
1411 while (optargs < context.layout->optargs) {
1412 eat_whitespace(p, os, context, false);
1413 if (p.next_token().cat() == catEscape ||
1414 p.next_token().character() != '[')
1416 p.get_token(); // eat '['
1418 context.check_layout(os);
1419 need_layout = false;
1421 begin_inset(os, "Argument\n");
1422 os << "status collapsed\n\n";
1423 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1425 eat_whitespace(p, os, context, false);
1428 unsigned int reqargs = 0;
1429 while (reqargs < context.layout->reqargs) {
1430 eat_whitespace(p, os, context, false);
1431 if (p.next_token().cat() != catBegin)
1433 p.get_token(); // eat '{'
1435 context.check_layout(os);
1436 need_layout = false;
1438 begin_inset(os, "Argument\n");
1439 os << "status collapsed\n\n";
1440 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1442 eat_whitespace(p, os, context, false);
1446 parse_text(p, os, FLAG_END, outer, context);
1447 context.check_end_layout(os);
1448 if (parent_context.deeper_paragraph) {
1449 // We must suppress the "end deeper" because we
1450 // suppressed the "begin deeper" above.
1451 context.need_end_deeper = false;
1453 context.check_end_deeper(os);
1454 parent_context.new_paragraph(os);
1456 if (!title_layout_found)
1457 title_layout_found = newlayout->intitle;
1460 // The single '=' is meant here.
1461 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1462 eat_whitespace(p, os, parent_context, false);
1463 parent_context.check_layout(os);
1464 begin_inset(os, "Flex ");
1465 os << to_utf8(newinsetlayout->name()) << '\n'
1466 << "status collapsed\n";
1467 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1471 else if (name == "appendix") {
1472 // This is no good latex style, but it works and is used in some documents...
1473 eat_whitespace(p, os, parent_context, false);
1474 parent_context.check_end_layout(os);
1475 Context context(true, parent_context.textclass, parent_context.layout,
1476 parent_context.layout, parent_context.font);
1477 context.check_layout(os);
1478 os << "\\start_of_appendix\n";
1479 parse_text(p, os, FLAG_END, outer, context);
1480 context.check_end_layout(os);
1484 else if (known_environments.find(name) != known_environments.end()) {
1485 vector<ArgumentType> arguments = known_environments[name];
1486 // The last "argument" denotes wether we may translate the
1487 // environment contents to LyX
1488 // The default required if no argument is given makes us
1489 // compatible with the reLyXre environment.
1490 ArgumentType contents = arguments.empty() ?
1493 if (!arguments.empty())
1494 arguments.pop_back();
1495 // See comment in parse_unknown_environment()
1496 bool const specialfont =
1497 (parent_context.font != parent_context.normalfont);
1498 bool const new_layout_allowed =
1499 parent_context.new_layout_allowed;
1501 parent_context.new_layout_allowed = false;
1502 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1503 outer, parent_context);
1504 if (contents == verbatim)
1505 handle_ert(os, p.verbatimEnvironment(name),
1508 parse_text_snippet(p, os, FLAG_END, outer,
1510 handle_ert(os, "\\end{" + name + "}", parent_context);
1512 parent_context.new_layout_allowed = new_layout_allowed;
1516 parse_unknown_environment(p, name, os, FLAG_END, outer,
1520 active_environments.pop_back();
1524 /// parses a comment and outputs it to \p os.
1525 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1527 LASSERT(t.cat() == catComment, return);
1528 if (!t.cs().empty()) {
1529 context.check_layout(os);
1530 handle_comment(os, '%' + t.cs(), context);
1531 if (p.next_token().cat() == catNewline) {
1532 // A newline after a comment line starts a new
1534 if (context.new_layout_allowed) {
1535 if(!context.atParagraphStart())
1536 // Only start a new paragraph if not already
1537 // done (we might get called recursively)
1538 context.new_paragraph(os);
1540 handle_ert(os, "\n", context);
1541 eat_whitespace(p, os, context, true);
1544 // "%\n" combination
1551 * Reads spaces and comments until the first non-space, non-comment token.
1552 * New paragraphs (double newlines or \\par) are handled like simple spaces
1553 * if \p eatParagraph is true.
1554 * Spaces are skipped, but comments are written to \p os.
1556 void eat_whitespace(Parser & p, ostream & os, Context & context,
1560 Token const & t = p.get_token();
1561 if (t.cat() == catComment)
1562 parse_comment(p, os, t, context);
1563 else if ((! eatParagraph && p.isParagraph()) ||
1564 (t.cat() != catSpace && t.cat() != catNewline)) {
1573 * Set a font attribute, parse text and reset the font attribute.
1574 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1575 * \param currentvalue Current value of the attribute. Is set to the new
1576 * value during parsing.
1577 * \param newvalue New value of the attribute
1579 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1580 Context & context, string const & attribute,
1581 string & currentvalue, string const & newvalue)
1583 context.check_layout(os);
1584 string const oldvalue = currentvalue;
1585 currentvalue = newvalue;
1586 os << '\n' << attribute << ' ' << newvalue << "\n";
1587 parse_text_snippet(p, os, flags, outer, context);
1588 context.check_layout(os);
1589 os << '\n' << attribute << ' ' << oldvalue << "\n";
1590 currentvalue = oldvalue;
1594 /// get the arguments of a natbib or jurabib citation command
1595 void get_cite_arguments(Parser & p, bool natbibOrder,
1596 string & before, string & after)
1598 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1600 // text before the citation
1602 // text after the citation
1603 after = p.getFullOpt();
1605 if (!after.empty()) {
1606 before = p.getFullOpt();
1607 if (natbibOrder && !before.empty())
1608 swap(before, after);
1613 /// Convert filenames with TeX macros and/or quotes to something LyX
1615 string const normalize_filename(string const & name)
1617 Parser p(trim(name, "\""));
1620 Token const & t = p.get_token();
1621 if (t.cat() != catEscape)
1623 else if (t.cs() == "lyxdot") {
1624 // This is used by LyX for simple dots in relative
1628 } else if (t.cs() == "space") {
1638 /// Convert \p name from TeX convention (relative to master file) to LyX
1639 /// convention (relative to .lyx file) if it is relative
1640 void fix_relative_filename(string & name)
1642 if (FileName::isAbsolute(name))
1645 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1646 from_utf8(getParentFilePath())));
1650 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1651 void parse_noweb(Parser & p, ostream & os, Context & context)
1653 // assemble the rest of the keyword
1657 Token const & t = p.get_token();
1658 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1661 scrap = (p.good() && p.next_token().asInput() == "=");
1663 name += p.get_token().asInput();
1666 name += t.asInput();
1669 if (!scrap || !context.new_layout_allowed ||
1670 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1671 cerr << "Warning: Could not interpret '" << name
1672 << "'. Ignoring it." << endl;
1676 // We use new_paragraph instead of check_end_layout because the stuff
1677 // following the noweb chunk needs to start with a \begin_layout.
1678 // This may create a new paragraph even if there was none in the
1679 // noweb file, but the alternative is an invalid LyX file. Since
1680 // noweb code chunks are implemented with a layout style in LyX they
1681 // always must be in an own paragraph.
1682 context.new_paragraph(os);
1683 Context newcontext(true, context.textclass,
1684 &context.textclass[from_ascii("Scrap")]);
1685 newcontext.check_layout(os);
1688 Token const & t = p.get_token();
1689 // We abuse the parser a bit, because this is no TeX syntax
1691 if (t.cat() == catEscape)
1692 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1695 Context tmp(false, context.textclass,
1696 &context.textclass[from_ascii("Scrap")]);
1697 tmp.need_end_layout = true;
1698 tmp.check_layout(oss);
1699 os << subst(t.asInput(), "\n", oss.str());
1701 // The scrap chunk is ended by an @ at the beginning of a line.
1702 // After the @ the line may contain a comment and/or
1703 // whitespace, but nothing else.
1704 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1705 (p.next_token().cat() == catSpace ||
1706 p.next_token().cat() == catNewline ||
1707 p.next_token().cat() == catComment)) {
1708 while (p.good() && p.next_token().cat() == catSpace)
1709 os << p.get_token().asInput();
1710 if (p.next_token().cat() == catComment)
1711 // The comment includes a final '\n'
1712 os << p.get_token().asInput();
1714 if (p.next_token().cat() == catNewline)
1721 newcontext.check_end_layout(os);
1725 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1726 bool is_macro(Parser & p)
1728 Token first = p.curr_token();
1729 if (first.cat() != catEscape || !p.good())
1731 if (first.cs() == "def")
1733 if (first.cs() != "global" && first.cs() != "long")
1735 Token second = p.get_token();
1737 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1738 second.cat() == catNewline || second.cat() == catComment)) {
1739 second = p.get_token();
1742 bool secondvalid = second.cat() == catEscape;
1744 bool thirdvalid = false;
1745 if (p.good() && first.cs() == "global" && secondvalid &&
1746 second.cs() == "long") {
1747 third = p.get_token();
1749 while (p.good() && !p.isParagraph() &&
1750 (third.cat() == catSpace ||
1751 third.cat() == catNewline ||
1752 third.cat() == catComment)) {
1753 third = p.get_token();
1756 thirdvalid = third.cat() == catEscape;
1758 for (int i = 0; i < pos; ++i)
1763 return (first.cs() == "global" || first.cs() == "long") &&
1764 second.cs() == "def";
1765 return first.cs() == "global" && second.cs() == "long" &&
1766 third.cs() == "def";
1770 /// Parse a macro definition (assumes that is_macro() returned true)
1771 void parse_macro(Parser & p, ostream & os, Context & context)
1773 context.check_layout(os);
1774 Token first = p.curr_token();
1777 string command = first.asInput();
1778 if (first.cs() != "def") {
1780 eat_whitespace(p, os, context, false);
1781 second = p.curr_token();
1782 command += second.asInput();
1783 if (second.cs() != "def") {
1785 eat_whitespace(p, os, context, false);
1786 third = p.curr_token();
1787 command += third.asInput();
1790 eat_whitespace(p, os, context, false);
1791 string const name = p.get_token().cs();
1792 eat_whitespace(p, os, context, false);
1798 while (p.next_token().cat() != catBegin) {
1799 if (p.next_token().cat() == catParameter) {
1804 // followed by number?
1805 if (p.next_token().cat() == catOther) {
1806 char c = p.getChar();
1808 // number = current arity + 1?
1809 if (c == arity + '0' + 1)
1814 paramtext += p.get_token().cs();
1816 paramtext += p.get_token().cs();
1821 // only output simple (i.e. compatible) macro as FormulaMacros
1822 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1824 context.check_layout(os);
1825 begin_inset(os, "FormulaMacro");
1826 os << "\n\\def" << ert;
1829 handle_ert(os, command + ert, context);
1832 } // anonymous namespace
1835 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1838 Layout const * newlayout = 0;
1839 InsetLayout const * newinsetlayout = 0;
1840 // Store the latest bibliographystyle and nocite{*} option
1841 // (needed for bibtex inset)
1843 string bibliographystyle;
1844 bool const use_natbib = preamble.isPackageUsed("natbib");
1845 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1847 bool title_layout_found = false;
1849 Token const & t = p.get_token();
1852 debugToken(cerr, t, flags);
1855 if (flags & FLAG_ITEM) {
1856 if (t.cat() == catSpace)
1859 flags &= ~FLAG_ITEM;
1860 if (t.cat() == catBegin) {
1861 // skip the brace and collect everything to the next matching
1863 flags |= FLAG_BRACE_LAST;
1867 // handle only this single token, leave the loop if done
1868 flags |= FLAG_LEAVE;
1871 if (t.cat() != catEscape && t.character() == ']' &&
1872 (flags & FLAG_BRACK_LAST))
1874 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1877 // If there is anything between \end{env} and \begin{env} we
1878 // don't need to output a separator.
1879 if (t.cat() != catSpace && t.cat() != catNewline &&
1880 t.asInput() != "\\begin")
1886 if (t.cat() == catMath) {
1887 // we are inside some text mode thingy, so opening new math is allowed
1888 context.check_layout(os);
1889 begin_inset(os, "Formula ");
1890 Token const & n = p.get_token();
1891 if (n.cat() == catMath && outer) {
1892 // TeX's $$...$$ syntax for displayed math
1894 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1896 p.get_token(); // skip the second '$' token
1898 // simple $...$ stuff
1901 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1907 else if (t.cat() == catSuper || t.cat() == catSub)
1908 cerr << "catcode " << t << " illegal in text mode\n";
1910 // Basic support for english quotes. This should be
1911 // extended to other quotes, but is not so easy (a
1912 // left english quote is the same as a right german
1914 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1915 context.check_layout(os);
1916 begin_inset(os, "Quotes ");
1922 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1923 context.check_layout(os);
1924 begin_inset(os, "Quotes ");
1931 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1932 context.check_layout(os);
1933 begin_inset(os, "Quotes ");
1940 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1941 context.check_layout(os);
1942 begin_inset(os, "Quotes ");
1949 else if (t.asInput() == "<"
1950 && p.next_token().asInput() == "<" && noweb_mode) {
1952 parse_noweb(p, os, context);
1955 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1956 check_space(p, os, context);
1958 else if (t.character() == '[' && noweb_mode &&
1959 p.next_token().character() == '[') {
1960 // These can contain underscores
1962 string const s = p.getFullOpt() + ']';
1963 if (p.next_token().character() == ']')
1966 cerr << "Warning: Inserting missing ']' in '"
1967 << s << "'." << endl;
1968 handle_ert(os, s, context);
1971 else if (t.cat() == catLetter) {
1972 context.check_layout(os);
1973 // Workaround for bug 4752.
1974 // FIXME: This whole code block needs to be removed
1975 // when the bug is fixed and tex2lyx produces
1976 // the updated file format.
1977 // The replacement algorithm in LyX is so stupid that
1978 // it even translates a phrase if it is part of a word.
1979 bool handled = false;
1980 for (int const * l = known_phrase_lengths; *l; ++l) {
1981 string phrase = t.cs();
1982 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1983 phrase += p.get_token().cs();
1984 if (is_known(phrase, known_coded_phrases)) {
1985 handle_ert(os, phrase, context);
1989 for (size_t i = 1; i < phrase.length(); ++i)
1997 else if (t.cat() == catOther ||
1998 t.cat() == catAlign ||
1999 t.cat() == catParameter) {
2000 // This translates "&" to "\\&" which may be wrong...
2001 context.check_layout(os);
2005 else if (p.isParagraph()) {
2006 if (context.new_layout_allowed)
2007 context.new_paragraph(os);
2009 handle_ert(os, "\\par ", context);
2010 eat_whitespace(p, os, context, true);
2013 else if (t.cat() == catActive) {
2014 context.check_layout(os);
2015 if (t.character() == '~') {
2016 if (context.layout->free_spacing)
2019 begin_inset(os, "space ~\n");
2026 else if (t.cat() == catBegin &&
2027 p.next_token().cat() == catEnd) {
2029 Token const prev = p.prev_token();
2031 if (p.next_token().character() == '`' ||
2032 (prev.character() == '-' &&
2033 p.next_token().character() == '-'))
2034 ; // ignore it in {}`` or -{}-
2036 handle_ert(os, "{}", context);
2040 else if (t.cat() == catBegin) {
2041 context.check_layout(os);
2042 // special handling of font attribute changes
2043 Token const prev = p.prev_token();
2044 Token const next = p.next_token();
2045 TeXFont const oldFont = context.font;
2046 if (next.character() == '[' ||
2047 next.character() == ']' ||
2048 next.character() == '*') {
2050 if (p.next_token().cat() == catEnd) {
2055 handle_ert(os, "{", context);
2056 parse_text_snippet(p, os,
2059 handle_ert(os, "}", context);
2061 } else if (! context.new_layout_allowed) {
2062 handle_ert(os, "{", context);
2063 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2065 handle_ert(os, "}", context);
2066 } else if (is_known(next.cs(), known_sizes)) {
2067 // next will change the size, so we must
2069 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2071 if (!context.atParagraphStart())
2073 << context.font.size << "\n";
2074 } else if (is_known(next.cs(), known_font_families)) {
2075 // next will change the font family, so we
2076 // must reset it here
2077 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2079 if (!context.atParagraphStart())
2081 << context.font.family << "\n";
2082 } else if (is_known(next.cs(), known_font_series)) {
2083 // next will change the font series, so we
2084 // must reset it here
2085 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2087 if (!context.atParagraphStart())
2089 << context.font.series << "\n";
2090 } else if (is_known(next.cs(), known_font_shapes)) {
2091 // next will change the font shape, so we
2092 // must reset it here
2093 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2095 if (!context.atParagraphStart())
2097 << context.font.shape << "\n";
2098 } else if (is_known(next.cs(), known_old_font_families) ||
2099 is_known(next.cs(), known_old_font_series) ||
2100 is_known(next.cs(), known_old_font_shapes)) {
2101 // next will change the font family, series
2102 // and shape, so we must reset it here
2103 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2105 if (!context.atParagraphStart())
2107 << context.font.family
2109 << context.font.series
2111 << context.font.shape << "\n";
2113 handle_ert(os, "{", context);
2114 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2116 handle_ert(os, "}", context);
2120 else if (t.cat() == catEnd) {
2121 if (flags & FLAG_BRACE_LAST) {
2124 cerr << "stray '}' in text\n";
2125 handle_ert(os, "}", context);
2128 else if (t.cat() == catComment)
2129 parse_comment(p, os, t, context);
2132 // control sequences
2135 else if (t.cs() == "(") {
2136 context.check_layout(os);
2137 begin_inset(os, "Formula");
2139 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2144 else if (t.cs() == "[") {
2145 context.check_layout(os);
2146 begin_inset(os, "Formula");
2148 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2153 else if (t.cs() == "begin")
2154 parse_environment(p, os, outer, last_env,
2155 title_layout_found, context);
2157 else if (t.cs() == "end") {
2158 if (flags & FLAG_END) {
2159 // eat environment name
2160 string const name = p.getArg('{', '}');
2161 if (name != active_environment())
2162 cerr << "\\end{" + name + "} does not match \\begin{"
2163 + active_environment() + "}\n";
2166 p.error("found 'end' unexpectedly");
2169 else if (t.cs() == "item") {
2172 bool optarg = false;
2173 if (p.next_token().cat() != catEscape &&
2174 p.next_token().character() == '[') {
2175 p.get_token(); // eat '['
2176 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2181 context.check_layout(os);
2182 if (context.has_item) {
2183 // An item in an unknown list-like environment
2184 // FIXME: Do this in check_layout()!
2185 context.has_item = false;
2187 handle_ert(os, "\\item", context);
2189 handle_ert(os, "\\item ", context);
2192 if (context.layout->labeltype != LABEL_MANUAL) {
2193 // LyX does not support \item[\mybullet]
2194 // in itemize environments
2195 handle_ert(os, "[", context);
2197 handle_ert(os, "]", context);
2198 } else if (!s.empty()) {
2199 // The space is needed to separate the
2200 // item from the rest of the sentence.
2202 eat_whitespace(p, os, context, false);
2207 else if (t.cs() == "bibitem") {
2209 context.check_layout(os);
2210 string label = convert_command_inset_arg(p.getArg('[', ']'));
2211 string key = convert_command_inset_arg(p.verbatim_item());
2212 if (contains(label, '\\') || contains(key, '\\')) {
2213 // LyX can't handle LaTeX commands in labels or keys
2214 handle_ert(os, t.asInput() + '[' + label +
2215 "]{" + p.verbatim_item() + '}',
2218 begin_command_inset(os, "bibitem", "bibitem");
2219 os << "label \"" << label << "\"\n"
2220 "key \"" << key << "\"\n";
2225 else if (is_macro(p))
2226 parse_macro(p, os, context);
2228 else if (t.cs() == "noindent") {
2230 context.add_par_extra_stuff("\\noindent\n");
2233 else if (t.cs() == "appendix") {
2234 context.add_par_extra_stuff("\\start_of_appendix\n");
2235 // We need to start a new paragraph. Otherwise the
2236 // appendix in 'bla\appendix\chapter{' would start
2238 context.new_paragraph(os);
2239 // We need to make sure that the paragraph is
2240 // generated even if it is empty. Otherwise the
2241 // appendix in '\par\appendix\par\chapter{' would
2243 context.check_layout(os);
2244 // FIXME: This is a hack to prevent paragraph
2245 // deletion if it is empty. Handle this better!
2247 "%dummy comment inserted by tex2lyx to "
2248 "ensure that this paragraph is not empty",
2250 // Both measures above may generate an additional
2251 // empty paragraph, but that does not hurt, because
2252 // whitespace does not matter here.
2253 eat_whitespace(p, os, context, true);
2256 // Must catch empty dates before findLayout is called below
2257 else if (t.cs() == "date") {
2258 string const date = p.verbatim_item();
2260 preamble.suppressDate(true);
2262 preamble.suppressDate(false);
2263 if (context.new_layout_allowed &&
2264 (newlayout = findLayout(context.textclass,
2267 output_command_layout(os, p, outer,
2268 context, newlayout);
2270 if (!title_layout_found)
2271 title_layout_found = newlayout->intitle;
2273 handle_ert(os, "\\date{" + date + '}',
2278 // Starred section headings
2279 // Must attempt to parse "Section*" before "Section".
2280 else if ((p.next_token().asInput() == "*") &&
2281 context.new_layout_allowed &&
2282 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2285 output_command_layout(os, p, outer, context, newlayout);
2287 if (!title_layout_found)
2288 title_layout_found = newlayout->intitle;
2291 // Section headings and the like
2292 else if (context.new_layout_allowed &&
2293 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2295 output_command_layout(os, p, outer, context, newlayout);
2297 if (!title_layout_found)
2298 title_layout_found = newlayout->intitle;
2301 else if (t.cs() == "caption") {
2303 context.check_layout(os);
2305 begin_inset(os, "Caption\n");
2306 Context newcontext(true, context.textclass);
2307 newcontext.font = context.font;
2308 newcontext.check_layout(os);
2309 if (p.next_token().cat() != catEscape &&
2310 p.next_token().character() == '[') {
2311 p.get_token(); // eat '['
2312 begin_inset(os, "Argument\n");
2313 os << "status collapsed\n";
2314 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2316 eat_whitespace(p, os, context, false);
2318 parse_text(p, os, FLAG_ITEM, outer, context);
2319 context.check_end_layout(os);
2320 // We don't need really a new paragraph, but
2321 // we must make sure that the next item gets a \begin_layout.
2322 context.new_paragraph(os);
2325 newcontext.check_end_layout(os);
2328 else if (t.cs() == "subfloat") {
2329 // the syntax is \subfloat[caption]{content}
2330 // if it is a table of figure depends on the surrounding float
2331 bool has_caption = false;
2333 // do nothing if there is no outer float
2334 if (!float_type.empty()) {
2335 context.check_layout(os);
2337 begin_inset(os, "Float " + float_type + "\n");
2339 << "\nsideways false"
2340 << "\nstatus collapsed\n\n";
2343 if (p.next_token().cat() != catEscape &&
2344 p.next_token().character() == '[') {
2345 p.get_token(); // eat '['
2346 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2350 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2351 // the caption comes always as the last
2353 // we must make sure that the caption gets a \begin_layout
2354 os << "\n\\begin_layout Plain Layout";
2356 begin_inset(os, "Caption\n");
2357 Context newcontext(true, context.textclass);
2358 newcontext.font = context.font;
2359 newcontext.check_layout(os);
2360 os << caption << "\n";
2361 newcontext.check_end_layout(os);
2362 // We don't need really a new paragraph, but
2363 // we must make sure that the next item gets a \begin_layout.
2364 //newcontext.new_paragraph(os);
2368 // We don't need really a new paragraph, but
2369 // we must make sure that the next item gets a \begin_layout.
2371 context.new_paragraph(os);
2374 context.check_end_layout(os);
2375 // close the layout we opened
2377 os << "\n\\end_layout\n";
2379 // if the float type is not supported or there is no surrounding float
2382 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2383 handle_ert(os, t.asInput() + '[' + opt_arg +
2384 "]{" + p.verbatim_item() + '}', context);
2386 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2390 else if (t.cs() == "includegraphics") {
2391 bool const clip = p.next_token().asInput() == "*";
2394 string const arg = p.getArg('[', ']');
2395 map<string, string> opts;
2396 vector<string> keys;
2397 split_map(arg, opts, keys);
2399 opts["clip"] = string();
2400 string name = normalize_filename(p.verbatim_item());
2402 string const path = getMasterFilePath();
2403 // We want to preserve relative / absolute filenames,
2404 // therefore path is only used for testing
2405 if (!makeAbsPath(name, path).exists()) {
2406 // The file extension is probably missing.
2407 // Now try to find it out.
2408 string const dvips_name =
2409 find_file(name, path,
2410 known_dvips_graphics_formats);
2411 string const pdftex_name =
2412 find_file(name, path,
2413 known_pdftex_graphics_formats);
2414 if (!dvips_name.empty()) {
2415 if (!pdftex_name.empty()) {
2416 cerr << "This file contains the "
2418 "\"\\includegraphics{"
2420 "However, files\n\""
2421 << dvips_name << "\" and\n\""
2422 << pdftex_name << "\"\n"
2423 "both exist, so I had to make a "
2424 "choice and took the first one.\n"
2425 "Please move the unwanted one "
2426 "someplace else and try again\n"
2427 "if my choice was wrong."
2431 } else if (!pdftex_name.empty()) {
2437 if (makeAbsPath(name, path).exists())
2438 fix_relative_filename(name);
2440 cerr << "Warning: Could not find graphics file '"
2441 << name << "'." << endl;
2443 context.check_layout(os);
2444 begin_inset(os, "Graphics ");
2445 os << "\n\tfilename " << name << '\n';
2446 if (opts.find("width") != opts.end())
2448 << translate_len(opts["width"]) << '\n';
2449 if (opts.find("height") != opts.end())
2451 << translate_len(opts["height"]) << '\n';
2452 if (opts.find("scale") != opts.end()) {
2453 istringstream iss(opts["scale"]);
2457 os << "\tscale " << val << '\n';
2459 if (opts.find("angle") != opts.end()) {
2460 os << "\trotateAngle "
2461 << opts["angle"] << '\n';
2462 vector<string>::const_iterator a =
2463 find(keys.begin(), keys.end(), "angle");
2464 vector<string>::const_iterator s =
2465 find(keys.begin(), keys.end(), "width");
2466 if (s == keys.end())
2467 s = find(keys.begin(), keys.end(), "height");
2468 if (s == keys.end())
2469 s = find(keys.begin(), keys.end(), "scale");
2470 if (s != keys.end() && distance(s, a) > 0)
2471 os << "\tscaleBeforeRotation\n";
2473 if (opts.find("origin") != opts.end()) {
2475 string const opt = opts["origin"];
2476 if (opt.find('l') != string::npos) ss << "left";
2477 if (opt.find('r') != string::npos) ss << "right";
2478 if (opt.find('c') != string::npos) ss << "center";
2479 if (opt.find('t') != string::npos) ss << "Top";
2480 if (opt.find('b') != string::npos) ss << "Bottom";
2481 if (opt.find('B') != string::npos) ss << "Baseline";
2482 if (!ss.str().empty())
2483 os << "\trotateOrigin " << ss.str() << '\n';
2485 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2487 if (opts.find("keepaspectratio") != opts.end())
2488 os << "\tkeepAspectRatio\n";
2489 if (opts.find("clip") != opts.end())
2491 if (opts.find("draft") != opts.end())
2493 if (opts.find("bb") != opts.end())
2494 os << "\tBoundingBox "
2495 << opts["bb"] << '\n';
2496 int numberOfbbOptions = 0;
2497 if (opts.find("bbllx") != opts.end())
2498 numberOfbbOptions++;
2499 if (opts.find("bblly") != opts.end())
2500 numberOfbbOptions++;
2501 if (opts.find("bburx") != opts.end())
2502 numberOfbbOptions++;
2503 if (opts.find("bbury") != opts.end())
2504 numberOfbbOptions++;
2505 if (numberOfbbOptions == 4)
2506 os << "\tBoundingBox "
2507 << opts["bbllx"] << " " << opts["bblly"] << " "
2508 << opts["bburx"] << " " << opts["bbury"] << '\n';
2509 else if (numberOfbbOptions > 0)
2510 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2511 numberOfbbOptions = 0;
2512 if (opts.find("natwidth") != opts.end())
2513 numberOfbbOptions++;
2514 if (opts.find("natheight") != opts.end())
2515 numberOfbbOptions++;
2516 if (numberOfbbOptions == 2)
2517 os << "\tBoundingBox 0bp 0bp "
2518 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2519 else if (numberOfbbOptions > 0)
2520 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2521 ostringstream special;
2522 if (opts.find("hiresbb") != opts.end())
2523 special << "hiresbb,";
2524 if (opts.find("trim") != opts.end())
2526 if (opts.find("viewport") != opts.end())
2527 special << "viewport=" << opts["viewport"] << ',';
2528 if (opts.find("totalheight") != opts.end())
2529 special << "totalheight=" << opts["totalheight"] << ',';
2530 if (opts.find("type") != opts.end())
2531 special << "type=" << opts["type"] << ',';
2532 if (opts.find("ext") != opts.end())
2533 special << "ext=" << opts["ext"] << ',';
2534 if (opts.find("read") != opts.end())
2535 special << "read=" << opts["read"] << ',';
2536 if (opts.find("command") != opts.end())
2537 special << "command=" << opts["command"] << ',';
2538 string s_special = special.str();
2539 if (!s_special.empty()) {
2540 // We had special arguments. Remove the trailing ','.
2541 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2543 // TODO: Handle the unknown settings better.
2544 // Warn about invalid options.
2545 // Check whether some option was given twice.
2549 else if (t.cs() == "footnote" ||
2550 (t.cs() == "thanks" && context.layout->intitle)) {
2552 context.check_layout(os);
2553 begin_inset(os, "Foot\n");
2554 os << "status collapsed\n\n";
2555 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2559 else if (t.cs() == "marginpar") {
2561 context.check_layout(os);
2562 begin_inset(os, "Marginal\n");
2563 os << "status collapsed\n\n";
2564 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2568 else if (t.cs() == "ensuremath") {
2570 context.check_layout(os);
2571 string const s = p.verbatim_item();
2572 //FIXME: this never triggers in UTF8
2573 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2576 handle_ert(os, "\\ensuremath{" + s + "}",
2580 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2581 if (title_layout_found) {
2583 skip_spaces_braces(p);
2585 handle_ert(os, t.asInput(), context);
2588 else if (t.cs() == "tableofcontents") {
2589 context.check_layout(os);
2590 begin_command_inset(os, "toc", "tableofcontents");
2592 skip_spaces_braces(p);
2595 else if (t.cs() == "listoffigures") {
2596 context.check_layout(os);
2597 begin_inset(os, "FloatList figure\n");
2599 skip_spaces_braces(p);
2602 else if (t.cs() == "listoftables") {
2603 context.check_layout(os);
2604 begin_inset(os, "FloatList table\n");
2606 skip_spaces_braces(p);
2609 else if (t.cs() == "listof") {
2610 p.skip_spaces(true);
2611 string const name = p.get_token().cs();
2612 if (context.textclass.floats().typeExist(name)) {
2613 context.check_layout(os);
2614 begin_inset(os, "FloatList ");
2617 p.get_token(); // swallow second arg
2619 handle_ert(os, "\\listof{" + name + "}", context);
2622 else if (t.cs() == "textrm")
2623 parse_text_attributes(p, os, FLAG_ITEM, outer,
2624 context, "\\family",
2625 context.font.family, "roman");
2627 else if (t.cs() == "textsf")
2628 parse_text_attributes(p, os, FLAG_ITEM, outer,
2629 context, "\\family",
2630 context.font.family, "sans");
2632 else if (t.cs() == "texttt")
2633 parse_text_attributes(p, os, FLAG_ITEM, outer,
2634 context, "\\family",
2635 context.font.family, "typewriter");
2637 else if (t.cs() == "textmd")
2638 parse_text_attributes(p, os, FLAG_ITEM, outer,
2639 context, "\\series",
2640 context.font.series, "medium");
2642 else if (t.cs() == "textbf")
2643 parse_text_attributes(p, os, FLAG_ITEM, outer,
2644 context, "\\series",
2645 context.font.series, "bold");
2647 else if (t.cs() == "textup")
2648 parse_text_attributes(p, os, FLAG_ITEM, outer,
2650 context.font.shape, "up");
2652 else if (t.cs() == "textit")
2653 parse_text_attributes(p, os, FLAG_ITEM, outer,
2655 context.font.shape, "italic");
2657 else if (t.cs() == "textsl")
2658 parse_text_attributes(p, os, FLAG_ITEM, outer,
2660 context.font.shape, "slanted");
2662 else if (t.cs() == "textsc")
2663 parse_text_attributes(p, os, FLAG_ITEM, outer,
2665 context.font.shape, "smallcaps");
2667 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2668 context.check_layout(os);
2669 TeXFont oldFont = context.font;
2670 context.font.init();
2671 context.font.size = oldFont.size;
2672 os << "\n\\family " << context.font.family << "\n";
2673 os << "\n\\series " << context.font.series << "\n";
2674 os << "\n\\shape " << context.font.shape << "\n";
2675 if (t.cs() == "textnormal") {
2676 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2677 output_font_change(os, context.font, oldFont);
2678 context.font = oldFont;
2680 eat_whitespace(p, os, context, false);
2683 else if (t.cs() == "textcolor") {
2684 // scheme is \textcolor{color name}{text}
2685 string const color = p.verbatim_item();
2686 // we only support the predefined colors of the color package
2687 if (color == "black" || color == "blue" || color == "cyan"
2688 || color == "green" || color == "magenta" || color == "red"
2689 || color == "white" || color == "yellow") {
2690 context.check_layout(os);
2691 os << "\n\\color " << color << "\n";
2692 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2693 context.check_layout(os);
2694 os << "\n\\color inherit\n";
2695 preamble.registerAutomaticallyLoadedPackage("color");
2697 // for custom defined colors
2698 handle_ert(os, t.asInput() + "{" + color + "}", context);
2701 else if (t.cs() == "underbar" || t.cs() == "uline") {
2702 // \underbar is not 100% correct (LyX outputs \uline
2703 // of ulem.sty). The difference is that \ulem allows
2704 // line breaks, and \underbar does not.
2705 // Do NOT handle \underline.
2706 // \underbar cuts through y, g, q, p etc.,
2707 // \underline does not.
2708 context.check_layout(os);
2709 os << "\n\\bar under\n";
2710 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2711 context.check_layout(os);
2712 os << "\n\\bar default\n";
2713 preamble.registerAutomaticallyLoadedPackage("ulem");
2716 else if (t.cs() == "sout") {
2717 context.check_layout(os);
2718 os << "\n\\strikeout on\n";
2719 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2720 context.check_layout(os);
2721 os << "\n\\strikeout default\n";
2722 preamble.registerAutomaticallyLoadedPackage("ulem");
2725 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2726 t.cs() == "emph" || t.cs() == "noun") {
2727 context.check_layout(os);
2728 os << "\n\\" << t.cs() << " on\n";
2729 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2730 context.check_layout(os);
2731 os << "\n\\" << t.cs() << " default\n";
2732 if (t.cs() == "uuline" || t.cs() == "uwave")
2733 preamble.registerAutomaticallyLoadedPackage("ulem");
2736 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2737 context.check_layout(os);
2738 string name = p.getArg('{', '}');
2739 string localtime = p.getArg('{', '}');
2740 preamble.registerAuthor(name);
2741 Author const & author = preamble.getAuthor(name);
2742 // from_ctime() will fail if LyX decides to output the
2743 // time in the text language. It might also use a wrong
2744 // time zone (if the original LyX document was exported
2745 // with a different time zone).
2746 time_t ptime = from_ctime(localtime);
2747 if (ptime == static_cast<time_t>(-1)) {
2748 cerr << "Warning: Could not parse time `" << localtime
2749 << "´ for change tracking, using current time instead.\n";
2750 ptime = current_time();
2752 if (t.cs() == "lyxadded")
2753 os << "\n\\change_inserted ";
2755 os << "\n\\change_deleted ";
2756 os << author.bufferId() << ' ' << ptime << '\n';
2757 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2758 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2759 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2760 LaTeXPackages::isAvailable("xcolor");
2761 // No need to test for luatex, since luatex comes in
2762 // two flavours (dvi and pdf), like latex, and those
2763 // are detected by pdflatex.
2764 if (pdflatex || xetex) {
2766 preamble.registerAutomaticallyLoadedPackage("ulem");
2767 preamble.registerAutomaticallyLoadedPackage("xcolor");
2768 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2772 preamble.registerAutomaticallyLoadedPackage("dvipost");
2773 } else if (xcolorulem) {
2774 preamble.registerAutomaticallyLoadedPackage("ulem");
2775 preamble.registerAutomaticallyLoadedPackage("xcolor");
2780 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2781 t.cs() == "vphantom") {
2782 context.check_layout(os);
2783 if (t.cs() == "phantom")
2784 begin_inset(os, "Phantom Phantom\n");
2785 if (t.cs() == "hphantom")
2786 begin_inset(os, "Phantom HPhantom\n");
2787 if (t.cs() == "vphantom")
2788 begin_inset(os, "Phantom VPhantom\n");
2789 os << "status open\n";
2790 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2795 else if (t.cs() == "href") {
2796 context.check_layout(os);
2797 string target = p.getArg('{', '}');
2798 string name = p.getArg('{', '}');
2800 size_t i = target.find(':');
2801 if (i != string::npos) {
2802 type = target.substr(0, i + 1);
2803 if (type == "mailto:" || type == "file:")
2804 target = target.substr(i + 1);
2805 // handle the case that name is equal to target, except of "http://"
2806 else if (target.substr(i + 3) == name && type == "http:")
2809 begin_command_inset(os, "href", "href");
2811 os << "name \"" << name << "\"\n";
2812 os << "target \"" << target << "\"\n";
2813 if (type == "mailto:" || type == "file:")
2814 os << "type \"" << type << "\"\n";
2816 skip_spaces_braces(p);
2819 else if (t.cs() == "lyxline") {
2820 // swallow size argument (it is not used anyway)
2822 if (!context.atParagraphStart()) {
2823 // so our line is in the middle of a paragraph
2824 // we need to add a new line, lest this line
2825 // follow the other content on that line and
2826 // run off the side of the page
2827 // FIXME: This may create an empty paragraph,
2828 // but without that it would not be
2829 // possible to set noindent below.
2830 // Fortunately LaTeX does not care
2831 // about the empty paragraph.
2832 context.new_paragraph(os);
2834 if (preamble.indentParagraphs()) {
2835 // we need to unindent, lest the line be too long
2836 context.add_par_extra_stuff("\\noindent\n");
2838 context.check_layout(os);
2839 begin_command_inset(os, "line", "rule");
2840 os << "offset \"0.5ex\"\n"
2841 "width \"100line%\"\n"
2846 else if (t.cs() == "rule") {
2847 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2848 string const width = p.getArg('{', '}');
2849 string const thickness = p.getArg('{', '}');
2850 context.check_layout(os);
2851 begin_command_inset(os, "line", "rule");
2852 if (!offset.empty())
2853 os << "offset \"" << translate_len(offset) << "\"\n";
2854 os << "width \"" << translate_len(width) << "\"\n"
2855 "height \"" << translate_len(thickness) << "\"\n";
2859 else if (is_known(t.cs(), known_phrases) ||
2860 (t.cs() == "protect" &&
2861 p.next_token().cat() == catEscape &&
2862 is_known(p.next_token().cs(), known_phrases))) {
2863 // LyX sometimes puts a \protect in front, so we have to ignore it
2864 // FIXME: This needs to be changed when bug 4752 is fixed.
2865 char const * const * where = is_known(
2866 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2868 context.check_layout(os);
2869 os << known_coded_phrases[where - known_phrases];
2870 skip_spaces_braces(p);
2873 else if (is_known(t.cs(), known_ref_commands)) {
2874 string const opt = p.getOpt();
2876 context.check_layout(os);
2877 char const * const * where = is_known(t.cs(),
2878 known_ref_commands);
2879 begin_command_inset(os, "ref",
2880 known_coded_ref_commands[where - known_ref_commands]);
2881 os << "reference \""
2882 << convert_command_inset_arg(p.verbatim_item())
2886 // LyX does not support optional arguments of ref commands
2887 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2888 p.verbatim_item() + "}", context);
2892 else if (use_natbib &&
2893 is_known(t.cs(), known_natbib_commands) &&
2894 ((t.cs() != "citefullauthor" &&
2895 t.cs() != "citeyear" &&
2896 t.cs() != "citeyearpar") ||
2897 p.next_token().asInput() != "*")) {
2898 context.check_layout(os);
2899 string command = t.cs();
2900 if (p.next_token().asInput() == "*") {
2904 if (command == "citefullauthor")
2905 // alternative name for "\\citeauthor*"
2906 command = "citeauthor*";
2908 // text before the citation
2910 // text after the citation
2912 get_cite_arguments(p, true, before, after);
2914 if (command == "cite") {
2915 // \cite without optional argument means
2916 // \citet, \cite with at least one optional
2917 // argument means \citep.
2918 if (before.empty() && after.empty())
2923 if (before.empty() && after == "[]")
2924 // avoid \citet[]{a}
2926 else if (before == "[]" && after == "[]") {
2927 // avoid \citet[][]{a}
2931 // remove the brackets around after and before
2932 if (!after.empty()) {
2934 after.erase(after.length() - 1, 1);
2935 after = convert_command_inset_arg(after);
2937 if (!before.empty()) {
2939 before.erase(before.length() - 1, 1);
2940 before = convert_command_inset_arg(before);
2942 begin_command_inset(os, "citation", command);
2943 os << "after " << '"' << after << '"' << "\n";
2944 os << "before " << '"' << before << '"' << "\n";
2946 << convert_command_inset_arg(p.verbatim_item())
2951 else if (use_jurabib &&
2952 is_known(t.cs(), known_jurabib_commands) &&
2953 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2954 context.check_layout(os);
2955 string command = t.cs();
2956 if (p.next_token().asInput() == "*") {
2960 char argumentOrder = '\0';
2961 vector<string> const options =
2962 preamble.getPackageOptions("jurabib");
2963 if (find(options.begin(), options.end(),
2964 "natbiborder") != options.end())
2965 argumentOrder = 'n';
2966 else if (find(options.begin(), options.end(),
2967 "jurabiborder") != options.end())
2968 argumentOrder = 'j';
2970 // text before the citation
2972 // text after the citation
2974 get_cite_arguments(p, argumentOrder != 'j', before, after);
2976 string const citation = p.verbatim_item();
2977 if (!before.empty() && argumentOrder == '\0') {
2978 cerr << "Warning: Assuming argument order "
2979 "of jurabib version 0.6 for\n'"
2980 << command << before << after << '{'
2981 << citation << "}'.\n"
2982 "Add 'jurabiborder' to the jurabib "
2983 "package options if you used an\n"
2984 "earlier jurabib version." << endl;
2986 if (!after.empty()) {
2988 after.erase(after.length() - 1, 1);
2990 if (!before.empty()) {
2992 before.erase(before.length() - 1, 1);
2994 begin_command_inset(os, "citation", command);
2995 os << "after " << '"' << after << '"' << "\n";
2996 os << "before " << '"' << before << '"' << "\n";
2997 os << "key " << '"' << citation << '"' << "\n";
3001 else if (t.cs() == "cite"
3002 || t.cs() == "nocite") {
3003 context.check_layout(os);
3004 string after = convert_command_inset_arg(p.getArg('[', ']'));
3005 string key = convert_command_inset_arg(p.verbatim_item());
3006 // store the case that it is "\nocite{*}" to use it later for
3009 begin_command_inset(os, "citation", t.cs());
3010 os << "after " << '"' << after << '"' << "\n";
3011 os << "key " << '"' << key << '"' << "\n";
3013 } else if (t.cs() == "nocite")
3017 else if (t.cs() == "index") {
3018 context.check_layout(os);
3019 begin_inset(os, "Index idx\n");
3020 os << "status collapsed\n";
3021 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3025 else if (t.cs() == "nomenclature") {
3026 context.check_layout(os);
3027 begin_command_inset(os, "nomenclature", "nomenclature");
3028 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3029 if (!prefix.empty())
3030 os << "prefix " << '"' << prefix << '"' << "\n";
3031 os << "symbol " << '"'
3032 << convert_command_inset_arg(p.verbatim_item());
3033 os << "\"\ndescription \""
3034 << convert_command_inset_arg(p.verbatim_item())
3039 else if (t.cs() == "label") {
3040 context.check_layout(os);
3041 begin_command_inset(os, "label", "label");
3043 << convert_command_inset_arg(p.verbatim_item())
3048 else if (t.cs() == "printindex") {
3049 context.check_layout(os);
3050 begin_command_inset(os, "index_print", "printindex");
3051 os << "type \"idx\"\n";
3053 skip_spaces_braces(p);
3056 else if (t.cs() == "printnomenclature") {
3058 string width_type = "";
3059 context.check_layout(os);
3060 begin_command_inset(os, "nomencl_print", "printnomenclature");
3061 // case of a custom width
3063 width = p.getArg('[', ']');
3064 width = translate_len(width);
3065 width_type = "custom";
3067 // case of no custom width
3068 // the case of no custom width but the width set
3069 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3070 // because the user could have set anything, not only the width
3071 // of the longest label (which would be width_type = "auto")
3072 string label = convert_command_inset_arg(p.getArg('{', '}'));
3073 if (label.empty() && width_type.empty())
3074 width_type = "none";
3075 os << "set_width \"" << width_type << "\"\n";
3076 if (width_type == "custom")
3077 os << "width \"" << width << '\"';
3079 skip_spaces_braces(p);
3082 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3083 context.check_layout(os);
3084 begin_inset(os, "script ");
3085 os << t.cs().substr(4) << '\n';
3086 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3088 if (t.cs() == "textsubscript")
3089 preamble.registerAutomaticallyLoadedPackage("subscript");
3092 else if (is_known(t.cs(), known_quotes)) {
3093 char const * const * where = is_known(t.cs(), known_quotes);
3094 context.check_layout(os);
3095 begin_inset(os, "Quotes ");
3096 os << known_coded_quotes[where - known_quotes];
3098 // LyX adds {} after the quote, so we have to eat
3099 // spaces here if there are any before a possible
3101 eat_whitespace(p, os, context, false);
3105 else if (is_known(t.cs(), known_sizes) &&
3106 context.new_layout_allowed) {
3107 char const * const * where = is_known(t.cs(), known_sizes);
3108 context.check_layout(os);
3109 TeXFont const oldFont = context.font;
3110 context.font.size = known_coded_sizes[where - known_sizes];
3111 output_font_change(os, oldFont, context.font);
3112 eat_whitespace(p, os, context, false);
3115 else if (is_known(t.cs(), known_font_families) &&
3116 context.new_layout_allowed) {
3117 char const * const * where =
3118 is_known(t.cs(), known_font_families);
3119 context.check_layout(os);
3120 TeXFont const oldFont = context.font;
3121 context.font.family =
3122 known_coded_font_families[where - known_font_families];
3123 output_font_change(os, oldFont, context.font);
3124 eat_whitespace(p, os, context, false);
3127 else if (is_known(t.cs(), known_font_series) &&
3128 context.new_layout_allowed) {
3129 char const * const * where =
3130 is_known(t.cs(), known_font_series);
3131 context.check_layout(os);
3132 TeXFont const oldFont = context.font;
3133 context.font.series =
3134 known_coded_font_series[where - known_font_series];
3135 output_font_change(os, oldFont, context.font);
3136 eat_whitespace(p, os, context, false);
3139 else if (is_known(t.cs(), known_font_shapes) &&
3140 context.new_layout_allowed) {
3141 char const * const * where =
3142 is_known(t.cs(), known_font_shapes);
3143 context.check_layout(os);
3144 TeXFont const oldFont = context.font;
3145 context.font.shape =
3146 known_coded_font_shapes[where - known_font_shapes];
3147 output_font_change(os, oldFont, context.font);
3148 eat_whitespace(p, os, context, false);
3150 else if (is_known(t.cs(), known_old_font_families) &&
3151 context.new_layout_allowed) {
3152 char const * const * where =
3153 is_known(t.cs(), known_old_font_families);
3154 context.check_layout(os);
3155 TeXFont const oldFont = context.font;
3156 context.font.init();
3157 context.font.size = oldFont.size;
3158 context.font.family =
3159 known_coded_font_families[where - known_old_font_families];
3160 output_font_change(os, oldFont, context.font);
3161 eat_whitespace(p, os, context, false);
3164 else if (is_known(t.cs(), known_old_font_series) &&
3165 context.new_layout_allowed) {
3166 char const * const * where =
3167 is_known(t.cs(), known_old_font_series);
3168 context.check_layout(os);
3169 TeXFont const oldFont = context.font;
3170 context.font.init();
3171 context.font.size = oldFont.size;
3172 context.font.series =
3173 known_coded_font_series[where - known_old_font_series];
3174 output_font_change(os, oldFont, context.font);
3175 eat_whitespace(p, os, context, false);
3178 else if (is_known(t.cs(), known_old_font_shapes) &&
3179 context.new_layout_allowed) {
3180 char const * const * where =
3181 is_known(t.cs(), known_old_font_shapes);
3182 context.check_layout(os);
3183 TeXFont const oldFont = context.font;
3184 context.font.init();
3185 context.font.size = oldFont.size;
3186 context.font.shape =
3187 known_coded_font_shapes[where - known_old_font_shapes];
3188 output_font_change(os, oldFont, context.font);
3189 eat_whitespace(p, os, context, false);
3192 else if (t.cs() == "selectlanguage") {
3193 context.check_layout(os);
3194 // save the language for the case that a
3195 // \foreignlanguage is used
3197 context.font.language = babel2lyx(p.verbatim_item());
3198 os << "\n\\lang " << context.font.language << "\n";
3201 else if (t.cs() == "foreignlanguage") {
3202 string const lang = babel2lyx(p.verbatim_item());
3203 parse_text_attributes(p, os, FLAG_ITEM, outer,
3205 context.font.language, lang);
3208 else if (t.cs() == "inputencoding") {
3209 // nothing to write here
3210 string const enc = subst(p.verbatim_item(), "\n", " ");
3214 else if (t.cs() == "ldots") {
3215 context.check_layout(os);
3216 os << "\\SpecialChar \\ldots{}\n";
3217 skip_spaces_braces(p);
3220 else if (t.cs() == "lyxarrow") {
3221 context.check_layout(os);
3222 os << "\\SpecialChar \\menuseparator\n";
3223 skip_spaces_braces(p);
3226 else if (t.cs() == "textcompwordmark") {
3227 context.check_layout(os);
3228 os << "\\SpecialChar \\textcompwordmark{}\n";
3229 skip_spaces_braces(p);
3232 else if (t.cs() == "slash") {
3233 context.check_layout(os);
3234 os << "\\SpecialChar \\slash{}\n";
3235 skip_spaces_braces(p);
3238 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3239 context.check_layout(os);
3240 os << "\\SpecialChar \\nobreakdash-\n";
3244 else if (t.cs() == "textquotedbl") {
3245 context.check_layout(os);
3250 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3251 context.check_layout(os);
3252 os << "\\SpecialChar \\@.\n";
3256 else if (t.cs() == "-") {
3257 context.check_layout(os);
3258 os << "\\SpecialChar \\-\n";
3261 else if (t.cs() == "textasciitilde") {
3262 context.check_layout(os);
3264 skip_spaces_braces(p);
3267 else if (t.cs() == "textasciicircum") {
3268 context.check_layout(os);
3270 skip_spaces_braces(p);
3273 else if (t.cs() == "textbackslash") {
3274 context.check_layout(os);
3275 os << "\n\\backslash\n";
3276 skip_spaces_braces(p);
3279 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3280 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3282 context.check_layout(os);
3286 else if (t.cs() == "char") {
3287 context.check_layout(os);
3288 if (p.next_token().character() == '`') {
3290 if (p.next_token().cs() == "\"") {
3295 handle_ert(os, "\\char`", context);
3298 handle_ert(os, "\\char", context);
3302 else if (t.cs() == "verb") {
3303 context.check_layout(os);
3304 char const delimiter = p.next_token().character();
3305 string const arg = p.getArg(delimiter, delimiter);
3307 oss << "\\verb" << delimiter << arg << delimiter;
3308 handle_ert(os, oss.str(), context);
3311 // Problem: \= creates a tabstop inside the tabbing environment
3312 // and else an accent. In the latter case we really would want
3313 // \={o} instead of \= o.
3314 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3315 handle_ert(os, t.asInput(), context);
3317 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3318 else if (t.cs().size() == 1
3319 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3320 context.check_layout(os);
3321 // try to see whether the string is in unicodesymbols
3323 string command = t.asInput() + "{"
3324 + trimSpaceAndEol(p.verbatim_item())
3326 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3329 cerr << "When parsing " << command
3330 << ", result is " << to_utf8(s)
3331 << "+" << to_utf8(rem) << endl;
3334 // we did not find a non-ert version
3335 handle_ert(os, command, context);
3338 else if (t.cs() == "\\") {
3339 context.check_layout(os);
3341 handle_ert(os, "\\\\" + p.getOpt(), context);
3342 else if (p.next_token().asInput() == "*") {
3344 // getOpt() eats the following space if there
3345 // is no optional argument, but that is OK
3346 // here since it has no effect in the output.
3347 handle_ert(os, "\\\\*" + p.getOpt(), context);
3350 begin_inset(os, "Newline newline");
3355 else if (t.cs() == "newline" ||
3356 (t.cs() == "linebreak" && !p.hasOpt())) {
3357 context.check_layout(os);
3358 begin_inset(os, "Newline ");
3361 skip_spaces_braces(p);
3364 else if (t.cs() == "input" || t.cs() == "include"
3365 || t.cs() == "verbatiminput") {
3366 string name = t.cs();
3367 if (t.cs() == "verbatiminput"
3368 && p.next_token().asInput() == "*")
3369 name += p.get_token().asInput();
3370 context.check_layout(os);
3371 string filename(normalize_filename(p.getArg('{', '}')));
3372 string const path = getMasterFilePath();
3373 // We want to preserve relative / absolute filenames,
3374 // therefore path is only used for testing
3375 if ((t.cs() == "include" || t.cs() == "input") &&
3376 !makeAbsPath(filename, path).exists()) {
3377 // The file extension is probably missing.
3378 // Now try to find it out.
3379 string const tex_name =
3380 find_file(filename, path,
3381 known_tex_extensions);
3382 if (!tex_name.empty())
3383 filename = tex_name;
3385 bool external = false;
3387 if (makeAbsPath(filename, path).exists()) {
3388 string const abstexname =
3389 makeAbsPath(filename, path).absFileName();
3390 string const abslyxname =
3391 changeExtension(abstexname, ".lyx");
3392 string const absfigname =
3393 changeExtension(abstexname, ".fig");
3394 fix_relative_filename(filename);
3395 string const lyxname =
3396 changeExtension(filename, ".lyx");
3398 external = FileName(absfigname).exists();
3399 if (t.cs() == "input") {
3400 string const ext = getExtension(abstexname);
3402 // Combined PS/LaTeX:
3403 // x.eps, x.pstex_t (old xfig)
3404 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3405 FileName const absepsname(
3406 changeExtension(abstexname, ".eps"));
3407 FileName const abspstexname(
3408 changeExtension(abstexname, ".pstex"));
3409 bool const xfigeps =
3410 (absepsname.exists() ||
3411 abspstexname.exists()) &&
3414 // Combined PDF/LaTeX:
3415 // x.pdf, x.pdftex_t (old xfig)
3416 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3417 FileName const abspdfname(
3418 changeExtension(abstexname, ".pdf"));
3419 bool const xfigpdf =
3420 abspdfname.exists() &&
3421 (ext == "pdftex_t" || ext == "pdf_t");
3425 // Combined PS/PDF/LaTeX:
3426 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3427 string const absbase2(
3428 removeExtension(abstexname) + "_pspdftex");
3429 FileName const abseps2name(
3430 addExtension(absbase2, ".eps"));
3431 FileName const abspdf2name(
3432 addExtension(absbase2, ".pdf"));
3433 bool const xfigboth =
3434 abspdf2name.exists() &&
3435 abseps2name.exists() && ext == "pspdftex";
3437 xfig = xfigpdf || xfigeps || xfigboth;
3438 external = external && xfig;
3441 outname = changeExtension(filename, ".fig");
3443 // Don't try to convert, the result
3444 // would be full of ERT.
3446 } else if (t.cs() != "verbatiminput" &&
3447 tex2lyx(abstexname, FileName(abslyxname),
3454 cerr << "Warning: Could not find included file '"
3455 << filename << "'." << endl;
3459 begin_inset(os, "External\n");
3460 os << "\ttemplate XFig\n"
3461 << "\tfilename " << outname << '\n';
3463 begin_command_inset(os, "include", name);
3464 os << "preview false\n"
3465 "filename \"" << outname << "\"\n";
3470 else if (t.cs() == "bibliographystyle") {
3471 // store new bibliographystyle
3472 bibliographystyle = p.verbatim_item();
3473 // If any other command than \bibliography and
3474 // \nocite{*} follows, we need to output the style
3475 // (because it might be used by that command).
3476 // Otherwise, it will automatically be output by LyX.
3479 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3480 if (t2.cat() == catBegin)
3482 if (t2.cat() != catEscape)
3484 if (t2.cs() == "nocite") {
3485 if (p.getArg('{', '}') == "*")
3487 } else if (t2.cs() == "bibliography")
3494 "\\bibliographystyle{" + bibliographystyle + '}',
3499 else if (t.cs() == "bibliography") {
3500 context.check_layout(os);
3501 begin_command_inset(os, "bibtex", "bibtex");
3502 if (!btprint.empty()) {
3503 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3504 // clear the string because the next BibTeX inset can be without the
3505 // \nocite{*} option
3508 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3509 // Do we have a bibliographystyle set?
3510 if (!bibliographystyle.empty())
3511 os << "options " << '"' << bibliographystyle << '"' << "\n";
3515 else if (t.cs() == "parbox") {
3516 // Test whether this is an outer box of a shaded box
3518 // swallow arguments
3519 while (p.hasOpt()) {
3521 p.skip_spaces(true);
3524 p.skip_spaces(true);
3526 if (p.next_token().cat() == catBegin)
3528 p.skip_spaces(true);
3529 Token to = p.get_token();
3530 bool shaded = false;
3531 if (to.asInput() == "\\begin") {
3532 p.skip_spaces(true);
3533 if (p.getArg('{', '}') == "shaded")
3538 parse_outer_box(p, os, FLAG_ITEM, outer,
3539 context, "parbox", "shaded");
3541 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3545 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3546 t.cs() == "shadowbox" || t.cs() == "doublebox")
3547 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3549 else if (t.cs() == "framebox") {
3550 string special = p.getFullOpt();
3551 special += p.getOpt();
3552 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3555 //\makebox() is part of the picture environment and different from \makebox{}
3556 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3557 else if (t.cs() == "makebox") {
3558 string arg = t.asInput();
3559 if (p.next_token().character() == '(') {
3560 //the syntax is: \makebox(x,y)[position]{content}
3561 arg += p.getFullParentheseArg();
3562 arg += p.getFullOpt();
3563 handle_ert(os, arg + p.get_token().asInput(), context);
3565 //the syntax is: \makebox[width][position]{content}
3566 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3570 else if (t.cs() == "smallskip" ||
3571 t.cs() == "medskip" ||
3572 t.cs() == "bigskip" ||
3573 t.cs() == "vfill") {
3574 context.check_layout(os);
3575 begin_inset(os, "VSpace ");
3578 skip_spaces_braces(p);
3581 else if (is_known(t.cs(), known_spaces)) {
3582 char const * const * where = is_known(t.cs(), known_spaces);
3583 context.check_layout(os);
3584 begin_inset(os, "space ");
3585 os << '\\' << known_coded_spaces[where - known_spaces]
3588 // LaTeX swallows whitespace after all spaces except
3589 // "\\,". We have to do that here, too, because LyX
3590 // adds "{}" which would make the spaces significant.
3592 eat_whitespace(p, os, context, false);
3593 // LyX adds "{}" after all spaces except "\\ " and
3594 // "\\,", so we have to remove "{}".
3595 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3596 // remove the braces after "\\,", too.
3601 else if (t.cs() == "newpage" ||
3602 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3603 t.cs() == "clearpage" ||
3604 t.cs() == "cleardoublepage") {
3605 context.check_layout(os);
3606 begin_inset(os, "Newpage ");
3609 skip_spaces_braces(p);
3612 else if (t.cs() == "DeclareRobustCommand" ||
3613 t.cs() == "DeclareRobustCommandx" ||
3614 t.cs() == "newcommand" ||
3615 t.cs() == "newcommandx" ||
3616 t.cs() == "providecommand" ||
3617 t.cs() == "providecommandx" ||
3618 t.cs() == "renewcommand" ||
3619 t.cs() == "renewcommandx") {
3620 // DeclareRobustCommand, DeclareRobustCommandx,
3621 // providecommand and providecommandx could be handled
3622 // by parse_command(), but we need to call
3623 // add_known_command() here.
3624 string name = t.asInput();
3625 if (p.next_token().asInput() == "*") {
3626 // Starred form. Eat '*'
3630 string const command = p.verbatim_item();
3631 string const opt1 = p.getFullOpt();
3632 string const opt2 = p.getFullOpt();
3633 add_known_command(command, opt1, !opt2.empty());
3634 string const ert = name + '{' + command + '}' +
3636 '{' + p.verbatim_item() + '}';
3638 if (t.cs() == "DeclareRobustCommand" ||
3639 t.cs() == "DeclareRobustCommandx" ||
3640 t.cs() == "providecommand" ||
3641 t.cs() == "providecommandx" ||
3642 name[name.length()-1] == '*')
3643 handle_ert(os, ert, context);
3645 context.check_layout(os);
3646 begin_inset(os, "FormulaMacro");
3652 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3653 // let could be handled by parse_command(),
3654 // but we need to call add_known_command() here.
3655 string ert = t.asInput();
3658 if (p.next_token().cat() == catBegin) {
3659 name = p.verbatim_item();
3660 ert += '{' + name + '}';
3662 name = p.verbatim_item();
3667 if (p.next_token().cat() == catBegin) {
3668 command = p.verbatim_item();
3669 ert += '{' + command + '}';
3671 command = p.verbatim_item();
3674 // If command is known, make name known too, to parse
3675 // its arguments correctly. For this reason we also
3676 // have commands in syntax.default that are hardcoded.
3677 CommandMap::iterator it = known_commands.find(command);
3678 if (it != known_commands.end())
3679 known_commands[t.asInput()] = it->second;
3680 handle_ert(os, ert, context);
3683 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3684 bool starred = false;
3685 if (p.next_token().asInput() == "*") {
3689 string name = t.asInput();
3690 string const length = p.verbatim_item();
3693 bool valid = splitLatexLength(length, valstring, unit);
3694 bool known_hspace = false;
3695 bool known_vspace = false;
3696 bool known_unit = false;
3699 istringstream iss(valstring);
3702 if (t.cs()[0] == 'h') {
3703 if (unit == "\\fill") {
3708 known_hspace = true;
3711 if (unit == "\\smallskipamount") {
3713 known_vspace = true;
3714 } else if (unit == "\\medskipamount") {
3716 known_vspace = true;
3717 } else if (unit == "\\bigskipamount") {
3719 known_vspace = true;
3720 } else if (unit == "\\fill") {
3722 known_vspace = true;
3726 if (!known_hspace && !known_vspace) {
3727 switch (unitFromString(unit)) {
3748 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3749 // Literal horizontal length or known variable
3750 context.check_layout(os);
3751 begin_inset(os, "space ");
3759 if (known_unit && !known_hspace)
3761 << translate_len(length);
3763 } else if (known_unit || known_vspace) {
3764 // Literal vertical length or known variable
3765 context.check_layout(os);
3766 begin_inset(os, "VSpace ");
3774 // LyX can't handle other length variables in Inset VSpace/space
3779 handle_ert(os, name + '{' + unit + '}', context);
3780 else if (value == -1.0)
3781 handle_ert(os, name + "{-" + unit + '}', context);
3783 handle_ert(os, name + '{' + valstring + unit + '}', context);
3785 handle_ert(os, name + '{' + length + '}', context);
3789 // The single '=' is meant here.
3790 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3792 context.check_layout(os);
3793 begin_inset(os, "Flex ");
3794 os << to_utf8(newinsetlayout->name()) << '\n'
3795 << "status collapsed\n";
3796 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3801 // try to see whether the string is in unicodesymbols
3802 // Only use text mode commands, since we are in text mode here,
3803 // and math commands may be invalid (bug 6797)
3805 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3806 rem, Encodings::TEXT_CMD);
3809 cerr << "When parsing " << t.cs()
3810 << ", result is " << to_utf8(s)
3811 << "+" << to_utf8(rem) << endl;
3812 context.check_layout(os);
3814 skip_spaces_braces(p);
3816 //cerr << "#: " << t << " mode: " << mode << endl;
3817 // heuristic: read up to next non-nested space
3819 string s = t.asInput();
3820 string z = p.verbatim_item();
3821 while (p.good() && z != " " && z.size()) {
3822 //cerr << "read: " << z << endl;
3824 z = p.verbatim_item();
3826 cerr << "found ERT: " << s << endl;
3827 handle_ert(os, s + ' ', context);
3830 string name = t.asInput();
3831 if (p.next_token().asInput() == "*") {
3832 // Starred commands like \vspace*{}
3833 p.get_token(); // Eat '*'
3836 if (!parse_command(name, p, os, outer, context))
3837 handle_ert(os, name, context);
3841 if (flags & FLAG_LEAVE) {
3842 flags &= ~FLAG_LEAVE;