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 ia 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 ia 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 ia 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 ia 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)
1842 Parser p(trim(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") {
1863 /// Convert \p name from TeX convention (relative to master file) to LyX
1864 /// convention (relative to .lyx file) if it is relative
1865 void fix_child_filename(string & name)
1867 string const absMasterTeX = getMasterFilePath(true);
1868 bool const isabs = FileName::isAbsolute(name);
1869 // convert from "relative to .tex master" to absolute original path
1871 name = makeAbsPath(name, absMasterTeX).absFileName();
1872 bool copyfile = copyFiles();
1873 string const absParentLyX = getParentFilePath(false);
1876 // convert from absolute original path to "relative to master file"
1877 string const rel = to_utf8(makeRelPath(from_utf8(name),
1878 from_utf8(absMasterTeX)));
1879 // re-interpret "relative to .tex file" as "relative to .lyx file"
1880 // (is different if the master .lyx file resides in a
1881 // different path than the master .tex file)
1882 string const absMasterLyX = getMasterFilePath(false);
1883 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1884 // Do not copy if the new path is impossible to create. Example:
1885 // absMasterTeX = "/foo/bar/"
1886 // absMasterLyX = "/bar/"
1887 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1888 if (contains(name, "/../"))
1895 // convert from absolute original path to
1896 // "relative to .lyx file"
1897 name = to_utf8(makeRelPath(from_utf8(abs),
1898 from_utf8(absParentLyX)));
1902 // convert from absolute original path to "relative to .lyx file"
1903 name = to_utf8(makeRelPath(from_utf8(name),
1904 from_utf8(absParentLyX)));
1909 void copy_file(FileName const & src, string dstname)
1913 string const absParent = getParentFilePath(false);
1915 if (FileName::isAbsolute(dstname))
1916 dst = FileName(dstname);
1918 dst = makeAbsPath(dstname, absParent);
1919 string const absMaster = getMasterFilePath(false);
1920 FileName const srcpath = src.onlyPath();
1921 FileName const dstpath = dst.onlyPath();
1922 if (equivalent(srcpath, dstpath))
1924 if (!dstpath.isDirectory()) {
1925 if (!dstpath.createPath()) {
1926 cerr << "Warning: Could not create directory for file `"
1927 << dst.absFileName() << "´." << endl;
1931 if (dst.isReadableFile()) {
1932 if (overwriteFiles())
1933 cerr << "Warning: Overwriting existing file `"
1934 << dst.absFileName() << "´." << endl;
1936 cerr << "Warning: Not overwriting existing file `"
1937 << dst.absFileName() << "´." << endl;
1941 if (!src.copyTo(dst))
1942 cerr << "Warning: Could not copy file `" << src.absFileName()
1943 << "´ to `" << dst.absFileName() << "´." << endl;
1947 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1948 void parse_noweb(Parser & p, ostream & os, Context & context)
1950 // assemble the rest of the keyword
1954 Token const & t = p.get_token();
1955 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1958 scrap = (p.good() && p.next_token().asInput() == "=");
1960 name += p.get_token().asInput();
1963 name += t.asInput();
1966 if (!scrap || !context.new_layout_allowed ||
1967 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1968 cerr << "Warning: Could not interpret '" << name
1969 << "'. Ignoring it." << endl;
1973 // We use new_paragraph instead of check_end_layout because the stuff
1974 // following the noweb chunk needs to start with a \begin_layout.
1975 // This may create a new paragraph even if there was none in the
1976 // noweb file, but the alternative is an invalid LyX file. Since
1977 // noweb code chunks are implemented with a layout style in LyX they
1978 // always must be in an own paragraph.
1979 context.new_paragraph(os);
1980 Context newcontext(true, context.textclass,
1981 &context.textclass[from_ascii("Scrap")]);
1982 newcontext.check_layout(os);
1985 Token const & t = p.get_token();
1986 // We abuse the parser a bit, because this is no TeX syntax
1988 if (t.cat() == catEscape)
1989 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1992 Context tmp(false, context.textclass,
1993 &context.textclass[from_ascii("Scrap")]);
1994 tmp.need_end_layout = true;
1995 tmp.check_layout(oss);
1996 os << subst(t.asInput(), "\n", oss.str());
1998 // The scrap chunk is ended by an @ at the beginning of a line.
1999 // After the @ the line may contain a comment and/or
2000 // whitespace, but nothing else.
2001 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2002 (p.next_token().cat() == catSpace ||
2003 p.next_token().cat() == catNewline ||
2004 p.next_token().cat() == catComment)) {
2005 while (p.good() && p.next_token().cat() == catSpace)
2006 os << p.get_token().asInput();
2007 if (p.next_token().cat() == catComment)
2008 // The comment includes a final '\n'
2009 os << p.get_token().asInput();
2011 if (p.next_token().cat() == catNewline)
2018 newcontext.check_end_layout(os);
2022 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2023 bool is_macro(Parser & p)
2025 Token first = p.curr_token();
2026 if (first.cat() != catEscape || !p.good())
2028 if (first.cs() == "def")
2030 if (first.cs() != "global" && first.cs() != "long")
2032 Token second = p.get_token();
2034 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2035 second.cat() == catNewline || second.cat() == catComment)) {
2036 second = p.get_token();
2039 bool secondvalid = second.cat() == catEscape;
2041 bool thirdvalid = false;
2042 if (p.good() && first.cs() == "global" && secondvalid &&
2043 second.cs() == "long") {
2044 third = p.get_token();
2046 while (p.good() && !p.isParagraph() &&
2047 (third.cat() == catSpace ||
2048 third.cat() == catNewline ||
2049 third.cat() == catComment)) {
2050 third = p.get_token();
2053 thirdvalid = third.cat() == catEscape;
2055 for (int i = 0; i < pos; ++i)
2060 return (first.cs() == "global" || first.cs() == "long") &&
2061 second.cs() == "def";
2062 return first.cs() == "global" && second.cs() == "long" &&
2063 third.cs() == "def";
2067 /// Parse a macro definition (assumes that is_macro() returned true)
2068 void parse_macro(Parser & p, ostream & os, Context & context)
2070 context.check_layout(os);
2071 Token first = p.curr_token();
2074 string command = first.asInput();
2075 if (first.cs() != "def") {
2077 eat_whitespace(p, os, context, false);
2078 second = p.curr_token();
2079 command += second.asInput();
2080 if (second.cs() != "def") {
2082 eat_whitespace(p, os, context, false);
2083 third = p.curr_token();
2084 command += third.asInput();
2087 eat_whitespace(p, os, context, false);
2088 string const name = p.get_token().cs();
2089 eat_whitespace(p, os, context, false);
2095 while (p.next_token().cat() != catBegin) {
2096 if (p.next_token().cat() == catParameter) {
2101 // followed by number?
2102 if (p.next_token().cat() == catOther) {
2103 char c = p.getChar();
2105 // number = current arity + 1?
2106 if (c == arity + '0' + 1)
2111 paramtext += p.get_token().cs();
2113 paramtext += p.get_token().cs();
2118 // only output simple (i.e. compatible) macro as FormulaMacros
2119 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2121 context.check_layout(os);
2122 begin_inset(os, "FormulaMacro");
2123 os << "\n\\def" << ert;
2126 handle_ert(os, command + ert, context);
2130 void registerExternalTemplatePackages(string const & name)
2132 external::TemplateManager const & etm = external::TemplateManager::get();
2133 external::Template const * const et = etm.getTemplateByName(name);
2136 external::Template::Formats::const_iterator cit = et->formats.end();
2138 cit = et->formats.find("PDFLaTeX");
2139 if (cit == et->formats.end())
2140 // If the template has not specified a PDFLaTeX output,
2141 // we try the LaTeX format.
2142 cit = et->formats.find("LaTeX");
2143 if (cit == et->formats.end())
2145 vector<string>::const_iterator qit = cit->second.requirements.begin();
2146 vector<string>::const_iterator qend = cit->second.requirements.end();
2147 for (; qit != qend; ++qit)
2148 preamble.registerAutomaticallyLoadedPackage(*qit);
2151 } // anonymous namespace
2154 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2157 Layout const * newlayout = 0;
2158 InsetLayout const * newinsetlayout = 0;
2159 char const * const * where = 0;
2160 // Store the latest bibliographystyle and nocite{*} option
2161 // (needed for bibtex inset)
2163 string bibliographystyle = "default";
2164 bool const use_natbib = preamble.isPackageUsed("natbib");
2165 bool const use_jurabib = preamble.isPackageUsed("jurabib");
2168 Token const & t = p.get_token();
2170 // it is impossible to determine the correct encoding for non-CJK Japanese.
2171 // Therefore write a note at the beginning of the document
2172 if (is_nonCJKJapanese) {
2173 context.check_layout(os);
2174 begin_inset(os, "Note Note\n");
2175 os << "status open\n\\begin_layout Plain Layout\n"
2176 << "\\series bold\n"
2177 << "Important information:\n"
2178 << "\\end_layout\n\n"
2179 << "\\begin_layout Plain Layout\n"
2180 << "This document is in Japanese (non-CJK).\n"
2181 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2182 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2183 << " encoding in the document settings.\n"
2184 << "\\end_layout\n";
2186 is_nonCJKJapanese = false;
2190 debugToken(cerr, t, flags);
2193 if (flags & FLAG_ITEM) {
2194 if (t.cat() == catSpace)
2197 flags &= ~FLAG_ITEM;
2198 if (t.cat() == catBegin) {
2199 // skip the brace and collect everything to the next matching
2201 flags |= FLAG_BRACE_LAST;
2205 // handle only this single token, leave the loop if done
2206 flags |= FLAG_LEAVE;
2209 if (t.cat() != catEscape && t.character() == ']' &&
2210 (flags & FLAG_BRACK_LAST))
2212 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2215 // If there is anything between \end{env} and \begin{env} we
2216 // don't need to output a separator.
2217 if (t.cat() != catSpace && t.cat() != catNewline &&
2218 t.asInput() != "\\begin")
2224 if (t.cat() == catMath) {
2225 // we are inside some text mode thingy, so opening new math is allowed
2226 context.check_layout(os);
2227 begin_inset(os, "Formula ");
2228 Token const & n = p.get_token();
2229 bool const display(n.cat() == catMath && outer);
2231 // TeX's $$...$$ syntax for displayed math
2233 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2235 p.get_token(); // skip the second '$' token
2237 // simple $...$ stuff
2240 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2245 // Prevent the conversion of a line break to a
2246 // space (bug 7668). This does not change the
2247 // output, but looks ugly in LyX.
2248 eat_whitespace(p, os, context, false);
2252 else if (t.cat() == catSuper || t.cat() == catSub)
2253 cerr << "catcode " << t << " illegal in text mode\n";
2255 // Basic support for english quotes. This should be
2256 // extended to other quotes, but is not so easy (a
2257 // left english quote is the same as a right german
2259 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2260 context.check_layout(os);
2261 begin_inset(os, "Quotes ");
2267 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2268 context.check_layout(os);
2269 begin_inset(os, "Quotes ");
2276 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2277 context.check_layout(os);
2278 begin_inset(os, "Quotes ");
2285 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2286 context.check_layout(os);
2287 begin_inset(os, "Quotes ");
2294 else if (t.asInput() == "<"
2295 && p.next_token().asInput() == "<" && noweb_mode) {
2297 parse_noweb(p, os, context);
2300 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2301 check_space(p, os, context);
2303 else if (t.character() == '[' && noweb_mode &&
2304 p.next_token().character() == '[') {
2305 // These can contain underscores
2307 string const s = p.getFullOpt() + ']';
2308 if (p.next_token().character() == ']')
2311 cerr << "Warning: Inserting missing ']' in '"
2312 << s << "'." << endl;
2313 handle_ert(os, s, context);
2316 else if (t.cat() == catLetter) {
2317 context.check_layout(os);
2318 // Workaround for bug 4752.
2319 // FIXME: This whole code block needs to be removed
2320 // when the bug is fixed and tex2lyx produces
2321 // the updated file format.
2322 // The replacement algorithm in LyX is so stupid that
2323 // it even translates a phrase if it is part of a word.
2324 bool handled = false;
2325 for (int const * l = known_phrase_lengths; *l; ++l) {
2326 string phrase = t.cs();
2327 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2328 phrase += p.get_token().cs();
2329 if (is_known(phrase, known_coded_phrases)) {
2330 handle_ert(os, phrase, context);
2334 for (size_t i = 1; i < phrase.length(); ++i)
2342 else if (t.cat() == catOther ||
2343 t.cat() == catAlign ||
2344 t.cat() == catParameter) {
2345 // This translates "&" to "\\&" which may be wrong...
2346 context.check_layout(os);
2350 else if (p.isParagraph()) {
2351 if (context.new_layout_allowed)
2352 context.new_paragraph(os);
2354 handle_ert(os, "\\par ", context);
2355 eat_whitespace(p, os, context, true);
2358 else if (t.cat() == catActive) {
2359 context.check_layout(os);
2360 if (t.character() == '~') {
2361 if (context.layout->free_spacing)
2364 begin_inset(os, "space ~\n");
2371 else if (t.cat() == catBegin) {
2372 Token const next = p.next_token();
2373 Token const end = p.next_next_token();
2374 if (next.cat() == catEnd) {
2376 Token const prev = p.prev_token();
2378 if (p.next_token().character() == '`' ||
2379 (prev.character() == '-' &&
2380 p.next_token().character() == '-'))
2381 ; // ignore it in {}`` or -{}-
2383 handle_ert(os, "{}", context);
2384 } else if (next.cat() == catEscape &&
2385 is_known(next.cs(), known_quotes) &&
2386 end.cat() == catEnd) {
2387 // Something like {\textquoteright} (e.g.
2388 // from writer2latex). LyX writes
2389 // \textquoteright{}, so we may skip the
2390 // braces here for better readability.
2391 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2394 context.check_layout(os);
2395 // special handling of font attribute changes
2396 Token const prev = p.prev_token();
2397 TeXFont const oldFont = context.font;
2398 if (next.character() == '[' ||
2399 next.character() == ']' ||
2400 next.character() == '*') {
2402 if (p.next_token().cat() == catEnd) {
2407 handle_ert(os, "{", context);
2408 parse_text_snippet(p, os,
2411 handle_ert(os, "}", context);
2413 } else if (! context.new_layout_allowed) {
2414 handle_ert(os, "{", context);
2415 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2417 handle_ert(os, "}", context);
2418 } else if (is_known(next.cs(), known_sizes)) {
2419 // next will change the size, so we must
2421 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2423 if (!context.atParagraphStart())
2425 << context.font.size << "\n";
2426 } else if (is_known(next.cs(), known_font_families)) {
2427 // next will change the font family, so we
2428 // must reset it here
2429 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2431 if (!context.atParagraphStart())
2433 << context.font.family << "\n";
2434 } else if (is_known(next.cs(), known_font_series)) {
2435 // next will change the font series, so we
2436 // must reset it here
2437 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2439 if (!context.atParagraphStart())
2441 << context.font.series << "\n";
2442 } else if (is_known(next.cs(), known_font_shapes)) {
2443 // next will change the font shape, so we
2444 // must reset it here
2445 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2447 if (!context.atParagraphStart())
2449 << context.font.shape << "\n";
2450 } else if (is_known(next.cs(), known_old_font_families) ||
2451 is_known(next.cs(), known_old_font_series) ||
2452 is_known(next.cs(), known_old_font_shapes)) {
2453 // next will change the font family, series
2454 // and shape, so we must reset it here
2455 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2457 if (!context.atParagraphStart())
2459 << context.font.family
2461 << context.font.series
2463 << context.font.shape << "\n";
2465 handle_ert(os, "{", context);
2466 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2468 handle_ert(os, "}", context);
2473 else if (t.cat() == catEnd) {
2474 if (flags & FLAG_BRACE_LAST) {
2477 cerr << "stray '}' in text\n";
2478 handle_ert(os, "}", context);
2481 else if (t.cat() == catComment)
2482 parse_comment(p, os, t, context);
2485 // control sequences
2488 else if (t.cs() == "(") {
2489 context.check_layout(os);
2490 begin_inset(os, "Formula");
2492 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2497 else if (t.cs() == "[") {
2498 context.check_layout(os);
2499 begin_inset(os, "Formula");
2501 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2504 // Prevent the conversion of a line break to a space
2505 // (bug 7668). This does not change the output, but
2506 // looks ugly in LyX.
2507 eat_whitespace(p, os, context, false);
2510 else if (t.cs() == "begin")
2511 parse_environment(p, os, outer, last_env,
2514 else if (t.cs() == "end") {
2515 if (flags & FLAG_END) {
2516 // eat environment name
2517 string const name = p.getArg('{', '}');
2518 if (name != active_environment())
2519 cerr << "\\end{" + name + "} does not match \\begin{"
2520 + active_environment() + "}\n";
2523 p.error("found 'end' unexpectedly");
2526 else if (t.cs() == "item") {
2528 bool const optarg = p.hasOpt();
2530 // FIXME: This swallows comments, but we cannot use
2531 // eat_whitespace() since we must not output
2532 // anything before the item.
2533 p.skip_spaces(true);
2534 s = p.verbatimOption();
2536 p.skip_spaces(false);
2538 context.check_layout(os);
2539 if (context.has_item) {
2540 // An item in an unknown list-like environment
2541 // FIXME: Do this in check_layout()!
2542 context.has_item = false;
2544 handle_ert(os, "\\item", context);
2546 handle_ert(os, "\\item ", context);
2549 if (context.layout->labeltype != LABEL_MANUAL) {
2550 // LyX does not support \item[\mybullet]
2551 // in itemize environments
2553 os << parse_text_snippet(p2,
2554 FLAG_BRACK_LAST, outer, context);
2555 } else if (!s.empty()) {
2556 // LyX adds braces around the argument,
2557 // so we need to remove them here.
2558 if (s.size() > 2 && s[0] == '{' &&
2559 s[s.size()-1] == '}')
2560 s = s.substr(1, s.size()-2);
2561 // If the argument contains a space we
2562 // must put it into ERT: Otherwise LyX
2563 // would misinterpret the space as
2564 // item delimiter (bug 7663)
2565 if (contains(s, ' ')) {
2566 handle_ert(os, s, context);
2569 os << parse_text_snippet(p2,
2573 // The space is needed to separate the
2574 // item from the rest of the sentence.
2576 eat_whitespace(p, os, context, false);
2581 else if (t.cs() == "bibitem") {
2583 context.check_layout(os);
2584 eat_whitespace(p, os, context, false);
2585 string label = convert_command_inset_arg(p.verbatimOption());
2586 string key = convert_command_inset_arg(p.verbatim_item());
2587 if (contains(label, '\\') || contains(key, '\\')) {
2588 // LyX can't handle LaTeX commands in labels or keys
2589 handle_ert(os, t.asInput() + '[' + label +
2590 "]{" + p.verbatim_item() + '}',
2593 begin_command_inset(os, "bibitem", "bibitem");
2594 os << "label \"" << label << "\"\n"
2595 "key \"" << key << "\"\n";
2600 else if (is_macro(p)) {
2601 // catch the case of \def\inputGnumericTable
2603 if (t.cs() == "def") {
2604 Token second = p.next_token();
2605 if (second.cs() == "inputGnumericTable") {
2609 Token third = p.get_token();
2611 if (third.cs() == "input") {
2615 string name = normalize_filename(p.verbatim_item());
2616 string const path = getMasterFilePath(true);
2617 // We want to preserve relative / absolute filenames,
2618 // therefore path is only used for testing
2619 // The file extension is in every case ".tex".
2620 // So we need to remove this extension and check for
2621 // the original one.
2622 name = removeExtension(name);
2623 if (!makeAbsPath(name, path).exists()) {
2624 char const * const Gnumeric_formats[] = {"gnumeric",
2626 string const Gnumeric_name =
2627 find_file(name, path, Gnumeric_formats);
2628 if (!Gnumeric_name.empty())
2629 name = Gnumeric_name;
2631 FileName const absname = makeAbsPath(name, path);
2632 if (absname.exists()) {
2633 fix_child_filename(name);
2634 copy_file(absname, name);
2636 cerr << "Warning: Could not find file '"
2637 << name << "'." << endl;
2638 context.check_layout(os);
2639 begin_inset(os, "External\n\ttemplate ");
2640 os << "GnumericSpreadsheet\n\tfilename "
2643 context.check_layout(os);
2645 // register the packages that are automatically loaded
2646 // by the Gnumeric template
2647 registerExternalTemplatePackages("GnumericSpreadsheet");
2652 parse_macro(p, os, context);
2655 else if (t.cs() == "noindent") {
2657 context.add_par_extra_stuff("\\noindent\n");
2660 else if (t.cs() == "appendix") {
2661 context.add_par_extra_stuff("\\start_of_appendix\n");
2662 // We need to start a new paragraph. Otherwise the
2663 // appendix in 'bla\appendix\chapter{' would start
2665 context.new_paragraph(os);
2666 // We need to make sure that the paragraph is
2667 // generated even if it is empty. Otherwise the
2668 // appendix in '\par\appendix\par\chapter{' would
2670 context.check_layout(os);
2671 // FIXME: This is a hack to prevent paragraph
2672 // deletion if it is empty. Handle this better!
2674 "%dummy comment inserted by tex2lyx to "
2675 "ensure that this paragraph is not empty",
2677 // Both measures above may generate an additional
2678 // empty paragraph, but that does not hurt, because
2679 // whitespace does not matter here.
2680 eat_whitespace(p, os, context, true);
2683 // Must catch empty dates before findLayout is called below
2684 else if (t.cs() == "date") {
2685 eat_whitespace(p, os, context, false);
2687 string const date = p.verbatim_item();
2690 preamble.suppressDate(true);
2693 preamble.suppressDate(false);
2694 if (context.new_layout_allowed &&
2695 (newlayout = findLayout(context.textclass,
2698 output_command_layout(os, p, outer,
2699 context, newlayout);
2700 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2701 if (!preamble.titleLayoutFound())
2702 preamble.titleLayoutFound(newlayout->intitle);
2703 set<string> const & req = newlayout->requires();
2704 set<string>::const_iterator it = req.begin();
2705 set<string>::const_iterator en = req.end();
2706 for (; it != en; ++it)
2707 preamble.registerAutomaticallyLoadedPackage(*it);
2710 "\\date{" + p.verbatim_item() + '}',
2715 // Starred section headings
2716 // Must attempt to parse "Section*" before "Section".
2717 else if ((p.next_token().asInput() == "*") &&
2718 context.new_layout_allowed &&
2719 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2722 output_command_layout(os, p, outer, context, newlayout);
2724 if (!preamble.titleLayoutFound())
2725 preamble.titleLayoutFound(newlayout->intitle);
2726 set<string> const & req = newlayout->requires();
2727 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2728 preamble.registerAutomaticallyLoadedPackage(*it);
2731 // Section headings and the like
2732 else if (context.new_layout_allowed &&
2733 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2735 output_command_layout(os, p, outer, context, newlayout);
2737 if (!preamble.titleLayoutFound())
2738 preamble.titleLayoutFound(newlayout->intitle);
2739 set<string> const & req = newlayout->requires();
2740 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2741 preamble.registerAutomaticallyLoadedPackage(*it);
2744 else if (t.cs() == "caption") {
2746 context.check_layout(os);
2748 begin_inset(os, "Caption\n");
2749 Context newcontext(true, context.textclass, 0, 0, context.font);
2750 newcontext.check_layout(os);
2751 // FIXME InsetArgument is now properly implemented in InsetLayout
2752 // (for captions, but also for others)
2753 if (p.next_token().cat() != catEscape &&
2754 p.next_token().character() == '[') {
2755 p.get_token(); // eat '['
2756 begin_inset(os, "Argument 1\n");
2757 os << "status collapsed\n";
2758 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2760 eat_whitespace(p, os, context, false);
2762 parse_text(p, os, FLAG_ITEM, outer, context);
2763 context.check_end_layout(os);
2764 // We don't need really a new paragraph, but
2765 // we must make sure that the next item gets a \begin_layout.
2766 context.new_paragraph(os);
2769 newcontext.check_end_layout(os);
2772 else if (t.cs() == "subfloat") {
2773 // the syntax is \subfloat[caption]{content}
2774 // if it is a table of figure depends on the surrounding float
2775 bool has_caption = false;
2777 // do nothing if there is no outer float
2778 if (!float_type.empty()) {
2779 context.check_layout(os);
2781 begin_inset(os, "Float " + float_type + "\n");
2783 << "\nsideways false"
2784 << "\nstatus collapsed\n\n";
2787 if (p.next_token().cat() != catEscape &&
2788 p.next_token().character() == '[') {
2789 p.get_token(); // eat '['
2790 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2794 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2795 // the caption comes always as the last
2797 // we must make sure that the caption gets a \begin_layout
2798 os << "\n\\begin_layout Plain Layout";
2800 begin_inset(os, "Caption\n");
2801 Context newcontext(true, context.textclass,
2802 0, 0, context.font);
2803 newcontext.check_layout(os);
2804 os << caption << "\n";
2805 newcontext.check_end_layout(os);
2806 // We don't need really a new paragraph, but
2807 // we must make sure that the next item gets a \begin_layout.
2808 //newcontext.new_paragraph(os);
2812 // We don't need really a new paragraph, but
2813 // we must make sure that the next item gets a \begin_layout.
2815 context.new_paragraph(os);
2818 context.check_end_layout(os);
2819 // close the layout we opened
2821 os << "\n\\end_layout\n";
2823 // if the float type is not supported or there is no surrounding float
2826 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2827 handle_ert(os, t.asInput() + '[' + opt_arg +
2828 "]{" + p.verbatim_item() + '}', context);
2830 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2834 else if (t.cs() == "includegraphics") {
2835 bool const clip = p.next_token().asInput() == "*";
2838 string const arg = p.getArg('[', ']');
2839 map<string, string> opts;
2840 vector<string> keys;
2841 split_map(arg, opts, keys);
2843 opts["clip"] = string();
2844 string name = normalize_filename(p.verbatim_item());
2846 string const path = getMasterFilePath(true);
2847 // We want to preserve relative / absolute filenames,
2848 // therefore path is only used for testing
2849 if (!makeAbsPath(name, path).exists()) {
2850 // The file extension is probably missing.
2851 // Now try to find it out.
2852 string const dvips_name =
2853 find_file(name, path,
2854 known_dvips_graphics_formats);
2855 string const pdftex_name =
2856 find_file(name, path,
2857 known_pdftex_graphics_formats);
2858 if (!dvips_name.empty()) {
2859 if (!pdftex_name.empty()) {
2860 cerr << "This file contains the "
2862 "\"\\includegraphics{"
2864 "However, files\n\""
2865 << dvips_name << "\" and\n\""
2866 << pdftex_name << "\"\n"
2867 "both exist, so I had to make a "
2868 "choice and took the first one.\n"
2869 "Please move the unwanted one "
2870 "someplace else and try again\n"
2871 "if my choice was wrong."
2875 } else if (!pdftex_name.empty()) {
2881 FileName const absname = makeAbsPath(name, path);
2882 if (absname.exists()) {
2883 fix_child_filename(name);
2884 copy_file(absname, name);
2886 cerr << "Warning: Could not find graphics file '"
2887 << name << "'." << endl;
2889 context.check_layout(os);
2890 begin_inset(os, "Graphics ");
2891 os << "\n\tfilename " << name << '\n';
2892 if (opts.find("width") != opts.end())
2894 << translate_len(opts["width"]) << '\n';
2895 if (opts.find("height") != opts.end())
2897 << translate_len(opts["height"]) << '\n';
2898 if (opts.find("scale") != opts.end()) {
2899 istringstream iss(opts["scale"]);
2903 os << "\tscale " << val << '\n';
2905 if (opts.find("angle") != opts.end()) {
2906 os << "\trotateAngle "
2907 << opts["angle"] << '\n';
2908 vector<string>::const_iterator a =
2909 find(keys.begin(), keys.end(), "angle");
2910 vector<string>::const_iterator s =
2911 find(keys.begin(), keys.end(), "width");
2912 if (s == keys.end())
2913 s = find(keys.begin(), keys.end(), "height");
2914 if (s == keys.end())
2915 s = find(keys.begin(), keys.end(), "scale");
2916 if (s != keys.end() && distance(s, a) > 0)
2917 os << "\tscaleBeforeRotation\n";
2919 if (opts.find("origin") != opts.end()) {
2921 string const opt = opts["origin"];
2922 if (opt.find('l') != string::npos) ss << "left";
2923 if (opt.find('r') != string::npos) ss << "right";
2924 if (opt.find('c') != string::npos) ss << "center";
2925 if (opt.find('t') != string::npos) ss << "Top";
2926 if (opt.find('b') != string::npos) ss << "Bottom";
2927 if (opt.find('B') != string::npos) ss << "Baseline";
2928 if (!ss.str().empty())
2929 os << "\trotateOrigin " << ss.str() << '\n';
2931 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2933 if (opts.find("keepaspectratio") != opts.end())
2934 os << "\tkeepAspectRatio\n";
2935 if (opts.find("clip") != opts.end())
2937 if (opts.find("draft") != opts.end())
2939 if (opts.find("bb") != opts.end())
2940 os << "\tBoundingBox "
2941 << opts["bb"] << '\n';
2942 int numberOfbbOptions = 0;
2943 if (opts.find("bbllx") != opts.end())
2944 numberOfbbOptions++;
2945 if (opts.find("bblly") != opts.end())
2946 numberOfbbOptions++;
2947 if (opts.find("bburx") != opts.end())
2948 numberOfbbOptions++;
2949 if (opts.find("bbury") != opts.end())
2950 numberOfbbOptions++;
2951 if (numberOfbbOptions == 4)
2952 os << "\tBoundingBox "
2953 << opts["bbllx"] << " " << opts["bblly"] << " "
2954 << opts["bburx"] << " " << opts["bbury"] << '\n';
2955 else if (numberOfbbOptions > 0)
2956 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2957 numberOfbbOptions = 0;
2958 if (opts.find("natwidth") != opts.end())
2959 numberOfbbOptions++;
2960 if (opts.find("natheight") != opts.end())
2961 numberOfbbOptions++;
2962 if (numberOfbbOptions == 2)
2963 os << "\tBoundingBox 0bp 0bp "
2964 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2965 else if (numberOfbbOptions > 0)
2966 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2967 ostringstream special;
2968 if (opts.find("hiresbb") != opts.end())
2969 special << "hiresbb,";
2970 if (opts.find("trim") != opts.end())
2972 if (opts.find("viewport") != opts.end())
2973 special << "viewport=" << opts["viewport"] << ',';
2974 if (opts.find("totalheight") != opts.end())
2975 special << "totalheight=" << opts["totalheight"] << ',';
2976 if (opts.find("type") != opts.end())
2977 special << "type=" << opts["type"] << ',';
2978 if (opts.find("ext") != opts.end())
2979 special << "ext=" << opts["ext"] << ',';
2980 if (opts.find("read") != opts.end())
2981 special << "read=" << opts["read"] << ',';
2982 if (opts.find("command") != opts.end())
2983 special << "command=" << opts["command"] << ',';
2984 string s_special = special.str();
2985 if (!s_special.empty()) {
2986 // We had special arguments. Remove the trailing ','.
2987 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2989 // TODO: Handle the unknown settings better.
2990 // Warn about invalid options.
2991 // Check whether some option was given twice.
2993 preamble.registerAutomaticallyLoadedPackage("graphicx");
2996 else if (t.cs() == "footnote" ||
2997 (t.cs() == "thanks" && context.layout->intitle)) {
2999 context.check_layout(os);
3000 begin_inset(os, "Foot\n");
3001 os << "status collapsed\n\n";
3002 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3006 else if (t.cs() == "marginpar") {
3008 context.check_layout(os);
3009 begin_inset(os, "Marginal\n");
3010 os << "status collapsed\n\n";
3011 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3015 else if (t.cs() == "lstinline") {
3017 parse_listings(p, os, context, true);
3020 else if (t.cs() == "ensuremath") {
3022 context.check_layout(os);
3023 string const s = p.verbatim_item();
3024 //FIXME: this never triggers in UTF8
3025 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3028 handle_ert(os, "\\ensuremath{" + s + "}",
3032 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3033 if (preamble.titleLayoutFound()) {
3035 skip_spaces_braces(p);
3037 handle_ert(os, t.asInput(), context);
3040 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3041 context.check_layout(os);
3042 begin_command_inset(os, "toc", t.cs());
3044 skip_spaces_braces(p);
3045 if (t.cs() == "lstlistoflistings")
3046 preamble.registerAutomaticallyLoadedPackage("listings");
3049 else if (t.cs() == "listoffigures") {
3050 context.check_layout(os);
3051 begin_inset(os, "FloatList figure\n");
3053 skip_spaces_braces(p);
3056 else if (t.cs() == "listoftables") {
3057 context.check_layout(os);
3058 begin_inset(os, "FloatList table\n");
3060 skip_spaces_braces(p);
3063 else if (t.cs() == "listof") {
3064 p.skip_spaces(true);
3065 string const name = p.get_token().cs();
3066 if (context.textclass.floats().typeExist(name)) {
3067 context.check_layout(os);
3068 begin_inset(os, "FloatList ");
3071 p.get_token(); // swallow second arg
3073 handle_ert(os, "\\listof{" + name + "}", context);
3076 else if ((where = is_known(t.cs(), known_text_font_families)))
3077 parse_text_attributes(p, os, FLAG_ITEM, outer,
3078 context, "\\family", context.font.family,
3079 known_coded_font_families[where - known_text_font_families]);
3081 else if ((where = is_known(t.cs(), known_text_font_series)))
3082 parse_text_attributes(p, os, FLAG_ITEM, outer,
3083 context, "\\series", context.font.series,
3084 known_coded_font_series[where - known_text_font_series]);
3086 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3087 parse_text_attributes(p, os, FLAG_ITEM, outer,
3088 context, "\\shape", context.font.shape,
3089 known_coded_font_shapes[where - known_text_font_shapes]);
3091 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3092 context.check_layout(os);
3093 TeXFont oldFont = context.font;
3094 context.font.init();
3095 context.font.size = oldFont.size;
3096 os << "\n\\family " << context.font.family << "\n";
3097 os << "\n\\series " << context.font.series << "\n";
3098 os << "\n\\shape " << context.font.shape << "\n";
3099 if (t.cs() == "textnormal") {
3100 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3101 output_font_change(os, context.font, oldFont);
3102 context.font = oldFont;
3104 eat_whitespace(p, os, context, false);
3107 else if (t.cs() == "textcolor") {
3108 // scheme is \textcolor{color name}{text}
3109 string const color = p.verbatim_item();
3110 // we only support the predefined colors of the color package
3111 if (color == "black" || color == "blue" || color == "cyan"
3112 || color == "green" || color == "magenta" || color == "red"
3113 || color == "white" || color == "yellow") {
3114 context.check_layout(os);
3115 os << "\n\\color " << color << "\n";
3116 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3117 context.check_layout(os);
3118 os << "\n\\color inherit\n";
3119 preamble.registerAutomaticallyLoadedPackage("color");
3121 // for custom defined colors
3122 handle_ert(os, t.asInput() + "{" + color + "}", context);
3125 else if (t.cs() == "underbar" || t.cs() == "uline") {
3126 // \underbar is not 100% correct (LyX outputs \uline
3127 // of ulem.sty). The difference is that \ulem allows
3128 // line breaks, and \underbar does not.
3129 // Do NOT handle \underline.
3130 // \underbar cuts through y, g, q, p etc.,
3131 // \underline does not.
3132 context.check_layout(os);
3133 os << "\n\\bar under\n";
3134 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3135 context.check_layout(os);
3136 os << "\n\\bar default\n";
3137 preamble.registerAutomaticallyLoadedPackage("ulem");
3140 else if (t.cs() == "sout") {
3141 context.check_layout(os);
3142 os << "\n\\strikeout on\n";
3143 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3144 context.check_layout(os);
3145 os << "\n\\strikeout default\n";
3146 preamble.registerAutomaticallyLoadedPackage("ulem");
3149 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3150 t.cs() == "emph" || t.cs() == "noun") {
3151 context.check_layout(os);
3152 os << "\n\\" << t.cs() << " on\n";
3153 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3154 context.check_layout(os);
3155 os << "\n\\" << t.cs() << " default\n";
3156 if (t.cs() == "uuline" || t.cs() == "uwave")
3157 preamble.registerAutomaticallyLoadedPackage("ulem");
3160 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3161 context.check_layout(os);
3162 string name = p.getArg('{', '}');
3163 string localtime = p.getArg('{', '}');
3164 preamble.registerAuthor(name);
3165 Author const & author = preamble.getAuthor(name);
3166 // from_ctime() will fail if LyX decides to output the
3167 // time in the text language. It might also use a wrong
3168 // time zone (if the original LyX document was exported
3169 // with a different time zone).
3170 time_t ptime = from_ctime(localtime);
3171 if (ptime == static_cast<time_t>(-1)) {
3172 cerr << "Warning: Could not parse time `" << localtime
3173 << "´ for change tracking, using current time instead.\n";
3174 ptime = current_time();
3176 if (t.cs() == "lyxadded")
3177 os << "\n\\change_inserted ";
3179 os << "\n\\change_deleted ";
3180 os << author.bufferId() << ' ' << ptime << '\n';
3181 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3182 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3183 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3184 LaTeXPackages::isAvailable("xcolor");
3185 // No need to test for luatex, since luatex comes in
3186 // two flavours (dvi and pdf), like latex, and those
3187 // are detected by pdflatex.
3188 if (pdflatex || xetex) {
3190 preamble.registerAutomaticallyLoadedPackage("ulem");
3191 preamble.registerAutomaticallyLoadedPackage("xcolor");
3192 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3196 preamble.registerAutomaticallyLoadedPackage("dvipost");
3197 } else if (xcolorulem) {
3198 preamble.registerAutomaticallyLoadedPackage("ulem");
3199 preamble.registerAutomaticallyLoadedPackage("xcolor");
3204 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3205 t.cs() == "vphantom") {
3206 context.check_layout(os);
3207 if (t.cs() == "phantom")
3208 begin_inset(os, "Phantom Phantom\n");
3209 if (t.cs() == "hphantom")
3210 begin_inset(os, "Phantom HPhantom\n");
3211 if (t.cs() == "vphantom")
3212 begin_inset(os, "Phantom VPhantom\n");
3213 os << "status open\n";
3214 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3219 else if (t.cs() == "href") {
3220 context.check_layout(os);
3221 string target = convert_command_inset_arg(p.verbatim_item());
3222 string name = convert_command_inset_arg(p.verbatim_item());
3224 size_t i = target.find(':');
3225 if (i != string::npos) {
3226 type = target.substr(0, i + 1);
3227 if (type == "mailto:" || type == "file:")
3228 target = target.substr(i + 1);
3229 // handle the case that name is equal to target, except of "http://"
3230 else if (target.substr(i + 3) == name && type == "http:")
3233 begin_command_inset(os, "href", "href");
3235 os << "name \"" << name << "\"\n";
3236 os << "target \"" << target << "\"\n";
3237 if (type == "mailto:" || type == "file:")
3238 os << "type \"" << type << "\"\n";
3240 skip_spaces_braces(p);
3243 else if (t.cs() == "lyxline") {
3244 // swallow size argument (it is not used anyway)
3246 if (!context.atParagraphStart()) {
3247 // so our line is in the middle of a paragraph
3248 // we need to add a new line, lest this line
3249 // follow the other content on that line and
3250 // run off the side of the page
3251 // FIXME: This may create an empty paragraph,
3252 // but without that it would not be
3253 // possible to set noindent below.
3254 // Fortunately LaTeX does not care
3255 // about the empty paragraph.
3256 context.new_paragraph(os);
3258 if (preamble.indentParagraphs()) {
3259 // we need to unindent, lest the line be too long
3260 context.add_par_extra_stuff("\\noindent\n");
3262 context.check_layout(os);
3263 begin_command_inset(os, "line", "rule");
3264 os << "offset \"0.5ex\"\n"
3265 "width \"100line%\"\n"
3270 else if (t.cs() == "rule") {
3271 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3272 string const width = p.getArg('{', '}');
3273 string const thickness = p.getArg('{', '}');
3274 context.check_layout(os);
3275 begin_command_inset(os, "line", "rule");
3276 if (!offset.empty())
3277 os << "offset \"" << translate_len(offset) << "\"\n";
3278 os << "width \"" << translate_len(width) << "\"\n"
3279 "height \"" << translate_len(thickness) << "\"\n";
3283 else if (is_known(t.cs(), known_phrases) ||
3284 (t.cs() == "protect" &&
3285 p.next_token().cat() == catEscape &&
3286 is_known(p.next_token().cs(), known_phrases))) {
3287 // LyX sometimes puts a \protect in front, so we have to ignore it
3288 // FIXME: This needs to be changed when bug 4752 is fixed.
3290 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3292 context.check_layout(os);
3293 os << known_coded_phrases[where - known_phrases];
3294 skip_spaces_braces(p);
3297 else if ((where = is_known(t.cs(), known_ref_commands))) {
3298 string const opt = p.getOpt();
3300 context.check_layout(os);
3301 begin_command_inset(os, "ref",
3302 known_coded_ref_commands[where - known_ref_commands]);
3303 os << "reference \""
3304 << convert_command_inset_arg(p.verbatim_item())
3307 if (t.cs() == "vref" || t.cs() == "vpageref")
3308 preamble.registerAutomaticallyLoadedPackage("varioref");
3311 // LyX does not support optional arguments of ref commands
3312 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3313 p.verbatim_item() + "}", context);
3317 else if (use_natbib &&
3318 is_known(t.cs(), known_natbib_commands) &&
3319 ((t.cs() != "citefullauthor" &&
3320 t.cs() != "citeyear" &&
3321 t.cs() != "citeyearpar") ||
3322 p.next_token().asInput() != "*")) {
3323 context.check_layout(os);
3324 string command = t.cs();
3325 if (p.next_token().asInput() == "*") {
3329 if (command == "citefullauthor")
3330 // alternative name for "\\citeauthor*"
3331 command = "citeauthor*";
3333 // text before the citation
3335 // text after the citation
3337 get_cite_arguments(p, true, before, after);
3339 if (command == "cite") {
3340 // \cite without optional argument means
3341 // \citet, \cite with at least one optional
3342 // argument means \citep.
3343 if (before.empty() && after.empty())
3348 if (before.empty() && after == "[]")
3349 // avoid \citet[]{a}
3351 else if (before == "[]" && after == "[]") {
3352 // avoid \citet[][]{a}
3356 // remove the brackets around after and before
3357 if (!after.empty()) {
3359 after.erase(after.length() - 1, 1);
3360 after = convert_command_inset_arg(after);
3362 if (!before.empty()) {
3364 before.erase(before.length() - 1, 1);
3365 before = convert_command_inset_arg(before);
3367 begin_command_inset(os, "citation", command);
3368 os << "after " << '"' << after << '"' << "\n";
3369 os << "before " << '"' << before << '"' << "\n";
3371 << convert_command_inset_arg(p.verbatim_item())
3376 else if (use_jurabib &&
3377 is_known(t.cs(), known_jurabib_commands) &&
3378 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3379 context.check_layout(os);
3380 string command = t.cs();
3381 if (p.next_token().asInput() == "*") {
3385 char argumentOrder = '\0';
3386 vector<string> const options =
3387 preamble.getPackageOptions("jurabib");
3388 if (find(options.begin(), options.end(),
3389 "natbiborder") != options.end())
3390 argumentOrder = 'n';
3391 else if (find(options.begin(), options.end(),
3392 "jurabiborder") != options.end())
3393 argumentOrder = 'j';
3395 // text before the citation
3397 // text after the citation
3399 get_cite_arguments(p, argumentOrder != 'j', before, after);
3401 string const citation = p.verbatim_item();
3402 if (!before.empty() && argumentOrder == '\0') {
3403 cerr << "Warning: Assuming argument order "
3404 "of jurabib version 0.6 for\n'"
3405 << command << before << after << '{'
3406 << citation << "}'.\n"
3407 "Add 'jurabiborder' to the jurabib "
3408 "package options if you used an\n"
3409 "earlier jurabib version." << endl;
3411 if (!after.empty()) {
3413 after.erase(after.length() - 1, 1);
3415 if (!before.empty()) {
3417 before.erase(before.length() - 1, 1);
3419 begin_command_inset(os, "citation", command);
3420 os << "after " << '"' << after << '"' << "\n";
3421 os << "before " << '"' << before << '"' << "\n";
3422 os << "key " << '"' << citation << '"' << "\n";
3426 else if (t.cs() == "cite"
3427 || t.cs() == "nocite") {
3428 context.check_layout(os);
3429 string after = convert_command_inset_arg(p.getArg('[', ']'));
3430 string key = convert_command_inset_arg(p.verbatim_item());
3431 // store the case that it is "\nocite{*}" to use it later for
3434 begin_command_inset(os, "citation", t.cs());
3435 os << "after " << '"' << after << '"' << "\n";
3436 os << "key " << '"' << key << '"' << "\n";
3438 } else if (t.cs() == "nocite")
3442 else if (t.cs() == "index" ||
3443 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3444 context.check_layout(os);
3445 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3446 p.getArg('[', ']') : "";
3447 string const kind = arg.empty() ? "idx" : arg;
3448 begin_inset(os, "Index ");
3449 os << kind << "\nstatus collapsed\n";
3450 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3453 preamble.registerAutomaticallyLoadedPackage("splitidx");
3456 else if (t.cs() == "nomenclature") {
3457 context.check_layout(os);
3458 begin_command_inset(os, "nomenclature", "nomenclature");
3459 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3460 if (!prefix.empty())
3461 os << "prefix " << '"' << prefix << '"' << "\n";
3462 os << "symbol " << '"'
3463 << convert_command_inset_arg(p.verbatim_item());
3464 os << "\"\ndescription \""
3465 << convert_command_inset_arg(p.verbatim_item())
3468 preamble.registerAutomaticallyLoadedPackage("nomencl");
3471 else if (t.cs() == "label") {
3472 context.check_layout(os);
3473 begin_command_inset(os, "label", "label");
3475 << convert_command_inset_arg(p.verbatim_item())
3480 else if (t.cs() == "printindex") {
3481 context.check_layout(os);
3482 begin_command_inset(os, "index_print", "printindex");
3483 os << "type \"idx\"\n";
3485 skip_spaces_braces(p);
3486 preamble.registerAutomaticallyLoadedPackage("makeidx");
3487 if (preamble.use_indices() == "true")
3488 preamble.registerAutomaticallyLoadedPackage("splitidx");
3491 else if (t.cs() == "printnomenclature") {
3493 string width_type = "";
3494 context.check_layout(os);
3495 begin_command_inset(os, "nomencl_print", "printnomenclature");
3496 // case of a custom width
3498 width = p.getArg('[', ']');
3499 width = translate_len(width);
3500 width_type = "custom";
3502 // case of no custom width
3503 // the case of no custom width but the width set
3504 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3505 // because the user could have set anything, not only the width
3506 // of the longest label (which would be width_type = "auto")
3507 string label = convert_command_inset_arg(p.getArg('{', '}'));
3508 if (label.empty() && width_type.empty())
3509 width_type = "none";
3510 os << "set_width \"" << width_type << "\"\n";
3511 if (width_type == "custom")
3512 os << "width \"" << width << '\"';
3514 skip_spaces_braces(p);
3515 preamble.registerAutomaticallyLoadedPackage("nomencl");
3518 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3519 context.check_layout(os);
3520 begin_inset(os, "script ");
3521 os << t.cs().substr(4) << '\n';
3522 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3524 if (t.cs() == "textsubscript")
3525 preamble.registerAutomaticallyLoadedPackage("subscript");
3528 else if ((where = is_known(t.cs(), known_quotes))) {
3529 context.check_layout(os);
3530 begin_inset(os, "Quotes ");
3531 os << known_coded_quotes[where - known_quotes];
3533 // LyX adds {} after the quote, so we have to eat
3534 // spaces here if there are any before a possible
3536 eat_whitespace(p, os, context, false);
3540 else if ((where = is_known(t.cs(), known_sizes)) &&
3541 context.new_layout_allowed) {
3542 context.check_layout(os);
3543 TeXFont const oldFont = context.font;
3544 context.font.size = known_coded_sizes[where - known_sizes];
3545 output_font_change(os, oldFont, context.font);
3546 eat_whitespace(p, os, context, false);
3549 else if ((where = is_known(t.cs(), known_font_families)) &&
3550 context.new_layout_allowed) {
3551 context.check_layout(os);
3552 TeXFont const oldFont = context.font;
3553 context.font.family =
3554 known_coded_font_families[where - known_font_families];
3555 output_font_change(os, oldFont, context.font);
3556 eat_whitespace(p, os, context, false);
3559 else if ((where = is_known(t.cs(), known_font_series)) &&
3560 context.new_layout_allowed) {
3561 context.check_layout(os);
3562 TeXFont const oldFont = context.font;
3563 context.font.series =
3564 known_coded_font_series[where - known_font_series];
3565 output_font_change(os, oldFont, context.font);
3566 eat_whitespace(p, os, context, false);
3569 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3570 context.new_layout_allowed) {
3571 context.check_layout(os);
3572 TeXFont const oldFont = context.font;
3573 context.font.shape =
3574 known_coded_font_shapes[where - known_font_shapes];
3575 output_font_change(os, oldFont, context.font);
3576 eat_whitespace(p, os, context, false);
3578 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3579 context.new_layout_allowed) {
3580 context.check_layout(os);
3581 TeXFont const oldFont = context.font;
3582 context.font.init();
3583 context.font.size = oldFont.size;
3584 context.font.family =
3585 known_coded_font_families[where - known_old_font_families];
3586 output_font_change(os, oldFont, context.font);
3587 eat_whitespace(p, os, context, false);
3590 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3591 context.new_layout_allowed) {
3592 context.check_layout(os);
3593 TeXFont const oldFont = context.font;
3594 context.font.init();
3595 context.font.size = oldFont.size;
3596 context.font.series =
3597 known_coded_font_series[where - known_old_font_series];
3598 output_font_change(os, oldFont, context.font);
3599 eat_whitespace(p, os, context, false);
3602 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3603 context.new_layout_allowed) {
3604 context.check_layout(os);
3605 TeXFont const oldFont = context.font;
3606 context.font.init();
3607 context.font.size = oldFont.size;
3608 context.font.shape =
3609 known_coded_font_shapes[where - known_old_font_shapes];
3610 output_font_change(os, oldFont, context.font);
3611 eat_whitespace(p, os, context, false);
3614 else if (t.cs() == "selectlanguage") {
3615 context.check_layout(os);
3616 // save the language for the case that a
3617 // \foreignlanguage is used
3618 context.font.language = babel2lyx(p.verbatim_item());
3619 os << "\n\\lang " << context.font.language << "\n";
3622 else if (t.cs() == "foreignlanguage") {
3623 string const lang = babel2lyx(p.verbatim_item());
3624 parse_text_attributes(p, os, FLAG_ITEM, outer,
3626 context.font.language, lang);
3629 else if (prefixIs(t.cs(), "text")
3630 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3631 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3633 // We have to output the whole command if it has an option
3634 // because LyX doesn't support this yet, see bug #8214,
3635 // only if there is a single option specifying a variant, we can handle it.
3637 string langopts = p.getOpt();
3638 // check if the option contains a variant, if yes, extract it
3639 string::size_type pos_var = langopts.find("variant");
3640 string::size_type i = langopts.find(',');
3641 string::size_type k = langopts.find('=', pos_var);
3642 if (pos_var != string::npos && i == string::npos) {
3644 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3645 lang = preamble.polyglossia2lyx(variant);
3646 parse_text_attributes(p, os, FLAG_ITEM, outer,
3648 context.font.language, lang);
3650 handle_ert(os, t.asInput() + langopts, context);
3652 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3653 parse_text_attributes(p, os, FLAG_ITEM, outer,
3655 context.font.language, lang);
3659 else if (t.cs() == "inputencoding") {
3660 // nothing to write here
3661 string const enc = subst(p.verbatim_item(), "\n", " ");
3665 else if ((where = is_known(t.cs(), known_special_chars))) {
3666 context.check_layout(os);
3667 os << "\\SpecialChar \\"
3668 << known_coded_special_chars[where - known_special_chars]
3670 skip_spaces_braces(p);
3673 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3674 context.check_layout(os);
3675 os << "\\SpecialChar \\nobreakdash-\n";
3679 else if (t.cs() == "textquotedbl") {
3680 context.check_layout(os);
3685 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3686 context.check_layout(os);
3687 os << "\\SpecialChar \\@.\n";
3691 else if (t.cs() == "-") {
3692 context.check_layout(os);
3693 os << "\\SpecialChar \\-\n";
3696 else if (t.cs() == "textasciitilde") {
3697 context.check_layout(os);
3699 skip_spaces_braces(p);
3702 else if (t.cs() == "textasciicircum") {
3703 context.check_layout(os);
3705 skip_spaces_braces(p);
3708 else if (t.cs() == "textbackslash") {
3709 context.check_layout(os);
3710 os << "\n\\backslash\n";
3711 skip_spaces_braces(p);
3714 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3715 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3717 context.check_layout(os);
3721 else if (t.cs() == "char") {
3722 context.check_layout(os);
3723 if (p.next_token().character() == '`') {
3725 if (p.next_token().cs() == "\"") {
3730 handle_ert(os, "\\char`", context);
3733 handle_ert(os, "\\char", context);
3737 else if (t.cs() == "verb") {
3738 context.check_layout(os);
3739 char const delimiter = p.next_token().character();
3740 // \verb is special: The usual escaping rules do not
3741 // apply, e.g. "\verb+\+" is valid and denotes a single
3742 // backslash (bug #4468). Therefore we do not allow
3743 // escaping in getArg().
3744 string const arg = p.getArg(delimiter, delimiter, false);
3746 oss << "\\verb" << delimiter << arg << delimiter;
3747 handle_ert(os, oss.str(), context);
3750 // Problem: \= creates a tabstop inside the tabbing environment
3751 // and else an accent. In the latter case we really would want
3752 // \={o} instead of \= o.
3753 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3754 handle_ert(os, t.asInput(), context);
3756 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3757 else if (t.cs().size() == 1
3758 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3759 context.check_layout(os);
3760 // try to see whether the string is in unicodesymbols
3763 string command = t.asInput() + "{"
3764 + trimSpaceAndEol(p.verbatim_item())
3767 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3768 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3769 termination, rem, &req);
3772 cerr << "When parsing " << command
3773 << ", result is " << to_utf8(s)
3774 << "+" << to_utf8(rem) << endl;
3776 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3777 preamble.registerAutomaticallyLoadedPackage(*it);
3779 // we did not find a non-ert version
3780 handle_ert(os, command, context);
3783 else if (t.cs() == "\\") {
3784 context.check_layout(os);
3786 handle_ert(os, "\\\\" + p.getOpt(), context);
3787 else if (p.next_token().asInput() == "*") {
3789 // getOpt() eats the following space if there
3790 // is no optional argument, but that is OK
3791 // here since it has no effect in the output.
3792 handle_ert(os, "\\\\*" + p.getOpt(), context);
3795 begin_inset(os, "Newline newline");
3800 else if (t.cs() == "newline" ||
3801 (t.cs() == "linebreak" && !p.hasOpt())) {
3802 context.check_layout(os);
3803 begin_inset(os, "Newline ");
3806 skip_spaces_braces(p);
3809 else if (t.cs() == "input" || t.cs() == "include"
3810 || t.cs() == "verbatiminput") {
3811 string name = t.cs();
3812 if (t.cs() == "verbatiminput"
3813 && p.next_token().asInput() == "*")
3814 name += p.get_token().asInput();
3815 context.check_layout(os);
3816 string filename(normalize_filename(p.getArg('{', '}')));
3817 string const path = getMasterFilePath(true);
3818 // We want to preserve relative / absolute filenames,
3819 // therefore path is only used for testing
3820 if ((t.cs() == "include" || t.cs() == "input") &&
3821 !makeAbsPath(filename, path).exists()) {
3822 // The file extension is probably missing.
3823 // Now try to find it out.
3824 string const tex_name =
3825 find_file(filename, path,
3826 known_tex_extensions);
3827 if (!tex_name.empty())
3828 filename = tex_name;
3830 bool external = false;
3832 if (makeAbsPath(filename, path).exists()) {
3833 string const abstexname =
3834 makeAbsPath(filename, path).absFileName();
3835 string const absfigname =
3836 changeExtension(abstexname, ".fig");
3837 fix_child_filename(filename);
3838 string const lyxname =
3839 changeExtension(filename, ".lyx");
3840 string const abslyxname = makeAbsPath(
3841 lyxname, getParentFilePath(false)).absFileName();
3843 if (!skipChildren())
3844 external = FileName(absfigname).exists();
3845 if (t.cs() == "input" && !skipChildren()) {
3846 string const ext = getExtension(abstexname);
3848 // Combined PS/LaTeX:
3849 // x.eps, x.pstex_t (old xfig)
3850 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3851 FileName const absepsname(
3852 changeExtension(abstexname, ".eps"));
3853 FileName const abspstexname(
3854 changeExtension(abstexname, ".pstex"));
3855 bool const xfigeps =
3856 (absepsname.exists() ||
3857 abspstexname.exists()) &&
3860 // Combined PDF/LaTeX:
3861 // x.pdf, x.pdftex_t (old xfig)
3862 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3863 FileName const abspdfname(
3864 changeExtension(abstexname, ".pdf"));
3865 bool const xfigpdf =
3866 abspdfname.exists() &&
3867 (ext == "pdftex_t" || ext == "pdf_t");
3871 // Combined PS/PDF/LaTeX:
3872 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3873 string const absbase2(
3874 removeExtension(abstexname) + "_pspdftex");
3875 FileName const abseps2name(
3876 addExtension(absbase2, ".eps"));
3877 FileName const abspdf2name(
3878 addExtension(absbase2, ".pdf"));
3879 bool const xfigboth =
3880 abspdf2name.exists() &&
3881 abseps2name.exists() && ext == "pspdftex";
3883 xfig = xfigpdf || xfigeps || xfigboth;
3884 external = external && xfig;
3887 outname = changeExtension(filename, ".fig");
3888 FileName abssrc(changeExtension(abstexname, ".fig"));
3889 copy_file(abssrc, outname);
3891 // Don't try to convert, the result
3892 // would be full of ERT.
3894 FileName abssrc(abstexname);
3895 copy_file(abssrc, outname);
3896 } else if (t.cs() != "verbatiminput" &&
3898 tex2lyx(abstexname, FileName(abslyxname),
3901 // no need to call copy_file
3902 // tex2lyx creates the file
3905 FileName abssrc(abstexname);
3906 copy_file(abssrc, outname);
3909 cerr << "Warning: Could not find included file '"
3910 << filename << "'." << endl;
3914 begin_inset(os, "External\n");
3915 os << "\ttemplate XFig\n"
3916 << "\tfilename " << outname << '\n';
3917 registerExternalTemplatePackages("XFig");
3919 begin_command_inset(os, "include", name);
3920 os << "preview false\n"
3921 "filename \"" << outname << "\"\n";
3922 if (t.cs() == "verbatiminput")
3923 preamble.registerAutomaticallyLoadedPackage("verbatim");
3928 else if (t.cs() == "bibliographystyle") {
3929 // store new bibliographystyle
3930 bibliographystyle = p.verbatim_item();
3931 // If any other command than \bibliography and
3932 // \nocite{*} follows, we need to output the style
3933 // (because it might be used by that command).
3934 // Otherwise, it will automatically be output by LyX.
3937 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3938 if (t2.cat() == catBegin)
3940 if (t2.cat() != catEscape)
3942 if (t2.cs() == "nocite") {
3943 if (p.getArg('{', '}') == "*")
3945 } else if (t2.cs() == "bibliography")
3952 "\\bibliographystyle{" + bibliographystyle + '}',
3957 else if (t.cs() == "bibliography") {
3958 context.check_layout(os);
3959 begin_command_inset(os, "bibtex", "bibtex");
3960 if (!btprint.empty()) {
3961 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3962 // clear the string because the next BibTeX inset can be without the
3963 // \nocite{*} option
3966 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3967 // Do we have a bibliographystyle set?
3968 if (!bibliographystyle.empty())
3969 os << "options " << '"' << bibliographystyle << '"' << "\n";
3973 else if (t.cs() == "parbox") {
3974 // Test whether this is an outer box of a shaded box
3976 // swallow arguments
3977 while (p.hasOpt()) {
3979 p.skip_spaces(true);
3982 p.skip_spaces(true);
3984 if (p.next_token().cat() == catBegin)
3986 p.skip_spaces(true);
3987 Token to = p.get_token();
3988 bool shaded = false;
3989 if (to.asInput() == "\\begin") {
3990 p.skip_spaces(true);
3991 if (p.getArg('{', '}') == "shaded")
3996 parse_outer_box(p, os, FLAG_ITEM, outer,
3997 context, "parbox", "shaded");
3999 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4003 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4004 t.cs() == "shadowbox" || t.cs() == "doublebox")
4005 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4007 else if (t.cs() == "framebox") {
4008 if (p.next_token().character() == '(') {
4009 //the syntax is: \framebox(x,y)[position]{content}
4010 string arg = t.asInput();
4011 arg += p.getFullParentheseArg();
4012 arg += p.getFullOpt();
4013 eat_whitespace(p, os, context, false);
4014 handle_ert(os, arg + '{', context);
4015 parse_text(p, os, FLAG_ITEM, outer, context);
4016 handle_ert(os, "}", context);
4018 string special = p.getFullOpt();
4019 special += p.getOpt();
4020 // LyX does not yet support \framebox without any option
4021 if (!special.empty())
4022 parse_outer_box(p, os, FLAG_ITEM, outer,
4023 context, t.cs(), special);
4025 eat_whitespace(p, os, context, false);
4026 handle_ert(os, "\\framebox{", context);
4027 parse_text(p, os, FLAG_ITEM, outer, context);
4028 handle_ert(os, "}", context);
4033 //\makebox() is part of the picture environment and different from \makebox{}
4034 //\makebox{} will be parsed by parse_box
4035 else if (t.cs() == "makebox") {
4036 if (p.next_token().character() == '(') {
4037 //the syntax is: \makebox(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 //the syntax is: \makebox[width][position]{content}
4047 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4051 else if (t.cs() == "smallskip" ||
4052 t.cs() == "medskip" ||
4053 t.cs() == "bigskip" ||
4054 t.cs() == "vfill") {
4055 context.check_layout(os);
4056 begin_inset(os, "VSpace ");
4059 skip_spaces_braces(p);
4062 else if ((where = is_known(t.cs(), known_spaces))) {
4063 context.check_layout(os);
4064 begin_inset(os, "space ");
4065 os << '\\' << known_coded_spaces[where - known_spaces]
4068 // LaTeX swallows whitespace after all spaces except
4069 // "\\,". We have to do that here, too, because LyX
4070 // adds "{}" which would make the spaces significant.
4072 eat_whitespace(p, os, context, false);
4073 // LyX adds "{}" after all spaces except "\\ " and
4074 // "\\,", so we have to remove "{}".
4075 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4076 // remove the braces after "\\,", too.
4081 else if (t.cs() == "newpage" ||
4082 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4083 t.cs() == "clearpage" ||
4084 t.cs() == "cleardoublepage") {
4085 context.check_layout(os);
4086 begin_inset(os, "Newpage ");
4089 skip_spaces_braces(p);
4092 else if (t.cs() == "DeclareRobustCommand" ||
4093 t.cs() == "DeclareRobustCommandx" ||
4094 t.cs() == "newcommand" ||
4095 t.cs() == "newcommandx" ||
4096 t.cs() == "providecommand" ||
4097 t.cs() == "providecommandx" ||
4098 t.cs() == "renewcommand" ||
4099 t.cs() == "renewcommandx") {
4100 // DeclareRobustCommand, DeclareRobustCommandx,
4101 // providecommand and providecommandx could be handled
4102 // by parse_command(), but we need to call
4103 // add_known_command() here.
4104 string name = t.asInput();
4105 if (p.next_token().asInput() == "*") {
4106 // Starred form. Eat '*'
4110 string const command = p.verbatim_item();
4111 string const opt1 = p.getFullOpt();
4112 string const opt2 = p.getFullOpt();
4113 add_known_command(command, opt1, !opt2.empty());
4114 string const ert = name + '{' + command + '}' +
4116 '{' + p.verbatim_item() + '}';
4118 if (t.cs() == "DeclareRobustCommand" ||
4119 t.cs() == "DeclareRobustCommandx" ||
4120 t.cs() == "providecommand" ||
4121 t.cs() == "providecommandx" ||
4122 name[name.length()-1] == '*')
4123 handle_ert(os, ert, context);
4125 context.check_layout(os);
4126 begin_inset(os, "FormulaMacro");
4132 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4133 // let could be handled by parse_command(),
4134 // but we need to call add_known_command() here.
4135 string ert = t.asInput();
4138 if (p.next_token().cat() == catBegin) {
4139 name = p.verbatim_item();
4140 ert += '{' + name + '}';
4142 name = p.verbatim_item();
4147 if (p.next_token().cat() == catBegin) {
4148 command = p.verbatim_item();
4149 ert += '{' + command + '}';
4151 command = p.verbatim_item();
4154 // If command is known, make name known too, to parse
4155 // its arguments correctly. For this reason we also
4156 // have commands in syntax.default that are hardcoded.
4157 CommandMap::iterator it = known_commands.find(command);
4158 if (it != known_commands.end())
4159 known_commands[t.asInput()] = it->second;
4160 handle_ert(os, ert, context);
4163 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4164 bool starred = false;
4165 if (p.next_token().asInput() == "*") {
4169 string name = t.asInput();
4170 string const length = p.verbatim_item();
4173 bool valid = splitLatexLength(length, valstring, unit);
4174 bool known_hspace = false;
4175 bool known_vspace = false;
4176 bool known_unit = false;
4179 istringstream iss(valstring);
4182 if (t.cs()[0] == 'h') {
4183 if (unit == "\\fill") {
4188 known_hspace = true;
4191 if (unit == "\\smallskipamount") {
4193 known_vspace = true;
4194 } else if (unit == "\\medskipamount") {
4196 known_vspace = true;
4197 } else if (unit == "\\bigskipamount") {
4199 known_vspace = true;
4200 } else if (unit == "\\fill") {
4202 known_vspace = true;
4206 if (!known_hspace && !known_vspace) {
4207 switch (unitFromString(unit)) {
4228 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4229 // Literal horizontal length or known variable
4230 context.check_layout(os);
4231 begin_inset(os, "space ");
4239 if (known_unit && !known_hspace)
4241 << translate_len(length);
4243 } else if (known_unit || known_vspace) {
4244 // Literal vertical length or known variable
4245 context.check_layout(os);
4246 begin_inset(os, "VSpace ");
4254 // LyX can't handle other length variables in Inset VSpace/space
4259 handle_ert(os, name + '{' + unit + '}', context);
4260 else if (value == -1.0)
4261 handle_ert(os, name + "{-" + unit + '}', context);
4263 handle_ert(os, name + '{' + valstring + unit + '}', context);
4265 handle_ert(os, name + '{' + length + '}', context);
4269 // The single '=' is meant here.
4270 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4272 context.check_layout(os);
4273 begin_inset(os, "Flex ");
4274 os << to_utf8(newinsetlayout->name()) << '\n'
4275 << "status collapsed\n";
4276 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4280 else if (t.cs() == "includepdf") {
4282 string const arg = p.getArg('[', ']');
4283 map<string, string> opts;
4284 vector<string> keys;
4285 split_map(arg, opts, keys);
4286 string name = normalize_filename(p.verbatim_item());
4287 string const path = getMasterFilePath(true);
4288 // We want to preserve relative / absolute filenames,
4289 // therefore path is only used for testing
4290 if (!makeAbsPath(name, path).exists()) {
4291 // The file extension is probably missing.
4292 // Now try to find it out.
4293 char const * const pdfpages_format[] = {"pdf", 0};
4294 string const pdftex_name =
4295 find_file(name, path, pdfpages_format);
4296 if (!pdftex_name.empty()) {
4301 FileName const absname = makeAbsPath(name, path);
4302 if (absname.exists())
4304 fix_child_filename(name);
4305 copy_file(absname, name);
4307 cerr << "Warning: Could not find file '"
4308 << name << "'." << endl;
4310 context.check_layout(os);
4311 begin_inset(os, "External\n\ttemplate ");
4312 os << "PDFPages\n\tfilename "
4314 // parse the options
4315 if (opts.find("pages") != opts.end())
4316 os << "\textra LaTeX \"pages="
4317 << opts["pages"] << "\"\n";
4318 if (opts.find("angle") != opts.end())
4319 os << "\trotateAngle "
4320 << opts["angle"] << '\n';
4321 if (opts.find("origin") != opts.end()) {
4323 string const opt = opts["origin"];
4324 if (opt == "tl") ss << "topleft";
4325 if (opt == "bl") ss << "bottomleft";
4326 if (opt == "Bl") ss << "baselineleft";
4327 if (opt == "c") ss << "center";
4328 if (opt == "tc") ss << "topcenter";
4329 if (opt == "bc") ss << "bottomcenter";
4330 if (opt == "Bc") ss << "baselinecenter";
4331 if (opt == "tr") ss << "topright";
4332 if (opt == "br") ss << "bottomright";
4333 if (opt == "Br") ss << "baselineright";
4334 if (!ss.str().empty())
4335 os << "\trotateOrigin " << ss.str() << '\n';
4337 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4339 if (opts.find("width") != opts.end())
4341 << translate_len(opts["width"]) << '\n';
4342 if (opts.find("height") != opts.end())
4344 << translate_len(opts["height"]) << '\n';
4345 if (opts.find("keepaspectratio") != opts.end())
4346 os << "\tkeepAspectRatio\n";
4348 context.check_layout(os);
4349 registerExternalTemplatePackages("PDFPages");
4352 else if (t.cs() == "loadgame") {
4354 string name = normalize_filename(p.verbatim_item());
4355 string const path = getMasterFilePath(true);
4356 // We want to preserve relative / absolute filenames,
4357 // therefore path is only used for testing
4358 if (!makeAbsPath(name, path).exists()) {
4359 // The file extension is probably missing.
4360 // Now try to find it out.
4361 char const * const lyxskak_format[] = {"fen", 0};
4362 string const lyxskak_name =
4363 find_file(name, path, lyxskak_format);
4364 if (!lyxskak_name.empty())
4365 name = lyxskak_name;
4367 FileName const absname = makeAbsPath(name, path);
4368 if (absname.exists())
4370 fix_child_filename(name);
4371 copy_file(absname, name);
4373 cerr << "Warning: Could not find file '"
4374 << name << "'." << endl;
4375 context.check_layout(os);
4376 begin_inset(os, "External\n\ttemplate ");
4377 os << "ChessDiagram\n\tfilename "
4380 context.check_layout(os);
4381 // after a \loadgame follows a \showboard
4382 if (p.get_token().asInput() == "showboard")
4384 registerExternalTemplatePackages("ChessDiagram");
4388 // try to see whether the string is in unicodesymbols
4389 // Only use text mode commands, since we are in text mode here,
4390 // and math commands may be invalid (bug 6797)
4394 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4395 Encodings::TEXT_CMD, termination, rem, &req);
4398 cerr << "When parsing " << t.cs()
4399 << ", result is " << to_utf8(s)
4400 << "+" << to_utf8(rem) << endl;
4401 context.check_layout(os);
4404 skip_spaces_braces(p);
4405 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4406 preamble.registerAutomaticallyLoadedPackage(*it);
4408 //cerr << "#: " << t << " mode: " << mode << endl;
4409 // heuristic: read up to next non-nested space
4411 string s = t.asInput();
4412 string z = p.verbatim_item();
4413 while (p.good() && z != " " && !z.empty()) {
4414 //cerr << "read: " << z << endl;
4416 z = p.verbatim_item();
4418 cerr << "found ERT: " << s << endl;
4419 handle_ert(os, s + ' ', context);
4422 string name = t.asInput();
4423 if (p.next_token().asInput() == "*") {
4424 // Starred commands like \vspace*{}
4425 p.get_token(); // Eat '*'
4428 if (!parse_command(name, p, os, outer, context))
4429 handle_ert(os, name, context);
4433 if (flags & FLAG_LEAVE) {
4434 flags &= ~FLAG_LEAVE;
4441 string guessLanguage(Parser & p, string const & lang)
4443 typedef std::map<std::string, size_t> LangMap;
4444 // map from language names to number of characters
4447 for (char const * const * i = supported_CJK_languages; *i; i++)
4448 used[string(*i)] = 0;
4451 Token const t = p.get_token();
4452 // comments are not counted for any language
4453 if (t.cat() == catComment)
4455 // commands are not counted as well, but we need to detect
4456 // \begin{CJK} and switch encoding if needed
4457 if (t.cat() == catEscape) {
4458 if (t.cs() == "inputencoding") {
4459 string const enc = subst(p.verbatim_item(), "\n", " ");
4463 if (t.cs() != "begin")
4466 // Non-CJK content is counted for lang.
4467 // We do not care about the real language here:
4468 // If we have more non-CJK contents than CJK contents,
4469 // we simply use the language that was specified as
4470 // babel main language.
4471 used[lang] += t.asInput().length();
4474 // Now we are starting an environment
4476 string const name = p.getArg('{', '}');
4477 if (name != "CJK") {
4481 // It is a CJK environment
4483 /* name = */ p.getArg('{', '}');
4484 string const encoding = p.getArg('{', '}');
4485 /* mapping = */ p.getArg('{', '}');
4486 string const encoding_old = p.getEncoding();
4487 char const * const * const where =
4488 is_known(encoding, supported_CJK_encodings);
4490 p.setEncoding(encoding);
4492 p.setEncoding("utf8");
4493 string const text = p.verbatimEnvironment("CJK");
4494 p.setEncoding(encoding_old);
4497 // ignore contents in unknown CJK encoding
4500 // the language of the text
4502 supported_CJK_languages[where - supported_CJK_encodings];
4503 used[cjk] += text.length();
4505 LangMap::const_iterator use = used.begin();
4506 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4507 if (it->second > use->second)