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 if (latex_width.empty() && inner_type != "makebox"
802 && outer_type != "framebox")
803 latex_width = "1\\columnwidth";
805 translate_len(latex_width, width_value, width_unit);
807 bool shadedparbox = false;
808 if (inner_type == "shaded") {
809 eat_whitespace(p, os, parent_context, false);
810 if (outer_type == "parbox") {
812 if (p.next_token().cat() == catBegin)
814 eat_whitespace(p, os, parent_context, false);
820 // If we already read the inner box we have to push the inner env
821 if (!outer_type.empty() && !inner_type.empty() &&
822 (inner_flags & FLAG_END))
823 active_environments.push_back(inner_type);
824 // LyX can't handle length variables
825 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
826 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
827 // Look whether there is some content after the end of the
828 // inner box, but before the end of the outer box.
829 // If yes, we need to output ERT.
831 if (inner_flags & FLAG_END)
832 p.verbatimEnvironment(inner_type);
836 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
837 if ((outer_env && p.next_token().asInput() != "\\end") ||
838 (!outer_env && p.next_token().cat() != catEnd)) {
839 // something is between the end of the inner box and
840 // the end of the outer box, so we need to use ERT.
845 // if only \makebox{content} was used we can its width to 1\width
846 // because this identic and also identic to \mbox
847 // this doesn't work for \framebox{content}, thus we have to use ERT for this
848 if (latex_width.empty() && inner_type == "makebox") {
851 width_special = "width";
852 } else if (latex_width.empty() && outer_type == "framebox") {
857 if (!outer_type.empty()) {
858 if (outer_flags & FLAG_END)
859 ss << "\\begin{" << outer_type << '}';
861 ss << '\\' << outer_type << '{';
862 if (!special.empty())
866 if (!inner_type.empty()) {
867 if (inner_type != "shaded") {
868 if (inner_flags & FLAG_END)
869 ss << "\\begin{" << inner_type << '}';
871 ss << '\\' << inner_type;
873 if (!position.empty())
874 ss << '[' << position << ']';
875 if (!latex_height.empty())
876 ss << '[' << latex_height << ']';
877 if (!inner_pos.empty())
878 ss << '[' << inner_pos << ']';
879 ss << '{' << latex_width << '}';
880 if (!(inner_flags & FLAG_END))
883 if (inner_type == "shaded")
884 ss << "\\begin{shaded}";
885 handle_ert(os, ss.str(), parent_context);
886 if (!inner_type.empty()) {
887 parse_text(p, os, inner_flags, outer, parent_context);
888 if (inner_flags & FLAG_END)
889 handle_ert(os, "\\end{" + inner_type + '}',
892 handle_ert(os, "}", parent_context);
894 if (!outer_type.empty()) {
895 // If we already read the inner box we have to pop
897 if (!inner_type.empty() && (inner_flags & FLAG_END))
898 active_environments.pop_back();
899 parse_text(p, os, outer_flags, outer, parent_context);
900 if (outer_flags & FLAG_END)
901 handle_ert(os, "\\end{" + outer_type + '}',
903 else if (inner_type.empty() && outer_type == "framebox")
904 // in this case it is already closed later
907 handle_ert(os, "}", parent_context);
910 // LyX does not like empty positions, so we have
911 // to set them to the LaTeX default values here.
912 if (position.empty())
914 if (inner_pos.empty())
915 inner_pos = position;
916 parent_context.check_layout(os);
917 begin_inset(os, "Box ");
918 if (outer_type == "framed")
920 else if (outer_type == "framebox")
922 else if (outer_type == "shadowbox")
924 else if ((outer_type == "shaded" && inner_type.empty()) ||
925 (outer_type == "minipage" && inner_type == "shaded") ||
926 (outer_type == "parbox" && inner_type == "shaded")) {
928 preamble.registerAutomaticallyLoadedPackage("color");
929 } else if (outer_type == "doublebox")
931 else if (outer_type.empty())
934 os << outer_type << '\n';
935 os << "position \"" << position << "\"\n";
936 os << "hor_pos \"" << hor_pos << "\"\n";
937 os << "has_inner_box " << !inner_type.empty() << "\n";
938 os << "inner_pos \"" << inner_pos << "\"\n";
939 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
941 os << "use_makebox " << (inner_type == "makebox") << '\n';
942 os << "width \"" << width_value << width_unit << "\"\n";
943 os << "special \"" << width_special << "\"\n";
944 os << "height \"" << height_value << height_unit << "\"\n";
945 os << "height_special \"" << height_special << "\"\n";
946 os << "status open\n\n";
948 // Unfortunately we can't use parse_text_in_inset:
949 // InsetBox::forcePlainLayout() is hard coded and does not
950 // use the inset layout. Apart from that do we call parse_text
951 // up to two times, but need only one check_end_layout.
952 bool const forcePlainLayout =
953 (!inner_type.empty() || inner_type == "makebox") &&
954 outer_type != "shaded" && outer_type != "framed";
955 Context context(true, parent_context.textclass);
956 if (forcePlainLayout)
957 context.layout = &context.textclass.plainLayout();
959 context.font = parent_context.font;
961 // If we have no inner box the contents will be read with the outer box
962 if (!inner_type.empty())
963 parse_text(p, os, inner_flags, outer, context);
965 // Ensure that the end of the outer box is parsed correctly:
966 // The opening brace has been eaten by parse_outer_box()
967 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
968 outer_flags &= ~FLAG_ITEM;
969 outer_flags |= FLAG_BRACE_LAST;
972 // Find end of outer box, output contents if inner_type is
973 // empty and output possible comments
974 if (!outer_type.empty()) {
975 // If we already read the inner box we have to pop
977 if (!inner_type.empty() && (inner_flags & FLAG_END))
978 active_environments.pop_back();
979 // This does not output anything but comments if
980 // inner_type is not empty (see use_ert)
981 parse_text(p, os, outer_flags, outer, context);
984 context.check_end_layout(os);
986 #ifdef PRESERVE_LAYOUT
987 // LyX puts a % after the end of the minipage
988 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
990 //handle_comment(os, "%dummy", parent_context);
993 parent_context.new_paragraph(os);
995 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
996 //handle_comment(os, "%dummy", parent_context);
999 // We add a protected space if something real follows
1000 if (p.good() && p.next_token().cat() != catComment) {
1001 begin_inset(os, "space ~\n");
1010 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1011 Context & parent_context, string const & outer_type,
1012 string const & special)
1014 eat_whitespace(p, os, parent_context, false);
1015 if (flags & FLAG_ITEM) {
1017 if (p.next_token().cat() == catBegin)
1020 cerr << "Warning: Ignoring missing '{' after \\"
1021 << outer_type << '.' << endl;
1022 eat_whitespace(p, os, parent_context, false);
1025 unsigned int inner_flags = 0;
1027 if (outer_type == "minipage" || outer_type == "parbox") {
1028 p.skip_spaces(true);
1029 while (p.hasOpt()) {
1031 p.skip_spaces(true);
1034 p.skip_spaces(true);
1035 if (outer_type == "parbox") {
1037 if (p.next_token().cat() == catBegin)
1039 p.skip_spaces(true);
1042 if (outer_type == "shaded") {
1043 // These boxes never have an inner box
1045 } else if (p.next_token().asInput() == "\\parbox") {
1046 inner = p.get_token().cs();
1047 inner_flags = FLAG_ITEM;
1048 } else if (p.next_token().asInput() == "\\begin") {
1049 // Is this a minipage or shaded box?
1052 inner = p.getArg('{', '}');
1054 if (inner == "minipage" || inner == "shaded")
1055 inner_flags = FLAG_END;
1060 if (inner_flags == FLAG_END) {
1061 if (inner != "shaded")
1065 eat_whitespace(p, os, parent_context, false);
1067 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1068 outer_type, special, inner);
1070 if (inner_flags == FLAG_ITEM) {
1072 eat_whitespace(p, os, parent_context, false);
1074 parse_box(p, os, flags, inner_flags, outer, parent_context,
1075 outer_type, special, inner);
1080 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1082 parent_context.check_layout(os);
1083 begin_inset(os, "listings\n");
1084 os << "inline false\n"
1085 << "status collapsed\n";
1086 Context context(true, parent_context.textclass);
1087 context.layout = &parent_context.textclass.plainLayout();
1088 context.check_layout(os);
1089 string const s = p.verbatimEnvironment("lstlisting");
1090 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1092 os << "\n\\backslash\n";
1093 else if (*it == '\n') {
1094 // avoid adding an empty paragraph at the end
1096 context.new_paragraph(os);
1097 context.check_layout(os);
1102 context.check_end_layout(os);
1107 /// parse an unknown environment
1108 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1109 unsigned flags, bool outer,
1110 Context & parent_context)
1112 if (name == "tabbing")
1113 // We need to remember that we have to handle '\=' specially
1114 flags |= FLAG_TABBING;
1116 // We need to translate font changes and paragraphs inside the
1117 // environment to ERT if we have a non standard font.
1118 // Otherwise things like
1119 // \large\begin{foo}\huge bar\end{foo}
1121 bool const specialfont =
1122 (parent_context.font != parent_context.normalfont);
1123 bool const new_layout_allowed = parent_context.new_layout_allowed;
1125 parent_context.new_layout_allowed = false;
1126 handle_ert(os, "\\begin{" + name + "}", parent_context);
1127 parse_text_snippet(p, os, flags, outer, parent_context);
1128 handle_ert(os, "\\end{" + name + "}", parent_context);
1130 parent_context.new_layout_allowed = new_layout_allowed;
1134 void parse_environment(Parser & p, ostream & os, bool outer,
1135 string & last_env, bool & title_layout_found,
1136 Context & parent_context)
1138 Layout const * newlayout;
1139 InsetLayout const * newinsetlayout = 0;
1140 string const name = p.getArg('{', '}');
1141 const bool is_starred = suffixIs(name, '*');
1142 string const unstarred_name = rtrim(name, "*");
1143 active_environments.push_back(name);
1145 if (is_math_env(name)) {
1146 parent_context.check_layout(os);
1147 begin_inset(os, "Formula ");
1148 os << "\\begin{" << name << "}";
1149 parse_math(p, os, FLAG_END, MATH_MODE);
1150 os << "\\end{" << name << "}";
1154 else if (name == "tabular" || name == "longtable") {
1155 eat_whitespace(p, os, parent_context, false);
1156 parent_context.check_layout(os);
1157 begin_inset(os, "Tabular ");
1158 handle_tabular(p, os, name == "longtable", parent_context);
1163 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1164 eat_whitespace(p, os, parent_context, false);
1165 parent_context.check_layout(os);
1166 begin_inset(os, "Float " + unstarred_name + "\n");
1167 // store the float type for subfloats
1168 // subfloats only work with figures and tables
1169 if (unstarred_name == "figure")
1170 float_type = unstarred_name;
1171 else if (unstarred_name == "table")
1172 float_type = unstarred_name;
1176 os << "placement " << p.getArg('[', ']') << '\n';
1177 os << "wide " << convert<string>(is_starred)
1178 << "\nsideways false"
1179 << "\nstatus open\n\n";
1180 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1182 // We don't need really a new paragraph, but
1183 // we must make sure that the next item gets a \begin_layout.
1184 parent_context.new_paragraph(os);
1186 // the float is parsed thus delete the type
1190 else if (unstarred_name == "sidewaysfigure"
1191 || unstarred_name == "sidewaystable") {
1192 eat_whitespace(p, os, parent_context, false);
1193 parent_context.check_layout(os);
1194 if (unstarred_name == "sidewaysfigure")
1195 begin_inset(os, "Float figure\n");
1197 begin_inset(os, "Float table\n");
1198 os << "wide " << convert<string>(is_starred)
1199 << "\nsideways true"
1200 << "\nstatus open\n\n";
1201 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1203 // We don't need really a new paragraph, but
1204 // we must make sure that the next item gets a \begin_layout.
1205 parent_context.new_paragraph(os);
1209 else if (name == "wrapfigure" || name == "wraptable") {
1210 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1211 eat_whitespace(p, os, parent_context, false);
1212 parent_context.check_layout(os);
1215 string overhang = "0col%";
1218 lines = p.getArg('[', ']');
1219 string const placement = p.getArg('{', '}');
1221 overhang = p.getArg('[', ']');
1222 string const width = p.getArg('{', '}');
1224 if (name == "wrapfigure")
1225 begin_inset(os, "Wrap figure\n");
1227 begin_inset(os, "Wrap table\n");
1228 os << "lines " << lines
1229 << "\nplacement " << placement
1230 << "\noverhang " << lyx::translate_len(overhang)
1231 << "\nwidth " << lyx::translate_len(width)
1232 << "\nstatus open\n\n";
1233 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1235 // We don't need really a new paragraph, but
1236 // we must make sure that the next item gets a \begin_layout.
1237 parent_context.new_paragraph(os);
1241 else if (name == "minipage") {
1242 eat_whitespace(p, os, parent_context, false);
1243 // Test whether this is an outer box of a shaded box
1245 // swallow arguments
1246 while (p.hasOpt()) {
1248 p.skip_spaces(true);
1251 p.skip_spaces(true);
1252 Token t = p.get_token();
1253 bool shaded = false;
1254 if (t.asInput() == "\\begin") {
1255 p.skip_spaces(true);
1256 if (p.getArg('{', '}') == "shaded")
1261 parse_outer_box(p, os, FLAG_END, outer,
1262 parent_context, name, "shaded");
1264 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1269 else if (name == "comment") {
1270 eat_whitespace(p, os, parent_context, false);
1271 parent_context.check_layout(os);
1272 begin_inset(os, "Note Comment\n");
1273 os << "status open\n";
1274 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1277 skip_braces(p); // eat {} that might by set by LyX behind comments
1280 else if (name == "lyxgreyedout") {
1281 eat_whitespace(p, os, parent_context, false);
1282 parent_context.check_layout(os);
1283 begin_inset(os, "Note Greyedout\n");
1284 os << "status open\n";
1285 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1288 if (!preamble.notefontcolor().empty())
1289 preamble.registerAutomaticallyLoadedPackage("color");
1292 else if (name == "framed" || name == "shaded") {
1293 eat_whitespace(p, os, parent_context, false);
1294 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1298 else if (name == "lstlisting") {
1299 eat_whitespace(p, os, parent_context, false);
1300 // FIXME handle listings with parameters
1301 // If this is added, don't forgot to handle the
1302 // automatic color package loading
1304 parse_unknown_environment(p, name, os, FLAG_END,
1305 outer, parent_context);
1307 parse_listings(p, os, parent_context);
1311 else if (!parent_context.new_layout_allowed)
1312 parse_unknown_environment(p, name, os, FLAG_END, outer,
1315 // Alignment and spacing settings
1316 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1317 // therefore are totally broken!
1318 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1319 // they are commands not environments. They are furthermore switches that
1320 // can be ended by another switches, but also by commands like \footnote or
1321 // \parbox. So the only safe way is to leave them untouched.
1322 else if (name == "center" || name == "centering" ||
1323 name == "flushleft" || name == "flushright" ||
1324 name == "singlespace" || name == "onehalfspace" ||
1325 name == "doublespace" || name == "spacing") {
1326 eat_whitespace(p, os, parent_context, false);
1327 // We must begin a new paragraph if not already done
1328 if (! parent_context.atParagraphStart()) {
1329 parent_context.check_end_layout(os);
1330 parent_context.new_paragraph(os);
1332 if (name == "flushleft")
1333 parent_context.add_extra_stuff("\\align left\n");
1334 else if (name == "flushright")
1335 parent_context.add_extra_stuff("\\align right\n");
1336 else if (name == "center" || name == "centering")
1337 parent_context.add_extra_stuff("\\align center\n");
1338 else if (name == "singlespace")
1339 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1340 else if (name == "onehalfspace")
1341 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1342 else if (name == "doublespace")
1343 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1344 else if (name == "spacing")
1345 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1346 parse_text(p, os, FLAG_END, outer, parent_context);
1347 // Just in case the environment is empty
1348 parent_context.extra_stuff.erase();
1349 // We must begin a new paragraph to reset the alignment
1350 parent_context.new_paragraph(os);
1354 // The single '=' is meant here.
1355 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1356 eat_whitespace(p, os, parent_context, false);
1357 Context context(true, parent_context.textclass, newlayout,
1358 parent_context.layout, parent_context.font);
1359 if (parent_context.deeper_paragraph) {
1360 // We are beginning a nested environment after a
1361 // deeper paragraph inside the outer list environment.
1362 // Therefore we don't need to output a "begin deeper".
1363 context.need_end_deeper = true;
1365 parent_context.check_end_layout(os);
1366 if (last_env == name) {
1367 // we need to output a separator since LyX would export
1368 // the two environments as one otherwise (bug 5716)
1369 docstring const sep = from_ascii("--Separator--");
1370 TeX2LyXDocClass const & textclass(parent_context.textclass);
1371 if (textclass.hasLayout(sep)) {
1372 Context newcontext(parent_context);
1373 newcontext.layout = &(textclass[sep]);
1374 newcontext.check_layout(os);
1375 newcontext.check_end_layout(os);
1377 parent_context.check_layout(os);
1378 begin_inset(os, "Note Note\n");
1379 os << "status closed\n";
1380 Context newcontext(true, textclass,
1381 &(textclass.defaultLayout()));
1382 newcontext.check_layout(os);
1383 newcontext.check_end_layout(os);
1385 parent_context.check_end_layout(os);
1388 switch (context.layout->latextype) {
1389 case LATEX_LIST_ENVIRONMENT:
1390 context.add_par_extra_stuff("\\labelwidthstring "
1391 + p.verbatim_item() + '\n');
1394 case LATEX_BIB_ENVIRONMENT:
1395 p.verbatim_item(); // swallow next arg
1401 context.check_deeper(os);
1402 // handle known optional and required arguments
1403 // layouts require all optional arguments before the required ones
1404 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1405 // It is impossible to place anything after the environment name,
1406 // but before the first \\item.
1407 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1408 bool need_layout = true;
1409 unsigned int optargs = 0;
1410 while (optargs < context.layout->optargs) {
1411 eat_whitespace(p, os, context, false);
1412 if (p.next_token().cat() == catEscape ||
1413 p.next_token().character() != '[')
1415 p.get_token(); // eat '['
1417 context.check_layout(os);
1418 need_layout = false;
1420 begin_inset(os, "Argument\n");
1421 os << "status collapsed\n\n";
1422 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1424 eat_whitespace(p, os, context, false);
1427 unsigned int reqargs = 0;
1428 while (reqargs < context.layout->reqargs) {
1429 eat_whitespace(p, os, context, false);
1430 if (p.next_token().cat() != catBegin)
1432 p.get_token(); // eat '{'
1434 context.check_layout(os);
1435 need_layout = false;
1437 begin_inset(os, "Argument\n");
1438 os << "status collapsed\n\n";
1439 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1441 eat_whitespace(p, os, context, false);
1445 parse_text(p, os, FLAG_END, outer, context);
1446 context.check_end_layout(os);
1447 if (parent_context.deeper_paragraph) {
1448 // We must suppress the "end deeper" because we
1449 // suppressed the "begin deeper" above.
1450 context.need_end_deeper = false;
1452 context.check_end_deeper(os);
1453 parent_context.new_paragraph(os);
1455 if (!title_layout_found)
1456 title_layout_found = newlayout->intitle;
1459 // The single '=' is meant here.
1460 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1461 eat_whitespace(p, os, parent_context, false);
1462 parent_context.check_layout(os);
1463 begin_inset(os, "Flex ");
1464 os << to_utf8(newinsetlayout->name()) << '\n'
1465 << "status collapsed\n";
1466 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1470 else if (name == "appendix") {
1471 // This is no good latex style, but it works and is used in some documents...
1472 eat_whitespace(p, os, parent_context, false);
1473 parent_context.check_end_layout(os);
1474 Context context(true, parent_context.textclass, parent_context.layout,
1475 parent_context.layout, parent_context.font);
1476 context.check_layout(os);
1477 os << "\\start_of_appendix\n";
1478 parse_text(p, os, FLAG_END, outer, context);
1479 context.check_end_layout(os);
1483 else if (known_environments.find(name) != known_environments.end()) {
1484 vector<ArgumentType> arguments = known_environments[name];
1485 // The last "argument" denotes wether we may translate the
1486 // environment contents to LyX
1487 // The default required if no argument is given makes us
1488 // compatible with the reLyXre environment.
1489 ArgumentType contents = arguments.empty() ?
1492 if (!arguments.empty())
1493 arguments.pop_back();
1494 // See comment in parse_unknown_environment()
1495 bool const specialfont =
1496 (parent_context.font != parent_context.normalfont);
1497 bool const new_layout_allowed =
1498 parent_context.new_layout_allowed;
1500 parent_context.new_layout_allowed = false;
1501 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1502 outer, parent_context);
1503 if (contents == verbatim)
1504 handle_ert(os, p.verbatimEnvironment(name),
1507 parse_text_snippet(p, os, FLAG_END, outer,
1509 handle_ert(os, "\\end{" + name + "}", parent_context);
1511 parent_context.new_layout_allowed = new_layout_allowed;
1515 parse_unknown_environment(p, name, os, FLAG_END, outer,
1519 active_environments.pop_back();
1523 /// parses a comment and outputs it to \p os.
1524 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1526 LASSERT(t.cat() == catComment, return);
1527 if (!t.cs().empty()) {
1528 context.check_layout(os);
1529 handle_comment(os, '%' + t.cs(), context);
1530 if (p.next_token().cat() == catNewline) {
1531 // A newline after a comment line starts a new
1533 if (context.new_layout_allowed) {
1534 if(!context.atParagraphStart())
1535 // Only start a new paragraph if not already
1536 // done (we might get called recursively)
1537 context.new_paragraph(os);
1539 handle_ert(os, "\n", context);
1540 eat_whitespace(p, os, context, true);
1543 // "%\n" combination
1550 * Reads spaces and comments until the first non-space, non-comment token.
1551 * New paragraphs (double newlines or \\par) are handled like simple spaces
1552 * if \p eatParagraph is true.
1553 * Spaces are skipped, but comments are written to \p os.
1555 void eat_whitespace(Parser & p, ostream & os, Context & context,
1559 Token const & t = p.get_token();
1560 if (t.cat() == catComment)
1561 parse_comment(p, os, t, context);
1562 else if ((! eatParagraph && p.isParagraph()) ||
1563 (t.cat() != catSpace && t.cat() != catNewline)) {
1572 * Set a font attribute, parse text and reset the font attribute.
1573 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1574 * \param currentvalue Current value of the attribute. Is set to the new
1575 * value during parsing.
1576 * \param newvalue New value of the attribute
1578 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1579 Context & context, string const & attribute,
1580 string & currentvalue, string const & newvalue)
1582 context.check_layout(os);
1583 string const oldvalue = currentvalue;
1584 currentvalue = newvalue;
1585 os << '\n' << attribute << ' ' << newvalue << "\n";
1586 parse_text_snippet(p, os, flags, outer, context);
1587 context.check_layout(os);
1588 os << '\n' << attribute << ' ' << oldvalue << "\n";
1589 currentvalue = oldvalue;
1593 /// get the arguments of a natbib or jurabib citation command
1594 void get_cite_arguments(Parser & p, bool natbibOrder,
1595 string & before, string & after)
1597 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1599 // text before the citation
1601 // text after the citation
1602 after = p.getFullOpt();
1604 if (!after.empty()) {
1605 before = p.getFullOpt();
1606 if (natbibOrder && !before.empty())
1607 swap(before, after);
1612 /// Convert filenames with TeX macros and/or quotes to something LyX
1614 string const normalize_filename(string const & name)
1616 Parser p(trim(name, "\""));
1619 Token const & t = p.get_token();
1620 if (t.cat() != catEscape)
1622 else if (t.cs() == "lyxdot") {
1623 // This is used by LyX for simple dots in relative
1627 } else if (t.cs() == "space") {
1637 /// Convert \p name from TeX convention (relative to master file) to LyX
1638 /// convention (relative to .lyx file) if it is relative
1639 void fix_relative_filename(string & name)
1641 if (FileName::isAbsolute(name))
1644 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1645 from_utf8(getParentFilePath())));
1649 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1650 void parse_noweb(Parser & p, ostream & os, Context & context)
1652 // assemble the rest of the keyword
1656 Token const & t = p.get_token();
1657 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1660 scrap = (p.good() && p.next_token().asInput() == "=");
1662 name += p.get_token().asInput();
1665 name += t.asInput();
1668 if (!scrap || !context.new_layout_allowed ||
1669 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1670 cerr << "Warning: Could not interpret '" << name
1671 << "'. Ignoring it." << endl;
1675 // We use new_paragraph instead of check_end_layout because the stuff
1676 // following the noweb chunk needs to start with a \begin_layout.
1677 // This may create a new paragraph even if there was none in the
1678 // noweb file, but the alternative is an invalid LyX file. Since
1679 // noweb code chunks are implemented with a layout style in LyX they
1680 // always must be in an own paragraph.
1681 context.new_paragraph(os);
1682 Context newcontext(true, context.textclass,
1683 &context.textclass[from_ascii("Scrap")]);
1684 newcontext.check_layout(os);
1687 Token const & t = p.get_token();
1688 // We abuse the parser a bit, because this is no TeX syntax
1690 if (t.cat() == catEscape)
1691 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1694 Context tmp(false, context.textclass,
1695 &context.textclass[from_ascii("Scrap")]);
1696 tmp.need_end_layout = true;
1697 tmp.check_layout(oss);
1698 os << subst(t.asInput(), "\n", oss.str());
1700 // The scrap chunk is ended by an @ at the beginning of a line.
1701 // After the @ the line may contain a comment and/or
1702 // whitespace, but nothing else.
1703 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1704 (p.next_token().cat() == catSpace ||
1705 p.next_token().cat() == catNewline ||
1706 p.next_token().cat() == catComment)) {
1707 while (p.good() && p.next_token().cat() == catSpace)
1708 os << p.get_token().asInput();
1709 if (p.next_token().cat() == catComment)
1710 // The comment includes a final '\n'
1711 os << p.get_token().asInput();
1713 if (p.next_token().cat() == catNewline)
1720 newcontext.check_end_layout(os);
1724 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1725 bool is_macro(Parser & p)
1727 Token first = p.curr_token();
1728 if (first.cat() != catEscape || !p.good())
1730 if (first.cs() == "def")
1732 if (first.cs() != "global" && first.cs() != "long")
1734 Token second = p.get_token();
1736 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1737 second.cat() == catNewline || second.cat() == catComment)) {
1738 second = p.get_token();
1741 bool secondvalid = second.cat() == catEscape;
1743 bool thirdvalid = false;
1744 if (p.good() && first.cs() == "global" && secondvalid &&
1745 second.cs() == "long") {
1746 third = p.get_token();
1748 while (p.good() && !p.isParagraph() &&
1749 (third.cat() == catSpace ||
1750 third.cat() == catNewline ||
1751 third.cat() == catComment)) {
1752 third = p.get_token();
1755 thirdvalid = third.cat() == catEscape;
1757 for (int i = 0; i < pos; ++i)
1762 return (first.cs() == "global" || first.cs() == "long") &&
1763 second.cs() == "def";
1764 return first.cs() == "global" && second.cs() == "long" &&
1765 third.cs() == "def";
1769 /// Parse a macro definition (assumes that is_macro() returned true)
1770 void parse_macro(Parser & p, ostream & os, Context & context)
1772 context.check_layout(os);
1773 Token first = p.curr_token();
1776 string command = first.asInput();
1777 if (first.cs() != "def") {
1779 eat_whitespace(p, os, context, false);
1780 second = p.curr_token();
1781 command += second.asInput();
1782 if (second.cs() != "def") {
1784 eat_whitespace(p, os, context, false);
1785 third = p.curr_token();
1786 command += third.asInput();
1789 eat_whitespace(p, os, context, false);
1790 string const name = p.get_token().cs();
1791 eat_whitespace(p, os, context, false);
1797 while (p.next_token().cat() != catBegin) {
1798 if (p.next_token().cat() == catParameter) {
1803 // followed by number?
1804 if (p.next_token().cat() == catOther) {
1805 char c = p.getChar();
1807 // number = current arity + 1?
1808 if (c == arity + '0' + 1)
1813 paramtext += p.get_token().cs();
1815 paramtext += p.get_token().cs();
1820 // only output simple (i.e. compatible) macro as FormulaMacros
1821 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1823 context.check_layout(os);
1824 begin_inset(os, "FormulaMacro");
1825 os << "\n\\def" << ert;
1828 handle_ert(os, command + ert, context);
1831 } // anonymous namespace
1834 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1837 Layout const * newlayout = 0;
1838 InsetLayout const * newinsetlayout = 0;
1839 // Store the latest bibliographystyle and nocite{*} option
1840 // (needed for bibtex inset)
1842 string bibliographystyle;
1843 bool const use_natbib = preamble.isPackageUsed("natbib");
1844 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1846 bool title_layout_found = false;
1848 Token const & t = p.get_token();
1851 debugToken(cerr, t, flags);
1854 if (flags & FLAG_ITEM) {
1855 if (t.cat() == catSpace)
1858 flags &= ~FLAG_ITEM;
1859 if (t.cat() == catBegin) {
1860 // skip the brace and collect everything to the next matching
1862 flags |= FLAG_BRACE_LAST;
1866 // handle only this single token, leave the loop if done
1867 flags |= FLAG_LEAVE;
1870 if (t.cat() != catEscape && t.character() == ']' &&
1871 (flags & FLAG_BRACK_LAST))
1873 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1876 // If there is anything between \end{env} and \begin{env} we
1877 // don't need to output a separator.
1878 if (t.cat() != catSpace && t.cat() != catNewline &&
1879 t.asInput() != "\\begin")
1885 if (t.cat() == catMath) {
1886 // we are inside some text mode thingy, so opening new math is allowed
1887 context.check_layout(os);
1888 begin_inset(os, "Formula ");
1889 Token const & n = p.get_token();
1890 if (n.cat() == catMath && outer) {
1891 // TeX's $$...$$ syntax for displayed math
1893 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1895 p.get_token(); // skip the second '$' token
1897 // simple $...$ stuff
1900 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1906 else if (t.cat() == catSuper || t.cat() == catSub)
1907 cerr << "catcode " << t << " illegal in text mode\n";
1909 // Basic support for english quotes. This should be
1910 // extended to other quotes, but is not so easy (a
1911 // left english quote is the same as a right german
1913 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1914 context.check_layout(os);
1915 begin_inset(os, "Quotes ");
1921 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1922 context.check_layout(os);
1923 begin_inset(os, "Quotes ");
1930 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1931 context.check_layout(os);
1932 begin_inset(os, "Quotes ");
1939 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1940 context.check_layout(os);
1941 begin_inset(os, "Quotes ");
1948 else if (t.asInput() == "<"
1949 && p.next_token().asInput() == "<" && noweb_mode) {
1951 parse_noweb(p, os, context);
1954 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1955 check_space(p, os, context);
1957 else if (t.character() == '[' && noweb_mode &&
1958 p.next_token().character() == '[') {
1959 // These can contain underscores
1961 string const s = p.getFullOpt() + ']';
1962 if (p.next_token().character() == ']')
1965 cerr << "Warning: Inserting missing ']' in '"
1966 << s << "'." << endl;
1967 handle_ert(os, s, context);
1970 else if (t.cat() == catLetter) {
1971 context.check_layout(os);
1972 // Workaround for bug 4752.
1973 // FIXME: This whole code block needs to be removed
1974 // when the bug is fixed and tex2lyx produces
1975 // the updated file format.
1976 // The replacement algorithm in LyX is so stupid that
1977 // it even translates a phrase if it is part of a word.
1978 bool handled = false;
1979 for (int const * l = known_phrase_lengths; *l; ++l) {
1980 string phrase = t.cs();
1981 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1982 phrase += p.get_token().cs();
1983 if (is_known(phrase, known_coded_phrases)) {
1984 handle_ert(os, phrase, context);
1988 for (size_t i = 1; i < phrase.length(); ++i)
1996 else if (t.cat() == catOther ||
1997 t.cat() == catAlign ||
1998 t.cat() == catParameter) {
1999 // This translates "&" to "\\&" which may be wrong...
2000 context.check_layout(os);
2004 else if (p.isParagraph()) {
2005 if (context.new_layout_allowed)
2006 context.new_paragraph(os);
2008 handle_ert(os, "\\par ", context);
2009 eat_whitespace(p, os, context, true);
2012 else if (t.cat() == catActive) {
2013 context.check_layout(os);
2014 if (t.character() == '~') {
2015 if (context.layout->free_spacing)
2018 begin_inset(os, "space ~\n");
2025 else if (t.cat() == catBegin &&
2026 p.next_token().cat() == catEnd) {
2028 Token const prev = p.prev_token();
2030 if (p.next_token().character() == '`' ||
2031 (prev.character() == '-' &&
2032 p.next_token().character() == '-'))
2033 ; // ignore it in {}`` or -{}-
2035 handle_ert(os, "{}", context);
2039 else if (t.cat() == catBegin) {
2040 context.check_layout(os);
2041 // special handling of font attribute changes
2042 Token const prev = p.prev_token();
2043 Token const next = p.next_token();
2044 TeXFont const oldFont = context.font;
2045 if (next.character() == '[' ||
2046 next.character() == ']' ||
2047 next.character() == '*') {
2049 if (p.next_token().cat() == catEnd) {
2054 handle_ert(os, "{", context);
2055 parse_text_snippet(p, os,
2058 handle_ert(os, "}", context);
2060 } else if (! context.new_layout_allowed) {
2061 handle_ert(os, "{", context);
2062 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2064 handle_ert(os, "}", context);
2065 } else if (is_known(next.cs(), known_sizes)) {
2066 // next will change the size, so we must
2068 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2070 if (!context.atParagraphStart())
2072 << context.font.size << "\n";
2073 } else if (is_known(next.cs(), known_font_families)) {
2074 // next will change the font family, so we
2075 // must reset it here
2076 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2078 if (!context.atParagraphStart())
2080 << context.font.family << "\n";
2081 } else if (is_known(next.cs(), known_font_series)) {
2082 // next will change the font series, so we
2083 // must reset it here
2084 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2086 if (!context.atParagraphStart())
2088 << context.font.series << "\n";
2089 } else if (is_known(next.cs(), known_font_shapes)) {
2090 // next will change the font shape, so we
2091 // must reset it here
2092 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2094 if (!context.atParagraphStart())
2096 << context.font.shape << "\n";
2097 } else if (is_known(next.cs(), known_old_font_families) ||
2098 is_known(next.cs(), known_old_font_series) ||
2099 is_known(next.cs(), known_old_font_shapes)) {
2100 // next will change the font family, series
2101 // and shape, so we must reset it here
2102 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2104 if (!context.atParagraphStart())
2106 << context.font.family
2108 << context.font.series
2110 << context.font.shape << "\n";
2112 handle_ert(os, "{", context);
2113 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2115 handle_ert(os, "}", context);
2119 else if (t.cat() == catEnd) {
2120 if (flags & FLAG_BRACE_LAST) {
2123 cerr << "stray '}' in text\n";
2124 handle_ert(os, "}", context);
2127 else if (t.cat() == catComment)
2128 parse_comment(p, os, t, context);
2131 // control sequences
2134 else if (t.cs() == "(") {
2135 context.check_layout(os);
2136 begin_inset(os, "Formula");
2138 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2143 else if (t.cs() == "[") {
2144 context.check_layout(os);
2145 begin_inset(os, "Formula");
2147 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2152 else if (t.cs() == "begin")
2153 parse_environment(p, os, outer, last_env,
2154 title_layout_found, context);
2156 else if (t.cs() == "end") {
2157 if (flags & FLAG_END) {
2158 // eat environment name
2159 string const name = p.getArg('{', '}');
2160 if (name != active_environment())
2161 cerr << "\\end{" + name + "} does not match \\begin{"
2162 + active_environment() + "}\n";
2165 p.error("found 'end' unexpectedly");
2168 else if (t.cs() == "item") {
2171 bool optarg = false;
2172 if (p.next_token().cat() != catEscape &&
2173 p.next_token().character() == '[') {
2174 p.get_token(); // eat '['
2175 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2180 context.check_layout(os);
2181 if (context.has_item) {
2182 // An item in an unknown list-like environment
2183 // FIXME: Do this in check_layout()!
2184 context.has_item = false;
2186 handle_ert(os, "\\item", context);
2188 handle_ert(os, "\\item ", context);
2191 if (context.layout->labeltype != LABEL_MANUAL) {
2192 // LyX does not support \item[\mybullet]
2193 // in itemize environments
2194 handle_ert(os, "[", context);
2196 handle_ert(os, "]", context);
2197 } else if (!s.empty()) {
2198 // The space is needed to separate the
2199 // item from the rest of the sentence.
2201 eat_whitespace(p, os, context, false);
2206 else if (t.cs() == "bibitem") {
2208 context.check_layout(os);
2209 string label = convert_command_inset_arg(p.getArg('[', ']'));
2210 string key = convert_command_inset_arg(p.verbatim_item());
2211 if (contains(label, '\\') || contains(key, '\\')) {
2212 // LyX can't handle LaTeX commands in labels or keys
2213 handle_ert(os, t.asInput() + '[' + label +
2214 "]{" + p.verbatim_item() + '}',
2217 begin_command_inset(os, "bibitem", "bibitem");
2218 os << "label \"" << label << "\"\n"
2219 "key \"" << key << "\"\n";
2224 else if (is_macro(p))
2225 parse_macro(p, os, context);
2227 else if (t.cs() == "noindent") {
2229 context.add_par_extra_stuff("\\noindent\n");
2232 else if (t.cs() == "appendix") {
2233 context.add_par_extra_stuff("\\start_of_appendix\n");
2234 // We need to start a new paragraph. Otherwise the
2235 // appendix in 'bla\appendix\chapter{' would start
2237 context.new_paragraph(os);
2238 // We need to make sure that the paragraph is
2239 // generated even if it is empty. Otherwise the
2240 // appendix in '\par\appendix\par\chapter{' would
2242 context.check_layout(os);
2243 // FIXME: This is a hack to prevent paragraph
2244 // deletion if it is empty. Handle this better!
2246 "%dummy comment inserted by tex2lyx to "
2247 "ensure that this paragraph is not empty",
2249 // Both measures above may generate an additional
2250 // empty paragraph, but that does not hurt, because
2251 // whitespace does not matter here.
2252 eat_whitespace(p, os, context, true);
2255 // Must catch empty dates before findLayout is called below
2256 else if (t.cs() == "date") {
2257 string const date = p.verbatim_item();
2259 preamble.suppressDate(true);
2261 preamble.suppressDate(false);
2262 if (context.new_layout_allowed &&
2263 (newlayout = findLayout(context.textclass,
2266 output_command_layout(os, p, outer,
2267 context, newlayout);
2269 if (!title_layout_found)
2270 title_layout_found = newlayout->intitle;
2272 handle_ert(os, "\\date{" + date + '}',
2277 // Starred section headings
2278 // Must attempt to parse "Section*" before "Section".
2279 else if ((p.next_token().asInput() == "*") &&
2280 context.new_layout_allowed &&
2281 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2284 output_command_layout(os, p, outer, context, newlayout);
2286 if (!title_layout_found)
2287 title_layout_found = newlayout->intitle;
2290 // Section headings and the like
2291 else if (context.new_layout_allowed &&
2292 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2294 output_command_layout(os, p, outer, context, newlayout);
2296 if (!title_layout_found)
2297 title_layout_found = newlayout->intitle;
2300 else if (t.cs() == "caption") {
2302 context.check_layout(os);
2304 begin_inset(os, "Caption\n");
2305 Context newcontext(true, context.textclass);
2306 newcontext.font = context.font;
2307 newcontext.check_layout(os);
2308 if (p.next_token().cat() != catEscape &&
2309 p.next_token().character() == '[') {
2310 p.get_token(); // eat '['
2311 begin_inset(os, "Argument\n");
2312 os << "status collapsed\n";
2313 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2315 eat_whitespace(p, os, context, false);
2317 parse_text(p, os, FLAG_ITEM, outer, context);
2318 context.check_end_layout(os);
2319 // We don't need really a new paragraph, but
2320 // we must make sure that the next item gets a \begin_layout.
2321 context.new_paragraph(os);
2324 newcontext.check_end_layout(os);
2327 else if (t.cs() == "subfloat") {
2328 // the syntax is \subfloat[caption]{content}
2329 // if it is a table of figure depends on the surrounding float
2330 bool has_caption = false;
2332 // do nothing if there is no outer float
2333 if (!float_type.empty()) {
2334 context.check_layout(os);
2336 begin_inset(os, "Float " + float_type + "\n");
2338 << "\nsideways false"
2339 << "\nstatus collapsed\n\n";
2342 if (p.next_token().cat() != catEscape &&
2343 p.next_token().character() == '[') {
2344 p.get_token(); // eat '['
2345 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2349 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2350 // the caption comes always as the last
2352 // we must make sure that the caption gets a \begin_layout
2353 os << "\n\\begin_layout Plain Layout";
2355 begin_inset(os, "Caption\n");
2356 Context newcontext(true, context.textclass);
2357 newcontext.font = context.font;
2358 newcontext.check_layout(os);
2359 os << caption << "\n";
2360 newcontext.check_end_layout(os);
2361 // We don't need really a new paragraph, but
2362 // we must make sure that the next item gets a \begin_layout.
2363 //newcontext.new_paragraph(os);
2367 // We don't need really a new paragraph, but
2368 // we must make sure that the next item gets a \begin_layout.
2370 context.new_paragraph(os);
2373 context.check_end_layout(os);
2374 // close the layout we opened
2376 os << "\n\\end_layout\n";
2378 // if the float type is not supported or there is no surrounding float
2381 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2382 handle_ert(os, t.asInput() + '[' + opt_arg +
2383 "]{" + p.verbatim_item() + '}', context);
2385 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2389 else if (t.cs() == "includegraphics") {
2390 bool const clip = p.next_token().asInput() == "*";
2393 string const arg = p.getArg('[', ']');
2394 map<string, string> opts;
2395 vector<string> keys;
2396 split_map(arg, opts, keys);
2398 opts["clip"] = string();
2399 string name = normalize_filename(p.verbatim_item());
2401 string const path = getMasterFilePath();
2402 // We want to preserve relative / absolute filenames,
2403 // therefore path is only used for testing
2404 if (!makeAbsPath(name, path).exists()) {
2405 // The file extension is probably missing.
2406 // Now try to find it out.
2407 string const dvips_name =
2408 find_file(name, path,
2409 known_dvips_graphics_formats);
2410 string const pdftex_name =
2411 find_file(name, path,
2412 known_pdftex_graphics_formats);
2413 if (!dvips_name.empty()) {
2414 if (!pdftex_name.empty()) {
2415 cerr << "This file contains the "
2417 "\"\\includegraphics{"
2419 "However, files\n\""
2420 << dvips_name << "\" and\n\""
2421 << pdftex_name << "\"\n"
2422 "both exist, so I had to make a "
2423 "choice and took the first one.\n"
2424 "Please move the unwanted one "
2425 "someplace else and try again\n"
2426 "if my choice was wrong."
2430 } else if (!pdftex_name.empty()) {
2436 if (makeAbsPath(name, path).exists())
2437 fix_relative_filename(name);
2439 cerr << "Warning: Could not find graphics file '"
2440 << name << "'." << endl;
2442 context.check_layout(os);
2443 begin_inset(os, "Graphics ");
2444 os << "\n\tfilename " << name << '\n';
2445 if (opts.find("width") != opts.end())
2447 << translate_len(opts["width"]) << '\n';
2448 if (opts.find("height") != opts.end())
2450 << translate_len(opts["height"]) << '\n';
2451 if (opts.find("scale") != opts.end()) {
2452 istringstream iss(opts["scale"]);
2456 os << "\tscale " << val << '\n';
2458 if (opts.find("angle") != opts.end()) {
2459 os << "\trotateAngle "
2460 << opts["angle"] << '\n';
2461 vector<string>::const_iterator a =
2462 find(keys.begin(), keys.end(), "angle");
2463 vector<string>::const_iterator s =
2464 find(keys.begin(), keys.end(), "width");
2465 if (s == keys.end())
2466 s = find(keys.begin(), keys.end(), "height");
2467 if (s == keys.end())
2468 s = find(keys.begin(), keys.end(), "scale");
2469 if (s != keys.end() && distance(s, a) > 0)
2470 os << "\tscaleBeforeRotation\n";
2472 if (opts.find("origin") != opts.end()) {
2474 string const opt = opts["origin"];
2475 if (opt.find('l') != string::npos) ss << "left";
2476 if (opt.find('r') != string::npos) ss << "right";
2477 if (opt.find('c') != string::npos) ss << "center";
2478 if (opt.find('t') != string::npos) ss << "Top";
2479 if (opt.find('b') != string::npos) ss << "Bottom";
2480 if (opt.find('B') != string::npos) ss << "Baseline";
2481 if (!ss.str().empty())
2482 os << "\trotateOrigin " << ss.str() << '\n';
2484 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2486 if (opts.find("keepaspectratio") != opts.end())
2487 os << "\tkeepAspectRatio\n";
2488 if (opts.find("clip") != opts.end())
2490 if (opts.find("draft") != opts.end())
2492 if (opts.find("bb") != opts.end())
2493 os << "\tBoundingBox "
2494 << opts["bb"] << '\n';
2495 int numberOfbbOptions = 0;
2496 if (opts.find("bbllx") != opts.end())
2497 numberOfbbOptions++;
2498 if (opts.find("bblly") != opts.end())
2499 numberOfbbOptions++;
2500 if (opts.find("bburx") != opts.end())
2501 numberOfbbOptions++;
2502 if (opts.find("bbury") != opts.end())
2503 numberOfbbOptions++;
2504 if (numberOfbbOptions == 4)
2505 os << "\tBoundingBox "
2506 << opts["bbllx"] << " " << opts["bblly"] << " "
2507 << opts["bburx"] << " " << opts["bbury"] << '\n';
2508 else if (numberOfbbOptions > 0)
2509 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2510 numberOfbbOptions = 0;
2511 if (opts.find("natwidth") != opts.end())
2512 numberOfbbOptions++;
2513 if (opts.find("natheight") != opts.end())
2514 numberOfbbOptions++;
2515 if (numberOfbbOptions == 2)
2516 os << "\tBoundingBox 0bp 0bp "
2517 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2518 else if (numberOfbbOptions > 0)
2519 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2520 ostringstream special;
2521 if (opts.find("hiresbb") != opts.end())
2522 special << "hiresbb,";
2523 if (opts.find("trim") != opts.end())
2525 if (opts.find("viewport") != opts.end())
2526 special << "viewport=" << opts["viewport"] << ',';
2527 if (opts.find("totalheight") != opts.end())
2528 special << "totalheight=" << opts["totalheight"] << ',';
2529 if (opts.find("type") != opts.end())
2530 special << "type=" << opts["type"] << ',';
2531 if (opts.find("ext") != opts.end())
2532 special << "ext=" << opts["ext"] << ',';
2533 if (opts.find("read") != opts.end())
2534 special << "read=" << opts["read"] << ',';
2535 if (opts.find("command") != opts.end())
2536 special << "command=" << opts["command"] << ',';
2537 string s_special = special.str();
2538 if (!s_special.empty()) {
2539 // We had special arguments. Remove the trailing ','.
2540 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2542 // TODO: Handle the unknown settings better.
2543 // Warn about invalid options.
2544 // Check whether some option was given twice.
2548 else if (t.cs() == "footnote" ||
2549 (t.cs() == "thanks" && context.layout->intitle)) {
2551 context.check_layout(os);
2552 begin_inset(os, "Foot\n");
2553 os << "status collapsed\n\n";
2554 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2558 else if (t.cs() == "marginpar") {
2560 context.check_layout(os);
2561 begin_inset(os, "Marginal\n");
2562 os << "status collapsed\n\n";
2563 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2567 else if (t.cs() == "ensuremath") {
2569 context.check_layout(os);
2570 string const s = p.verbatim_item();
2571 //FIXME: this never triggers in UTF8
2572 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2575 handle_ert(os, "\\ensuremath{" + s + "}",
2579 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2580 if (title_layout_found) {
2582 skip_spaces_braces(p);
2584 handle_ert(os, t.asInput(), context);
2587 else if (t.cs() == "tableofcontents") {
2588 context.check_layout(os);
2589 begin_command_inset(os, "toc", "tableofcontents");
2591 skip_spaces_braces(p);
2594 else if (t.cs() == "listoffigures") {
2595 context.check_layout(os);
2596 begin_inset(os, "FloatList figure\n");
2598 skip_spaces_braces(p);
2601 else if (t.cs() == "listoftables") {
2602 context.check_layout(os);
2603 begin_inset(os, "FloatList table\n");
2605 skip_spaces_braces(p);
2608 else if (t.cs() == "listof") {
2609 p.skip_spaces(true);
2610 string const name = p.get_token().cs();
2611 if (context.textclass.floats().typeExist(name)) {
2612 context.check_layout(os);
2613 begin_inset(os, "FloatList ");
2616 p.get_token(); // swallow second arg
2618 handle_ert(os, "\\listof{" + name + "}", context);
2621 else if (t.cs() == "textrm")
2622 parse_text_attributes(p, os, FLAG_ITEM, outer,
2623 context, "\\family",
2624 context.font.family, "roman");
2626 else if (t.cs() == "textsf")
2627 parse_text_attributes(p, os, FLAG_ITEM, outer,
2628 context, "\\family",
2629 context.font.family, "sans");
2631 else if (t.cs() == "texttt")
2632 parse_text_attributes(p, os, FLAG_ITEM, outer,
2633 context, "\\family",
2634 context.font.family, "typewriter");
2636 else if (t.cs() == "textmd")
2637 parse_text_attributes(p, os, FLAG_ITEM, outer,
2638 context, "\\series",
2639 context.font.series, "medium");
2641 else if (t.cs() == "textbf")
2642 parse_text_attributes(p, os, FLAG_ITEM, outer,
2643 context, "\\series",
2644 context.font.series, "bold");
2646 else if (t.cs() == "textup")
2647 parse_text_attributes(p, os, FLAG_ITEM, outer,
2649 context.font.shape, "up");
2651 else if (t.cs() == "textit")
2652 parse_text_attributes(p, os, FLAG_ITEM, outer,
2654 context.font.shape, "italic");
2656 else if (t.cs() == "textsl")
2657 parse_text_attributes(p, os, FLAG_ITEM, outer,
2659 context.font.shape, "slanted");
2661 else if (t.cs() == "textsc")
2662 parse_text_attributes(p, os, FLAG_ITEM, outer,
2664 context.font.shape, "smallcaps");
2666 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2667 context.check_layout(os);
2668 TeXFont oldFont = context.font;
2669 context.font.init();
2670 context.font.size = oldFont.size;
2671 os << "\n\\family " << context.font.family << "\n";
2672 os << "\n\\series " << context.font.series << "\n";
2673 os << "\n\\shape " << context.font.shape << "\n";
2674 if (t.cs() == "textnormal") {
2675 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2676 output_font_change(os, context.font, oldFont);
2677 context.font = oldFont;
2679 eat_whitespace(p, os, context, false);
2682 else if (t.cs() == "textcolor") {
2683 // scheme is \textcolor{color name}{text}
2684 string const color = p.verbatim_item();
2685 // we only support the predefined colors of the color package
2686 if (color == "black" || color == "blue" || color == "cyan"
2687 || color == "green" || color == "magenta" || color == "red"
2688 || color == "white" || color == "yellow") {
2689 context.check_layout(os);
2690 os << "\n\\color " << color << "\n";
2691 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2692 context.check_layout(os);
2693 os << "\n\\color inherit\n";
2694 preamble.registerAutomaticallyLoadedPackage("color");
2696 // for custom defined colors
2697 handle_ert(os, t.asInput() + "{" + color + "}", context);
2700 else if (t.cs() == "underbar" || t.cs() == "uline") {
2701 // \underbar is not 100% correct (LyX outputs \uline
2702 // of ulem.sty). The difference is that \ulem allows
2703 // line breaks, and \underbar does not.
2704 // Do NOT handle \underline.
2705 // \underbar cuts through y, g, q, p etc.,
2706 // \underline does not.
2707 context.check_layout(os);
2708 os << "\n\\bar under\n";
2709 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2710 context.check_layout(os);
2711 os << "\n\\bar default\n";
2712 preamble.registerAutomaticallyLoadedPackage("ulem");
2715 else if (t.cs() == "sout") {
2716 context.check_layout(os);
2717 os << "\n\\strikeout on\n";
2718 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2719 context.check_layout(os);
2720 os << "\n\\strikeout default\n";
2721 preamble.registerAutomaticallyLoadedPackage("ulem");
2724 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2725 t.cs() == "emph" || t.cs() == "noun") {
2726 context.check_layout(os);
2727 os << "\n\\" << t.cs() << " on\n";
2728 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2729 context.check_layout(os);
2730 os << "\n\\" << t.cs() << " default\n";
2731 if (t.cs() == "uuline" || t.cs() == "uwave")
2732 preamble.registerAutomaticallyLoadedPackage("ulem");
2735 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2736 context.check_layout(os);
2737 string name = p.getArg('{', '}');
2738 string localtime = p.getArg('{', '}');
2739 preamble.registerAuthor(name);
2740 Author const & author = preamble.getAuthor(name);
2741 // from_ctime() will fail if LyX decides to output the
2742 // time in the text language. It might also use a wrong
2743 // time zone (if the original LyX document was exported
2744 // with a different time zone).
2745 time_t ptime = from_ctime(localtime);
2746 if (ptime == static_cast<time_t>(-1)) {
2747 cerr << "Warning: Could not parse time `" << localtime
2748 << "´ for change tracking, using current time instead.\n";
2749 ptime = current_time();
2751 if (t.cs() == "lyxadded")
2752 os << "\n\\change_inserted ";
2754 os << "\n\\change_deleted ";
2755 os << author.bufferId() << ' ' << ptime << '\n';
2756 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2757 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2758 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2759 LaTeXPackages::isAvailable("xcolor");
2760 // No need to test for luatex, since luatex comes in
2761 // two flavours (dvi and pdf), like latex, and those
2762 // are detected by pdflatex.
2763 if (pdflatex || xetex) {
2765 preamble.registerAutomaticallyLoadedPackage("ulem");
2766 preamble.registerAutomaticallyLoadedPackage("xcolor");
2767 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2771 preamble.registerAutomaticallyLoadedPackage("dvipost");
2772 } else if (xcolorulem) {
2773 preamble.registerAutomaticallyLoadedPackage("ulem");
2774 preamble.registerAutomaticallyLoadedPackage("xcolor");
2779 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2780 t.cs() == "vphantom") {
2781 context.check_layout(os);
2782 if (t.cs() == "phantom")
2783 begin_inset(os, "Phantom Phantom\n");
2784 if (t.cs() == "hphantom")
2785 begin_inset(os, "Phantom HPhantom\n");
2786 if (t.cs() == "vphantom")
2787 begin_inset(os, "Phantom VPhantom\n");
2788 os << "status open\n";
2789 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2794 else if (t.cs() == "href") {
2795 context.check_layout(os);
2796 string target = p.getArg('{', '}');
2797 string name = p.getArg('{', '}');
2799 size_t i = target.find(':');
2800 if (i != string::npos) {
2801 type = target.substr(0, i + 1);
2802 if (type == "mailto:" || type == "file:")
2803 target = target.substr(i + 1);
2804 // handle the case that name is equal to target, except of "http://"
2805 else if (target.substr(i + 3) == name && type == "http:")
2808 begin_command_inset(os, "href", "href");
2810 os << "name \"" << name << "\"\n";
2811 os << "target \"" << target << "\"\n";
2812 if (type == "mailto:" || type == "file:")
2813 os << "type \"" << type << "\"\n";
2815 skip_spaces_braces(p);
2818 else if (t.cs() == "lyxline") {
2819 // swallow size argument (it is not used anyway)
2821 if (!context.atParagraphStart()) {
2822 // so our line is in the middle of a paragraph
2823 // we need to add a new line, lest this line
2824 // follow the other content on that line and
2825 // run off the side of the page
2826 // FIXME: This may create an empty paragraph,
2827 // but without that it would not be
2828 // possible to set noindent below.
2829 // Fortunately LaTeX does not care
2830 // about the empty paragraph.
2831 context.new_paragraph(os);
2833 if (preamble.indentParagraphs()) {
2834 // we need to unindent, lest the line be too long
2835 context.add_par_extra_stuff("\\noindent\n");
2837 context.check_layout(os);
2838 begin_command_inset(os, "line", "rule");
2839 os << "offset \"0.5ex\"\n"
2840 "width \"100line%\"\n"
2845 else if (t.cs() == "rule") {
2846 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2847 string const width = p.getArg('{', '}');
2848 string const thickness = p.getArg('{', '}');
2849 context.check_layout(os);
2850 begin_command_inset(os, "line", "rule");
2851 if (!offset.empty())
2852 os << "offset \"" << translate_len(offset) << "\"\n";
2853 os << "width \"" << translate_len(width) << "\"\n"
2854 "height \"" << translate_len(thickness) << "\"\n";
2858 else if (is_known(t.cs(), known_phrases) ||
2859 (t.cs() == "protect" &&
2860 p.next_token().cat() == catEscape &&
2861 is_known(p.next_token().cs(), known_phrases))) {
2862 // LyX sometimes puts a \protect in front, so we have to ignore it
2863 // FIXME: This needs to be changed when bug 4752 is fixed.
2864 char const * const * where = is_known(
2865 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2867 context.check_layout(os);
2868 os << known_coded_phrases[where - known_phrases];
2869 skip_spaces_braces(p);
2872 else if (is_known(t.cs(), known_ref_commands)) {
2873 string const opt = p.getOpt();
2875 context.check_layout(os);
2876 char const * const * where = is_known(t.cs(),
2877 known_ref_commands);
2878 begin_command_inset(os, "ref",
2879 known_coded_ref_commands[where - known_ref_commands]);
2880 os << "reference \""
2881 << convert_command_inset_arg(p.verbatim_item())
2885 // LyX does not support optional arguments of ref commands
2886 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2887 p.verbatim_item() + "}", context);
2891 else if (use_natbib &&
2892 is_known(t.cs(), known_natbib_commands) &&
2893 ((t.cs() != "citefullauthor" &&
2894 t.cs() != "citeyear" &&
2895 t.cs() != "citeyearpar") ||
2896 p.next_token().asInput() != "*")) {
2897 context.check_layout(os);
2898 string command = t.cs();
2899 if (p.next_token().asInput() == "*") {
2903 if (command == "citefullauthor")
2904 // alternative name for "\\citeauthor*"
2905 command = "citeauthor*";
2907 // text before the citation
2909 // text after the citation
2911 get_cite_arguments(p, true, before, after);
2913 if (command == "cite") {
2914 // \cite without optional argument means
2915 // \citet, \cite with at least one optional
2916 // argument means \citep.
2917 if (before.empty() && after.empty())
2922 if (before.empty() && after == "[]")
2923 // avoid \citet[]{a}
2925 else if (before == "[]" && after == "[]") {
2926 // avoid \citet[][]{a}
2930 // remove the brackets around after and before
2931 if (!after.empty()) {
2933 after.erase(after.length() - 1, 1);
2934 after = convert_command_inset_arg(after);
2936 if (!before.empty()) {
2938 before.erase(before.length() - 1, 1);
2939 before = convert_command_inset_arg(before);
2941 begin_command_inset(os, "citation", command);
2942 os << "after " << '"' << after << '"' << "\n";
2943 os << "before " << '"' << before << '"' << "\n";
2945 << convert_command_inset_arg(p.verbatim_item())
2950 else if (use_jurabib &&
2951 is_known(t.cs(), known_jurabib_commands) &&
2952 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2953 context.check_layout(os);
2954 string command = t.cs();
2955 if (p.next_token().asInput() == "*") {
2959 char argumentOrder = '\0';
2960 vector<string> const options =
2961 preamble.getPackageOptions("jurabib");
2962 if (find(options.begin(), options.end(),
2963 "natbiborder") != options.end())
2964 argumentOrder = 'n';
2965 else if (find(options.begin(), options.end(),
2966 "jurabiborder") != options.end())
2967 argumentOrder = 'j';
2969 // text before the citation
2971 // text after the citation
2973 get_cite_arguments(p, argumentOrder != 'j', before, after);
2975 string const citation = p.verbatim_item();
2976 if (!before.empty() && argumentOrder == '\0') {
2977 cerr << "Warning: Assuming argument order "
2978 "of jurabib version 0.6 for\n'"
2979 << command << before << after << '{'
2980 << citation << "}'.\n"
2981 "Add 'jurabiborder' to the jurabib "
2982 "package options if you used an\n"
2983 "earlier jurabib version." << endl;
2985 if (!after.empty()) {
2987 after.erase(after.length() - 1, 1);
2989 if (!before.empty()) {
2991 before.erase(before.length() - 1, 1);
2993 begin_command_inset(os, "citation", command);
2994 os << "after " << '"' << after << '"' << "\n";
2995 os << "before " << '"' << before << '"' << "\n";
2996 os << "key " << '"' << citation << '"' << "\n";
3000 else if (t.cs() == "cite"
3001 || t.cs() == "nocite") {
3002 context.check_layout(os);
3003 string after = convert_command_inset_arg(p.getArg('[', ']'));
3004 string key = convert_command_inset_arg(p.verbatim_item());
3005 // store the case that it is "\nocite{*}" to use it later for
3008 begin_command_inset(os, "citation", t.cs());
3009 os << "after " << '"' << after << '"' << "\n";
3010 os << "key " << '"' << key << '"' << "\n";
3012 } else if (t.cs() == "nocite")
3016 else if (t.cs() == "index") {
3017 context.check_layout(os);
3018 begin_inset(os, "Index idx\n");
3019 os << "status collapsed\n";
3020 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3024 else if (t.cs() == "nomenclature") {
3025 context.check_layout(os);
3026 begin_command_inset(os, "nomenclature", "nomenclature");
3027 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3028 if (!prefix.empty())
3029 os << "prefix " << '"' << prefix << '"' << "\n";
3030 os << "symbol " << '"'
3031 << convert_command_inset_arg(p.verbatim_item());
3032 os << "\"\ndescription \""
3033 << convert_command_inset_arg(p.verbatim_item())
3038 else if (t.cs() == "label") {
3039 context.check_layout(os);
3040 begin_command_inset(os, "label", "label");
3042 << convert_command_inset_arg(p.verbatim_item())
3047 else if (t.cs() == "printindex") {
3048 context.check_layout(os);
3049 begin_command_inset(os, "index_print", "printindex");
3050 os << "type \"idx\"\n";
3052 skip_spaces_braces(p);
3055 else if (t.cs() == "printnomenclature") {
3057 string width_type = "";
3058 context.check_layout(os);
3059 begin_command_inset(os, "nomencl_print", "printnomenclature");
3060 // case of a custom width
3062 width = p.getArg('[', ']');
3063 width = translate_len(width);
3064 width_type = "custom";
3066 // case of no custom width
3067 // the case of no custom width but the width set
3068 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3069 // because the user could have set anything, not only the width
3070 // of the longest label (which would be width_type = "auto")
3071 string label = convert_command_inset_arg(p.getArg('{', '}'));
3072 if (label.empty() && width_type.empty())
3073 width_type = "none";
3074 os << "set_width \"" << width_type << "\"\n";
3075 if (width_type == "custom")
3076 os << "width \"" << width << '\"';
3078 skip_spaces_braces(p);
3081 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3082 context.check_layout(os);
3083 begin_inset(os, "script ");
3084 os << t.cs().substr(4) << '\n';
3085 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3087 if (t.cs() == "textsubscript")
3088 preamble.registerAutomaticallyLoadedPackage("subscript");
3091 else if (is_known(t.cs(), known_quotes)) {
3092 char const * const * where = is_known(t.cs(), known_quotes);
3093 context.check_layout(os);
3094 begin_inset(os, "Quotes ");
3095 os << known_coded_quotes[where - known_quotes];
3097 // LyX adds {} after the quote, so we have to eat
3098 // spaces here if there are any before a possible
3100 eat_whitespace(p, os, context, false);
3104 else if (is_known(t.cs(), known_sizes) &&
3105 context.new_layout_allowed) {
3106 char const * const * where = is_known(t.cs(), known_sizes);
3107 context.check_layout(os);
3108 TeXFont const oldFont = context.font;
3109 context.font.size = known_coded_sizes[where - known_sizes];
3110 output_font_change(os, oldFont, context.font);
3111 eat_whitespace(p, os, context, false);
3114 else if (is_known(t.cs(), known_font_families) &&
3115 context.new_layout_allowed) {
3116 char const * const * where =
3117 is_known(t.cs(), known_font_families);
3118 context.check_layout(os);
3119 TeXFont const oldFont = context.font;
3120 context.font.family =
3121 known_coded_font_families[where - known_font_families];
3122 output_font_change(os, oldFont, context.font);
3123 eat_whitespace(p, os, context, false);
3126 else if (is_known(t.cs(), known_font_series) &&
3127 context.new_layout_allowed) {
3128 char const * const * where =
3129 is_known(t.cs(), known_font_series);
3130 context.check_layout(os);
3131 TeXFont const oldFont = context.font;
3132 context.font.series =
3133 known_coded_font_series[where - known_font_series];
3134 output_font_change(os, oldFont, context.font);
3135 eat_whitespace(p, os, context, false);
3138 else if (is_known(t.cs(), known_font_shapes) &&
3139 context.new_layout_allowed) {
3140 char const * const * where =
3141 is_known(t.cs(), known_font_shapes);
3142 context.check_layout(os);
3143 TeXFont const oldFont = context.font;
3144 context.font.shape =
3145 known_coded_font_shapes[where - known_font_shapes];
3146 output_font_change(os, oldFont, context.font);
3147 eat_whitespace(p, os, context, false);
3149 else if (is_known(t.cs(), known_old_font_families) &&
3150 context.new_layout_allowed) {
3151 char const * const * where =
3152 is_known(t.cs(), known_old_font_families);
3153 context.check_layout(os);
3154 TeXFont const oldFont = context.font;
3155 context.font.init();
3156 context.font.size = oldFont.size;
3157 context.font.family =
3158 known_coded_font_families[where - known_old_font_families];
3159 output_font_change(os, oldFont, context.font);
3160 eat_whitespace(p, os, context, false);
3163 else if (is_known(t.cs(), known_old_font_series) &&
3164 context.new_layout_allowed) {
3165 char const * const * where =
3166 is_known(t.cs(), known_old_font_series);
3167 context.check_layout(os);
3168 TeXFont const oldFont = context.font;
3169 context.font.init();
3170 context.font.size = oldFont.size;
3171 context.font.series =
3172 known_coded_font_series[where - known_old_font_series];
3173 output_font_change(os, oldFont, context.font);
3174 eat_whitespace(p, os, context, false);
3177 else if (is_known(t.cs(), known_old_font_shapes) &&
3178 context.new_layout_allowed) {
3179 char const * const * where =
3180 is_known(t.cs(), known_old_font_shapes);
3181 context.check_layout(os);
3182 TeXFont const oldFont = context.font;
3183 context.font.init();
3184 context.font.size = oldFont.size;
3185 context.font.shape =
3186 known_coded_font_shapes[where - known_old_font_shapes];
3187 output_font_change(os, oldFont, context.font);
3188 eat_whitespace(p, os, context, false);
3191 else if (t.cs() == "selectlanguage") {
3192 context.check_layout(os);
3193 // save the language for the case that a
3194 // \foreignlanguage is used
3196 context.font.language = babel2lyx(p.verbatim_item());
3197 os << "\n\\lang " << context.font.language << "\n";
3200 else if (t.cs() == "foreignlanguage") {
3201 string const lang = babel2lyx(p.verbatim_item());
3202 parse_text_attributes(p, os, FLAG_ITEM, outer,
3204 context.font.language, lang);
3207 else if (t.cs() == "inputencoding") {
3208 // nothing to write here
3209 string const enc = subst(p.verbatim_item(), "\n", " ");
3213 else if (t.cs() == "ldots") {
3214 context.check_layout(os);
3215 os << "\\SpecialChar \\ldots{}\n";
3216 skip_spaces_braces(p);
3219 else if (t.cs() == "lyxarrow") {
3220 context.check_layout(os);
3221 os << "\\SpecialChar \\menuseparator\n";
3222 skip_spaces_braces(p);
3225 else if (t.cs() == "textcompwordmark") {
3226 context.check_layout(os);
3227 os << "\\SpecialChar \\textcompwordmark{}\n";
3228 skip_spaces_braces(p);
3231 else if (t.cs() == "slash") {
3232 context.check_layout(os);
3233 os << "\\SpecialChar \\slash{}\n";
3234 skip_spaces_braces(p);
3237 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3238 context.check_layout(os);
3239 os << "\\SpecialChar \\nobreakdash-\n";
3243 else if (t.cs() == "textquotedbl") {
3244 context.check_layout(os);
3249 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3250 context.check_layout(os);
3251 os << "\\SpecialChar \\@.\n";
3255 else if (t.cs() == "-") {
3256 context.check_layout(os);
3257 os << "\\SpecialChar \\-\n";
3260 else if (t.cs() == "textasciitilde") {
3261 context.check_layout(os);
3263 skip_spaces_braces(p);
3266 else if (t.cs() == "textasciicircum") {
3267 context.check_layout(os);
3269 skip_spaces_braces(p);
3272 else if (t.cs() == "textbackslash") {
3273 context.check_layout(os);
3274 os << "\n\\backslash\n";
3275 skip_spaces_braces(p);
3278 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3279 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3281 context.check_layout(os);
3285 else if (t.cs() == "char") {
3286 context.check_layout(os);
3287 if (p.next_token().character() == '`') {
3289 if (p.next_token().cs() == "\"") {
3294 handle_ert(os, "\\char`", context);
3297 handle_ert(os, "\\char", context);
3301 else if (t.cs() == "verb") {
3302 context.check_layout(os);
3303 char const delimiter = p.next_token().character();
3304 string const arg = p.getArg(delimiter, delimiter);
3306 oss << "\\verb" << delimiter << arg << delimiter;
3307 handle_ert(os, oss.str(), context);
3310 // Problem: \= creates a tabstop inside the tabbing environment
3311 // and else an accent. In the latter case we really would want
3312 // \={o} instead of \= o.
3313 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3314 handle_ert(os, t.asInput(), context);
3316 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3317 else if (t.cs().size() == 1
3318 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3319 context.check_layout(os);
3320 // try to see whether the string is in unicodesymbols
3322 string command = t.asInput() + "{"
3323 + trimSpaceAndEol(p.verbatim_item())
3325 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3328 cerr << "When parsing " << command
3329 << ", result is " << to_utf8(s)
3330 << "+" << to_utf8(rem) << endl;
3333 // we did not find a non-ert version
3334 handle_ert(os, command, context);
3337 else if (t.cs() == "\\") {
3338 context.check_layout(os);
3340 handle_ert(os, "\\\\" + p.getOpt(), context);
3341 else if (p.next_token().asInput() == "*") {
3343 // getOpt() eats the following space if there
3344 // is no optional argument, but that is OK
3345 // here since it has no effect in the output.
3346 handle_ert(os, "\\\\*" + p.getOpt(), context);
3349 begin_inset(os, "Newline newline");
3354 else if (t.cs() == "newline" ||
3355 (t.cs() == "linebreak" && !p.hasOpt())) {
3356 context.check_layout(os);
3357 begin_inset(os, "Newline ");
3360 skip_spaces_braces(p);
3363 else if (t.cs() == "input" || t.cs() == "include"
3364 || t.cs() == "verbatiminput") {
3365 string name = t.cs();
3366 if (t.cs() == "verbatiminput"
3367 && p.next_token().asInput() == "*")
3368 name += p.get_token().asInput();
3369 context.check_layout(os);
3370 string filename(normalize_filename(p.getArg('{', '}')));
3371 string const path = getMasterFilePath();
3372 // We want to preserve relative / absolute filenames,
3373 // therefore path is only used for testing
3374 if ((t.cs() == "include" || t.cs() == "input") &&
3375 !makeAbsPath(filename, path).exists()) {
3376 // The file extension is probably missing.
3377 // Now try to find it out.
3378 string const tex_name =
3379 find_file(filename, path,
3380 known_tex_extensions);
3381 if (!tex_name.empty())
3382 filename = tex_name;
3384 bool external = false;
3386 if (makeAbsPath(filename, path).exists()) {
3387 string const abstexname =
3388 makeAbsPath(filename, path).absFileName();
3389 string const abslyxname =
3390 changeExtension(abstexname, ".lyx");
3391 string const absfigname =
3392 changeExtension(abstexname, ".fig");
3393 fix_relative_filename(filename);
3394 string const lyxname =
3395 changeExtension(filename, ".lyx");
3397 external = FileName(absfigname).exists();
3398 if (t.cs() == "input") {
3399 string const ext = getExtension(abstexname);
3401 // Combined PS/LaTeX:
3402 // x.eps, x.pstex_t (old xfig)
3403 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3404 FileName const absepsname(
3405 changeExtension(abstexname, ".eps"));
3406 FileName const abspstexname(
3407 changeExtension(abstexname, ".pstex"));
3408 bool const xfigeps =
3409 (absepsname.exists() ||
3410 abspstexname.exists()) &&
3413 // Combined PDF/LaTeX:
3414 // x.pdf, x.pdftex_t (old xfig)
3415 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3416 FileName const abspdfname(
3417 changeExtension(abstexname, ".pdf"));
3418 bool const xfigpdf =
3419 abspdfname.exists() &&
3420 (ext == "pdftex_t" || ext == "pdf_t");
3424 // Combined PS/PDF/LaTeX:
3425 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3426 string const absbase2(
3427 removeExtension(abstexname) + "_pspdftex");
3428 FileName const abseps2name(
3429 addExtension(absbase2, ".eps"));
3430 FileName const abspdf2name(
3431 addExtension(absbase2, ".pdf"));
3432 bool const xfigboth =
3433 abspdf2name.exists() &&
3434 abseps2name.exists() && ext == "pspdftex";
3436 xfig = xfigpdf || xfigeps || xfigboth;
3437 external = external && xfig;
3440 outname = changeExtension(filename, ".fig");
3442 // Don't try to convert, the result
3443 // would be full of ERT.
3445 } else if (t.cs() != "verbatiminput" &&
3446 tex2lyx(abstexname, FileName(abslyxname),
3453 cerr << "Warning: Could not find included file '"
3454 << filename << "'." << endl;
3458 begin_inset(os, "External\n");
3459 os << "\ttemplate XFig\n"
3460 << "\tfilename " << outname << '\n';
3462 begin_command_inset(os, "include", name);
3463 os << "preview false\n"
3464 "filename \"" << outname << "\"\n";
3469 else if (t.cs() == "bibliographystyle") {
3470 // store new bibliographystyle
3471 bibliographystyle = p.verbatim_item();
3472 // If any other command than \bibliography and
3473 // \nocite{*} follows, we need to output the style
3474 // (because it might be used by that command).
3475 // Otherwise, it will automatically be output by LyX.
3478 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3479 if (t2.cat() == catBegin)
3481 if (t2.cat() != catEscape)
3483 if (t2.cs() == "nocite") {
3484 if (p.getArg('{', '}') == "*")
3486 } else if (t2.cs() == "bibliography")
3493 "\\bibliographystyle{" + bibliographystyle + '}',
3498 else if (t.cs() == "bibliography") {
3499 context.check_layout(os);
3500 begin_command_inset(os, "bibtex", "bibtex");
3501 if (!btprint.empty()) {
3502 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3503 // clear the string because the next BibTeX inset can be without the
3504 // \nocite{*} option
3507 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3508 // Do we have a bibliographystyle set?
3509 if (!bibliographystyle.empty())
3510 os << "options " << '"' << bibliographystyle << '"' << "\n";
3514 else if (t.cs() == "parbox") {
3515 // Test whether this is an outer box of a shaded box
3517 // swallow arguments
3518 while (p.hasOpt()) {
3520 p.skip_spaces(true);
3523 p.skip_spaces(true);
3525 if (p.next_token().cat() == catBegin)
3527 p.skip_spaces(true);
3528 Token to = p.get_token();
3529 bool shaded = false;
3530 if (to.asInput() == "\\begin") {
3531 p.skip_spaces(true);
3532 if (p.getArg('{', '}') == "shaded")
3537 parse_outer_box(p, os, FLAG_ITEM, outer,
3538 context, "parbox", "shaded");
3540 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3544 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3545 t.cs() == "shadowbox" || t.cs() == "doublebox")
3546 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3548 else if (t.cs() == "framebox") {
3549 string special = p.getFullOpt();
3550 special += p.getOpt();
3551 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3554 //\makebox() is part of the picture environment and different from \makebox{}
3555 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3556 else if (t.cs() == "makebox") {
3557 string arg = t.asInput();
3558 if (p.next_token().character() == '(') {
3559 //the syntax is: \makebox(x,y)[position]{content}
3560 arg += p.getFullParentheseArg();
3561 arg += p.getFullOpt();
3562 handle_ert(os, arg + p.get_token().asInput(), context);
3564 //the syntax is: \makebox[width][position]{content}
3565 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3569 else if (t.cs() == "smallskip" ||
3570 t.cs() == "medskip" ||
3571 t.cs() == "bigskip" ||
3572 t.cs() == "vfill") {
3573 context.check_layout(os);
3574 begin_inset(os, "VSpace ");
3577 skip_spaces_braces(p);
3580 else if (is_known(t.cs(), known_spaces)) {
3581 char const * const * where = is_known(t.cs(), known_spaces);
3582 context.check_layout(os);
3583 begin_inset(os, "space ");
3584 os << '\\' << known_coded_spaces[where - known_spaces]
3587 // LaTeX swallows whitespace after all spaces except
3588 // "\\,". We have to do that here, too, because LyX
3589 // adds "{}" which would make the spaces significant.
3591 eat_whitespace(p, os, context, false);
3592 // LyX adds "{}" after all spaces except "\\ " and
3593 // "\\,", so we have to remove "{}".
3594 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3595 // remove the braces after "\\,", too.
3600 else if (t.cs() == "newpage" ||
3601 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3602 t.cs() == "clearpage" ||
3603 t.cs() == "cleardoublepage") {
3604 context.check_layout(os);
3605 begin_inset(os, "Newpage ");
3608 skip_spaces_braces(p);
3611 else if (t.cs() == "DeclareRobustCommand" ||
3612 t.cs() == "DeclareRobustCommandx" ||
3613 t.cs() == "newcommand" ||
3614 t.cs() == "newcommandx" ||
3615 t.cs() == "providecommand" ||
3616 t.cs() == "providecommandx" ||
3617 t.cs() == "renewcommand" ||
3618 t.cs() == "renewcommandx") {
3619 // DeclareRobustCommand, DeclareRobustCommandx,
3620 // providecommand and providecommandx could be handled
3621 // by parse_command(), but we need to call
3622 // add_known_command() here.
3623 string name = t.asInput();
3624 if (p.next_token().asInput() == "*") {
3625 // Starred form. Eat '*'
3629 string const command = p.verbatim_item();
3630 string const opt1 = p.getFullOpt();
3631 string const opt2 = p.getFullOpt();
3632 add_known_command(command, opt1, !opt2.empty());
3633 string const ert = name + '{' + command + '}' +
3635 '{' + p.verbatim_item() + '}';
3637 if (t.cs() == "DeclareRobustCommand" ||
3638 t.cs() == "DeclareRobustCommandx" ||
3639 t.cs() == "providecommand" ||
3640 t.cs() == "providecommandx" ||
3641 name[name.length()-1] == '*')
3642 handle_ert(os, ert, context);
3644 context.check_layout(os);
3645 begin_inset(os, "FormulaMacro");
3651 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3652 // let could be handled by parse_command(),
3653 // but we need to call add_known_command() here.
3654 string ert = t.asInput();
3657 if (p.next_token().cat() == catBegin) {
3658 name = p.verbatim_item();
3659 ert += '{' + name + '}';
3661 name = p.verbatim_item();
3666 if (p.next_token().cat() == catBegin) {
3667 command = p.verbatim_item();
3668 ert += '{' + command + '}';
3670 command = p.verbatim_item();
3673 // If command is known, make name known too, to parse
3674 // its arguments correctly. For this reason we also
3675 // have commands in syntax.default that are hardcoded.
3676 CommandMap::iterator it = known_commands.find(command);
3677 if (it != known_commands.end())
3678 known_commands[t.asInput()] = it->second;
3679 handle_ert(os, ert, context);
3682 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3683 bool starred = false;
3684 if (p.next_token().asInput() == "*") {
3688 string name = t.asInput();
3689 string const length = p.verbatim_item();
3692 bool valid = splitLatexLength(length, valstring, unit);
3693 bool known_hspace = false;
3694 bool known_vspace = false;
3695 bool known_unit = false;
3698 istringstream iss(valstring);
3701 if (t.cs()[0] == 'h') {
3702 if (unit == "\\fill") {
3707 known_hspace = true;
3710 if (unit == "\\smallskipamount") {
3712 known_vspace = true;
3713 } else if (unit == "\\medskipamount") {
3715 known_vspace = true;
3716 } else if (unit == "\\bigskipamount") {
3718 known_vspace = true;
3719 } else if (unit == "\\fill") {
3721 known_vspace = true;
3725 if (!known_hspace && !known_vspace) {
3726 switch (unitFromString(unit)) {
3747 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3748 // Literal horizontal length or known variable
3749 context.check_layout(os);
3750 begin_inset(os, "space ");
3758 if (known_unit && !known_hspace)
3760 << translate_len(length);
3762 } else if (known_unit || known_vspace) {
3763 // Literal vertical length or known variable
3764 context.check_layout(os);
3765 begin_inset(os, "VSpace ");
3773 // LyX can't handle other length variables in Inset VSpace/space
3778 handle_ert(os, name + '{' + unit + '}', context);
3779 else if (value == -1.0)
3780 handle_ert(os, name + "{-" + unit + '}', context);
3782 handle_ert(os, name + '{' + valstring + unit + '}', context);
3784 handle_ert(os, name + '{' + length + '}', context);
3788 // The single '=' is meant here.
3789 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3791 context.check_layout(os);
3792 begin_inset(os, "Flex ");
3793 os << to_utf8(newinsetlayout->name()) << '\n'
3794 << "status collapsed\n";
3795 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3800 // try to see whether the string is in unicodesymbols
3801 // Only use text mode commands, since we are in text mode here,
3802 // and math commands may be invalid (bug 6797)
3804 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3805 rem, Encodings::TEXT_CMD);
3808 cerr << "When parsing " << t.cs()
3809 << ", result is " << to_utf8(s)
3810 << "+" << to_utf8(rem) << endl;
3811 context.check_layout(os);
3813 skip_spaces_braces(p);
3815 //cerr << "#: " << t << " mode: " << mode << endl;
3816 // heuristic: read up to next non-nested space
3818 string s = t.asInput();
3819 string z = p.verbatim_item();
3820 while (p.good() && z != " " && z.size()) {
3821 //cerr << "read: " << z << endl;
3823 z = p.verbatim_item();
3825 cerr << "found ERT: " << s << endl;
3826 handle_ert(os, s + ' ', context);
3829 string name = t.asInput();
3830 if (p.next_token().asInput() == "*") {
3831 // Starred commands like \vspace*{}
3832 p.get_token(); // Eat '*'
3835 if (!parse_command(name, p, os, outer, context))
3836 handle_ert(os, name, context);
3840 if (flags & FLAG_LEAVE) {
3841 flags &= ~FLAG_LEAVE;