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