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 "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49 Context const & context, InsetLayout const * layout)
51 bool const forcePlainLayout =
52 layout ? layout->forcePlainLayout() : false;
53 Context newcontext(true, context.textclass);
55 newcontext.layout = &context.textclass.plainLayout();
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context const & context, string const & name)
68 InsetLayout const * layout = 0;
69 DocumentClass::InsetLayouts::const_iterator it =
70 context.textclass.insetLayouts().find(from_ascii(name));
71 if (it != context.textclass.insetLayouts().end())
72 layout = &(it->second);
73 parse_text_in_inset(p, os, flags, outer, context, layout);
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context newcontext(context);
81 // Don't inherit the paragraph-level extra stuff
82 newcontext.par_extra_stuff.clear();
83 parse_text(p, os, flags, outer, newcontext);
84 // Make sure that we don't create invalid .lyx files
85 context.need_layout = newcontext.need_layout;
86 context.need_end_layout = newcontext.need_end_layout;
91 * Thin wrapper around parse_text_snippet() using a string.
93 * We completely ignore \c context.need_layout and \c context.need_end_layout,
94 * because our return value is not used directly (otherwise the stream version
95 * of parse_text_snippet() could be used). That means that the caller needs
96 * to do layout management manually.
97 * This is intended to parse text that does not create any layout changes.
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
102 Context newcontext(context);
103 newcontext.need_layout = false;
104 newcontext.need_end_layout = false;
105 newcontext.new_layout_allowed = false;
106 // Avoid warning by Context::~Context()
107 newcontext.par_extra_stuff.clear();
109 parse_text_snippet(p, os, flags, outer, newcontext);
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115 "vpageref", "prettyref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "eqref", 0 };
121 * supported CJK encodings
122 * SJIS and Bg5 cannot be supported as they are not
124 * JIS does not work with LyX's encoding conversion
126 const char * const supported_CJK_encodings[] = {
127 "EUC-JP", "KS", "GB", "UTF8", 0};
130 * the same as supported_CJK_encodings with their corresponding LyX language name
131 * please keep this in sync with supported_CJK_encodings line by line!
133 const char * const supported_CJK_languages[] = {
134 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional", 0};
138 * The starred forms are also known except for "citefullauthor",
139 * "citeyear" and "citeyearpar".
141 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
142 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
143 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
147 * No starred form other than "cite*" known.
149 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
150 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
151 // jurabib commands not (yet) supported by LyX:
153 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
154 // "footciteauthor", "footciteyear", "footciteyearpar",
155 "citefield", "citetitle", 0 };
157 /// LaTeX names for quotes
158 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
159 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
160 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
161 "guilsinglleft", "frq", "guilsinglright", 0};
163 /// the same as known_quotes with .lyx names
164 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
165 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
166 "gld", "grd", "gls", "ers", "fls",
167 "fls", "frs", "frs", 0};
169 /// LaTeX names for font sizes
170 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
171 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
173 /// the same as known_sizes with .lyx names
174 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
175 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
177 /// LaTeX 2.09 names for font families
178 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
180 /// LaTeX names for font families
181 char const * const known_font_families[] = { "rmfamily", "sffamily",
184 /// LaTeX names for font family changing commands
185 char const * const known_text_font_families[] = { "textrm", "textsf",
188 /// The same as known_old_font_families, known_font_families and
189 /// known_text_font_families with .lyx names
190 char const * const known_coded_font_families[] = { "roman", "sans",
193 /// LaTeX 2.09 names for font series
194 char const * const known_old_font_series[] = { "bf", 0};
196 /// LaTeX names for font series
197 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
199 /// LaTeX names for font series changing commands
200 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
202 /// The same as known_old_font_series, known_font_series and
203 /// known_text_font_series with .lyx names
204 char const * const known_coded_font_series[] = { "bold", "medium", 0};
206 /// LaTeX 2.09 names for font shapes
207 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
209 /// LaTeX names for font shapes
210 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
213 /// LaTeX names for font shape changing commands
214 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
217 /// The same as known_old_font_shapes, known_font_shapes and
218 /// known_text_font_shapes with .lyx names
219 char const * const known_coded_font_shapes[] = { "italic", "slanted",
220 "smallcaps", "up", 0};
222 /// Known special characters which need skip_spaces_braces() afterwards
223 char const * const known_special_chars[] = {"ldots", "lyxarrow",
224 "textcompwordmark", "slash", 0};
226 /// the same as known_special_chars with .lyx names
227 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
228 "textcompwordmark{}", "slash{}", 0};
231 * Graphics file extensions known by the dvips driver of the graphics package.
232 * These extensions are used to complete the filename of an included
233 * graphics file if it does not contain an extension.
234 * The order must be the same that latex uses to find a file, because we
235 * will use the first extension that matches.
236 * This is only an approximation for the common cases. If we would want to
237 * do it right in all cases, we would need to know which graphics driver is
238 * used and know the extensions of every driver of the graphics package.
240 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
241 "ps.gz", "eps.Z", "ps.Z", 0};
244 * Graphics file extensions known by the pdftex driver of the graphics package.
245 * \sa known_dvips_graphics_formats
247 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
251 * Known file extensions for TeX files as used by \\include.
253 char const * const known_tex_extensions[] = {"tex", 0};
255 /// spaces known by InsetSpace
256 char const * const known_spaces[] = { " ", "space", ",",
257 "thinspace", "quad", "qquad", "enspace", "enskip",
258 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
259 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
260 "upbracefill", "downbracefill", 0};
262 /// the same as known_spaces with .lyx names
263 char const * const known_coded_spaces[] = { "space{}", "space{}",
264 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
265 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
266 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
267 "upbracefill{}", "downbracefill{}", 0};
269 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
270 /// them in ERT. "LaTeXe" must come before "LaTeX"!
271 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
272 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
273 int const known_phrase_lengths[] = {3, 5, 7, 0};
275 // string to store the float type to be able to determine the type of subfloats
276 string float_type = "";
279 /// splits "x=z, y=b" into a map and an ordered keyword vector
280 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
285 keys.resize(v.size());
286 for (size_t i = 0; i < v.size(); ++i) {
287 size_t const pos = v[i].find('=');
288 string const index = trimSpaceAndEol(v[i].substr(0, pos));
289 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
297 * Split a LaTeX length into value and unit.
298 * The latter can be a real unit like "pt", or a latex length variable
299 * like "\textwidth". The unit may contain additional stuff like glue
300 * lengths, but we don't care, because such lengths are ERT anyway.
301 * \returns true if \p value and \p unit are valid.
303 bool splitLatexLength(string const & len, string & value, string & unit)
307 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
308 //'4,5' is a valid LaTeX length number. Change it to '4.5'
309 string const length = subst(len, ',', '.');
310 if (i == string::npos)
313 if (len[0] == '\\') {
314 // We had something like \textwidth without a factor
320 value = trimSpaceAndEol(string(length, 0, i));
324 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
325 if (contains(len, '\\'))
326 unit = trimSpaceAndEol(string(len, i));
328 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
333 /// A simple function to translate a latex length to something LyX can
334 /// understand. Not perfect, but rather best-effort.
335 bool translate_len(string const & length, string & valstring, string & unit)
337 if (!splitLatexLength(length, valstring, unit))
339 // LyX uses percent values
341 istringstream iss(valstring);
346 string const percentval = oss.str();
348 if (unit.empty() || unit[0] != '\\')
350 string::size_type const i = unit.find(' ');
351 string const endlen = (i == string::npos) ? string() : string(unit, i);
352 if (unit == "\\textwidth") {
353 valstring = percentval;
354 unit = "text%" + endlen;
355 } else if (unit == "\\columnwidth") {
356 valstring = percentval;
357 unit = "col%" + endlen;
358 } else if (unit == "\\paperwidth") {
359 valstring = percentval;
360 unit = "page%" + endlen;
361 } else if (unit == "\\linewidth") {
362 valstring = percentval;
363 unit = "line%" + endlen;
364 } else if (unit == "\\paperheight") {
365 valstring = percentval;
366 unit = "pheight%" + endlen;
367 } else if (unit == "\\textheight") {
368 valstring = percentval;
369 unit = "theight%" + endlen;
377 string translate_len(string const & length)
381 if (translate_len(length, value, unit))
383 // If the input is invalid, return what we have.
391 * Translates a LaTeX length into \p value, \p unit and
392 * \p special parts suitable for a box inset.
393 * The difference from translate_len() is that a box inset knows about
394 * some special "units" that are stored in \p special.
396 void translate_box_len(string const & length, string & value, string & unit, string & special)
398 if (translate_len(length, value, unit)) {
399 if (unit == "\\height" || unit == "\\depth" ||
400 unit == "\\totalheight" || unit == "\\width") {
401 special = unit.substr(1);
402 // The unit is not used, but LyX requires a dummy setting
415 * Find a file with basename \p name in path \p path and an extension
418 string find_file(string const & name, string const & path,
419 char const * const * extensions)
421 for (char const * const * what = extensions; *what; ++what) {
422 string const trial = addExtension(name, *what);
423 if (makeAbsPath(trial, path).exists())
430 void begin_inset(ostream & os, string const & name)
432 os << "\n\\begin_inset " << name;
436 void begin_command_inset(ostream & os, string const & name,
437 string const & latexname)
439 begin_inset(os, "CommandInset ");
440 os << name << "\nLatexCommand " << latexname << '\n';
444 void end_inset(ostream & os)
446 os << "\n\\end_inset\n\n";
450 bool skip_braces(Parser & p)
452 if (p.next_token().cat() != catBegin)
455 if (p.next_token().cat() == catEnd) {
464 /// replace LaTeX commands in \p s from the unicodesymbols file with their
466 docstring convert_unicodesymbols(docstring s)
469 for (size_t i = 0; i < s.size();) {
478 docstring parsed = encodings.fromLaTeXCommand(s,
479 Encodings::TEXT_CMD, termination, rem, &req);
480 set<string>::const_iterator it = req.begin();
481 set<string>::const_iterator en = req.end();
482 for (; it != en; ++it)
483 preamble.registerAutomaticallyLoadedPackage(*it);
486 if (s.empty() || s[0] != '\\')
495 /// try to convert \p s to a valid InsetCommand argument
496 string convert_command_inset_arg(string s)
499 // since we don't know the input encoding we can't use from_utf8
500 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
501 // LyX cannot handle newlines in a latex command
502 return subst(s, "\n", " ");
506 void handle_backslash(ostream & os, string const & s)
508 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
510 os << "\n\\backslash\n";
517 void handle_ert(ostream & os, string const & s, Context & context)
519 // We must have a valid layout before outputting the ERT inset.
520 context.check_layout(os);
521 Context newcontext(true, context.textclass);
522 begin_inset(os, "ERT");
523 os << "\nstatus collapsed\n";
524 newcontext.check_layout(os);
525 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
527 os << "\n\\backslash\n";
528 else if (*it == '\n') {
529 newcontext.new_paragraph(os);
530 newcontext.check_layout(os);
534 newcontext.check_end_layout(os);
539 void handle_comment(ostream & os, string const & s, Context & context)
541 // TODO: Handle this better
542 Context newcontext(true, context.textclass);
543 begin_inset(os, "ERT");
544 os << "\nstatus collapsed\n";
545 newcontext.check_layout(os);
546 handle_backslash(os, s);
547 // make sure that our comment is the last thing on the line
548 newcontext.new_paragraph(os);
549 newcontext.check_layout(os);
550 newcontext.check_end_layout(os);
555 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
557 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
560 if (checkModule(name, command))
561 return findLayoutWithoutModule(textclass, name, command);
566 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
568 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
571 if (checkModule(name, command))
572 return findInsetLayoutWithoutModule(textclass, name, command);
577 void eat_whitespace(Parser &, ostream &, Context &, bool);
581 * Skips whitespace and braces.
582 * This should be called after a command has been parsed that is not put into
583 * ERT, and where LyX adds "{}" if needed.
585 void skip_spaces_braces(Parser & p, bool keepws = false)
587 /* The following four examples produce the same typeset output and
588 should be handled by this function:
596 // Unfortunately we need to skip comments, too.
597 // We can't use eat_whitespace since writing them after the {}
598 // results in different output in some cases.
599 bool const skipped_spaces = p.skip_spaces(true);
600 bool const skipped_braces = skip_braces(p);
601 if (keepws && skipped_spaces && !skipped_braces)
602 // put back the space (it is better handled by check_space)
603 p.unskip_spaces(true);
607 void output_command_layout(ostream & os, Parser & p, bool outer,
608 Context & parent_context,
609 Layout const * newlayout)
611 TeXFont const oldFont = parent_context.font;
612 // save the current font size
613 string const size = oldFont.size;
614 // reset the font size to default, because the font size switches
615 // don't affect section headings and the like
616 parent_context.font.size = Context::normalfont.size;
617 // we only need to write the font change if we have an open layout
618 if (!parent_context.atParagraphStart())
619 output_font_change(os, oldFont, parent_context.font);
620 parent_context.check_end_layout(os);
621 Context context(true, parent_context.textclass, newlayout,
622 parent_context.layout, parent_context.font);
623 if (parent_context.deeper_paragraph) {
624 // We are beginning a nested environment after a
625 // deeper paragraph inside the outer list environment.
626 // Therefore we don't need to output a "begin deeper".
627 context.need_end_deeper = true;
629 context.check_deeper(os);
630 context.check_layout(os);
631 // FIXME: Adjust to format 446!
632 // Since format 446, layouts do not require anymore all optional
633 // arguments before the required ones. Needs to be implemented!
635 while (optargs < context.layout->optArgs()) {
636 eat_whitespace(p, os, context, false);
637 if (p.next_token().cat() == catEscape ||
638 p.next_token().character() != '[')
640 p.get_token(); // eat '['
641 // FIXME: Just a workaround. InsetArgument::updateBuffer
642 // will compute a proper ID for all "999" Arguments
643 // (which is also what lyx2lyx produces).
644 // However, tex2lyx should be able to output proper IDs
646 begin_inset(os, "Argument 999\n");
647 os << "status collapsed\n\n";
648 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
650 eat_whitespace(p, os, context, false);
654 while (reqargs < context.layout->requiredArgs()) {
655 eat_whitespace(p, os, context, false);
656 if (p.next_token().cat() != catBegin)
658 p.get_token(); // eat '{'
659 // FIXME: Just a workaround. InsetArgument::updateBuffer
660 // will compute a proper ID for all "999" Arguments
661 // (which is also what lyx2lyx produces).
662 // However, tex2lyx should be able to output proper IDs
664 begin_inset(os, "Argument 999\n");
665 os << "status collapsed\n\n";
666 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
668 eat_whitespace(p, os, context, false);
671 parse_text(p, os, FLAG_ITEM, outer, context);
672 context.check_end_layout(os);
673 if (parent_context.deeper_paragraph) {
674 // We must suppress the "end deeper" because we
675 // suppressed the "begin deeper" above.
676 context.need_end_deeper = false;
678 context.check_end_deeper(os);
679 // We don't need really a new paragraph, but
680 // we must make sure that the next item gets a \begin_layout.
681 parent_context.new_paragraph(os);
682 // Set the font size to the original value. No need to output it here
683 // (Context::begin_layout() will do that if needed)
684 parent_context.font.size = size;
689 * Output a space if necessary.
690 * This function gets called for every whitespace token.
692 * We have three cases here:
693 * 1. A space must be suppressed. Example: The lyxcode case below
694 * 2. A space may be suppressed. Example: Spaces before "\par"
695 * 3. A space must not be suppressed. Example: A space between two words
697 * We currently handle only 1. and 3 and from 2. only the case of
698 * spaces before newlines as a side effect.
700 * 2. could be used to suppress as many spaces as possible. This has two effects:
701 * - Reimporting LyX generated LaTeX files changes almost no whitespace
702 * - Superflous whitespace from non LyX generated LaTeX files is removed.
703 * The drawback is that the logic inside the function becomes
704 * complicated, and that is the reason why it is not implemented.
706 void check_space(Parser & p, ostream & os, Context & context)
708 Token const next = p.next_token();
709 Token const curr = p.curr_token();
710 // A space before a single newline and vice versa must be ignored
711 // LyX emits a newline before \end{lyxcode}.
712 // This newline must be ignored,
713 // otherwise LyX will add an additional protected space.
714 if (next.cat() == catSpace ||
715 next.cat() == catNewline ||
716 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
719 context.check_layout(os);
725 * Parse all arguments of \p command
727 void parse_arguments(string const & command,
728 vector<ArgumentType> const & template_arguments,
729 Parser & p, ostream & os, bool outer, Context & context)
731 string ert = command;
732 size_t no_arguments = template_arguments.size();
733 for (size_t i = 0; i < no_arguments; ++i) {
734 switch (template_arguments[i]) {
737 // This argument contains regular LaTeX
738 handle_ert(os, ert + '{', context);
739 eat_whitespace(p, os, context, false);
740 if (template_arguments[i] == required)
741 parse_text(p, os, FLAG_ITEM, outer, context);
743 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
747 // This argument consists only of a single item.
748 // The presence of '{' or not must be preserved.
750 if (p.next_token().cat() == catBegin)
751 ert += '{' + p.verbatim_item() + '}';
753 ert += p.verbatim_item();
757 // This argument may contain special characters
758 ert += '{' + p.verbatim_item() + '}';
762 // true because we must not eat whitespace
763 // if an optional arg follows we must not strip the
764 // brackets from this one
765 if (i < no_arguments - 1 &&
766 template_arguments[i+1] == optional)
767 ert += p.getFullOpt(true);
769 ert += p.getOpt(true);
773 handle_ert(os, ert, context);
778 * Check whether \p command is a known command. If yes,
779 * handle the command with all arguments.
780 * \return true if the command was parsed, false otherwise.
782 bool parse_command(string const & command, Parser & p, ostream & os,
783 bool outer, Context & context)
785 if (known_commands.find(command) != known_commands.end()) {
786 parse_arguments(command, known_commands[command], p, os,
794 /// Parses a minipage or parbox
795 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
796 unsigned inner_flags, bool outer, Context & parent_context,
797 string const & outer_type, string const & special,
798 string const & inner_type)
802 string hor_pos = "c";
803 // We need to set the height to the LaTeX default of 1\\totalheight
804 // for the case when no height argument is given
805 string height_value = "1";
806 string height_unit = "in";
807 string height_special = "totalheight";
812 string width_special = "none";
813 if (!inner_type.empty() && p.hasOpt()) {
814 if (inner_type != "makebox")
815 position = p.getArg('[', ']');
817 latex_width = p.getArg('[', ']');
818 translate_box_len(latex_width, width_value, width_unit, width_special);
821 if (position != "t" && position != "c" && position != "b") {
822 cerr << "invalid position " << position << " for "
823 << inner_type << endl;
827 if (inner_type != "makebox") {
828 latex_height = p.getArg('[', ']');
829 translate_box_len(latex_height, height_value, height_unit, height_special);
831 string const opt = p.getArg('[', ']');
834 if (hor_pos != "l" && hor_pos != "c" &&
835 hor_pos != "r" && hor_pos != "s") {
836 cerr << "invalid hor_pos " << hor_pos
837 << " for " << inner_type << endl;
844 inner_pos = p.getArg('[', ']');
845 if (inner_pos != "c" && inner_pos != "t" &&
846 inner_pos != "b" && inner_pos != "s") {
847 cerr << "invalid inner_pos "
848 << inner_pos << " for "
849 << inner_type << endl;
850 inner_pos = position;
855 if (inner_type.empty()) {
856 if (special.empty() && outer_type != "framebox")
857 latex_width = "1\\columnwidth";
860 latex_width = p2.getArg('[', ']');
861 string const opt = p2.getArg('[', ']');
864 if (hor_pos != "l" && hor_pos != "c" &&
865 hor_pos != "r" && hor_pos != "s") {
866 cerr << "invalid hor_pos " << hor_pos
867 << " for " << outer_type << endl;
872 } else if (inner_type != "makebox")
873 latex_width = p.verbatim_item();
874 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
875 // as this is LyX's standard for such cases (except for makebox)
876 // \framebox is more special and handled below
877 if (latex_width.empty() && inner_type != "makebox"
878 && outer_type != "framebox")
879 latex_width = "1\\columnwidth";
881 translate_len(latex_width, width_value, width_unit);
883 bool shadedparbox = false;
884 if (inner_type == "shaded") {
885 eat_whitespace(p, os, parent_context, false);
886 if (outer_type == "parbox") {
888 if (p.next_token().cat() == catBegin)
890 eat_whitespace(p, os, parent_context, false);
896 // If we already read the inner box we have to push the inner env
897 if (!outer_type.empty() && !inner_type.empty() &&
898 (inner_flags & FLAG_END))
899 active_environments.push_back(inner_type);
900 // LyX can't handle length variables
901 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
902 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
903 // Look whether there is some content after the end of the
904 // inner box, but before the end of the outer box.
905 // If yes, we need to output ERT.
907 if (inner_flags & FLAG_END)
908 p.verbatimEnvironment(inner_type);
912 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
913 if ((outer_env && p.next_token().asInput() != "\\end") ||
914 (!outer_env && p.next_token().cat() != catEnd)) {
915 // something is between the end of the inner box and
916 // the end of the outer box, so we need to use ERT.
921 // if only \makebox{content} was used we can set its width to 1\width
922 // because this identic and also identic to \mbox
923 // this doesn't work for \framebox{content}, thus we have to use ERT for this
924 if (latex_width.empty() && inner_type == "makebox") {
927 width_special = "width";
928 } else if (latex_width.empty() && outer_type == "framebox") {
933 if (!outer_type.empty()) {
934 if (outer_flags & FLAG_END)
935 ss << "\\begin{" << outer_type << '}';
937 ss << '\\' << outer_type << '{';
938 if (!special.empty())
942 if (!inner_type.empty()) {
943 if (inner_type != "shaded") {
944 if (inner_flags & FLAG_END)
945 ss << "\\begin{" << inner_type << '}';
947 ss << '\\' << inner_type;
949 if (!position.empty())
950 ss << '[' << position << ']';
951 if (!latex_height.empty())
952 ss << '[' << latex_height << ']';
953 if (!inner_pos.empty())
954 ss << '[' << inner_pos << ']';
955 ss << '{' << latex_width << '}';
956 if (!(inner_flags & FLAG_END))
959 if (inner_type == "shaded")
960 ss << "\\begin{shaded}";
961 handle_ert(os, ss.str(), parent_context);
962 if (!inner_type.empty()) {
963 parse_text(p, os, inner_flags, outer, parent_context);
964 if (inner_flags & FLAG_END)
965 handle_ert(os, "\\end{" + inner_type + '}',
968 handle_ert(os, "}", parent_context);
970 if (!outer_type.empty()) {
971 // If we already read the inner box we have to pop
973 if (!inner_type.empty() && (inner_flags & FLAG_END))
974 active_environments.pop_back();
976 // Ensure that the end of the outer box is parsed correctly:
977 // The opening brace has been eaten by parse_outer_box()
978 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
979 outer_flags &= ~FLAG_ITEM;
980 outer_flags |= FLAG_BRACE_LAST;
982 parse_text(p, os, outer_flags, outer, parent_context);
983 if (outer_flags & FLAG_END)
984 handle_ert(os, "\\end{" + outer_type + '}',
986 else if (inner_type.empty() && outer_type == "framebox")
987 // in this case it is already closed later
990 handle_ert(os, "}", parent_context);
993 // LyX does not like empty positions, so we have
994 // to set them to the LaTeX default values here.
995 if (position.empty())
997 if (inner_pos.empty())
998 inner_pos = position;
999 parent_context.check_layout(os);
1000 begin_inset(os, "Box ");
1001 if (outer_type == "framed")
1003 else if (outer_type == "framebox")
1005 else if (outer_type == "shadowbox")
1006 os << "Shadowbox\n";
1007 else if ((outer_type == "shaded" && inner_type.empty()) ||
1008 (outer_type == "minipage" && inner_type == "shaded") ||
1009 (outer_type == "parbox" && inner_type == "shaded")) {
1011 preamble.registerAutomaticallyLoadedPackage("color");
1012 } else if (outer_type == "doublebox")
1013 os << "Doublebox\n";
1014 else if (outer_type.empty())
1015 os << "Frameless\n";
1017 os << outer_type << '\n';
1018 os << "position \"" << position << "\"\n";
1019 os << "hor_pos \"" << hor_pos << "\"\n";
1020 os << "has_inner_box " << !inner_type.empty() << "\n";
1021 os << "inner_pos \"" << inner_pos << "\"\n";
1022 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1024 os << "use_makebox " << (inner_type == "makebox") << '\n';
1025 os << "width \"" << width_value << width_unit << "\"\n";
1026 os << "special \"" << width_special << "\"\n";
1027 os << "height \"" << height_value << height_unit << "\"\n";
1028 os << "height_special \"" << height_special << "\"\n";
1029 os << "status open\n\n";
1031 // Unfortunately we can't use parse_text_in_inset:
1032 // InsetBox::forcePlainLayout() is hard coded and does not
1033 // use the inset layout. Apart from that do we call parse_text
1034 // up to two times, but need only one check_end_layout.
1035 bool const forcePlainLayout =
1036 (!inner_type.empty() || inner_type == "makebox") &&
1037 outer_type != "shaded" && outer_type != "framed";
1038 Context context(true, parent_context.textclass);
1039 if (forcePlainLayout)
1040 context.layout = &context.textclass.plainLayout();
1042 context.font = parent_context.font;
1044 // If we have no inner box the contents will be read with the outer box
1045 if (!inner_type.empty())
1046 parse_text(p, os, inner_flags, outer, context);
1048 // Ensure that the end of the outer box is parsed correctly:
1049 // The opening brace has been eaten by parse_outer_box()
1050 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1051 outer_flags &= ~FLAG_ITEM;
1052 outer_flags |= FLAG_BRACE_LAST;
1055 // Find end of outer box, output contents if inner_type is
1056 // empty and output possible comments
1057 if (!outer_type.empty()) {
1058 // If we already read the inner box we have to pop
1060 if (!inner_type.empty() && (inner_flags & FLAG_END))
1061 active_environments.pop_back();
1062 // This does not output anything but comments if
1063 // inner_type is not empty (see use_ert)
1064 parse_text(p, os, outer_flags, outer, context);
1067 context.check_end_layout(os);
1069 #ifdef PRESERVE_LAYOUT
1070 // LyX puts a % after the end of the minipage
1071 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1073 //handle_comment(os, "%dummy", parent_context);
1076 parent_context.new_paragraph(os);
1078 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1079 //handle_comment(os, "%dummy", parent_context);
1082 // We add a protected space if something real follows
1083 if (p.good() && p.next_token().cat() != catComment) {
1084 begin_inset(os, "space ~\n");
1093 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1094 Context & parent_context, string const & outer_type,
1095 string const & special)
1097 eat_whitespace(p, os, parent_context, false);
1098 if (flags & FLAG_ITEM) {
1100 if (p.next_token().cat() == catBegin)
1103 cerr << "Warning: Ignoring missing '{' after \\"
1104 << outer_type << '.' << endl;
1105 eat_whitespace(p, os, parent_context, false);
1108 unsigned int inner_flags = 0;
1110 if (outer_type == "minipage" || outer_type == "parbox") {
1111 p.skip_spaces(true);
1112 while (p.hasOpt()) {
1114 p.skip_spaces(true);
1117 p.skip_spaces(true);
1118 if (outer_type == "parbox") {
1120 if (p.next_token().cat() == catBegin)
1122 p.skip_spaces(true);
1125 if (outer_type == "shaded") {
1126 // These boxes never have an inner box
1128 } else if (p.next_token().asInput() == "\\parbox") {
1129 inner = p.get_token().cs();
1130 inner_flags = FLAG_ITEM;
1131 } else if (p.next_token().asInput() == "\\begin") {
1132 // Is this a minipage or shaded box?
1135 inner = p.getArg('{', '}');
1137 if (inner == "minipage" || inner == "shaded")
1138 inner_flags = FLAG_END;
1143 if (inner_flags == FLAG_END) {
1144 if (inner != "shaded")
1148 eat_whitespace(p, os, parent_context, false);
1150 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1151 outer_type, special, inner);
1153 if (inner_flags == FLAG_ITEM) {
1155 eat_whitespace(p, os, parent_context, false);
1157 parse_box(p, os, flags, inner_flags, outer, parent_context,
1158 outer_type, special, inner);
1163 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1165 parent_context.check_layout(os);
1166 begin_inset(os, "listings\n");
1168 string arg = p.verbatimOption();
1169 os << "lstparams " << '"' << arg << '"' << '\n';
1170 if (arg.find("\\color") != string::npos)
1171 preamble.registerAutomaticallyLoadedPackage("color");
1174 os << "inline true\n";
1176 os << "inline false\n";
1177 os << "status collapsed\n";
1178 Context context(true, parent_context.textclass);
1179 context.layout = &parent_context.textclass.plainLayout();
1182 s = p.plainCommand('!', '!', "lstinline");
1183 context.new_paragraph(os);
1184 context.check_layout(os);
1186 s = p.plainEnvironment("lstlisting");
1187 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1189 os << "\n\\backslash\n";
1190 else if (*it == '\n') {
1191 // avoid adding an empty paragraph at the end
1193 context.new_paragraph(os);
1194 context.check_layout(os);
1199 context.check_end_layout(os);
1204 /// parse an unknown environment
1205 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1206 unsigned flags, bool outer,
1207 Context & parent_context)
1209 if (name == "tabbing")
1210 // We need to remember that we have to handle '\=' specially
1211 flags |= FLAG_TABBING;
1213 // We need to translate font changes and paragraphs inside the
1214 // environment to ERT if we have a non standard font.
1215 // Otherwise things like
1216 // \large\begin{foo}\huge bar\end{foo}
1218 bool const specialfont =
1219 (parent_context.font != parent_context.normalfont);
1220 bool const new_layout_allowed = parent_context.new_layout_allowed;
1222 parent_context.new_layout_allowed = false;
1223 handle_ert(os, "\\begin{" + name + "}", parent_context);
1224 parse_text_snippet(p, os, flags, outer, parent_context);
1225 handle_ert(os, "\\end{" + name + "}", parent_context);
1227 parent_context.new_layout_allowed = new_layout_allowed;
1231 void parse_environment(Parser & p, ostream & os, bool outer,
1232 string & last_env, Context & parent_context)
1234 Layout const * newlayout;
1235 InsetLayout const * newinsetlayout = 0;
1236 string const name = p.getArg('{', '}');
1237 const bool is_starred = suffixIs(name, '*');
1238 string const unstarred_name = rtrim(name, "*");
1239 active_environments.push_back(name);
1241 if (is_math_env(name)) {
1242 parent_context.check_layout(os);
1243 begin_inset(os, "Formula ");
1244 os << "\\begin{" << name << "}";
1245 parse_math(p, os, FLAG_END, MATH_MODE);
1246 os << "\\end{" << name << "}";
1248 if (is_display_math_env(name)) {
1249 // Prevent the conversion of a line break to a space
1250 // (bug 7668). This does not change the output, but
1251 // looks ugly in LyX.
1252 eat_whitespace(p, os, parent_context, false);
1256 else if (is_known(name, preamble.polyglossia_languages)) {
1257 // We must begin a new paragraph if not already done
1258 if (! parent_context.atParagraphStart()) {
1259 parent_context.check_end_layout(os);
1260 parent_context.new_paragraph(os);
1262 // save the language in the context so that it is
1263 // handled by parse_text
1264 parent_context.font.language = preamble.polyglossia2lyx(name);
1265 parse_text(p, os, FLAG_END, outer, parent_context);
1266 // Just in case the environment is empty
1267 parent_context.extra_stuff.erase();
1268 // We must begin a new paragraph to reset the language
1269 parent_context.new_paragraph(os);
1273 else if (unstarred_name == "tabular" || name == "longtable") {
1274 eat_whitespace(p, os, parent_context, false);
1275 string width = "0pt";
1276 if (name == "tabular*") {
1277 width = lyx::translate_len(p.getArg('{', '}'));
1278 eat_whitespace(p, os, parent_context, false);
1280 parent_context.check_layout(os);
1281 begin_inset(os, "Tabular ");
1282 handle_tabular(p, os, name, width, parent_context);
1287 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1288 eat_whitespace(p, os, parent_context, false);
1289 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1290 eat_whitespace(p, os, parent_context, false);
1291 parent_context.check_layout(os);
1292 begin_inset(os, "Float " + unstarred_name + "\n");
1293 // store the float type for subfloats
1294 // subfloats only work with figures and tables
1295 if (unstarred_name == "figure")
1296 float_type = unstarred_name;
1297 else if (unstarred_name == "table")
1298 float_type = unstarred_name;
1302 os << "placement " << opt << '\n';
1303 if (contains(opt, "H"))
1304 preamble.registerAutomaticallyLoadedPackage("float");
1306 Floating const & fl = parent_context.textclass.floats()
1307 .getType(unstarred_name);
1308 if (!fl.floattype().empty() && fl.usesFloatPkg())
1309 preamble.registerAutomaticallyLoadedPackage("float");
1312 os << "wide " << convert<string>(is_starred)
1313 << "\nsideways false"
1314 << "\nstatus open\n\n";
1315 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1317 // We don't need really a new paragraph, but
1318 // we must make sure that the next item gets a \begin_layout.
1319 parent_context.new_paragraph(os);
1321 // the float is parsed thus delete the type
1325 else if (unstarred_name == "sidewaysfigure"
1326 || unstarred_name == "sidewaystable") {
1327 eat_whitespace(p, os, parent_context, false);
1328 parent_context.check_layout(os);
1329 if (unstarred_name == "sidewaysfigure")
1330 begin_inset(os, "Float figure\n");
1332 begin_inset(os, "Float table\n");
1333 os << "wide " << convert<string>(is_starred)
1334 << "\nsideways true"
1335 << "\nstatus open\n\n";
1336 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1338 // We don't need really a new paragraph, but
1339 // we must make sure that the next item gets a \begin_layout.
1340 parent_context.new_paragraph(os);
1342 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1345 else if (name == "wrapfigure" || name == "wraptable") {
1346 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1347 eat_whitespace(p, os, parent_context, false);
1348 parent_context.check_layout(os);
1351 string overhang = "0col%";
1354 lines = p.getArg('[', ']');
1355 string const placement = p.getArg('{', '}');
1357 overhang = p.getArg('[', ']');
1358 string const width = p.getArg('{', '}');
1360 if (name == "wrapfigure")
1361 begin_inset(os, "Wrap figure\n");
1363 begin_inset(os, "Wrap table\n");
1364 os << "lines " << lines
1365 << "\nplacement " << placement
1366 << "\noverhang " << lyx::translate_len(overhang)
1367 << "\nwidth " << lyx::translate_len(width)
1368 << "\nstatus open\n\n";
1369 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1371 // We don't need really a new paragraph, but
1372 // we must make sure that the next item gets a \begin_layout.
1373 parent_context.new_paragraph(os);
1375 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1378 else if (name == "minipage") {
1379 eat_whitespace(p, os, parent_context, false);
1380 // Test whether this is an outer box of a shaded box
1382 // swallow arguments
1383 while (p.hasOpt()) {
1385 p.skip_spaces(true);
1388 p.skip_spaces(true);
1389 Token t = p.get_token();
1390 bool shaded = false;
1391 if (t.asInput() == "\\begin") {
1392 p.skip_spaces(true);
1393 if (p.getArg('{', '}') == "shaded")
1398 parse_outer_box(p, os, FLAG_END, outer,
1399 parent_context, name, "shaded");
1401 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1406 else if (name == "comment") {
1407 eat_whitespace(p, os, parent_context, false);
1408 parent_context.check_layout(os);
1409 begin_inset(os, "Note Comment\n");
1410 os << "status open\n";
1411 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1414 skip_braces(p); // eat {} that might by set by LyX behind comments
1415 preamble.registerAutomaticallyLoadedPackage("verbatim");
1418 else if (name == "verbatim") {
1419 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1420 string const s = p.plainEnvironment("verbatim");
1421 string::const_iterator it2 = s.begin();
1422 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1424 os << "\\backslash ";
1425 else if (*it == '\n') {
1427 // avoid adding an empty paragraph at the end
1428 // FIXME: if there are 2 consecutive spaces at the end ignore it
1429 // because LyX will re-add a \n
1430 // This hack must be removed once bug 8049 is fixed!
1431 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1432 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1436 os << "\n\\end_layout\n\n";
1438 // reset to Standard layout
1439 os << "\n\\begin_layout Standard\n";
1442 else if (name == "CJK") {
1443 // the scheme is \begin{CJK}{encoding}{mapping}{text}
1444 // It is impossible to decide if a CJK environment was in its own paragraph or within
1445 // a line. We therefore always assume a paragraph since the latter is a rare case.
1446 eat_whitespace(p, os, parent_context, false);
1447 parent_context.check_end_layout(os);
1448 // store the encoding to be able to reset it
1449 string const encoding_old = p.getEncoding();
1450 string const encoding = p.getArg('{', '}');
1451 // SJIS and Bg5 cannot be handled by iconv
1452 // JIS does not work with LyX's encoding conversion
1453 if (encoding != "Bg5" && encoding != "JIS" && encoding != "SJIS")
1454 p.setEncoding(encoding);
1456 p.setEncoding("utf8");
1457 // LyX doesn't support the second argument so if
1458 // this is used we need to output everything as ERT
1459 string const mapping = p.getArg('{', '}');
1460 char const * const * const where =
1461 is_known(encoding, supported_CJK_encodings);
1462 if ((!mapping.empty() && mapping != " ") || !where) {
1463 parent_context.check_layout(os);
1464 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1466 // we must parse the content as verbatim because e.g. JIS can contain
1467 // normally invalid characters
1468 string const s = p.plainEnvironment("CJK");
1469 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1471 handle_ert(os, "\\", parent_context);
1472 else if (*it == '$')
1473 handle_ert(os, "$", parent_context);
1477 handle_ert(os, "\\end{" + name + "}",
1481 supported_CJK_languages[where - supported_CJK_encodings];
1482 // store the language because we must reset it at the end
1483 string const lang_old = parent_context.font.language;
1484 parent_context.font.language = lang;
1485 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1486 parent_context.font.language = lang_old;
1487 parent_context.new_paragraph(os);
1489 p.setEncoding(encoding_old);
1493 else if (name == "lyxgreyedout") {
1494 eat_whitespace(p, os, parent_context, false);
1495 parent_context.check_layout(os);
1496 begin_inset(os, "Note Greyedout\n");
1497 os << "status open\n";
1498 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1501 if (!preamble.notefontcolor().empty())
1502 preamble.registerAutomaticallyLoadedPackage("color");
1505 else if (name == "framed" || name == "shaded") {
1506 eat_whitespace(p, os, parent_context, false);
1507 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1511 else if (name == "lstlisting") {
1512 eat_whitespace(p, os, parent_context, false);
1513 parse_listings(p, os, parent_context, false);
1517 else if (!parent_context.new_layout_allowed)
1518 parse_unknown_environment(p, name, os, FLAG_END, outer,
1521 // Alignment and spacing settings
1522 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1523 // therefore are totally broken!
1524 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1525 // they are commands not environments. They are furthermore switches that
1526 // can be ended by another switches, but also by commands like \footnote or
1527 // \parbox. So the only safe way is to leave them untouched.
1528 else if (name == "center" || name == "centering" ||
1529 name == "flushleft" || name == "flushright" ||
1530 name == "singlespace" || name == "onehalfspace" ||
1531 name == "doublespace" || name == "spacing") {
1532 eat_whitespace(p, os, parent_context, false);
1533 // We must begin a new paragraph if not already done
1534 if (! parent_context.atParagraphStart()) {
1535 parent_context.check_end_layout(os);
1536 parent_context.new_paragraph(os);
1538 if (name == "flushleft")
1539 parent_context.add_extra_stuff("\\align left\n");
1540 else if (name == "flushright")
1541 parent_context.add_extra_stuff("\\align right\n");
1542 else if (name == "center" || name == "centering")
1543 parent_context.add_extra_stuff("\\align center\n");
1544 else if (name == "singlespace")
1545 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1546 else if (name == "onehalfspace") {
1547 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1548 preamble.registerAutomaticallyLoadedPackage("setspace");
1549 } else if (name == "doublespace") {
1550 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1551 preamble.registerAutomaticallyLoadedPackage("setspace");
1552 } else if (name == "spacing") {
1553 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1554 preamble.registerAutomaticallyLoadedPackage("setspace");
1556 parse_text(p, os, FLAG_END, outer, parent_context);
1557 // Just in case the environment is empty
1558 parent_context.extra_stuff.erase();
1559 // We must begin a new paragraph to reset the alignment
1560 parent_context.new_paragraph(os);
1564 // The single '=' is meant here.
1565 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1566 eat_whitespace(p, os, parent_context, false);
1567 Context context(true, parent_context.textclass, newlayout,
1568 parent_context.layout, parent_context.font);
1569 if (parent_context.deeper_paragraph) {
1570 // We are beginning a nested environment after a
1571 // deeper paragraph inside the outer list environment.
1572 // Therefore we don't need to output a "begin deeper".
1573 context.need_end_deeper = true;
1575 parent_context.check_end_layout(os);
1576 if (last_env == name) {
1577 // we need to output a separator since LyX would export
1578 // the two environments as one otherwise (bug 5716)
1579 docstring const sep = from_ascii("--Separator--");
1580 TeX2LyXDocClass const & textclass(parent_context.textclass);
1581 if (textclass.hasLayout(sep)) {
1582 Context newcontext(parent_context);
1583 newcontext.layout = &(textclass[sep]);
1584 newcontext.check_layout(os);
1585 newcontext.check_end_layout(os);
1587 parent_context.check_layout(os);
1588 begin_inset(os, "Note Note\n");
1589 os << "status closed\n";
1590 Context newcontext(true, textclass,
1591 &(textclass.defaultLayout()));
1592 newcontext.check_layout(os);
1593 newcontext.check_end_layout(os);
1595 parent_context.check_end_layout(os);
1598 switch (context.layout->latextype) {
1599 case LATEX_LIST_ENVIRONMENT:
1600 context.add_par_extra_stuff("\\labelwidthstring "
1601 + p.verbatim_item() + '\n');
1604 case LATEX_BIB_ENVIRONMENT:
1605 p.verbatim_item(); // swallow next arg
1611 context.check_deeper(os);
1612 // handle known optional and required arguments
1613 // FIXME: Since format 446, layouts do not require anymore all optional
1614 // arguments before the required ones. Needs to be implemented!
1615 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1616 // It is impossible to place anything after the environment name,
1617 // but before the first \\item.
1618 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1619 bool need_layout = true;
1621 while (optargs < context.layout->optArgs()) {
1622 eat_whitespace(p, os, context, false);
1623 if (p.next_token().cat() == catEscape ||
1624 p.next_token().character() != '[')
1626 p.get_token(); // eat '['
1628 context.check_layout(os);
1629 need_layout = false;
1631 // FIXME: Just a workaround. InsetArgument::updateBuffer
1632 // will compute a proper ID for all "999" Arguments
1633 // (which is also what lyx2lyx produces).
1634 // However, tex2lyx should be able to output proper IDs
1636 begin_inset(os, "Argument 999\n");
1637 os << "status collapsed\n\n";
1638 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1640 eat_whitespace(p, os, context, false);
1644 while (reqargs < context.layout->requiredArgs()) {
1645 eat_whitespace(p, os, context, false);
1646 if (p.next_token().cat() != catBegin)
1648 p.get_token(); // eat '{'
1650 context.check_layout(os);
1651 need_layout = false;
1653 // FIXME: Just a workaround. InsetArgument::updateBuffer
1654 // will compute a proper ID for all "999" Arguments
1655 // (which is also what lyx2lyx produces).
1656 // However, tex2lyx should be able to output proper IDs
1658 begin_inset(os, "Argument 999\n");
1659 os << "status collapsed\n\n";
1660 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1662 eat_whitespace(p, os, context, false);
1666 parse_text(p, os, FLAG_END, outer, context);
1667 context.check_end_layout(os);
1668 if (parent_context.deeper_paragraph) {
1669 // We must suppress the "end deeper" because we
1670 // suppressed the "begin deeper" above.
1671 context.need_end_deeper = false;
1673 context.check_end_deeper(os);
1674 parent_context.new_paragraph(os);
1676 if (!preamble.titleLayoutFound())
1677 preamble.titleLayoutFound(newlayout->intitle);
1678 set<string> const & req = newlayout->requires();
1679 set<string>::const_iterator it = req.begin();
1680 set<string>::const_iterator en = req.end();
1681 for (; it != en; ++it)
1682 preamble.registerAutomaticallyLoadedPackage(*it);
1685 // The single '=' is meant here.
1686 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1687 eat_whitespace(p, os, parent_context, false);
1688 parent_context.check_layout(os);
1689 begin_inset(os, "Flex ");
1690 os << to_utf8(newinsetlayout->name()) << '\n'
1691 << "status collapsed\n";
1692 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1696 else if (name == "appendix") {
1697 // This is no good latex style, but it works and is used in some documents...
1698 eat_whitespace(p, os, parent_context, false);
1699 parent_context.check_end_layout(os);
1700 Context context(true, parent_context.textclass, parent_context.layout,
1701 parent_context.layout, parent_context.font);
1702 context.check_layout(os);
1703 os << "\\start_of_appendix\n";
1704 parse_text(p, os, FLAG_END, outer, context);
1705 context.check_end_layout(os);
1709 else if (known_environments.find(name) != known_environments.end()) {
1710 vector<ArgumentType> arguments = known_environments[name];
1711 // The last "argument" denotes wether we may translate the
1712 // environment contents to LyX
1713 // The default required if no argument is given makes us
1714 // compatible with the reLyXre environment.
1715 ArgumentType contents = arguments.empty() ?
1718 if (!arguments.empty())
1719 arguments.pop_back();
1720 // See comment in parse_unknown_environment()
1721 bool const specialfont =
1722 (parent_context.font != parent_context.normalfont);
1723 bool const new_layout_allowed =
1724 parent_context.new_layout_allowed;
1726 parent_context.new_layout_allowed = false;
1727 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1728 outer, parent_context);
1729 if (contents == verbatim)
1730 handle_ert(os, p.verbatimEnvironment(name),
1733 parse_text_snippet(p, os, FLAG_END, outer,
1735 handle_ert(os, "\\end{" + name + "}", parent_context);
1737 parent_context.new_layout_allowed = new_layout_allowed;
1741 parse_unknown_environment(p, name, os, FLAG_END, outer,
1745 active_environments.pop_back();
1749 /// parses a comment and outputs it to \p os.
1750 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1752 LASSERT(t.cat() == catComment, return);
1753 if (!t.cs().empty()) {
1754 context.check_layout(os);
1755 handle_comment(os, '%' + t.cs(), context);
1756 if (p.next_token().cat() == catNewline) {
1757 // A newline after a comment line starts a new
1759 if (context.new_layout_allowed) {
1760 if(!context.atParagraphStart())
1761 // Only start a new paragraph if not already
1762 // done (we might get called recursively)
1763 context.new_paragraph(os);
1765 handle_ert(os, "\n", context);
1766 eat_whitespace(p, os, context, true);
1769 // "%\n" combination
1776 * Reads spaces and comments until the first non-space, non-comment token.
1777 * New paragraphs (double newlines or \\par) are handled like simple spaces
1778 * if \p eatParagraph is true.
1779 * Spaces are skipped, but comments are written to \p os.
1781 void eat_whitespace(Parser & p, ostream & os, Context & context,
1785 Token const & t = p.get_token();
1786 if (t.cat() == catComment)
1787 parse_comment(p, os, t, context);
1788 else if ((! eatParagraph && p.isParagraph()) ||
1789 (t.cat() != catSpace && t.cat() != catNewline)) {
1798 * Set a font attribute, parse text and reset the font attribute.
1799 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1800 * \param currentvalue Current value of the attribute. Is set to the new
1801 * value during parsing.
1802 * \param newvalue New value of the attribute
1804 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1805 Context & context, string const & attribute,
1806 string & currentvalue, string const & newvalue)
1808 context.check_layout(os);
1809 string const oldvalue = currentvalue;
1810 currentvalue = newvalue;
1811 os << '\n' << attribute << ' ' << newvalue << "\n";
1812 parse_text_snippet(p, os, flags, outer, context);
1813 context.check_layout(os);
1814 os << '\n' << attribute << ' ' << oldvalue << "\n";
1815 currentvalue = oldvalue;
1819 /// get the arguments of a natbib or jurabib citation command
1820 void get_cite_arguments(Parser & p, bool natbibOrder,
1821 string & before, string & after)
1823 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1825 // text before the citation
1827 // text after the citation
1828 after = p.getFullOpt();
1830 if (!after.empty()) {
1831 before = p.getFullOpt();
1832 if (natbibOrder && !before.empty())
1833 swap(before, after);
1838 /// Convert filenames with TeX macros and/or quotes to something LyX
1840 string const normalize_filename(string const & name)
1845 Token const & t = p.get_token();
1846 if (t.cat() != catEscape)
1848 else if (t.cs() == "lyxdot") {
1849 // This is used by LyX for simple dots in relative
1853 } else if (t.cs() == "space") {
1856 } else if (t.cs() == "string") {
1857 // Convert \string" to " and \string~ to ~
1858 Token const & n = p.next_token();
1859 if (n.asInput() != "\"" && n.asInput() != "~")
1864 // Strip quotes. This is a bit complicated (see latex_path()).
1865 string full = os.str();
1866 if (!full.empty() && full[0] == '"') {
1867 string base = removeExtension(full);
1868 string ext = getExtension(full);
1869 if (!base.empty() && base[base.length()-1] == '"')
1872 return addExtension(trim(base, "\""), ext);
1873 if (full[full.length()-1] == '"')
1876 return trim(full, "\"");
1882 /// Convert \p name from TeX convention (relative to master file) to LyX
1883 /// convention (relative to .lyx file) if it is relative
1884 void fix_child_filename(string & name)
1886 string const absMasterTeX = getMasterFilePath(true);
1887 bool const isabs = FileName::isAbsolute(name);
1888 // convert from "relative to .tex master" to absolute original path
1890 name = makeAbsPath(name, absMasterTeX).absFileName();
1891 bool copyfile = copyFiles();
1892 string const absParentLyX = getParentFilePath(false);
1895 // convert from absolute original path to "relative to master file"
1896 string const rel = to_utf8(makeRelPath(from_utf8(name),
1897 from_utf8(absMasterTeX)));
1898 // re-interpret "relative to .tex file" as "relative to .lyx file"
1899 // (is different if the master .lyx file resides in a
1900 // different path than the master .tex file)
1901 string const absMasterLyX = getMasterFilePath(false);
1902 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1903 // Do not copy if the new path is impossible to create. Example:
1904 // absMasterTeX = "/foo/bar/"
1905 // absMasterLyX = "/bar/"
1906 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1907 if (contains(name, "/../"))
1914 // convert from absolute original path to
1915 // "relative to .lyx file"
1916 name = to_utf8(makeRelPath(from_utf8(abs),
1917 from_utf8(absParentLyX)));
1921 // convert from absolute original path to "relative to .lyx file"
1922 name = to_utf8(makeRelPath(from_utf8(name),
1923 from_utf8(absParentLyX)));
1928 void copy_file(FileName const & src, string dstname)
1932 string const absParent = getParentFilePath(false);
1934 if (FileName::isAbsolute(dstname))
1935 dst = FileName(dstname);
1937 dst = makeAbsPath(dstname, absParent);
1938 string const absMaster = getMasterFilePath(false);
1939 FileName const srcpath = src.onlyPath();
1940 FileName const dstpath = dst.onlyPath();
1941 if (equivalent(srcpath, dstpath))
1943 if (!dstpath.isDirectory()) {
1944 if (!dstpath.createPath()) {
1945 cerr << "Warning: Could not create directory for file `"
1946 << dst.absFileName() << "´." << endl;
1950 if (dst.isReadableFile()) {
1951 if (overwriteFiles())
1952 cerr << "Warning: Overwriting existing file `"
1953 << dst.absFileName() << "´." << endl;
1955 cerr << "Warning: Not overwriting existing file `"
1956 << dst.absFileName() << "´." << endl;
1960 if (!src.copyTo(dst))
1961 cerr << "Warning: Could not copy file `" << src.absFileName()
1962 << "´ to `" << dst.absFileName() << "´." << endl;
1966 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1967 void parse_noweb(Parser & p, ostream & os, Context & context)
1969 // assemble the rest of the keyword
1973 Token const & t = p.get_token();
1974 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1977 chunk = (p.good() && p.next_token().asInput() == "=");
1979 name += p.get_token().asInput();
1982 name += t.asInput();
1985 if (!chunk || !context.new_layout_allowed ||
1986 !context.textclass.hasLayout(from_ascii("Chunk"))) {
1987 cerr << "Warning: Could not interpret '" << name
1988 << "'. Ignoring it." << endl;
1992 // We use new_paragraph instead of check_end_layout because the stuff
1993 // following the noweb chunk needs to start with a \begin_layout.
1994 // This may create a new paragraph even if there was none in the
1995 // noweb file, but the alternative is an invalid LyX file. Since
1996 // noweb code chunks are implemented with a layout style in LyX they
1997 // always must be in an own paragraph.
1998 context.new_paragraph(os);
1999 Context newcontext(true, context.textclass,
2000 &context.textclass[from_ascii("Chunk")]);
2001 newcontext.check_layout(os);
2004 Token const & t = p.get_token();
2005 // We abuse the parser a bit, because this is no TeX syntax
2007 if (t.cat() == catEscape)
2008 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2011 Context tmp(false, context.textclass,
2012 &context.textclass[from_ascii("Chunk")]);
2013 tmp.need_end_layout = true;
2014 tmp.check_layout(oss);
2015 os << subst(t.asInput(), "\n", oss.str());
2017 // The chunk is ended by an @ at the beginning of a line.
2018 // After the @ the line may contain a comment and/or
2019 // whitespace, but nothing else.
2020 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2021 (p.next_token().cat() == catSpace ||
2022 p.next_token().cat() == catNewline ||
2023 p.next_token().cat() == catComment)) {
2024 while (p.good() && p.next_token().cat() == catSpace)
2025 os << p.get_token().asInput();
2026 if (p.next_token().cat() == catComment)
2027 // The comment includes a final '\n'
2028 os << p.get_token().asInput();
2030 if (p.next_token().cat() == catNewline)
2037 newcontext.check_end_layout(os);
2041 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2042 bool is_macro(Parser & p)
2044 Token first = p.curr_token();
2045 if (first.cat() != catEscape || !p.good())
2047 if (first.cs() == "def")
2049 if (first.cs() != "global" && first.cs() != "long")
2051 Token second = p.get_token();
2053 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2054 second.cat() == catNewline || second.cat() == catComment)) {
2055 second = p.get_token();
2058 bool secondvalid = second.cat() == catEscape;
2060 bool thirdvalid = false;
2061 if (p.good() && first.cs() == "global" && secondvalid &&
2062 second.cs() == "long") {
2063 third = p.get_token();
2065 while (p.good() && !p.isParagraph() &&
2066 (third.cat() == catSpace ||
2067 third.cat() == catNewline ||
2068 third.cat() == catComment)) {
2069 third = p.get_token();
2072 thirdvalid = third.cat() == catEscape;
2074 for (int i = 0; i < pos; ++i)
2079 return (first.cs() == "global" || first.cs() == "long") &&
2080 second.cs() == "def";
2081 return first.cs() == "global" && second.cs() == "long" &&
2082 third.cs() == "def";
2086 /// Parse a macro definition (assumes that is_macro() returned true)
2087 void parse_macro(Parser & p, ostream & os, Context & context)
2089 context.check_layout(os);
2090 Token first = p.curr_token();
2093 string command = first.asInput();
2094 if (first.cs() != "def") {
2096 eat_whitespace(p, os, context, false);
2097 second = p.curr_token();
2098 command += second.asInput();
2099 if (second.cs() != "def") {
2101 eat_whitespace(p, os, context, false);
2102 third = p.curr_token();
2103 command += third.asInput();
2106 eat_whitespace(p, os, context, false);
2107 string const name = p.get_token().cs();
2108 eat_whitespace(p, os, context, false);
2114 while (p.next_token().cat() != catBegin) {
2115 if (p.next_token().cat() == catParameter) {
2120 // followed by number?
2121 if (p.next_token().cat() == catOther) {
2122 char c = p.getChar();
2124 // number = current arity + 1?
2125 if (c == arity + '0' + 1)
2130 paramtext += p.get_token().cs();
2132 paramtext += p.get_token().cs();
2137 // only output simple (i.e. compatible) macro as FormulaMacros
2138 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2140 context.check_layout(os);
2141 begin_inset(os, "FormulaMacro");
2142 os << "\n\\def" << ert;
2145 handle_ert(os, command + ert, context);
2149 void registerExternalTemplatePackages(string const & name)
2151 external::TemplateManager const & etm = external::TemplateManager::get();
2152 external::Template const * const et = etm.getTemplateByName(name);
2155 external::Template::Formats::const_iterator cit = et->formats.end();
2157 cit = et->formats.find("PDFLaTeX");
2158 if (cit == et->formats.end())
2159 // If the template has not specified a PDFLaTeX output,
2160 // we try the LaTeX format.
2161 cit = et->formats.find("LaTeX");
2162 if (cit == et->formats.end())
2164 vector<string>::const_iterator qit = cit->second.requirements.begin();
2165 vector<string>::const_iterator qend = cit->second.requirements.end();
2166 for (; qit != qend; ++qit)
2167 preamble.registerAutomaticallyLoadedPackage(*qit);
2170 } // anonymous namespace
2173 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2176 Layout const * newlayout = 0;
2177 InsetLayout const * newinsetlayout = 0;
2178 char const * const * where = 0;
2179 // Store the latest bibliographystyle and nocite{*} option
2180 // (needed for bibtex inset)
2182 string bibliographystyle = "default";
2183 bool const use_natbib = isProvided("natbib");
2184 bool const use_jurabib = isProvided("jurabib");
2187 Token const & t = p.get_token();
2189 // it is impossible to determine the correct encoding for non-CJK Japanese.
2190 // Therefore write a note at the beginning of the document
2191 if (is_nonCJKJapanese) {
2192 context.check_layout(os);
2193 begin_inset(os, "Note Note\n");
2194 os << "status open\n\\begin_layout Plain Layout\n"
2195 << "\\series bold\n"
2196 << "Important information:\n"
2197 << "\\end_layout\n\n"
2198 << "\\begin_layout Plain Layout\n"
2199 << "This document is in Japanese (non-CJK).\n"
2200 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2201 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2202 << " encoding in the document settings.\n"
2203 << "\\end_layout\n";
2205 is_nonCJKJapanese = false;
2209 debugToken(cerr, t, flags);
2212 if (flags & FLAG_ITEM) {
2213 if (t.cat() == catSpace)
2216 flags &= ~FLAG_ITEM;
2217 if (t.cat() == catBegin) {
2218 // skip the brace and collect everything to the next matching
2220 flags |= FLAG_BRACE_LAST;
2224 // handle only this single token, leave the loop if done
2225 flags |= FLAG_LEAVE;
2228 if (t.cat() != catEscape && t.character() == ']' &&
2229 (flags & FLAG_BRACK_LAST))
2231 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2234 // If there is anything between \end{env} and \begin{env} we
2235 // don't need to output a separator.
2236 if (t.cat() != catSpace && t.cat() != catNewline &&
2237 t.asInput() != "\\begin")
2243 if (t.cat() == catMath) {
2244 // we are inside some text mode thingy, so opening new math is allowed
2245 context.check_layout(os);
2246 begin_inset(os, "Formula ");
2247 Token const & n = p.get_token();
2248 bool const display(n.cat() == catMath && outer);
2250 // TeX's $$...$$ syntax for displayed math
2252 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2254 p.get_token(); // skip the second '$' token
2256 // simple $...$ stuff
2259 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2264 // Prevent the conversion of a line break to a
2265 // space (bug 7668). This does not change the
2266 // output, but looks ugly in LyX.
2267 eat_whitespace(p, os, context, false);
2271 else if (t.cat() == catSuper || t.cat() == catSub)
2272 cerr << "catcode " << t << " illegal in text mode\n";
2274 // Basic support for english quotes. This should be
2275 // extended to other quotes, but is not so easy (a
2276 // left english quote is the same as a right german
2278 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2279 context.check_layout(os);
2280 begin_inset(os, "Quotes ");
2286 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2287 context.check_layout(os);
2288 begin_inset(os, "Quotes ");
2295 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2296 context.check_layout(os);
2297 begin_inset(os, "Quotes ");
2304 else if (t.asInput() == "<"
2305 && p.next_token().asInput() == "<" && noweb_mode) {
2307 parse_noweb(p, os, context);
2310 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2311 context.check_layout(os);
2312 begin_inset(os, "Quotes ");
2319 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2320 check_space(p, os, context);
2322 else if (t.character() == '[' && noweb_mode &&
2323 p.next_token().character() == '[') {
2324 // These can contain underscores
2326 string const s = p.getFullOpt() + ']';
2327 if (p.next_token().character() == ']')
2330 cerr << "Warning: Inserting missing ']' in '"
2331 << s << "'." << endl;
2332 handle_ert(os, s, context);
2335 else if (t.cat() == catLetter) {
2336 context.check_layout(os);
2337 // Workaround for bug 4752.
2338 // FIXME: This whole code block needs to be removed
2339 // when the bug is fixed and tex2lyx produces
2340 // the updated file format.
2341 // The replacement algorithm in LyX is so stupid that
2342 // it even translates a phrase if it is part of a word.
2343 bool handled = false;
2344 for (int const * l = known_phrase_lengths; *l; ++l) {
2345 string phrase = t.cs();
2346 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2347 phrase += p.get_token().cs();
2348 if (is_known(phrase, known_coded_phrases)) {
2349 handle_ert(os, phrase, context);
2353 for (size_t i = 1; i < phrase.length(); ++i)
2361 else if (t.cat() == catOther ||
2362 t.cat() == catAlign ||
2363 t.cat() == catParameter) {
2364 // This translates "&" to "\\&" which may be wrong...
2365 context.check_layout(os);
2369 else if (p.isParagraph()) {
2370 if (context.new_layout_allowed)
2371 context.new_paragraph(os);
2373 handle_ert(os, "\\par ", context);
2374 eat_whitespace(p, os, context, true);
2377 else if (t.cat() == catActive) {
2378 context.check_layout(os);
2379 if (t.character() == '~') {
2380 if (context.layout->free_spacing)
2383 begin_inset(os, "space ~\n");
2390 else if (t.cat() == catBegin) {
2391 Token const next = p.next_token();
2392 Token const end = p.next_next_token();
2393 if (next.cat() == catEnd) {
2395 Token const prev = p.prev_token();
2397 if (p.next_token().character() == '`' ||
2398 (prev.character() == '-' &&
2399 p.next_token().character() == '-'))
2400 ; // ignore it in {}`` or -{}-
2402 handle_ert(os, "{}", context);
2403 } else if (next.cat() == catEscape &&
2404 is_known(next.cs(), known_quotes) &&
2405 end.cat() == catEnd) {
2406 // Something like {\textquoteright} (e.g.
2407 // from writer2latex). LyX writes
2408 // \textquoteright{}, so we may skip the
2409 // braces here for better readability.
2410 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2413 context.check_layout(os);
2414 // special handling of font attribute changes
2415 Token const prev = p.prev_token();
2416 TeXFont const oldFont = context.font;
2417 if (next.character() == '[' ||
2418 next.character() == ']' ||
2419 next.character() == '*') {
2421 if (p.next_token().cat() == catEnd) {
2426 handle_ert(os, "{", context);
2427 parse_text_snippet(p, os,
2430 handle_ert(os, "}", context);
2432 } else if (! context.new_layout_allowed) {
2433 handle_ert(os, "{", context);
2434 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2436 handle_ert(os, "}", context);
2437 } else if (is_known(next.cs(), known_sizes)) {
2438 // next will change the size, so we must
2440 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2442 if (!context.atParagraphStart())
2444 << context.font.size << "\n";
2445 } else if (is_known(next.cs(), known_font_families)) {
2446 // next will change the font family, so we
2447 // must reset it here
2448 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2450 if (!context.atParagraphStart())
2452 << context.font.family << "\n";
2453 } else if (is_known(next.cs(), known_font_series)) {
2454 // next will change the font series, so we
2455 // must reset it here
2456 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2458 if (!context.atParagraphStart())
2460 << context.font.series << "\n";
2461 } else if (is_known(next.cs(), known_font_shapes)) {
2462 // next will change the font shape, so we
2463 // must reset it here
2464 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2466 if (!context.atParagraphStart())
2468 << context.font.shape << "\n";
2469 } else if (is_known(next.cs(), known_old_font_families) ||
2470 is_known(next.cs(), known_old_font_series) ||
2471 is_known(next.cs(), known_old_font_shapes)) {
2472 // next will change the font family, series
2473 // and shape, so we must reset it here
2474 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2476 if (!context.atParagraphStart())
2478 << context.font.family
2480 << context.font.series
2482 << context.font.shape << "\n";
2484 handle_ert(os, "{", context);
2485 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2487 handle_ert(os, "}", context);
2492 else if (t.cat() == catEnd) {
2493 if (flags & FLAG_BRACE_LAST) {
2496 cerr << "stray '}' in text\n";
2497 handle_ert(os, "}", context);
2500 else if (t.cat() == catComment)
2501 parse_comment(p, os, t, context);
2504 // control sequences
2507 else if (t.cs() == "(") {
2508 context.check_layout(os);
2509 begin_inset(os, "Formula");
2511 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2516 else if (t.cs() == "[") {
2517 context.check_layout(os);
2518 begin_inset(os, "Formula");
2520 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2523 // Prevent the conversion of a line break to a space
2524 // (bug 7668). This does not change the output, but
2525 // looks ugly in LyX.
2526 eat_whitespace(p, os, context, false);
2529 else if (t.cs() == "begin")
2530 parse_environment(p, os, outer, last_env,
2533 else if (t.cs() == "end") {
2534 if (flags & FLAG_END) {
2535 // eat environment name
2536 string const name = p.getArg('{', '}');
2537 if (name != active_environment())
2538 cerr << "\\end{" + name + "} does not match \\begin{"
2539 + active_environment() + "}\n";
2542 p.error("found 'end' unexpectedly");
2545 else if (t.cs() == "item") {
2547 bool const optarg = p.hasOpt();
2549 // FIXME: This swallows comments, but we cannot use
2550 // eat_whitespace() since we must not output
2551 // anything before the item.
2552 p.skip_spaces(true);
2553 s = p.verbatimOption();
2555 p.skip_spaces(false);
2557 context.check_layout(os);
2558 if (context.has_item) {
2559 // An item in an unknown list-like environment
2560 // FIXME: Do this in check_layout()!
2561 context.has_item = false;
2563 handle_ert(os, "\\item", context);
2565 handle_ert(os, "\\item ", context);
2568 if (context.layout->labeltype != LABEL_MANUAL) {
2569 // LyX does not support \item[\mybullet]
2570 // in itemize environments
2572 os << parse_text_snippet(p2,
2573 FLAG_BRACK_LAST, outer, context);
2574 } else if (!s.empty()) {
2575 // LyX adds braces around the argument,
2576 // so we need to remove them here.
2577 if (s.size() > 2 && s[0] == '{' &&
2578 s[s.size()-1] == '}')
2579 s = s.substr(1, s.size()-2);
2580 // If the argument contains a space we
2581 // must put it into ERT: Otherwise LyX
2582 // would misinterpret the space as
2583 // item delimiter (bug 7663)
2584 if (contains(s, ' ')) {
2585 handle_ert(os, s, context);
2588 os << parse_text_snippet(p2,
2592 // The space is needed to separate the
2593 // item from the rest of the sentence.
2595 eat_whitespace(p, os, context, false);
2600 else if (t.cs() == "bibitem") {
2602 context.check_layout(os);
2603 eat_whitespace(p, os, context, false);
2604 string label = convert_command_inset_arg(p.verbatimOption());
2605 string key = convert_command_inset_arg(p.verbatim_item());
2606 if (contains(label, '\\') || contains(key, '\\')) {
2607 // LyX can't handle LaTeX commands in labels or keys
2608 handle_ert(os, t.asInput() + '[' + label +
2609 "]{" + p.verbatim_item() + '}',
2612 begin_command_inset(os, "bibitem", "bibitem");
2613 os << "label \"" << label << "\"\n"
2614 "key \"" << key << "\"\n";
2619 else if (is_macro(p)) {
2620 // catch the case of \def\inputGnumericTable
2622 if (t.cs() == "def") {
2623 Token second = p.next_token();
2624 if (second.cs() == "inputGnumericTable") {
2628 Token third = p.get_token();
2630 if (third.cs() == "input") {
2634 string name = normalize_filename(p.verbatim_item());
2635 string const path = getMasterFilePath(true);
2636 // We want to preserve relative / absolute filenames,
2637 // therefore path is only used for testing
2638 // The file extension is in every case ".tex".
2639 // So we need to remove this extension and check for
2640 // the original one.
2641 name = removeExtension(name);
2642 if (!makeAbsPath(name, path).exists()) {
2643 char const * const Gnumeric_formats[] = {"gnumeric",
2645 string const Gnumeric_name =
2646 find_file(name, path, Gnumeric_formats);
2647 if (!Gnumeric_name.empty())
2648 name = Gnumeric_name;
2650 FileName const absname = makeAbsPath(name, path);
2651 if (absname.exists()) {
2652 fix_child_filename(name);
2653 copy_file(absname, name);
2655 cerr << "Warning: Could not find file '"
2656 << name << "'." << endl;
2657 context.check_layout(os);
2658 begin_inset(os, "External\n\ttemplate ");
2659 os << "GnumericSpreadsheet\n\tfilename "
2662 context.check_layout(os);
2664 // register the packages that are automatically loaded
2665 // by the Gnumeric template
2666 registerExternalTemplatePackages("GnumericSpreadsheet");
2671 parse_macro(p, os, context);
2674 else if (t.cs() == "noindent") {
2676 context.add_par_extra_stuff("\\noindent\n");
2679 else if (t.cs() == "appendix") {
2680 context.add_par_extra_stuff("\\start_of_appendix\n");
2681 // We need to start a new paragraph. Otherwise the
2682 // appendix in 'bla\appendix\chapter{' would start
2684 context.new_paragraph(os);
2685 // We need to make sure that the paragraph is
2686 // generated even if it is empty. Otherwise the
2687 // appendix in '\par\appendix\par\chapter{' would
2689 context.check_layout(os);
2690 // FIXME: This is a hack to prevent paragraph
2691 // deletion if it is empty. Handle this better!
2693 "%dummy comment inserted by tex2lyx to "
2694 "ensure that this paragraph is not empty",
2696 // Both measures above may generate an additional
2697 // empty paragraph, but that does not hurt, because
2698 // whitespace does not matter here.
2699 eat_whitespace(p, os, context, true);
2702 // Must catch empty dates before findLayout is called below
2703 else if (t.cs() == "date") {
2704 eat_whitespace(p, os, context, false);
2706 string const date = p.verbatim_item();
2709 preamble.suppressDate(true);
2712 preamble.suppressDate(false);
2713 if (context.new_layout_allowed &&
2714 (newlayout = findLayout(context.textclass,
2717 output_command_layout(os, p, outer,
2718 context, newlayout);
2719 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2720 if (!preamble.titleLayoutFound())
2721 preamble.titleLayoutFound(newlayout->intitle);
2722 set<string> const & req = newlayout->requires();
2723 set<string>::const_iterator it = req.begin();
2724 set<string>::const_iterator en = req.end();
2725 for (; it != en; ++it)
2726 preamble.registerAutomaticallyLoadedPackage(*it);
2729 "\\date{" + p.verbatim_item() + '}',
2734 // Starred section headings
2735 // Must attempt to parse "Section*" before "Section".
2736 else if ((p.next_token().asInput() == "*") &&
2737 context.new_layout_allowed &&
2738 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2741 output_command_layout(os, p, outer, context, newlayout);
2743 if (!preamble.titleLayoutFound())
2744 preamble.titleLayoutFound(newlayout->intitle);
2745 set<string> const & req = newlayout->requires();
2746 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2747 preamble.registerAutomaticallyLoadedPackage(*it);
2750 // Section headings and the like
2751 else if (context.new_layout_allowed &&
2752 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2754 output_command_layout(os, p, outer, context, newlayout);
2756 if (!preamble.titleLayoutFound())
2757 preamble.titleLayoutFound(newlayout->intitle);
2758 set<string> const & req = newlayout->requires();
2759 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2760 preamble.registerAutomaticallyLoadedPackage(*it);
2763 else if (t.cs() == "caption") {
2765 context.check_layout(os);
2767 begin_inset(os, "Caption\n");
2768 Context newcontext(true, context.textclass, 0, 0, context.font);
2769 newcontext.check_layout(os);
2770 // FIXME InsetArgument is now properly implemented in InsetLayout
2771 // (for captions, but also for others)
2772 if (p.next_token().cat() != catEscape &&
2773 p.next_token().character() == '[') {
2774 p.get_token(); // eat '['
2775 begin_inset(os, "Argument 1\n");
2776 os << "status collapsed\n";
2777 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2779 eat_whitespace(p, os, context, false);
2781 parse_text(p, os, FLAG_ITEM, outer, context);
2782 context.check_end_layout(os);
2783 // We don't need really a new paragraph, but
2784 // we must make sure that the next item gets a \begin_layout.
2785 context.new_paragraph(os);
2788 newcontext.check_end_layout(os);
2791 else if (t.cs() == "subfloat") {
2792 // the syntax is \subfloat[caption]{content}
2793 // if it is a table of figure depends on the surrounding float
2794 bool has_caption = false;
2796 // do nothing if there is no outer float
2797 if (!float_type.empty()) {
2798 context.check_layout(os);
2800 begin_inset(os, "Float " + float_type + "\n");
2802 << "\nsideways false"
2803 << "\nstatus collapsed\n\n";
2806 if (p.next_token().cat() != catEscape &&
2807 p.next_token().character() == '[') {
2808 p.get_token(); // eat '['
2809 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2813 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2814 // the caption comes always as the last
2816 // we must make sure that the caption gets a \begin_layout
2817 os << "\n\\begin_layout Plain Layout";
2819 begin_inset(os, "Caption\n");
2820 Context newcontext(true, context.textclass,
2821 0, 0, context.font);
2822 newcontext.check_layout(os);
2823 os << caption << "\n";
2824 newcontext.check_end_layout(os);
2825 // We don't need really a new paragraph, but
2826 // we must make sure that the next item gets a \begin_layout.
2827 //newcontext.new_paragraph(os);
2831 // We don't need really a new paragraph, but
2832 // we must make sure that the next item gets a \begin_layout.
2834 context.new_paragraph(os);
2837 context.check_end_layout(os);
2838 // close the layout we opened
2840 os << "\n\\end_layout\n";
2842 // if the float type is not supported or there is no surrounding float
2845 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2846 handle_ert(os, t.asInput() + '[' + opt_arg +
2847 "]{" + p.verbatim_item() + '}', context);
2849 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2853 else if (t.cs() == "includegraphics") {
2854 bool const clip = p.next_token().asInput() == "*";
2857 string const arg = p.getArg('[', ']');
2858 map<string, string> opts;
2859 vector<string> keys;
2860 split_map(arg, opts, keys);
2862 opts["clip"] = string();
2863 string name = normalize_filename(p.verbatim_item());
2865 string const path = getMasterFilePath(true);
2866 // We want to preserve relative / absolute filenames,
2867 // therefore path is only used for testing
2868 if (!makeAbsPath(name, path).exists()) {
2869 // The file extension is probably missing.
2870 // Now try to find it out.
2871 string const dvips_name =
2872 find_file(name, path,
2873 known_dvips_graphics_formats);
2874 string const pdftex_name =
2875 find_file(name, path,
2876 known_pdftex_graphics_formats);
2877 if (!dvips_name.empty()) {
2878 if (!pdftex_name.empty()) {
2879 cerr << "This file contains the "
2881 "\"\\includegraphics{"
2883 "However, files\n\""
2884 << dvips_name << "\" and\n\""
2885 << pdftex_name << "\"\n"
2886 "both exist, so I had to make a "
2887 "choice and took the first one.\n"
2888 "Please move the unwanted one "
2889 "someplace else and try again\n"
2890 "if my choice was wrong."
2894 } else if (!pdftex_name.empty()) {
2900 FileName const absname = makeAbsPath(name, path);
2901 if (absname.exists()) {
2902 fix_child_filename(name);
2903 copy_file(absname, name);
2905 cerr << "Warning: Could not find graphics file '"
2906 << name << "'." << endl;
2908 context.check_layout(os);
2909 begin_inset(os, "Graphics ");
2910 os << "\n\tfilename " << name << '\n';
2911 if (opts.find("width") != opts.end())
2913 << translate_len(opts["width"]) << '\n';
2914 if (opts.find("height") != opts.end())
2916 << translate_len(opts["height"]) << '\n';
2917 if (opts.find("scale") != opts.end()) {
2918 istringstream iss(opts["scale"]);
2922 os << "\tscale " << val << '\n';
2924 if (opts.find("angle") != opts.end()) {
2925 os << "\trotateAngle "
2926 << opts["angle"] << '\n';
2927 vector<string>::const_iterator a =
2928 find(keys.begin(), keys.end(), "angle");
2929 vector<string>::const_iterator s =
2930 find(keys.begin(), keys.end(), "width");
2931 if (s == keys.end())
2932 s = find(keys.begin(), keys.end(), "height");
2933 if (s == keys.end())
2934 s = find(keys.begin(), keys.end(), "scale");
2935 if (s != keys.end() && distance(s, a) > 0)
2936 os << "\tscaleBeforeRotation\n";
2938 if (opts.find("origin") != opts.end()) {
2940 string const opt = opts["origin"];
2941 if (opt.find('l') != string::npos) ss << "left";
2942 if (opt.find('r') != string::npos) ss << "right";
2943 if (opt.find('c') != string::npos) ss << "center";
2944 if (opt.find('t') != string::npos) ss << "Top";
2945 if (opt.find('b') != string::npos) ss << "Bottom";
2946 if (opt.find('B') != string::npos) ss << "Baseline";
2947 if (!ss.str().empty())
2948 os << "\trotateOrigin " << ss.str() << '\n';
2950 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2952 if (opts.find("keepaspectratio") != opts.end())
2953 os << "\tkeepAspectRatio\n";
2954 if (opts.find("clip") != opts.end())
2956 if (opts.find("draft") != opts.end())
2958 if (opts.find("bb") != opts.end())
2959 os << "\tBoundingBox "
2960 << opts["bb"] << '\n';
2961 int numberOfbbOptions = 0;
2962 if (opts.find("bbllx") != opts.end())
2963 numberOfbbOptions++;
2964 if (opts.find("bblly") != opts.end())
2965 numberOfbbOptions++;
2966 if (opts.find("bburx") != opts.end())
2967 numberOfbbOptions++;
2968 if (opts.find("bbury") != opts.end())
2969 numberOfbbOptions++;
2970 if (numberOfbbOptions == 4)
2971 os << "\tBoundingBox "
2972 << opts["bbllx"] << " " << opts["bblly"] << " "
2973 << opts["bburx"] << " " << opts["bbury"] << '\n';
2974 else if (numberOfbbOptions > 0)
2975 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2976 numberOfbbOptions = 0;
2977 if (opts.find("natwidth") != opts.end())
2978 numberOfbbOptions++;
2979 if (opts.find("natheight") != opts.end())
2980 numberOfbbOptions++;
2981 if (numberOfbbOptions == 2)
2982 os << "\tBoundingBox 0bp 0bp "
2983 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2984 else if (numberOfbbOptions > 0)
2985 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2986 ostringstream special;
2987 if (opts.find("hiresbb") != opts.end())
2988 special << "hiresbb,";
2989 if (opts.find("trim") != opts.end())
2991 if (opts.find("viewport") != opts.end())
2992 special << "viewport=" << opts["viewport"] << ',';
2993 if (opts.find("totalheight") != opts.end())
2994 special << "totalheight=" << opts["totalheight"] << ',';
2995 if (opts.find("type") != opts.end())
2996 special << "type=" << opts["type"] << ',';
2997 if (opts.find("ext") != opts.end())
2998 special << "ext=" << opts["ext"] << ',';
2999 if (opts.find("read") != opts.end())
3000 special << "read=" << opts["read"] << ',';
3001 if (opts.find("command") != opts.end())
3002 special << "command=" << opts["command"] << ',';
3003 string s_special = special.str();
3004 if (!s_special.empty()) {
3005 // We had special arguments. Remove the trailing ','.
3006 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3008 // TODO: Handle the unknown settings better.
3009 // Warn about invalid options.
3010 // Check whether some option was given twice.
3012 preamble.registerAutomaticallyLoadedPackage("graphicx");
3015 else if (t.cs() == "footnote" ||
3016 (t.cs() == "thanks" && context.layout->intitle)) {
3018 context.check_layout(os);
3019 begin_inset(os, "Foot\n");
3020 os << "status collapsed\n\n";
3021 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3025 else if (t.cs() == "marginpar") {
3027 context.check_layout(os);
3028 begin_inset(os, "Marginal\n");
3029 os << "status collapsed\n\n";
3030 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3034 else if (t.cs() == "lstinline") {
3036 parse_listings(p, os, context, true);
3039 else if (t.cs() == "ensuremath") {
3041 context.check_layout(os);
3042 string const s = p.verbatim_item();
3043 //FIXME: this never triggers in UTF8
3044 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3047 handle_ert(os, "\\ensuremath{" + s + "}",
3051 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3052 if (preamble.titleLayoutFound()) {
3054 skip_spaces_braces(p);
3056 handle_ert(os, t.asInput(), context);
3059 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3060 context.check_layout(os);
3061 begin_command_inset(os, "toc", t.cs());
3063 skip_spaces_braces(p);
3064 if (t.cs() == "lstlistoflistings")
3065 preamble.registerAutomaticallyLoadedPackage("listings");
3068 else if (t.cs() == "listoffigures") {
3069 context.check_layout(os);
3070 begin_inset(os, "FloatList figure\n");
3072 skip_spaces_braces(p);
3075 else if (t.cs() == "listoftables") {
3076 context.check_layout(os);
3077 begin_inset(os, "FloatList table\n");
3079 skip_spaces_braces(p);
3082 else if (t.cs() == "listof") {
3083 p.skip_spaces(true);
3084 string const name = p.get_token().cs();
3085 if (context.textclass.floats().typeExist(name)) {
3086 context.check_layout(os);
3087 begin_inset(os, "FloatList ");
3090 p.get_token(); // swallow second arg
3092 handle_ert(os, "\\listof{" + name + "}", context);
3095 else if ((where = is_known(t.cs(), known_text_font_families)))
3096 parse_text_attributes(p, os, FLAG_ITEM, outer,
3097 context, "\\family", context.font.family,
3098 known_coded_font_families[where - known_text_font_families]);
3100 else if ((where = is_known(t.cs(), known_text_font_series)))
3101 parse_text_attributes(p, os, FLAG_ITEM, outer,
3102 context, "\\series", context.font.series,
3103 known_coded_font_series[where - known_text_font_series]);
3105 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3106 parse_text_attributes(p, os, FLAG_ITEM, outer,
3107 context, "\\shape", context.font.shape,
3108 known_coded_font_shapes[where - known_text_font_shapes]);
3110 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3111 context.check_layout(os);
3112 TeXFont oldFont = context.font;
3113 context.font.init();
3114 context.font.size = oldFont.size;
3115 os << "\n\\family " << context.font.family << "\n";
3116 os << "\n\\series " << context.font.series << "\n";
3117 os << "\n\\shape " << context.font.shape << "\n";
3118 if (t.cs() == "textnormal") {
3119 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3120 output_font_change(os, context.font, oldFont);
3121 context.font = oldFont;
3123 eat_whitespace(p, os, context, false);
3126 else if (t.cs() == "textcolor") {
3127 // scheme is \textcolor{color name}{text}
3128 string const color = p.verbatim_item();
3129 // we only support the predefined colors of the color package
3130 if (color == "black" || color == "blue" || color == "cyan"
3131 || color == "green" || color == "magenta" || color == "red"
3132 || color == "white" || color == "yellow") {
3133 context.check_layout(os);
3134 os << "\n\\color " << color << "\n";
3135 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3136 context.check_layout(os);
3137 os << "\n\\color inherit\n";
3138 preamble.registerAutomaticallyLoadedPackage("color");
3140 // for custom defined colors
3141 handle_ert(os, t.asInput() + "{" + color + "}", context);
3144 else if (t.cs() == "underbar" || t.cs() == "uline") {
3145 // \underbar is not 100% correct (LyX outputs \uline
3146 // of ulem.sty). The difference is that \ulem allows
3147 // line breaks, and \underbar does not.
3148 // Do NOT handle \underline.
3149 // \underbar cuts through y, g, q, p etc.,
3150 // \underline does not.
3151 context.check_layout(os);
3152 os << "\n\\bar under\n";
3153 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3154 context.check_layout(os);
3155 os << "\n\\bar default\n";
3156 preamble.registerAutomaticallyLoadedPackage("ulem");
3159 else if (t.cs() == "sout") {
3160 context.check_layout(os);
3161 os << "\n\\strikeout on\n";
3162 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3163 context.check_layout(os);
3164 os << "\n\\strikeout default\n";
3165 preamble.registerAutomaticallyLoadedPackage("ulem");
3168 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3169 t.cs() == "emph" || t.cs() == "noun") {
3170 context.check_layout(os);
3171 os << "\n\\" << t.cs() << " on\n";
3172 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3173 context.check_layout(os);
3174 os << "\n\\" << t.cs() << " default\n";
3175 if (t.cs() == "uuline" || t.cs() == "uwave")
3176 preamble.registerAutomaticallyLoadedPackage("ulem");
3179 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3180 context.check_layout(os);
3181 string name = p.getArg('{', '}');
3182 string localtime = p.getArg('{', '}');
3183 preamble.registerAuthor(name);
3184 Author const & author = preamble.getAuthor(name);
3185 // from_ctime() will fail if LyX decides to output the
3186 // time in the text language. It might also use a wrong
3187 // time zone (if the original LyX document was exported
3188 // with a different time zone).
3189 time_t ptime = from_ctime(localtime);
3190 if (ptime == static_cast<time_t>(-1)) {
3191 cerr << "Warning: Could not parse time `" << localtime
3192 << "´ for change tracking, using current time instead.\n";
3193 ptime = current_time();
3195 if (t.cs() == "lyxadded")
3196 os << "\n\\change_inserted ";
3198 os << "\n\\change_deleted ";
3199 os << author.bufferId() << ' ' << ptime << '\n';
3200 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3201 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3202 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3203 LaTeXPackages::isAvailable("xcolor");
3204 // No need to test for luatex, since luatex comes in
3205 // two flavours (dvi and pdf), like latex, and those
3206 // are detected by pdflatex.
3207 if (pdflatex || xetex) {
3209 preamble.registerAutomaticallyLoadedPackage("ulem");
3210 preamble.registerAutomaticallyLoadedPackage("xcolor");
3211 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3215 preamble.registerAutomaticallyLoadedPackage("dvipost");
3216 } else if (xcolorulem) {
3217 preamble.registerAutomaticallyLoadedPackage("ulem");
3218 preamble.registerAutomaticallyLoadedPackage("xcolor");
3223 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3224 t.cs() == "vphantom") {
3225 context.check_layout(os);
3226 if (t.cs() == "phantom")
3227 begin_inset(os, "Phantom Phantom\n");
3228 if (t.cs() == "hphantom")
3229 begin_inset(os, "Phantom HPhantom\n");
3230 if (t.cs() == "vphantom")
3231 begin_inset(os, "Phantom VPhantom\n");
3232 os << "status open\n";
3233 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3238 else if (t.cs() == "href") {
3239 context.check_layout(os);
3240 string target = convert_command_inset_arg(p.verbatim_item());
3241 string name = convert_command_inset_arg(p.verbatim_item());
3243 size_t i = target.find(':');
3244 if (i != string::npos) {
3245 type = target.substr(0, i + 1);
3246 if (type == "mailto:" || type == "file:")
3247 target = target.substr(i + 1);
3248 // handle the case that name is equal to target, except of "http://"
3249 else if (target.substr(i + 3) == name && type == "http:")
3252 begin_command_inset(os, "href", "href");
3254 os << "name \"" << name << "\"\n";
3255 os << "target \"" << target << "\"\n";
3256 if (type == "mailto:" || type == "file:")
3257 os << "type \"" << type << "\"\n";
3259 skip_spaces_braces(p);
3262 else if (t.cs() == "lyxline") {
3263 // swallow size argument (it is not used anyway)
3265 if (!context.atParagraphStart()) {
3266 // so our line is in the middle of a paragraph
3267 // we need to add a new line, lest this line
3268 // follow the other content on that line and
3269 // run off the side of the page
3270 // FIXME: This may create an empty paragraph,
3271 // but without that it would not be
3272 // possible to set noindent below.
3273 // Fortunately LaTeX does not care
3274 // about the empty paragraph.
3275 context.new_paragraph(os);
3277 if (preamble.indentParagraphs()) {
3278 // we need to unindent, lest the line be too long
3279 context.add_par_extra_stuff("\\noindent\n");
3281 context.check_layout(os);
3282 begin_command_inset(os, "line", "rule");
3283 os << "offset \"0.5ex\"\n"
3284 "width \"100line%\"\n"
3289 else if (t.cs() == "rule") {
3290 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3291 string const width = p.getArg('{', '}');
3292 string const thickness = p.getArg('{', '}');
3293 context.check_layout(os);
3294 begin_command_inset(os, "line", "rule");
3295 if (!offset.empty())
3296 os << "offset \"" << translate_len(offset) << "\"\n";
3297 os << "width \"" << translate_len(width) << "\"\n"
3298 "height \"" << translate_len(thickness) << "\"\n";
3302 else if (is_known(t.cs(), known_phrases) ||
3303 (t.cs() == "protect" &&
3304 p.next_token().cat() == catEscape &&
3305 is_known(p.next_token().cs(), known_phrases))) {
3306 // LyX sometimes puts a \protect in front, so we have to ignore it
3307 // FIXME: This needs to be changed when bug 4752 is fixed.
3309 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3311 context.check_layout(os);
3312 os << known_coded_phrases[where - known_phrases];
3313 skip_spaces_braces(p);
3316 else if ((where = is_known(t.cs(), known_ref_commands))) {
3317 string const opt = p.getOpt();
3319 context.check_layout(os);
3320 begin_command_inset(os, "ref",
3321 known_coded_ref_commands[where - known_ref_commands]);
3322 os << "reference \""
3323 << convert_command_inset_arg(p.verbatim_item())
3326 if (t.cs() == "vref" || t.cs() == "vpageref")
3327 preamble.registerAutomaticallyLoadedPackage("varioref");
3330 // LyX does not support optional arguments of ref commands
3331 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3332 p.verbatim_item() + "}", context);
3336 else if (use_natbib &&
3337 is_known(t.cs(), known_natbib_commands) &&
3338 ((t.cs() != "citefullauthor" &&
3339 t.cs() != "citeyear" &&
3340 t.cs() != "citeyearpar") ||
3341 p.next_token().asInput() != "*")) {
3342 context.check_layout(os);
3343 string command = t.cs();
3344 if (p.next_token().asInput() == "*") {
3348 if (command == "citefullauthor")
3349 // alternative name for "\\citeauthor*"
3350 command = "citeauthor*";
3352 // text before the citation
3354 // text after the citation
3356 get_cite_arguments(p, true, before, after);
3358 if (command == "cite") {
3359 // \cite without optional argument means
3360 // \citet, \cite with at least one optional
3361 // argument means \citep.
3362 if (before.empty() && after.empty())
3367 if (before.empty() && after == "[]")
3368 // avoid \citet[]{a}
3370 else if (before == "[]" && after == "[]") {
3371 // avoid \citet[][]{a}
3375 // remove the brackets around after and before
3376 if (!after.empty()) {
3378 after.erase(after.length() - 1, 1);
3379 after = convert_command_inset_arg(after);
3381 if (!before.empty()) {
3383 before.erase(before.length() - 1, 1);
3384 before = convert_command_inset_arg(before);
3386 begin_command_inset(os, "citation", command);
3387 os << "after " << '"' << after << '"' << "\n";
3388 os << "before " << '"' << before << '"' << "\n";
3390 << convert_command_inset_arg(p.verbatim_item())
3393 // Need to set the cite engine if natbib is loaded by
3394 // the document class directly
3395 if (preamble.citeEngine() == "basic")
3396 preamble.citeEngine("natbib");
3399 else if (use_jurabib &&
3400 is_known(t.cs(), known_jurabib_commands) &&
3401 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3402 context.check_layout(os);
3403 string command = t.cs();
3404 if (p.next_token().asInput() == "*") {
3408 char argumentOrder = '\0';
3409 vector<string> const options =
3410 preamble.getPackageOptions("jurabib");
3411 if (find(options.begin(), options.end(),
3412 "natbiborder") != options.end())
3413 argumentOrder = 'n';
3414 else if (find(options.begin(), options.end(),
3415 "jurabiborder") != options.end())
3416 argumentOrder = 'j';
3418 // text before the citation
3420 // text after the citation
3422 get_cite_arguments(p, argumentOrder != 'j', before, after);
3424 string const citation = p.verbatim_item();
3425 if (!before.empty() && argumentOrder == '\0') {
3426 cerr << "Warning: Assuming argument order "
3427 "of jurabib version 0.6 for\n'"
3428 << command << before << after << '{'
3429 << citation << "}'.\n"
3430 "Add 'jurabiborder' to the jurabib "
3431 "package options if you used an\n"
3432 "earlier jurabib version." << endl;
3434 if (!after.empty()) {
3436 after.erase(after.length() - 1, 1);
3438 if (!before.empty()) {
3440 before.erase(before.length() - 1, 1);
3442 begin_command_inset(os, "citation", command);
3443 os << "after " << '"' << after << '"' << "\n";
3444 os << "before " << '"' << before << '"' << "\n";
3445 os << "key " << '"' << citation << '"' << "\n";
3447 // Need to set the cite engine if jurabib is loaded by
3448 // the document class directly
3449 if (preamble.citeEngine() == "basic")
3450 preamble.citeEngine("jurabib");
3453 else if (t.cs() == "cite"
3454 || t.cs() == "nocite") {
3455 context.check_layout(os);
3456 string after = convert_command_inset_arg(p.getArg('[', ']'));
3457 string key = convert_command_inset_arg(p.verbatim_item());
3458 // store the case that it is "\nocite{*}" to use it later for
3461 begin_command_inset(os, "citation", t.cs());
3462 os << "after " << '"' << after << '"' << "\n";
3463 os << "key " << '"' << key << '"' << "\n";
3465 } else if (t.cs() == "nocite")
3469 else if (t.cs() == "index" ||
3470 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3471 context.check_layout(os);
3472 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3473 p.getArg('[', ']') : "";
3474 string const kind = arg.empty() ? "idx" : arg;
3475 begin_inset(os, "Index ");
3476 os << kind << "\nstatus collapsed\n";
3477 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3480 preamble.registerAutomaticallyLoadedPackage("splitidx");
3483 else if (t.cs() == "nomenclature") {
3484 context.check_layout(os);
3485 begin_command_inset(os, "nomenclature", "nomenclature");
3486 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3487 if (!prefix.empty())
3488 os << "prefix " << '"' << prefix << '"' << "\n";
3489 os << "symbol " << '"'
3490 << convert_command_inset_arg(p.verbatim_item());
3491 os << "\"\ndescription \""
3492 << convert_command_inset_arg(p.verbatim_item())
3495 preamble.registerAutomaticallyLoadedPackage("nomencl");
3498 else if (t.cs() == "label") {
3499 context.check_layout(os);
3500 begin_command_inset(os, "label", "label");
3502 << convert_command_inset_arg(p.verbatim_item())
3507 else if (t.cs() == "printindex") {
3508 context.check_layout(os);
3509 begin_command_inset(os, "index_print", "printindex");
3510 os << "type \"idx\"\n";
3512 skip_spaces_braces(p);
3513 preamble.registerAutomaticallyLoadedPackage("makeidx");
3514 if (preamble.use_indices() == "true")
3515 preamble.registerAutomaticallyLoadedPackage("splitidx");
3518 else if (t.cs() == "printnomenclature") {
3520 string width_type = "";
3521 context.check_layout(os);
3522 begin_command_inset(os, "nomencl_print", "printnomenclature");
3523 // case of a custom width
3525 width = p.getArg('[', ']');
3526 width = translate_len(width);
3527 width_type = "custom";
3529 // case of no custom width
3530 // the case of no custom width but the width set
3531 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3532 // because the user could have set anything, not only the width
3533 // of the longest label (which would be width_type = "auto")
3534 string label = convert_command_inset_arg(p.getArg('{', '}'));
3535 if (label.empty() && width_type.empty())
3536 width_type = "none";
3537 os << "set_width \"" << width_type << "\"\n";
3538 if (width_type == "custom")
3539 os << "width \"" << width << '\"';
3541 skip_spaces_braces(p);
3542 preamble.registerAutomaticallyLoadedPackage("nomencl");
3545 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3546 context.check_layout(os);
3547 begin_inset(os, "script ");
3548 os << t.cs().substr(4) << '\n';
3549 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3551 if (t.cs() == "textsubscript")
3552 preamble.registerAutomaticallyLoadedPackage("subscript");
3555 else if ((where = is_known(t.cs(), known_quotes))) {
3556 context.check_layout(os);
3557 begin_inset(os, "Quotes ");
3558 os << known_coded_quotes[where - known_quotes];
3560 // LyX adds {} after the quote, so we have to eat
3561 // spaces here if there are any before a possible
3563 eat_whitespace(p, os, context, false);
3567 else if ((where = is_known(t.cs(), known_sizes)) &&
3568 context.new_layout_allowed) {
3569 context.check_layout(os);
3570 TeXFont const oldFont = context.font;
3571 context.font.size = known_coded_sizes[where - known_sizes];
3572 output_font_change(os, oldFont, context.font);
3573 eat_whitespace(p, os, context, false);
3576 else if ((where = is_known(t.cs(), known_font_families)) &&
3577 context.new_layout_allowed) {
3578 context.check_layout(os);
3579 TeXFont const oldFont = context.font;
3580 context.font.family =
3581 known_coded_font_families[where - known_font_families];
3582 output_font_change(os, oldFont, context.font);
3583 eat_whitespace(p, os, context, false);
3586 else if ((where = is_known(t.cs(), known_font_series)) &&
3587 context.new_layout_allowed) {
3588 context.check_layout(os);
3589 TeXFont const oldFont = context.font;
3590 context.font.series =
3591 known_coded_font_series[where - known_font_series];
3592 output_font_change(os, oldFont, context.font);
3593 eat_whitespace(p, os, context, false);
3596 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3597 context.new_layout_allowed) {
3598 context.check_layout(os);
3599 TeXFont const oldFont = context.font;
3600 context.font.shape =
3601 known_coded_font_shapes[where - known_font_shapes];
3602 output_font_change(os, oldFont, context.font);
3603 eat_whitespace(p, os, context, false);
3605 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3606 context.new_layout_allowed) {
3607 context.check_layout(os);
3608 TeXFont const oldFont = context.font;
3609 context.font.init();
3610 context.font.size = oldFont.size;
3611 context.font.family =
3612 known_coded_font_families[where - known_old_font_families];
3613 output_font_change(os, oldFont, context.font);
3614 eat_whitespace(p, os, context, false);
3617 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3618 context.new_layout_allowed) {
3619 context.check_layout(os);
3620 TeXFont const oldFont = context.font;
3621 context.font.init();
3622 context.font.size = oldFont.size;
3623 context.font.series =
3624 known_coded_font_series[where - known_old_font_series];
3625 output_font_change(os, oldFont, context.font);
3626 eat_whitespace(p, os, context, false);
3629 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3630 context.new_layout_allowed) {
3631 context.check_layout(os);
3632 TeXFont const oldFont = context.font;
3633 context.font.init();
3634 context.font.size = oldFont.size;
3635 context.font.shape =
3636 known_coded_font_shapes[where - known_old_font_shapes];
3637 output_font_change(os, oldFont, context.font);
3638 eat_whitespace(p, os, context, false);
3641 else if (t.cs() == "selectlanguage") {
3642 context.check_layout(os);
3643 // save the language for the case that a
3644 // \foreignlanguage is used
3645 context.font.language = babel2lyx(p.verbatim_item());
3646 os << "\n\\lang " << context.font.language << "\n";
3649 else if (t.cs() == "foreignlanguage") {
3650 string const lang = babel2lyx(p.verbatim_item());
3651 parse_text_attributes(p, os, FLAG_ITEM, outer,
3653 context.font.language, lang);
3656 else if (prefixIs(t.cs(), "text")
3657 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3658 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3660 // We have to output the whole command if it has an option
3661 // because LyX doesn't support this yet, see bug #8214,
3662 // only if there is a single option specifying a variant, we can handle it.
3664 string langopts = p.getOpt();
3665 // check if the option contains a variant, if yes, extract it
3666 string::size_type pos_var = langopts.find("variant");
3667 string::size_type i = langopts.find(',');
3668 string::size_type k = langopts.find('=', pos_var);
3669 if (pos_var != string::npos && i == string::npos) {
3671 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3672 lang = preamble.polyglossia2lyx(variant);
3673 parse_text_attributes(p, os, FLAG_ITEM, outer,
3675 context.font.language, lang);
3677 handle_ert(os, t.asInput() + langopts, context);
3679 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3680 parse_text_attributes(p, os, FLAG_ITEM, outer,
3682 context.font.language, lang);
3686 else if (t.cs() == "inputencoding") {
3687 // nothing to write here
3688 string const enc = subst(p.verbatim_item(), "\n", " ");
3692 else if ((where = is_known(t.cs(), known_special_chars))) {
3693 context.check_layout(os);
3694 os << "\\SpecialChar \\"
3695 << known_coded_special_chars[where - known_special_chars]
3697 skip_spaces_braces(p);
3700 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3701 context.check_layout(os);
3702 os << "\\SpecialChar \\nobreakdash-\n";
3706 else if (t.cs() == "textquotedbl") {
3707 context.check_layout(os);
3712 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3713 context.check_layout(os);
3714 os << "\\SpecialChar \\@.\n";
3718 else if (t.cs() == "-") {
3719 context.check_layout(os);
3720 os << "\\SpecialChar \\-\n";
3723 else if (t.cs() == "textasciitilde") {
3724 context.check_layout(os);
3726 skip_spaces_braces(p);
3729 else if (t.cs() == "textasciicircum") {
3730 context.check_layout(os);
3732 skip_spaces_braces(p);
3735 else if (t.cs() == "textbackslash") {
3736 context.check_layout(os);
3737 os << "\n\\backslash\n";
3738 skip_spaces_braces(p);
3741 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3742 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3744 context.check_layout(os);
3748 else if (t.cs() == "char") {
3749 context.check_layout(os);
3750 if (p.next_token().character() == '`') {
3752 if (p.next_token().cs() == "\"") {
3757 handle_ert(os, "\\char`", context);
3760 handle_ert(os, "\\char", context);
3764 else if (t.cs() == "verb") {
3765 context.check_layout(os);
3766 char const delimiter = p.next_token().character();
3767 // \verb is special: The usual escaping rules do not
3768 // apply, e.g. "\verb+\+" is valid and denotes a single
3769 // backslash (bug #4468). Therefore we do not allow
3770 // escaping in getArg().
3771 string const arg = p.getArg(delimiter, delimiter, false);
3773 oss << "\\verb" << delimiter << arg << delimiter;
3774 handle_ert(os, oss.str(), context);
3777 // Problem: \= creates a tabstop inside the tabbing environment
3778 // and else an accent. In the latter case we really would want
3779 // \={o} instead of \= o.
3780 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3781 handle_ert(os, t.asInput(), context);
3783 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3784 else if (t.cs().size() == 1
3785 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3786 context.check_layout(os);
3787 // try to see whether the string is in unicodesymbols
3790 string command = t.asInput() + "{"
3791 + trimSpaceAndEol(p.verbatim_item())
3794 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3795 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3796 termination, rem, &req);
3799 cerr << "When parsing " << command
3800 << ", result is " << to_utf8(s)
3801 << "+" << to_utf8(rem) << endl;
3803 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3804 preamble.registerAutomaticallyLoadedPackage(*it);
3806 // we did not find a non-ert version
3807 handle_ert(os, command, context);
3810 else if (t.cs() == "\\") {
3811 context.check_layout(os);
3813 handle_ert(os, "\\\\" + p.getOpt(), context);
3814 else if (p.next_token().asInput() == "*") {
3816 // getOpt() eats the following space if there
3817 // is no optional argument, but that is OK
3818 // here since it has no effect in the output.
3819 handle_ert(os, "\\\\*" + p.getOpt(), context);
3822 begin_inset(os, "Newline newline");
3827 else if (t.cs() == "newline" ||
3828 (t.cs() == "linebreak" && !p.hasOpt())) {
3829 context.check_layout(os);
3830 begin_inset(os, "Newline ");
3833 skip_spaces_braces(p);
3836 else if (t.cs() == "input" || t.cs() == "include"
3837 || t.cs() == "verbatiminput") {
3838 string name = t.cs();
3839 if (t.cs() == "verbatiminput"
3840 && p.next_token().asInput() == "*")
3841 name += p.get_token().asInput();
3842 context.check_layout(os);
3843 string filename(normalize_filename(p.getArg('{', '}')));
3844 string const path = getMasterFilePath(true);
3845 // We want to preserve relative / absolute filenames,
3846 // therefore path is only used for testing
3847 if ((t.cs() == "include" || t.cs() == "input") &&
3848 !makeAbsPath(filename, path).exists()) {
3849 // The file extension is probably missing.
3850 // Now try to find it out.
3851 string const tex_name =
3852 find_file(filename, path,
3853 known_tex_extensions);
3854 if (!tex_name.empty())
3855 filename = tex_name;
3857 bool external = false;
3859 if (makeAbsPath(filename, path).exists()) {
3860 string const abstexname =
3861 makeAbsPath(filename, path).absFileName();
3862 string const absfigname =
3863 changeExtension(abstexname, ".fig");
3864 fix_child_filename(filename);
3865 string const lyxname =
3866 changeExtension(filename, ".lyx");
3867 string const abslyxname = makeAbsPath(
3868 lyxname, getParentFilePath(false)).absFileName();
3870 if (!skipChildren())
3871 external = FileName(absfigname).exists();
3872 if (t.cs() == "input" && !skipChildren()) {
3873 string const ext = getExtension(abstexname);
3875 // Combined PS/LaTeX:
3876 // x.eps, x.pstex_t (old xfig)
3877 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3878 FileName const absepsname(
3879 changeExtension(abstexname, ".eps"));
3880 FileName const abspstexname(
3881 changeExtension(abstexname, ".pstex"));
3882 bool const xfigeps =
3883 (absepsname.exists() ||
3884 abspstexname.exists()) &&
3887 // Combined PDF/LaTeX:
3888 // x.pdf, x.pdftex_t (old xfig)
3889 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3890 FileName const abspdfname(
3891 changeExtension(abstexname, ".pdf"));
3892 bool const xfigpdf =
3893 abspdfname.exists() &&
3894 (ext == "pdftex_t" || ext == "pdf_t");
3898 // Combined PS/PDF/LaTeX:
3899 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3900 string const absbase2(
3901 removeExtension(abstexname) + "_pspdftex");
3902 FileName const abseps2name(
3903 addExtension(absbase2, ".eps"));
3904 FileName const abspdf2name(
3905 addExtension(absbase2, ".pdf"));
3906 bool const xfigboth =
3907 abspdf2name.exists() &&
3908 abseps2name.exists() && ext == "pspdftex";
3910 xfig = xfigpdf || xfigeps || xfigboth;
3911 external = external && xfig;
3914 outname = changeExtension(filename, ".fig");
3915 FileName abssrc(changeExtension(abstexname, ".fig"));
3916 copy_file(abssrc, outname);
3918 // Don't try to convert, the result
3919 // would be full of ERT.
3921 FileName abssrc(abstexname);
3922 copy_file(abssrc, outname);
3923 } else if (t.cs() != "verbatiminput" &&
3925 tex2lyx(abstexname, FileName(abslyxname),
3928 // no need to call copy_file
3929 // tex2lyx creates the file
3932 FileName abssrc(abstexname);
3933 copy_file(abssrc, outname);
3936 cerr << "Warning: Could not find included file '"
3937 << filename << "'." << endl;
3941 begin_inset(os, "External\n");
3942 os << "\ttemplate XFig\n"
3943 << "\tfilename " << outname << '\n';
3944 registerExternalTemplatePackages("XFig");
3946 begin_command_inset(os, "include", name);
3947 outname = subst(outname, "\"", "\\\"");
3948 os << "preview false\n"
3949 "filename \"" << outname << "\"\n";
3950 if (t.cs() == "verbatiminput")
3951 preamble.registerAutomaticallyLoadedPackage("verbatim");
3956 else if (t.cs() == "bibliographystyle") {
3957 // store new bibliographystyle
3958 bibliographystyle = p.verbatim_item();
3959 // If any other command than \bibliography and
3960 // \nocite{*} follows, we need to output the style
3961 // (because it might be used by that command).
3962 // Otherwise, it will automatically be output by LyX.
3965 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3966 if (t2.cat() == catBegin)
3968 if (t2.cat() != catEscape)
3970 if (t2.cs() == "nocite") {
3971 if (p.getArg('{', '}') == "*")
3973 } else if (t2.cs() == "bibliography")
3980 "\\bibliographystyle{" + bibliographystyle + '}',
3985 else if (t.cs() == "bibliography") {
3986 context.check_layout(os);
3987 begin_command_inset(os, "bibtex", "bibtex");
3988 if (!btprint.empty()) {
3989 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3990 // clear the string because the next BibTeX inset can be without the
3991 // \nocite{*} option
3994 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3995 // Do we have a bibliographystyle set?
3996 if (!bibliographystyle.empty())
3997 os << "options " << '"' << bibliographystyle << '"' << "\n";
4001 else if (t.cs() == "parbox") {
4002 // Test whether this is an outer box of a shaded box
4004 // swallow arguments
4005 while (p.hasOpt()) {
4007 p.skip_spaces(true);
4010 p.skip_spaces(true);
4012 if (p.next_token().cat() == catBegin)
4014 p.skip_spaces(true);
4015 Token to = p.get_token();
4016 bool shaded = false;
4017 if (to.asInput() == "\\begin") {
4018 p.skip_spaces(true);
4019 if (p.getArg('{', '}') == "shaded")
4024 parse_outer_box(p, os, FLAG_ITEM, outer,
4025 context, "parbox", "shaded");
4027 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4031 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4032 t.cs() == "shadowbox" || t.cs() == "doublebox")
4033 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4035 else if (t.cs() == "framebox") {
4036 if (p.next_token().character() == '(') {
4037 //the syntax is: \framebox(x,y)[position]{content}
4038 string arg = t.asInput();
4039 arg += p.getFullParentheseArg();
4040 arg += p.getFullOpt();
4041 eat_whitespace(p, os, context, false);
4042 handle_ert(os, arg + '{', context);
4043 parse_text(p, os, FLAG_ITEM, outer, context);
4044 handle_ert(os, "}", context);
4046 string special = p.getFullOpt();
4047 special += p.getOpt();
4048 // LyX does not yet support \framebox without any option
4049 if (!special.empty())
4050 parse_outer_box(p, os, FLAG_ITEM, outer,
4051 context, t.cs(), special);
4053 eat_whitespace(p, os, context, false);
4054 handle_ert(os, "\\framebox{", context);
4055 parse_text(p, os, FLAG_ITEM, outer, context);
4056 handle_ert(os, "}", context);
4061 //\makebox() is part of the picture environment and different from \makebox{}
4062 //\makebox{} will be parsed by parse_box
4063 else if (t.cs() == "makebox") {
4064 if (p.next_token().character() == '(') {
4065 //the syntax is: \makebox(x,y)[position]{content}
4066 string arg = t.asInput();
4067 arg += p.getFullParentheseArg();
4068 arg += p.getFullOpt();
4069 eat_whitespace(p, os, context, false);
4070 handle_ert(os, arg + '{', context);
4071 parse_text(p, os, FLAG_ITEM, outer, context);
4072 handle_ert(os, "}", context);
4074 //the syntax is: \makebox[width][position]{content}
4075 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4079 else if (t.cs() == "smallskip" ||
4080 t.cs() == "medskip" ||
4081 t.cs() == "bigskip" ||
4082 t.cs() == "vfill") {
4083 context.check_layout(os);
4084 begin_inset(os, "VSpace ");
4087 skip_spaces_braces(p);
4090 else if ((where = is_known(t.cs(), known_spaces))) {
4091 context.check_layout(os);
4092 begin_inset(os, "space ");
4093 os << '\\' << known_coded_spaces[where - known_spaces]
4096 // LaTeX swallows whitespace after all spaces except
4097 // "\\,". We have to do that here, too, because LyX
4098 // adds "{}" which would make the spaces significant.
4100 eat_whitespace(p, os, context, false);
4101 // LyX adds "{}" after all spaces except "\\ " and
4102 // "\\,", so we have to remove "{}".
4103 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4104 // remove the braces after "\\,", too.
4109 else if (t.cs() == "newpage" ||
4110 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4111 t.cs() == "clearpage" ||
4112 t.cs() == "cleardoublepage") {
4113 context.check_layout(os);
4114 begin_inset(os, "Newpage ");
4117 skip_spaces_braces(p);
4120 else if (t.cs() == "DeclareRobustCommand" ||
4121 t.cs() == "DeclareRobustCommandx" ||
4122 t.cs() == "newcommand" ||
4123 t.cs() == "newcommandx" ||
4124 t.cs() == "providecommand" ||
4125 t.cs() == "providecommandx" ||
4126 t.cs() == "renewcommand" ||
4127 t.cs() == "renewcommandx") {
4128 // DeclareRobustCommand, DeclareRobustCommandx,
4129 // providecommand and providecommandx could be handled
4130 // by parse_command(), but we need to call
4131 // add_known_command() here.
4132 string name = t.asInput();
4133 if (p.next_token().asInput() == "*") {
4134 // Starred form. Eat '*'
4138 string const command = p.verbatim_item();
4139 string const opt1 = p.getFullOpt();
4140 string const opt2 = p.getFullOpt();
4141 add_known_command(command, opt1, !opt2.empty());
4142 string const ert = name + '{' + command + '}' +
4144 '{' + p.verbatim_item() + '}';
4146 if (t.cs() == "DeclareRobustCommand" ||
4147 t.cs() == "DeclareRobustCommandx" ||
4148 t.cs() == "providecommand" ||
4149 t.cs() == "providecommandx" ||
4150 name[name.length()-1] == '*')
4151 handle_ert(os, ert, context);
4153 context.check_layout(os);
4154 begin_inset(os, "FormulaMacro");
4160 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4161 // let could be handled by parse_command(),
4162 // but we need to call add_known_command() here.
4163 string ert = t.asInput();
4166 if (p.next_token().cat() == catBegin) {
4167 name = p.verbatim_item();
4168 ert += '{' + name + '}';
4170 name = p.verbatim_item();
4175 if (p.next_token().cat() == catBegin) {
4176 command = p.verbatim_item();
4177 ert += '{' + command + '}';
4179 command = p.verbatim_item();
4182 // If command is known, make name known too, to parse
4183 // its arguments correctly. For this reason we also
4184 // have commands in syntax.default that are hardcoded.
4185 CommandMap::iterator it = known_commands.find(command);
4186 if (it != known_commands.end())
4187 known_commands[t.asInput()] = it->second;
4188 handle_ert(os, ert, context);
4191 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4192 bool starred = false;
4193 if (p.next_token().asInput() == "*") {
4197 string name = t.asInput();
4198 string const length = p.verbatim_item();
4201 bool valid = splitLatexLength(length, valstring, unit);
4202 bool known_hspace = false;
4203 bool known_vspace = false;
4204 bool known_unit = false;
4207 istringstream iss(valstring);
4210 if (t.cs()[0] == 'h') {
4211 if (unit == "\\fill") {
4216 known_hspace = true;
4219 if (unit == "\\smallskipamount") {
4221 known_vspace = true;
4222 } else if (unit == "\\medskipamount") {
4224 known_vspace = true;
4225 } else if (unit == "\\bigskipamount") {
4227 known_vspace = true;
4228 } else if (unit == "\\fill") {
4230 known_vspace = true;
4234 if (!known_hspace && !known_vspace) {
4235 switch (unitFromString(unit)) {
4256 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4257 // Literal horizontal length or known variable
4258 context.check_layout(os);
4259 begin_inset(os, "space ");
4267 if (known_unit && !known_hspace)
4269 << translate_len(length);
4271 } else if (known_unit || known_vspace) {
4272 // Literal vertical length or known variable
4273 context.check_layout(os);
4274 begin_inset(os, "VSpace ");
4282 // LyX can't handle other length variables in Inset VSpace/space
4287 handle_ert(os, name + '{' + unit + '}', context);
4288 else if (value == -1.0)
4289 handle_ert(os, name + "{-" + unit + '}', context);
4291 handle_ert(os, name + '{' + valstring + unit + '}', context);
4293 handle_ert(os, name + '{' + length + '}', context);
4297 // The single '=' is meant here.
4298 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4300 context.check_layout(os);
4301 begin_inset(os, "Flex ");
4302 os << to_utf8(newinsetlayout->name()) << '\n'
4303 << "status collapsed\n";
4304 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4308 else if (t.cs() == "includepdf") {
4310 string const arg = p.getArg('[', ']');
4311 map<string, string> opts;
4312 vector<string> keys;
4313 split_map(arg, opts, keys);
4314 string name = normalize_filename(p.verbatim_item());
4315 string const path = getMasterFilePath(true);
4316 // We want to preserve relative / absolute filenames,
4317 // therefore path is only used for testing
4318 if (!makeAbsPath(name, path).exists()) {
4319 // The file extension is probably missing.
4320 // Now try to find it out.
4321 char const * const pdfpages_format[] = {"pdf", 0};
4322 string const pdftex_name =
4323 find_file(name, path, pdfpages_format);
4324 if (!pdftex_name.empty()) {
4329 FileName const absname = makeAbsPath(name, path);
4330 if (absname.exists())
4332 fix_child_filename(name);
4333 copy_file(absname, name);
4335 cerr << "Warning: Could not find file '"
4336 << name << "'." << endl;
4338 context.check_layout(os);
4339 begin_inset(os, "External\n\ttemplate ");
4340 os << "PDFPages\n\tfilename "
4342 // parse the options
4343 if (opts.find("pages") != opts.end())
4344 os << "\textra LaTeX \"pages="
4345 << opts["pages"] << "\"\n";
4346 if (opts.find("angle") != opts.end())
4347 os << "\trotateAngle "
4348 << opts["angle"] << '\n';
4349 if (opts.find("origin") != opts.end()) {
4351 string const opt = opts["origin"];
4352 if (opt == "tl") ss << "topleft";
4353 if (opt == "bl") ss << "bottomleft";
4354 if (opt == "Bl") ss << "baselineleft";
4355 if (opt == "c") ss << "center";
4356 if (opt == "tc") ss << "topcenter";
4357 if (opt == "bc") ss << "bottomcenter";
4358 if (opt == "Bc") ss << "baselinecenter";
4359 if (opt == "tr") ss << "topright";
4360 if (opt == "br") ss << "bottomright";
4361 if (opt == "Br") ss << "baselineright";
4362 if (!ss.str().empty())
4363 os << "\trotateOrigin " << ss.str() << '\n';
4365 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4367 if (opts.find("width") != opts.end())
4369 << translate_len(opts["width"]) << '\n';
4370 if (opts.find("height") != opts.end())
4372 << translate_len(opts["height"]) << '\n';
4373 if (opts.find("keepaspectratio") != opts.end())
4374 os << "\tkeepAspectRatio\n";
4376 context.check_layout(os);
4377 registerExternalTemplatePackages("PDFPages");
4380 else if (t.cs() == "loadgame") {
4382 string name = normalize_filename(p.verbatim_item());
4383 string const path = getMasterFilePath(true);
4384 // We want to preserve relative / absolute filenames,
4385 // therefore path is only used for testing
4386 if (!makeAbsPath(name, path).exists()) {
4387 // The file extension is probably missing.
4388 // Now try to find it out.
4389 char const * const lyxskak_format[] = {"fen", 0};
4390 string const lyxskak_name =
4391 find_file(name, path, lyxskak_format);
4392 if (!lyxskak_name.empty())
4393 name = lyxskak_name;
4395 FileName const absname = makeAbsPath(name, path);
4396 if (absname.exists())
4398 fix_child_filename(name);
4399 copy_file(absname, name);
4401 cerr << "Warning: Could not find file '"
4402 << name << "'." << endl;
4403 context.check_layout(os);
4404 begin_inset(os, "External\n\ttemplate ");
4405 os << "ChessDiagram\n\tfilename "
4408 context.check_layout(os);
4409 // after a \loadgame follows a \showboard
4410 if (p.get_token().asInput() == "showboard")
4412 registerExternalTemplatePackages("ChessDiagram");
4416 // try to see whether the string is in unicodesymbols
4417 // Only use text mode commands, since we are in text mode here,
4418 // and math commands may be invalid (bug 6797)
4422 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4423 Encodings::TEXT_CMD, termination, rem, &req);
4426 cerr << "When parsing " << t.cs()
4427 << ", result is " << to_utf8(s)
4428 << "+" << to_utf8(rem) << endl;
4429 context.check_layout(os);
4432 skip_spaces_braces(p);
4433 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4434 preamble.registerAutomaticallyLoadedPackage(*it);
4436 //cerr << "#: " << t << " mode: " << mode << endl;
4437 // heuristic: read up to next non-nested space
4439 string s = t.asInput();
4440 string z = p.verbatim_item();
4441 while (p.good() && z != " " && !z.empty()) {
4442 //cerr << "read: " << z << endl;
4444 z = p.verbatim_item();
4446 cerr << "found ERT: " << s << endl;
4447 handle_ert(os, s + ' ', context);
4450 string name = t.asInput();
4451 if (p.next_token().asInput() == "*") {
4452 // Starred commands like \vspace*{}
4453 p.get_token(); // Eat '*'
4456 if (!parse_command(name, p, os, outer, context))
4457 handle_ert(os, name, context);
4461 if (flags & FLAG_LEAVE) {
4462 flags &= ~FLAG_LEAVE;
4469 string guessLanguage(Parser & p, string const & lang)
4471 typedef std::map<std::string, size_t> LangMap;
4472 // map from language names to number of characters
4475 for (char const * const * i = supported_CJK_languages; *i; i++)
4476 used[string(*i)] = 0;
4479 Token const t = p.get_token();
4480 // comments are not counted for any language
4481 if (t.cat() == catComment)
4483 // commands are not counted as well, but we need to detect
4484 // \begin{CJK} and switch encoding if needed
4485 if (t.cat() == catEscape) {
4486 if (t.cs() == "inputencoding") {
4487 string const enc = subst(p.verbatim_item(), "\n", " ");
4491 if (t.cs() != "begin")
4494 // Non-CJK content is counted for lang.
4495 // We do not care about the real language here:
4496 // If we have more non-CJK contents than CJK contents,
4497 // we simply use the language that was specified as
4498 // babel main language.
4499 used[lang] += t.asInput().length();
4502 // Now we are starting an environment
4504 string const name = p.getArg('{', '}');
4505 if (name != "CJK") {
4509 // It is a CJK environment
4511 /* name = */ p.getArg('{', '}');
4512 string const encoding = p.getArg('{', '}');
4513 /* mapping = */ p.getArg('{', '}');
4514 string const encoding_old = p.getEncoding();
4515 char const * const * const where =
4516 is_known(encoding, supported_CJK_encodings);
4518 p.setEncoding(encoding);
4520 p.setEncoding("utf8");
4521 string const text = p.verbatimEnvironment("CJK");
4522 p.setEncoding(encoding_old);
4525 // ignore contents in unknown CJK encoding
4528 // the language of the text
4530 supported_CJK_languages[where - supported_CJK_encodings];
4531 used[cjk] += text.length();
4533 LangMap::const_iterator use = used.begin();
4534 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4535 if (it->second > use->second)