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!
633 while (optargs < context.layout->optArgs()) {
634 eat_whitespace(p, os, context, false);
635 if (p.next_token().cat() == catEscape ||
636 p.next_token().character() != '[')
638 p.get_token(); // eat '['
639 // FIXME: Just a workaround
640 begin_inset(os, "Argument 999\n");
641 os << "status collapsed\n\n";
642 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
644 eat_whitespace(p, os, context, false);
648 while (reqargs < context.layout->requiredArgs()) {
649 eat_whitespace(p, os, context, false);
650 if (p.next_token().cat() != catBegin)
652 p.get_token(); // eat '{'
653 // FIXME: Just a workaround
654 begin_inset(os, "Argument 999\n");
655 os << "status collapsed\n\n";
656 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
658 eat_whitespace(p, os, context, false);
661 parse_text(p, os, FLAG_ITEM, outer, context);
662 context.check_end_layout(os);
663 if (parent_context.deeper_paragraph) {
664 // We must suppress the "end deeper" because we
665 // suppressed the "begin deeper" above.
666 context.need_end_deeper = false;
668 context.check_end_deeper(os);
669 // We don't need really a new paragraph, but
670 // we must make sure that the next item gets a \begin_layout.
671 parent_context.new_paragraph(os);
672 // Set the font size to the original value. No need to output it here
673 // (Context::begin_layout() will do that if needed)
674 parent_context.font.size = size;
679 * Output a space if necessary.
680 * This function gets called for every whitespace token.
682 * We have three cases here:
683 * 1. A space must be suppressed. Example: The lyxcode case below
684 * 2. A space may be suppressed. Example: Spaces before "\par"
685 * 3. A space must not be suppressed. Example: A space between two words
687 * We currently handle only 1. and 3 and from 2. only the case of
688 * spaces before newlines as a side effect.
690 * 2. could be used to suppress as many spaces as possible. This has two effects:
691 * - Reimporting LyX generated LaTeX files changes almost no whitespace
692 * - Superflous whitespace from non LyX generated LaTeX files is removed.
693 * The drawback is that the logic inside the function becomes
694 * complicated, and that is the reason why it is not implemented.
696 void check_space(Parser & p, ostream & os, Context & context)
698 Token const next = p.next_token();
699 Token const curr = p.curr_token();
700 // A space before a single newline and vice versa must be ignored
701 // LyX emits a newline before \end{lyxcode}.
702 // This newline must be ignored,
703 // otherwise LyX will add an additional protected space.
704 if (next.cat() == catSpace ||
705 next.cat() == catNewline ||
706 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
709 context.check_layout(os);
715 * Parse all arguments of \p command
717 void parse_arguments(string const & command,
718 vector<ArgumentType> const & template_arguments,
719 Parser & p, ostream & os, bool outer, Context & context)
721 string ert = command;
722 size_t no_arguments = template_arguments.size();
723 for (size_t i = 0; i < no_arguments; ++i) {
724 switch (template_arguments[i]) {
727 // This argument contains regular LaTeX
728 handle_ert(os, ert + '{', context);
729 eat_whitespace(p, os, context, false);
730 if (template_arguments[i] == required)
731 parse_text(p, os, FLAG_ITEM, outer, context);
733 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
737 // This argument consists only of a single item.
738 // The presence of '{' or not must be preserved.
740 if (p.next_token().cat() == catBegin)
741 ert += '{' + p.verbatim_item() + '}';
743 ert += p.verbatim_item();
747 // This argument may contain special characters
748 ert += '{' + p.verbatim_item() + '}';
752 // true because we must not eat whitespace
753 // if an optional arg follows we must not strip the
754 // brackets from this one
755 if (i < no_arguments - 1 &&
756 template_arguments[i+1] == optional)
757 ert += p.getFullOpt(true);
759 ert += p.getOpt(true);
763 handle_ert(os, ert, context);
768 * Check whether \p command is a known command. If yes,
769 * handle the command with all arguments.
770 * \return true if the command was parsed, false otherwise.
772 bool parse_command(string const & command, Parser & p, ostream & os,
773 bool outer, Context & context)
775 if (known_commands.find(command) != known_commands.end()) {
776 parse_arguments(command, known_commands[command], p, os,
784 /// Parses a minipage or parbox
785 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
786 unsigned inner_flags, bool outer, Context & parent_context,
787 string const & outer_type, string const & special,
788 string const & inner_type)
792 string hor_pos = "c";
793 // We need to set the height to the LaTeX default of 1\\totalheight
794 // for the case when no height argument is given
795 string height_value = "1";
796 string height_unit = "in";
797 string height_special = "totalheight";
802 string width_special = "none";
803 if (!inner_type.empty() && p.hasOpt()) {
804 if (inner_type != "makebox")
805 position = p.getArg('[', ']');
807 latex_width = p.getArg('[', ']');
808 translate_box_len(latex_width, width_value, width_unit, width_special);
811 if (position != "t" && position != "c" && position != "b") {
812 cerr << "invalid position " << position << " for "
813 << inner_type << endl;
817 if (inner_type != "makebox") {
818 latex_height = p.getArg('[', ']');
819 translate_box_len(latex_height, height_value, height_unit, height_special);
821 string const opt = p.getArg('[', ']');
824 if (hor_pos != "l" && hor_pos != "c" &&
825 hor_pos != "r" && hor_pos != "s") {
826 cerr << "invalid hor_pos " << hor_pos
827 << " for " << inner_type << endl;
834 inner_pos = p.getArg('[', ']');
835 if (inner_pos != "c" && inner_pos != "t" &&
836 inner_pos != "b" && inner_pos != "s") {
837 cerr << "invalid inner_pos "
838 << inner_pos << " for "
839 << inner_type << endl;
840 inner_pos = position;
845 if (inner_type.empty()) {
846 if (special.empty() && outer_type != "framebox")
847 latex_width = "1\\columnwidth";
850 latex_width = p2.getArg('[', ']');
851 string const opt = p2.getArg('[', ']');
854 if (hor_pos != "l" && hor_pos != "c" &&
855 hor_pos != "r" && hor_pos != "s") {
856 cerr << "invalid hor_pos " << hor_pos
857 << " for " << outer_type << endl;
862 } else if (inner_type != "makebox")
863 latex_width = p.verbatim_item();
864 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
865 // as this is LyX's standard for such cases (except for makebox)
866 // \framebox is more special and handled below
867 if (latex_width.empty() && inner_type != "makebox"
868 && outer_type != "framebox")
869 latex_width = "1\\columnwidth";
871 translate_len(latex_width, width_value, width_unit);
873 bool shadedparbox = false;
874 if (inner_type == "shaded") {
875 eat_whitespace(p, os, parent_context, false);
876 if (outer_type == "parbox") {
878 if (p.next_token().cat() == catBegin)
880 eat_whitespace(p, os, parent_context, false);
886 // If we already read the inner box we have to push the inner env
887 if (!outer_type.empty() && !inner_type.empty() &&
888 (inner_flags & FLAG_END))
889 active_environments.push_back(inner_type);
890 // LyX can't handle length variables
891 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
892 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
893 // Look whether there is some content after the end of the
894 // inner box, but before the end of the outer box.
895 // If yes, we need to output ERT.
897 if (inner_flags & FLAG_END)
898 p.verbatimEnvironment(inner_type);
902 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
903 if ((outer_env && p.next_token().asInput() != "\\end") ||
904 (!outer_env && p.next_token().cat() != catEnd)) {
905 // something is between the end of the inner box and
906 // the end of the outer box, so we need to use ERT.
911 // if only \makebox{content} was used we can set its width to 1\width
912 // because this identic and also identic to \mbox
913 // this doesn't work for \framebox{content}, thus we have to use ERT for this
914 if (latex_width.empty() && inner_type == "makebox") {
917 width_special = "width";
918 } else if (latex_width.empty() && outer_type == "framebox") {
923 if (!outer_type.empty()) {
924 if (outer_flags & FLAG_END)
925 ss << "\\begin{" << outer_type << '}';
927 ss << '\\' << outer_type << '{';
928 if (!special.empty())
932 if (!inner_type.empty()) {
933 if (inner_type != "shaded") {
934 if (inner_flags & FLAG_END)
935 ss << "\\begin{" << inner_type << '}';
937 ss << '\\' << inner_type;
939 if (!position.empty())
940 ss << '[' << position << ']';
941 if (!latex_height.empty())
942 ss << '[' << latex_height << ']';
943 if (!inner_pos.empty())
944 ss << '[' << inner_pos << ']';
945 ss << '{' << latex_width << '}';
946 if (!(inner_flags & FLAG_END))
949 if (inner_type == "shaded")
950 ss << "\\begin{shaded}";
951 handle_ert(os, ss.str(), parent_context);
952 if (!inner_type.empty()) {
953 parse_text(p, os, inner_flags, outer, parent_context);
954 if (inner_flags & FLAG_END)
955 handle_ert(os, "\\end{" + inner_type + '}',
958 handle_ert(os, "}", parent_context);
960 if (!outer_type.empty()) {
961 // If we already read the inner box we have to pop
963 if (!inner_type.empty() && (inner_flags & FLAG_END))
964 active_environments.pop_back();
966 // Ensure that the end of the outer box is parsed correctly:
967 // The opening brace has been eaten by parse_outer_box()
968 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
969 outer_flags &= ~FLAG_ITEM;
970 outer_flags |= FLAG_BRACE_LAST;
972 parse_text(p, os, outer_flags, outer, parent_context);
973 if (outer_flags & FLAG_END)
974 handle_ert(os, "\\end{" + outer_type + '}',
976 else if (inner_type.empty() && outer_type == "framebox")
977 // in this case it is already closed later
980 handle_ert(os, "}", parent_context);
983 // LyX does not like empty positions, so we have
984 // to set them to the LaTeX default values here.
985 if (position.empty())
987 if (inner_pos.empty())
988 inner_pos = position;
989 parent_context.check_layout(os);
990 begin_inset(os, "Box ");
991 if (outer_type == "framed")
993 else if (outer_type == "framebox")
995 else if (outer_type == "shadowbox")
997 else if ((outer_type == "shaded" && inner_type.empty()) ||
998 (outer_type == "minipage" && inner_type == "shaded") ||
999 (outer_type == "parbox" && inner_type == "shaded")) {
1001 preamble.registerAutomaticallyLoadedPackage("color");
1002 } else if (outer_type == "doublebox")
1003 os << "Doublebox\n";
1004 else if (outer_type.empty())
1005 os << "Frameless\n";
1007 os << outer_type << '\n';
1008 os << "position \"" << position << "\"\n";
1009 os << "hor_pos \"" << hor_pos << "\"\n";
1010 os << "has_inner_box " << !inner_type.empty() << "\n";
1011 os << "inner_pos \"" << inner_pos << "\"\n";
1012 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1014 os << "use_makebox " << (inner_type == "makebox") << '\n';
1015 os << "width \"" << width_value << width_unit << "\"\n";
1016 os << "special \"" << width_special << "\"\n";
1017 os << "height \"" << height_value << height_unit << "\"\n";
1018 os << "height_special \"" << height_special << "\"\n";
1019 os << "status open\n\n";
1021 // Unfortunately we can't use parse_text_in_inset:
1022 // InsetBox::forcePlainLayout() is hard coded and does not
1023 // use the inset layout. Apart from that do we call parse_text
1024 // up to two times, but need only one check_end_layout.
1025 bool const forcePlainLayout =
1026 (!inner_type.empty() || inner_type == "makebox") &&
1027 outer_type != "shaded" && outer_type != "framed";
1028 Context context(true, parent_context.textclass);
1029 if (forcePlainLayout)
1030 context.layout = &context.textclass.plainLayout();
1032 context.font = parent_context.font;
1034 // If we have no inner box the contents will be read with the outer box
1035 if (!inner_type.empty())
1036 parse_text(p, os, inner_flags, outer, context);
1038 // Ensure that the end of the outer box is parsed correctly:
1039 // The opening brace has been eaten by parse_outer_box()
1040 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1041 outer_flags &= ~FLAG_ITEM;
1042 outer_flags |= FLAG_BRACE_LAST;
1045 // Find end of outer box, output contents if inner_type is
1046 // empty and output possible comments
1047 if (!outer_type.empty()) {
1048 // If we already read the inner box we have to pop
1050 if (!inner_type.empty() && (inner_flags & FLAG_END))
1051 active_environments.pop_back();
1052 // This does not output anything but comments if
1053 // inner_type is not empty (see use_ert)
1054 parse_text(p, os, outer_flags, outer, context);
1057 context.check_end_layout(os);
1059 #ifdef PRESERVE_LAYOUT
1060 // LyX puts a % after the end of the minipage
1061 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1063 //handle_comment(os, "%dummy", parent_context);
1066 parent_context.new_paragraph(os);
1068 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1069 //handle_comment(os, "%dummy", parent_context);
1072 // We add a protected space if something real follows
1073 if (p.good() && p.next_token().cat() != catComment) {
1074 begin_inset(os, "space ~\n");
1083 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1084 Context & parent_context, string const & outer_type,
1085 string const & special)
1087 eat_whitespace(p, os, parent_context, false);
1088 if (flags & FLAG_ITEM) {
1090 if (p.next_token().cat() == catBegin)
1093 cerr << "Warning: Ignoring missing '{' after \\"
1094 << outer_type << '.' << endl;
1095 eat_whitespace(p, os, parent_context, false);
1098 unsigned int inner_flags = 0;
1100 if (outer_type == "minipage" || outer_type == "parbox") {
1101 p.skip_spaces(true);
1102 while (p.hasOpt()) {
1104 p.skip_spaces(true);
1107 p.skip_spaces(true);
1108 if (outer_type == "parbox") {
1110 if (p.next_token().cat() == catBegin)
1112 p.skip_spaces(true);
1115 if (outer_type == "shaded") {
1116 // These boxes never have an inner box
1118 } else if (p.next_token().asInput() == "\\parbox") {
1119 inner = p.get_token().cs();
1120 inner_flags = FLAG_ITEM;
1121 } else if (p.next_token().asInput() == "\\begin") {
1122 // Is this a minipage or shaded box?
1125 inner = p.getArg('{', '}');
1127 if (inner == "minipage" || inner == "shaded")
1128 inner_flags = FLAG_END;
1133 if (inner_flags == FLAG_END) {
1134 if (inner != "shaded")
1138 eat_whitespace(p, os, parent_context, false);
1140 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1141 outer_type, special, inner);
1143 if (inner_flags == FLAG_ITEM) {
1145 eat_whitespace(p, os, parent_context, false);
1147 parse_box(p, os, flags, inner_flags, outer, parent_context,
1148 outer_type, special, inner);
1153 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1155 parent_context.check_layout(os);
1156 begin_inset(os, "listings\n");
1158 string arg = p.verbatimOption();
1159 os << "lstparams " << '"' << arg << '"' << '\n';
1160 if (arg.find("\\color") != string::npos)
1161 preamble.registerAutomaticallyLoadedPackage("color");
1164 os << "inline true\n";
1166 os << "inline false\n";
1167 os << "status collapsed\n";
1168 Context context(true, parent_context.textclass);
1169 context.layout = &parent_context.textclass.plainLayout();
1172 s = p.plainCommand('!', '!', "lstinline");
1173 context.new_paragraph(os);
1174 context.check_layout(os);
1176 s = p.plainEnvironment("lstlisting");
1177 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1179 os << "\n\\backslash\n";
1180 else if (*it == '\n') {
1181 // avoid adding an empty paragraph at the end
1183 context.new_paragraph(os);
1184 context.check_layout(os);
1189 context.check_end_layout(os);
1194 /// parse an unknown environment
1195 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1196 unsigned flags, bool outer,
1197 Context & parent_context)
1199 if (name == "tabbing")
1200 // We need to remember that we have to handle '\=' specially
1201 flags |= FLAG_TABBING;
1203 // We need to translate font changes and paragraphs inside the
1204 // environment to ERT if we have a non standard font.
1205 // Otherwise things like
1206 // \large\begin{foo}\huge bar\end{foo}
1208 bool const specialfont =
1209 (parent_context.font != parent_context.normalfont);
1210 bool const new_layout_allowed = parent_context.new_layout_allowed;
1212 parent_context.new_layout_allowed = false;
1213 handle_ert(os, "\\begin{" + name + "}", parent_context);
1214 parse_text_snippet(p, os, flags, outer, parent_context);
1215 handle_ert(os, "\\end{" + name + "}", parent_context);
1217 parent_context.new_layout_allowed = new_layout_allowed;
1221 void parse_environment(Parser & p, ostream & os, bool outer,
1222 string & last_env, Context & parent_context)
1224 Layout const * newlayout;
1225 InsetLayout const * newinsetlayout = 0;
1226 string const name = p.getArg('{', '}');
1227 const bool is_starred = suffixIs(name, '*');
1228 string const unstarred_name = rtrim(name, "*");
1229 active_environments.push_back(name);
1231 if (is_math_env(name)) {
1232 parent_context.check_layout(os);
1233 begin_inset(os, "Formula ");
1234 os << "\\begin{" << name << "}";
1235 parse_math(p, os, FLAG_END, MATH_MODE);
1236 os << "\\end{" << name << "}";
1238 if (is_display_math_env(name)) {
1239 // Prevent the conversion of a line break to a space
1240 // (bug 7668). This does not change the output, but
1241 // looks ugly in LyX.
1242 eat_whitespace(p, os, parent_context, false);
1246 else if (is_known(name, preamble.polyglossia_languages)) {
1247 // We must begin a new paragraph if not already done
1248 if (! parent_context.atParagraphStart()) {
1249 parent_context.check_end_layout(os);
1250 parent_context.new_paragraph(os);
1252 // save the language in the context so that it is
1253 // handled by parse_text
1254 parent_context.font.language = preamble.polyglossia2lyx(name);
1255 parse_text(p, os, FLAG_END, outer, parent_context);
1256 // Just in case the environment is empty
1257 parent_context.extra_stuff.erase();
1258 // We must begin a new paragraph to reset the language
1259 parent_context.new_paragraph(os);
1263 else if (unstarred_name == "tabular" || name == "longtable") {
1264 eat_whitespace(p, os, parent_context, false);
1265 string width = "0pt";
1266 if (name == "tabular*") {
1267 width = lyx::translate_len(p.getArg('{', '}'));
1268 eat_whitespace(p, os, parent_context, false);
1270 parent_context.check_layout(os);
1271 begin_inset(os, "Tabular ");
1272 handle_tabular(p, os, name, width, parent_context);
1277 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1278 eat_whitespace(p, os, parent_context, false);
1279 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1280 eat_whitespace(p, os, parent_context, false);
1281 parent_context.check_layout(os);
1282 begin_inset(os, "Float " + unstarred_name + "\n");
1283 // store the float type for subfloats
1284 // subfloats only work with figures and tables
1285 if (unstarred_name == "figure")
1286 float_type = unstarred_name;
1287 else if (unstarred_name == "table")
1288 float_type = unstarred_name;
1292 os << "placement " << opt << '\n';
1293 if (contains(opt, "H"))
1294 preamble.registerAutomaticallyLoadedPackage("float");
1296 Floating const & fl = parent_context.textclass.floats()
1297 .getType(unstarred_name);
1298 if (!fl.floattype().empty() && fl.usesFloatPkg())
1299 preamble.registerAutomaticallyLoadedPackage("float");
1302 os << "wide " << convert<string>(is_starred)
1303 << "\nsideways false"
1304 << "\nstatus open\n\n";
1305 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1307 // We don't need really a new paragraph, but
1308 // we must make sure that the next item gets a \begin_layout.
1309 parent_context.new_paragraph(os);
1311 // the float is parsed thus delete the type
1315 else if (unstarred_name == "sidewaysfigure"
1316 || unstarred_name == "sidewaystable") {
1317 eat_whitespace(p, os, parent_context, false);
1318 parent_context.check_layout(os);
1319 if (unstarred_name == "sidewaysfigure")
1320 begin_inset(os, "Float figure\n");
1322 begin_inset(os, "Float table\n");
1323 os << "wide " << convert<string>(is_starred)
1324 << "\nsideways true"
1325 << "\nstatus open\n\n";
1326 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1328 // We don't need really a new paragraph, but
1329 // we must make sure that the next item gets a \begin_layout.
1330 parent_context.new_paragraph(os);
1332 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1335 else if (name == "wrapfigure" || name == "wraptable") {
1336 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1337 eat_whitespace(p, os, parent_context, false);
1338 parent_context.check_layout(os);
1341 string overhang = "0col%";
1344 lines = p.getArg('[', ']');
1345 string const placement = p.getArg('{', '}');
1347 overhang = p.getArg('[', ']');
1348 string const width = p.getArg('{', '}');
1350 if (name == "wrapfigure")
1351 begin_inset(os, "Wrap figure\n");
1353 begin_inset(os, "Wrap table\n");
1354 os << "lines " << lines
1355 << "\nplacement " << placement
1356 << "\noverhang " << lyx::translate_len(overhang)
1357 << "\nwidth " << lyx::translate_len(width)
1358 << "\nstatus open\n\n";
1359 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1361 // We don't need really a new paragraph, but
1362 // we must make sure that the next item gets a \begin_layout.
1363 parent_context.new_paragraph(os);
1365 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1368 else if (name == "minipage") {
1369 eat_whitespace(p, os, parent_context, false);
1370 // Test whether this is an outer box of a shaded box
1372 // swallow arguments
1373 while (p.hasOpt()) {
1375 p.skip_spaces(true);
1378 p.skip_spaces(true);
1379 Token t = p.get_token();
1380 bool shaded = false;
1381 if (t.asInput() == "\\begin") {
1382 p.skip_spaces(true);
1383 if (p.getArg('{', '}') == "shaded")
1388 parse_outer_box(p, os, FLAG_END, outer,
1389 parent_context, name, "shaded");
1391 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1396 else if (name == "comment") {
1397 eat_whitespace(p, os, parent_context, false);
1398 parent_context.check_layout(os);
1399 begin_inset(os, "Note Comment\n");
1400 os << "status open\n";
1401 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1404 skip_braces(p); // eat {} that might by set by LyX behind comments
1405 preamble.registerAutomaticallyLoadedPackage("verbatim");
1408 else if (name == "verbatim") {
1409 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1410 string const s = p.plainEnvironment("verbatim");
1411 string::const_iterator it2 = s.begin();
1412 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1414 os << "\\backslash ";
1415 else if (*it == '\n') {
1417 // avoid adding an empty paragraph at the end
1418 // FIXME: if there are 2 consecutive spaces at the end ignore it
1419 // because LyX will re-add a \n
1420 // This hack must be removed once bug 8049 is fixed!
1421 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1422 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1426 os << "\n\\end_layout\n\n";
1428 // reset to Standard layout
1429 os << "\n\\begin_layout Standard\n";
1432 else if (name == "CJK") {
1433 // the scheme is \begin{CJK}{encoding}{mapping}{text}
1434 // It is impossible to decide if a CJK environment was in its own paragraph or within
1435 // a line. We therefore always assume a paragraph since the latter is a rare case.
1436 eat_whitespace(p, os, parent_context, false);
1437 parent_context.check_end_layout(os);
1438 // store the encoding to be able to reset it
1439 string const encoding_old = p.getEncoding();
1440 string const encoding = p.getArg('{', '}');
1441 // SJIS and Bg5 cannot be handled by iconv
1442 // JIS does not work with LyX's encoding conversion
1443 if (encoding != "Bg5" && encoding != "JIS" && encoding != "SJIS")
1444 p.setEncoding(encoding);
1446 p.setEncoding("utf8");
1447 // LyX doesn't support the second argument so if
1448 // this is used we need to output everything as ERT
1449 string const mapping = p.getArg('{', '}');
1450 char const * const * const where =
1451 is_known(encoding, supported_CJK_encodings);
1452 if ((!mapping.empty() && mapping != " ") || !where) {
1453 parent_context.check_layout(os);
1454 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1456 // we must parse the content as verbatim because e.g. JIS can contain
1457 // normally invalid characters
1458 string const s = p.plainEnvironment("CJK");
1459 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1461 handle_ert(os, "\\", parent_context);
1462 else if (*it == '$')
1463 handle_ert(os, "$", parent_context);
1467 handle_ert(os, "\\end{" + name + "}",
1471 supported_CJK_languages[where - supported_CJK_encodings];
1472 // store the language because we must reset it at the end
1473 string const lang_old = parent_context.font.language;
1474 parent_context.font.language = lang;
1475 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1476 parent_context.font.language = lang_old;
1477 parent_context.new_paragraph(os);
1479 p.setEncoding(encoding_old);
1483 else if (name == "lyxgreyedout") {
1484 eat_whitespace(p, os, parent_context, false);
1485 parent_context.check_layout(os);
1486 begin_inset(os, "Note Greyedout\n");
1487 os << "status open\n";
1488 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1491 if (!preamble.notefontcolor().empty())
1492 preamble.registerAutomaticallyLoadedPackage("color");
1495 else if (name == "framed" || name == "shaded") {
1496 eat_whitespace(p, os, parent_context, false);
1497 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1501 else if (name == "lstlisting") {
1502 eat_whitespace(p, os, parent_context, false);
1503 parse_listings(p, os, parent_context, false);
1507 else if (!parent_context.new_layout_allowed)
1508 parse_unknown_environment(p, name, os, FLAG_END, outer,
1511 // Alignment and spacing settings
1512 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1513 // therefore are totally broken!
1514 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1515 // they are commands not environments. They are furthermore switches that
1516 // can be ended by another switches, but also by commands like \footnote or
1517 // \parbox. So the only safe way is to leave them untouched.
1518 else if (name == "center" || name == "centering" ||
1519 name == "flushleft" || name == "flushright" ||
1520 name == "singlespace" || name == "onehalfspace" ||
1521 name == "doublespace" || name == "spacing") {
1522 eat_whitespace(p, os, parent_context, false);
1523 // We must begin a new paragraph if not already done
1524 if (! parent_context.atParagraphStart()) {
1525 parent_context.check_end_layout(os);
1526 parent_context.new_paragraph(os);
1528 if (name == "flushleft")
1529 parent_context.add_extra_stuff("\\align left\n");
1530 else if (name == "flushright")
1531 parent_context.add_extra_stuff("\\align right\n");
1532 else if (name == "center" || name == "centering")
1533 parent_context.add_extra_stuff("\\align center\n");
1534 else if (name == "singlespace")
1535 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1536 else if (name == "onehalfspace") {
1537 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1538 preamble.registerAutomaticallyLoadedPackage("setspace");
1539 } else if (name == "doublespace") {
1540 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1541 preamble.registerAutomaticallyLoadedPackage("setspace");
1542 } else if (name == "spacing") {
1543 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1544 preamble.registerAutomaticallyLoadedPackage("setspace");
1546 parse_text(p, os, FLAG_END, outer, parent_context);
1547 // Just in case the environment is empty
1548 parent_context.extra_stuff.erase();
1549 // We must begin a new paragraph to reset the alignment
1550 parent_context.new_paragraph(os);
1554 // The single '=' is meant here.
1555 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1556 eat_whitespace(p, os, parent_context, false);
1557 Context context(true, parent_context.textclass, newlayout,
1558 parent_context.layout, parent_context.font);
1559 if (parent_context.deeper_paragraph) {
1560 // We are beginning a nested environment after a
1561 // deeper paragraph inside the outer list environment.
1562 // Therefore we don't need to output a "begin deeper".
1563 context.need_end_deeper = true;
1565 parent_context.check_end_layout(os);
1566 if (last_env == name) {
1567 // we need to output a separator since LyX would export
1568 // the two environments as one otherwise (bug 5716)
1569 docstring const sep = from_ascii("--Separator--");
1570 TeX2LyXDocClass const & textclass(parent_context.textclass);
1571 if (textclass.hasLayout(sep)) {
1572 Context newcontext(parent_context);
1573 newcontext.layout = &(textclass[sep]);
1574 newcontext.check_layout(os);
1575 newcontext.check_end_layout(os);
1577 parent_context.check_layout(os);
1578 begin_inset(os, "Note Note\n");
1579 os << "status closed\n";
1580 Context newcontext(true, textclass,
1581 &(textclass.defaultLayout()));
1582 newcontext.check_layout(os);
1583 newcontext.check_end_layout(os);
1585 parent_context.check_end_layout(os);
1588 switch (context.layout->latextype) {
1589 case LATEX_LIST_ENVIRONMENT:
1590 context.add_par_extra_stuff("\\labelwidthstring "
1591 + p.verbatim_item() + '\n');
1594 case LATEX_BIB_ENVIRONMENT:
1595 p.verbatim_item(); // swallow next arg
1601 context.check_deeper(os);
1602 // handle known optional and required arguments
1603 // layouts require all optional arguments before the required ones
1604 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1605 // It is impossible to place anything after the environment name,
1606 // but before the first \\item.
1607 // FIXME: Adjust to format 446!
1608 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1609 bool need_layout = true;
1611 while (optargs < context.layout->optArgs()) {
1612 eat_whitespace(p, os, context, false);
1613 if (p.next_token().cat() == catEscape ||
1614 p.next_token().character() != '[')
1616 p.get_token(); // eat '['
1618 context.check_layout(os);
1619 need_layout = false;
1621 // FIXME: Just a workaround
1622 begin_inset(os, "Argument 999\n");
1623 os << "status collapsed\n\n";
1624 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1626 eat_whitespace(p, os, context, false);
1630 while (reqargs < context.layout->requiredArgs()) {
1631 eat_whitespace(p, os, context, false);
1632 if (p.next_token().cat() != catBegin)
1634 p.get_token(); // eat '{'
1636 context.check_layout(os);
1637 need_layout = false;
1639 // FIXME: Just a workaround
1640 begin_inset(os, "Argument 999\n");
1641 os << "status collapsed\n\n";
1642 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1644 eat_whitespace(p, os, context, false);
1648 parse_text(p, os, FLAG_END, outer, context);
1649 context.check_end_layout(os);
1650 if (parent_context.deeper_paragraph) {
1651 // We must suppress the "end deeper" because we
1652 // suppressed the "begin deeper" above.
1653 context.need_end_deeper = false;
1655 context.check_end_deeper(os);
1656 parent_context.new_paragraph(os);
1658 if (!preamble.titleLayoutFound())
1659 preamble.titleLayoutFound(newlayout->intitle);
1660 set<string> const & req = newlayout->requires();
1661 set<string>::const_iterator it = req.begin();
1662 set<string>::const_iterator en = req.end();
1663 for (; it != en; ++it)
1664 preamble.registerAutomaticallyLoadedPackage(*it);
1667 // The single '=' is meant here.
1668 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1669 eat_whitespace(p, os, parent_context, false);
1670 parent_context.check_layout(os);
1671 begin_inset(os, "Flex ");
1672 os << to_utf8(newinsetlayout->name()) << '\n'
1673 << "status collapsed\n";
1674 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1678 else if (name == "appendix") {
1679 // This is no good latex style, but it works and is used in some documents...
1680 eat_whitespace(p, os, parent_context, false);
1681 parent_context.check_end_layout(os);
1682 Context context(true, parent_context.textclass, parent_context.layout,
1683 parent_context.layout, parent_context.font);
1684 context.check_layout(os);
1685 os << "\\start_of_appendix\n";
1686 parse_text(p, os, FLAG_END, outer, context);
1687 context.check_end_layout(os);
1691 else if (known_environments.find(name) != known_environments.end()) {
1692 vector<ArgumentType> arguments = known_environments[name];
1693 // The last "argument" denotes wether we may translate the
1694 // environment contents to LyX
1695 // The default required if no argument is given makes us
1696 // compatible with the reLyXre environment.
1697 ArgumentType contents = arguments.empty() ?
1700 if (!arguments.empty())
1701 arguments.pop_back();
1702 // See comment in parse_unknown_environment()
1703 bool const specialfont =
1704 (parent_context.font != parent_context.normalfont);
1705 bool const new_layout_allowed =
1706 parent_context.new_layout_allowed;
1708 parent_context.new_layout_allowed = false;
1709 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1710 outer, parent_context);
1711 if (contents == verbatim)
1712 handle_ert(os, p.verbatimEnvironment(name),
1715 parse_text_snippet(p, os, FLAG_END, outer,
1717 handle_ert(os, "\\end{" + name + "}", parent_context);
1719 parent_context.new_layout_allowed = new_layout_allowed;
1723 parse_unknown_environment(p, name, os, FLAG_END, outer,
1727 active_environments.pop_back();
1731 /// parses a comment and outputs it to \p os.
1732 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1734 LASSERT(t.cat() == catComment, return);
1735 if (!t.cs().empty()) {
1736 context.check_layout(os);
1737 handle_comment(os, '%' + t.cs(), context);
1738 if (p.next_token().cat() == catNewline) {
1739 // A newline after a comment line starts a new
1741 if (context.new_layout_allowed) {
1742 if(!context.atParagraphStart())
1743 // Only start a new paragraph if not already
1744 // done (we might get called recursively)
1745 context.new_paragraph(os);
1747 handle_ert(os, "\n", context);
1748 eat_whitespace(p, os, context, true);
1751 // "%\n" combination
1758 * Reads spaces and comments until the first non-space, non-comment token.
1759 * New paragraphs (double newlines or \\par) are handled like simple spaces
1760 * if \p eatParagraph is true.
1761 * Spaces are skipped, but comments are written to \p os.
1763 void eat_whitespace(Parser & p, ostream & os, Context & context,
1767 Token const & t = p.get_token();
1768 if (t.cat() == catComment)
1769 parse_comment(p, os, t, context);
1770 else if ((! eatParagraph && p.isParagraph()) ||
1771 (t.cat() != catSpace && t.cat() != catNewline)) {
1780 * Set a font attribute, parse text and reset the font attribute.
1781 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1782 * \param currentvalue Current value of the attribute. Is set to the new
1783 * value during parsing.
1784 * \param newvalue New value of the attribute
1786 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1787 Context & context, string const & attribute,
1788 string & currentvalue, string const & newvalue)
1790 context.check_layout(os);
1791 string const oldvalue = currentvalue;
1792 currentvalue = newvalue;
1793 os << '\n' << attribute << ' ' << newvalue << "\n";
1794 parse_text_snippet(p, os, flags, outer, context);
1795 context.check_layout(os);
1796 os << '\n' << attribute << ' ' << oldvalue << "\n";
1797 currentvalue = oldvalue;
1801 /// get the arguments of a natbib or jurabib citation command
1802 void get_cite_arguments(Parser & p, bool natbibOrder,
1803 string & before, string & after)
1805 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1807 // text before the citation
1809 // text after the citation
1810 after = p.getFullOpt();
1812 if (!after.empty()) {
1813 before = p.getFullOpt();
1814 if (natbibOrder && !before.empty())
1815 swap(before, after);
1820 /// Convert filenames with TeX macros and/or quotes to something LyX
1822 string const normalize_filename(string const & name)
1824 Parser p(trim(name, "\""));
1827 Token const & t = p.get_token();
1828 if (t.cat() != catEscape)
1830 else if (t.cs() == "lyxdot") {
1831 // This is used by LyX for simple dots in relative
1835 } else if (t.cs() == "space") {
1845 /// Convert \p name from TeX convention (relative to master file) to LyX
1846 /// convention (relative to .lyx file) if it is relative
1847 void fix_child_filename(string & name)
1849 string const absMasterTeX = getMasterFilePath(true);
1850 bool const isabs = FileName::isAbsolute(name);
1851 // convert from "relative to .tex master" to absolute original path
1853 name = makeAbsPath(name, absMasterTeX).absFileName();
1854 bool copyfile = copyFiles();
1855 string const absParentLyX = getParentFilePath(false);
1858 // convert from absolute original path to "relative to master file"
1859 string const rel = to_utf8(makeRelPath(from_utf8(name),
1860 from_utf8(absMasterTeX)));
1861 // re-interpret "relative to .tex file" as "relative to .lyx file"
1862 // (is different if the master .lyx file resides in a
1863 // different path than the master .tex file)
1864 string const absMasterLyX = getMasterFilePath(false);
1865 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1866 // Do not copy if the new path is impossible to create. Example:
1867 // absMasterTeX = "/foo/bar/"
1868 // absMasterLyX = "/bar/"
1869 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1870 if (contains(name, "/../"))
1877 // convert from absolute original path to
1878 // "relative to .lyx file"
1879 name = to_utf8(makeRelPath(from_utf8(abs),
1880 from_utf8(absParentLyX)));
1884 // convert from absolute original path to "relative to .lyx file"
1885 name = to_utf8(makeRelPath(from_utf8(name),
1886 from_utf8(absParentLyX)));
1891 void copy_file(FileName const & src, string dstname)
1895 string const absParent = getParentFilePath(false);
1897 if (FileName::isAbsolute(dstname))
1898 dst = FileName(dstname);
1900 dst = makeAbsPath(dstname, absParent);
1901 string const absMaster = getMasterFilePath(false);
1902 FileName const srcpath = src.onlyPath();
1903 FileName const dstpath = dst.onlyPath();
1904 if (equivalent(srcpath, dstpath))
1906 if (!dstpath.isDirectory()) {
1907 if (!dstpath.createPath()) {
1908 cerr << "Warning: Could not create directory for file `"
1909 << dst.absFileName() << "´." << endl;
1913 if (dst.isReadableFile()) {
1914 if (overwriteFiles())
1915 cerr << "Warning: Overwriting existing file `"
1916 << dst.absFileName() << "´." << endl;
1918 cerr << "Warning: Not overwriting existing file `"
1919 << dst.absFileName() << "´." << endl;
1923 if (!src.copyTo(dst))
1924 cerr << "Warning: Could not copy file `" << src.absFileName()
1925 << "´ to `" << dst.absFileName() << "´." << endl;
1929 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1930 void parse_noweb(Parser & p, ostream & os, Context & context)
1932 // assemble the rest of the keyword
1936 Token const & t = p.get_token();
1937 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1940 scrap = (p.good() && p.next_token().asInput() == "=");
1942 name += p.get_token().asInput();
1945 name += t.asInput();
1948 if (!scrap || !context.new_layout_allowed ||
1949 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1950 cerr << "Warning: Could not interpret '" << name
1951 << "'. Ignoring it." << endl;
1955 // We use new_paragraph instead of check_end_layout because the stuff
1956 // following the noweb chunk needs to start with a \begin_layout.
1957 // This may create a new paragraph even if there was none in the
1958 // noweb file, but the alternative is an invalid LyX file. Since
1959 // noweb code chunks are implemented with a layout style in LyX they
1960 // always must be in an own paragraph.
1961 context.new_paragraph(os);
1962 Context newcontext(true, context.textclass,
1963 &context.textclass[from_ascii("Scrap")]);
1964 newcontext.check_layout(os);
1967 Token const & t = p.get_token();
1968 // We abuse the parser a bit, because this is no TeX syntax
1970 if (t.cat() == catEscape)
1971 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1974 Context tmp(false, context.textclass,
1975 &context.textclass[from_ascii("Scrap")]);
1976 tmp.need_end_layout = true;
1977 tmp.check_layout(oss);
1978 os << subst(t.asInput(), "\n", oss.str());
1980 // The scrap chunk is ended by an @ at the beginning of a line.
1981 // After the @ the line may contain a comment and/or
1982 // whitespace, but nothing else.
1983 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1984 (p.next_token().cat() == catSpace ||
1985 p.next_token().cat() == catNewline ||
1986 p.next_token().cat() == catComment)) {
1987 while (p.good() && p.next_token().cat() == catSpace)
1988 os << p.get_token().asInput();
1989 if (p.next_token().cat() == catComment)
1990 // The comment includes a final '\n'
1991 os << p.get_token().asInput();
1993 if (p.next_token().cat() == catNewline)
2000 newcontext.check_end_layout(os);
2004 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2005 bool is_macro(Parser & p)
2007 Token first = p.curr_token();
2008 if (first.cat() != catEscape || !p.good())
2010 if (first.cs() == "def")
2012 if (first.cs() != "global" && first.cs() != "long")
2014 Token second = p.get_token();
2016 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2017 second.cat() == catNewline || second.cat() == catComment)) {
2018 second = p.get_token();
2021 bool secondvalid = second.cat() == catEscape;
2023 bool thirdvalid = false;
2024 if (p.good() && first.cs() == "global" && secondvalid &&
2025 second.cs() == "long") {
2026 third = p.get_token();
2028 while (p.good() && !p.isParagraph() &&
2029 (third.cat() == catSpace ||
2030 third.cat() == catNewline ||
2031 third.cat() == catComment)) {
2032 third = p.get_token();
2035 thirdvalid = third.cat() == catEscape;
2037 for (int i = 0; i < pos; ++i)
2042 return (first.cs() == "global" || first.cs() == "long") &&
2043 second.cs() == "def";
2044 return first.cs() == "global" && second.cs() == "long" &&
2045 third.cs() == "def";
2049 /// Parse a macro definition (assumes that is_macro() returned true)
2050 void parse_macro(Parser & p, ostream & os, Context & context)
2052 context.check_layout(os);
2053 Token first = p.curr_token();
2056 string command = first.asInput();
2057 if (first.cs() != "def") {
2059 eat_whitespace(p, os, context, false);
2060 second = p.curr_token();
2061 command += second.asInput();
2062 if (second.cs() != "def") {
2064 eat_whitespace(p, os, context, false);
2065 third = p.curr_token();
2066 command += third.asInput();
2069 eat_whitespace(p, os, context, false);
2070 string const name = p.get_token().cs();
2071 eat_whitespace(p, os, context, false);
2077 while (p.next_token().cat() != catBegin) {
2078 if (p.next_token().cat() == catParameter) {
2083 // followed by number?
2084 if (p.next_token().cat() == catOther) {
2085 char c = p.getChar();
2087 // number = current arity + 1?
2088 if (c == arity + '0' + 1)
2093 paramtext += p.get_token().cs();
2095 paramtext += p.get_token().cs();
2100 // only output simple (i.e. compatible) macro as FormulaMacros
2101 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2103 context.check_layout(os);
2104 begin_inset(os, "FormulaMacro");
2105 os << "\n\\def" << ert;
2108 handle_ert(os, command + ert, context);
2112 void registerExternalTemplatePackages(string const & name)
2114 external::TemplateManager const & etm = external::TemplateManager::get();
2115 external::Template const * const et = etm.getTemplateByName(name);
2118 external::Template::Formats::const_iterator cit = et->formats.end();
2120 cit = et->formats.find("PDFLaTeX");
2121 if (cit == et->formats.end())
2122 // If the template has not specified a PDFLaTeX output,
2123 // we try the LaTeX format.
2124 cit = et->formats.find("LaTeX");
2125 if (cit == et->formats.end())
2127 vector<string>::const_iterator qit = cit->second.requirements.begin();
2128 vector<string>::const_iterator qend = cit->second.requirements.end();
2129 for (; qit != qend; ++qit)
2130 preamble.registerAutomaticallyLoadedPackage(*qit);
2133 } // anonymous namespace
2136 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2139 Layout const * newlayout = 0;
2140 InsetLayout const * newinsetlayout = 0;
2141 char const * const * where = 0;
2142 // Store the latest bibliographystyle and nocite{*} option
2143 // (needed for bibtex inset)
2145 string bibliographystyle = "default";
2146 bool const use_natbib = preamble.isPackageUsed("natbib");
2147 bool const use_jurabib = preamble.isPackageUsed("jurabib");
2150 Token const & t = p.get_token();
2152 // it is impossible to determine the correct encoding for non-CJK Japanese.
2153 // Therefore write a note at the beginning of the document
2154 if (is_nonCJKJapanese) {
2155 context.check_layout(os);
2156 begin_inset(os, "Note Note\n");
2157 os << "status open\n\\begin_layout Plain Layout\n"
2158 << "\\series bold\n"
2159 << "Important information:\n"
2160 << "\\end_layout\n\n"
2161 << "\\begin_layout Plain Layout\n"
2162 << "This document is in Japanese (non-CJK).\n"
2163 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2164 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2165 << " encoding in the document settings.\n"
2166 << "\\end_layout\n";
2168 is_nonCJKJapanese = false;
2172 debugToken(cerr, t, flags);
2175 if (flags & FLAG_ITEM) {
2176 if (t.cat() == catSpace)
2179 flags &= ~FLAG_ITEM;
2180 if (t.cat() == catBegin) {
2181 // skip the brace and collect everything to the next matching
2183 flags |= FLAG_BRACE_LAST;
2187 // handle only this single token, leave the loop if done
2188 flags |= FLAG_LEAVE;
2191 if (t.cat() != catEscape && t.character() == ']' &&
2192 (flags & FLAG_BRACK_LAST))
2194 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2197 // If there is anything between \end{env} and \begin{env} we
2198 // don't need to output a separator.
2199 if (t.cat() != catSpace && t.cat() != catNewline &&
2200 t.asInput() != "\\begin")
2206 if (t.cat() == catMath) {
2207 // we are inside some text mode thingy, so opening new math is allowed
2208 context.check_layout(os);
2209 begin_inset(os, "Formula ");
2210 Token const & n = p.get_token();
2211 bool const display(n.cat() == catMath && outer);
2213 // TeX's $$...$$ syntax for displayed math
2215 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2217 p.get_token(); // skip the second '$' token
2219 // simple $...$ stuff
2222 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2227 // Prevent the conversion of a line break to a
2228 // space (bug 7668). This does not change the
2229 // output, but looks ugly in LyX.
2230 eat_whitespace(p, os, context, false);
2234 else if (t.cat() == catSuper || t.cat() == catSub)
2235 cerr << "catcode " << t << " illegal in text mode\n";
2237 // Basic support for english quotes. This should be
2238 // extended to other quotes, but is not so easy (a
2239 // left english quote is the same as a right german
2241 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2242 context.check_layout(os);
2243 begin_inset(os, "Quotes ");
2249 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2250 context.check_layout(os);
2251 begin_inset(os, "Quotes ");
2258 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2259 context.check_layout(os);
2260 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() == "<"
2277 && p.next_token().asInput() == "<" && noweb_mode) {
2279 parse_noweb(p, os, context);
2282 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2283 check_space(p, os, context);
2285 else if (t.character() == '[' && noweb_mode &&
2286 p.next_token().character() == '[') {
2287 // These can contain underscores
2289 string const s = p.getFullOpt() + ']';
2290 if (p.next_token().character() == ']')
2293 cerr << "Warning: Inserting missing ']' in '"
2294 << s << "'." << endl;
2295 handle_ert(os, s, context);
2298 else if (t.cat() == catLetter) {
2299 context.check_layout(os);
2300 // Workaround for bug 4752.
2301 // FIXME: This whole code block needs to be removed
2302 // when the bug is fixed and tex2lyx produces
2303 // the updated file format.
2304 // The replacement algorithm in LyX is so stupid that
2305 // it even translates a phrase if it is part of a word.
2306 bool handled = false;
2307 for (int const * l = known_phrase_lengths; *l; ++l) {
2308 string phrase = t.cs();
2309 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2310 phrase += p.get_token().cs();
2311 if (is_known(phrase, known_coded_phrases)) {
2312 handle_ert(os, phrase, context);
2316 for (size_t i = 1; i < phrase.length(); ++i)
2324 else if (t.cat() == catOther ||
2325 t.cat() == catAlign ||
2326 t.cat() == catParameter) {
2327 // This translates "&" to "\\&" which may be wrong...
2328 context.check_layout(os);
2332 else if (p.isParagraph()) {
2333 if (context.new_layout_allowed)
2334 context.new_paragraph(os);
2336 handle_ert(os, "\\par ", context);
2337 eat_whitespace(p, os, context, true);
2340 else if (t.cat() == catActive) {
2341 context.check_layout(os);
2342 if (t.character() == '~') {
2343 if (context.layout->free_spacing)
2346 begin_inset(os, "space ~\n");
2353 else if (t.cat() == catBegin) {
2354 Token const next = p.next_token();
2355 Token const end = p.next_next_token();
2356 if (next.cat() == catEnd) {
2358 Token const prev = p.prev_token();
2360 if (p.next_token().character() == '`' ||
2361 (prev.character() == '-' &&
2362 p.next_token().character() == '-'))
2363 ; // ignore it in {}`` or -{}-
2365 handle_ert(os, "{}", context);
2366 } else if (next.cat() == catEscape &&
2367 is_known(next.cs(), known_quotes) &&
2368 end.cat() == catEnd) {
2369 // Something like {\textquoteright} (e.g.
2370 // from writer2latex). LyX writes
2371 // \textquoteright{}, so we may skip the
2372 // braces here for better readability.
2373 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2376 context.check_layout(os);
2377 // special handling of font attribute changes
2378 Token const prev = p.prev_token();
2379 TeXFont const oldFont = context.font;
2380 if (next.character() == '[' ||
2381 next.character() == ']' ||
2382 next.character() == '*') {
2384 if (p.next_token().cat() == catEnd) {
2389 handle_ert(os, "{", context);
2390 parse_text_snippet(p, os,
2393 handle_ert(os, "}", context);
2395 } else if (! context.new_layout_allowed) {
2396 handle_ert(os, "{", context);
2397 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2399 handle_ert(os, "}", context);
2400 } else if (is_known(next.cs(), known_sizes)) {
2401 // next will change the size, so we must
2403 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2405 if (!context.atParagraphStart())
2407 << context.font.size << "\n";
2408 } else if (is_known(next.cs(), known_font_families)) {
2409 // next will change the font family, so we
2410 // must reset it here
2411 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2413 if (!context.atParagraphStart())
2415 << context.font.family << "\n";
2416 } else if (is_known(next.cs(), known_font_series)) {
2417 // next will change the font series, so we
2418 // must reset it here
2419 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2421 if (!context.atParagraphStart())
2423 << context.font.series << "\n";
2424 } else if (is_known(next.cs(), known_font_shapes)) {
2425 // next will change the font shape, so we
2426 // must reset it here
2427 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2429 if (!context.atParagraphStart())
2431 << context.font.shape << "\n";
2432 } else if (is_known(next.cs(), known_old_font_families) ||
2433 is_known(next.cs(), known_old_font_series) ||
2434 is_known(next.cs(), known_old_font_shapes)) {
2435 // next will change the font family, series
2436 // and shape, so we must reset it here
2437 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2439 if (!context.atParagraphStart())
2441 << context.font.family
2443 << context.font.series
2445 << context.font.shape << "\n";
2447 handle_ert(os, "{", context);
2448 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2450 handle_ert(os, "}", context);
2455 else if (t.cat() == catEnd) {
2456 if (flags & FLAG_BRACE_LAST) {
2459 cerr << "stray '}' in text\n";
2460 handle_ert(os, "}", context);
2463 else if (t.cat() == catComment)
2464 parse_comment(p, os, t, context);
2467 // control sequences
2470 else if (t.cs() == "(") {
2471 context.check_layout(os);
2472 begin_inset(os, "Formula");
2474 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2479 else if (t.cs() == "[") {
2480 context.check_layout(os);
2481 begin_inset(os, "Formula");
2483 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2486 // Prevent the conversion of a line break to a space
2487 // (bug 7668). This does not change the output, but
2488 // looks ugly in LyX.
2489 eat_whitespace(p, os, context, false);
2492 else if (t.cs() == "begin")
2493 parse_environment(p, os, outer, last_env,
2496 else if (t.cs() == "end") {
2497 if (flags & FLAG_END) {
2498 // eat environment name
2499 string const name = p.getArg('{', '}');
2500 if (name != active_environment())
2501 cerr << "\\end{" + name + "} does not match \\begin{"
2502 + active_environment() + "}\n";
2505 p.error("found 'end' unexpectedly");
2508 else if (t.cs() == "item") {
2510 bool const optarg = p.hasOpt();
2512 // FIXME: This swallows comments, but we cannot use
2513 // eat_whitespace() since we must not output
2514 // anything before the item.
2515 p.skip_spaces(true);
2516 s = p.verbatimOption();
2518 p.skip_spaces(false);
2520 context.check_layout(os);
2521 if (context.has_item) {
2522 // An item in an unknown list-like environment
2523 // FIXME: Do this in check_layout()!
2524 context.has_item = false;
2526 handle_ert(os, "\\item", context);
2528 handle_ert(os, "\\item ", context);
2531 if (context.layout->labeltype != LABEL_MANUAL) {
2532 // LyX does not support \item[\mybullet]
2533 // in itemize environments
2535 os << parse_text_snippet(p2,
2536 FLAG_BRACK_LAST, outer, context);
2537 } else if (!s.empty()) {
2538 // LyX adds braces around the argument,
2539 // so we need to remove them here.
2540 if (s.size() > 2 && s[0] == '{' &&
2541 s[s.size()-1] == '}')
2542 s = s.substr(1, s.size()-2);
2543 // If the argument contains a space we
2544 // must put it into ERT: Otherwise LyX
2545 // would misinterpret the space as
2546 // item delimiter (bug 7663)
2547 if (contains(s, ' ')) {
2548 handle_ert(os, s, context);
2551 os << parse_text_snippet(p2,
2555 // The space is needed to separate the
2556 // item from the rest of the sentence.
2558 eat_whitespace(p, os, context, false);
2563 else if (t.cs() == "bibitem") {
2565 context.check_layout(os);
2566 eat_whitespace(p, os, context, false);
2567 string label = convert_command_inset_arg(p.verbatimOption());
2568 string key = convert_command_inset_arg(p.verbatim_item());
2569 if (contains(label, '\\') || contains(key, '\\')) {
2570 // LyX can't handle LaTeX commands in labels or keys
2571 handle_ert(os, t.asInput() + '[' + label +
2572 "]{" + p.verbatim_item() + '}',
2575 begin_command_inset(os, "bibitem", "bibitem");
2576 os << "label \"" << label << "\"\n"
2577 "key \"" << key << "\"\n";
2582 else if (is_macro(p)) {
2583 // catch the case of \def\inputGnumericTable
2585 if (t.cs() == "def") {
2586 Token second = p.next_token();
2587 if (second.cs() == "inputGnumericTable") {
2591 Token third = p.get_token();
2593 if (third.cs() == "input") {
2597 string name = normalize_filename(p.verbatim_item());
2598 string const path = getMasterFilePath(true);
2599 // We want to preserve relative / absolute filenames,
2600 // therefore path is only used for testing
2601 // The file extension is in every case ".tex".
2602 // So we need to remove this extension and check for
2603 // the original one.
2604 name = removeExtension(name);
2605 if (!makeAbsPath(name, path).exists()) {
2606 char const * const Gnumeric_formats[] = {"gnumeric",
2608 string const Gnumeric_name =
2609 find_file(name, path, Gnumeric_formats);
2610 if (!Gnumeric_name.empty())
2611 name = Gnumeric_name;
2613 FileName const absname = makeAbsPath(name, path);
2614 if (absname.exists()) {
2615 fix_child_filename(name);
2616 copy_file(absname, name);
2618 cerr << "Warning: Could not find file '"
2619 << name << "'." << endl;
2620 context.check_layout(os);
2621 begin_inset(os, "External\n\ttemplate ");
2622 os << "GnumericSpreadsheet\n\tfilename "
2625 context.check_layout(os);
2627 // register the packages that are automatically loaded
2628 // by the Gnumeric template
2629 registerExternalTemplatePackages("GnumericSpreadsheet");
2634 parse_macro(p, os, context);
2637 else if (t.cs() == "noindent") {
2639 context.add_par_extra_stuff("\\noindent\n");
2642 else if (t.cs() == "appendix") {
2643 context.add_par_extra_stuff("\\start_of_appendix\n");
2644 // We need to start a new paragraph. Otherwise the
2645 // appendix in 'bla\appendix\chapter{' would start
2647 context.new_paragraph(os);
2648 // We need to make sure that the paragraph is
2649 // generated even if it is empty. Otherwise the
2650 // appendix in '\par\appendix\par\chapter{' would
2652 context.check_layout(os);
2653 // FIXME: This is a hack to prevent paragraph
2654 // deletion if it is empty. Handle this better!
2656 "%dummy comment inserted by tex2lyx to "
2657 "ensure that this paragraph is not empty",
2659 // Both measures above may generate an additional
2660 // empty paragraph, but that does not hurt, because
2661 // whitespace does not matter here.
2662 eat_whitespace(p, os, context, true);
2665 // Must catch empty dates before findLayout is called below
2666 else if (t.cs() == "date") {
2667 eat_whitespace(p, os, context, false);
2669 string const date = p.verbatim_item();
2672 preamble.suppressDate(true);
2675 preamble.suppressDate(false);
2676 if (context.new_layout_allowed &&
2677 (newlayout = findLayout(context.textclass,
2680 output_command_layout(os, p, outer,
2681 context, newlayout);
2682 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2683 if (!preamble.titleLayoutFound())
2684 preamble.titleLayoutFound(newlayout->intitle);
2685 set<string> const & req = newlayout->requires();
2686 set<string>::const_iterator it = req.begin();
2687 set<string>::const_iterator en = req.end();
2688 for (; it != en; ++it)
2689 preamble.registerAutomaticallyLoadedPackage(*it);
2692 "\\date{" + p.verbatim_item() + '}',
2697 // Starred section headings
2698 // Must attempt to parse "Section*" before "Section".
2699 else if ((p.next_token().asInput() == "*") &&
2700 context.new_layout_allowed &&
2701 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2704 output_command_layout(os, p, outer, context, newlayout);
2706 if (!preamble.titleLayoutFound())
2707 preamble.titleLayoutFound(newlayout->intitle);
2708 set<string> const & req = newlayout->requires();
2709 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2710 preamble.registerAutomaticallyLoadedPackage(*it);
2713 // Section headings and the like
2714 else if (context.new_layout_allowed &&
2715 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2717 output_command_layout(os, p, outer, context, newlayout);
2719 if (!preamble.titleLayoutFound())
2720 preamble.titleLayoutFound(newlayout->intitle);
2721 set<string> const & req = newlayout->requires();
2722 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2723 preamble.registerAutomaticallyLoadedPackage(*it);
2726 else if (t.cs() == "caption") {
2728 context.check_layout(os);
2730 begin_inset(os, "Caption\n");
2731 Context newcontext(true, context.textclass, 0, 0, context.font);
2732 newcontext.check_layout(os);
2733 if (p.next_token().cat() != catEscape &&
2734 p.next_token().character() == '[') {
2735 p.get_token(); // eat '['
2736 begin_inset(os, "Argument\n");
2737 os << "status collapsed\n";
2738 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2740 eat_whitespace(p, os, context, false);
2742 parse_text(p, os, FLAG_ITEM, outer, context);
2743 context.check_end_layout(os);
2744 // We don't need really a new paragraph, but
2745 // we must make sure that the next item gets a \begin_layout.
2746 context.new_paragraph(os);
2749 newcontext.check_end_layout(os);
2752 else if (t.cs() == "subfloat") {
2753 // the syntax is \subfloat[caption]{content}
2754 // if it is a table of figure depends on the surrounding float
2755 bool has_caption = false;
2757 // do nothing if there is no outer float
2758 if (!float_type.empty()) {
2759 context.check_layout(os);
2761 begin_inset(os, "Float " + float_type + "\n");
2763 << "\nsideways false"
2764 << "\nstatus collapsed\n\n";
2767 if (p.next_token().cat() != catEscape &&
2768 p.next_token().character() == '[') {
2769 p.get_token(); // eat '['
2770 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2774 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2775 // the caption comes always as the last
2777 // we must make sure that the caption gets a \begin_layout
2778 os << "\n\\begin_layout Plain Layout";
2780 begin_inset(os, "Caption\n");
2781 Context newcontext(true, context.textclass,
2782 0, 0, context.font);
2783 newcontext.check_layout(os);
2784 os << caption << "\n";
2785 newcontext.check_end_layout(os);
2786 // We don't need really a new paragraph, but
2787 // we must make sure that the next item gets a \begin_layout.
2788 //newcontext.new_paragraph(os);
2792 // We don't need really a new paragraph, but
2793 // we must make sure that the next item gets a \begin_layout.
2795 context.new_paragraph(os);
2798 context.check_end_layout(os);
2799 // close the layout we opened
2801 os << "\n\\end_layout\n";
2803 // if the float type is not supported or there is no surrounding float
2806 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2807 handle_ert(os, t.asInput() + '[' + opt_arg +
2808 "]{" + p.verbatim_item() + '}', context);
2810 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2814 else if (t.cs() == "includegraphics") {
2815 bool const clip = p.next_token().asInput() == "*";
2818 string const arg = p.getArg('[', ']');
2819 map<string, string> opts;
2820 vector<string> keys;
2821 split_map(arg, opts, keys);
2823 opts["clip"] = string();
2824 string name = normalize_filename(p.verbatim_item());
2826 string const path = getMasterFilePath(true);
2827 // We want to preserve relative / absolute filenames,
2828 // therefore path is only used for testing
2829 if (!makeAbsPath(name, path).exists()) {
2830 // The file extension is probably missing.
2831 // Now try to find it out.
2832 string const dvips_name =
2833 find_file(name, path,
2834 known_dvips_graphics_formats);
2835 string const pdftex_name =
2836 find_file(name, path,
2837 known_pdftex_graphics_formats);
2838 if (!dvips_name.empty()) {
2839 if (!pdftex_name.empty()) {
2840 cerr << "This file contains the "
2842 "\"\\includegraphics{"
2844 "However, files\n\""
2845 << dvips_name << "\" and\n\""
2846 << pdftex_name << "\"\n"
2847 "both exist, so I had to make a "
2848 "choice and took the first one.\n"
2849 "Please move the unwanted one "
2850 "someplace else and try again\n"
2851 "if my choice was wrong."
2855 } else if (!pdftex_name.empty()) {
2861 FileName const absname = makeAbsPath(name, path);
2862 if (absname.exists()) {
2863 fix_child_filename(name);
2864 copy_file(absname, name);
2866 cerr << "Warning: Could not find graphics file '"
2867 << name << "'." << endl;
2869 context.check_layout(os);
2870 begin_inset(os, "Graphics ");
2871 os << "\n\tfilename " << name << '\n';
2872 if (opts.find("width") != opts.end())
2874 << translate_len(opts["width"]) << '\n';
2875 if (opts.find("height") != opts.end())
2877 << translate_len(opts["height"]) << '\n';
2878 if (opts.find("scale") != opts.end()) {
2879 istringstream iss(opts["scale"]);
2883 os << "\tscale " << val << '\n';
2885 if (opts.find("angle") != opts.end()) {
2886 os << "\trotateAngle "
2887 << opts["angle"] << '\n';
2888 vector<string>::const_iterator a =
2889 find(keys.begin(), keys.end(), "angle");
2890 vector<string>::const_iterator s =
2891 find(keys.begin(), keys.end(), "width");
2892 if (s == keys.end())
2893 s = find(keys.begin(), keys.end(), "height");
2894 if (s == keys.end())
2895 s = find(keys.begin(), keys.end(), "scale");
2896 if (s != keys.end() && distance(s, a) > 0)
2897 os << "\tscaleBeforeRotation\n";
2899 if (opts.find("origin") != opts.end()) {
2901 string const opt = opts["origin"];
2902 if (opt.find('l') != string::npos) ss << "left";
2903 if (opt.find('r') != string::npos) ss << "right";
2904 if (opt.find('c') != string::npos) ss << "center";
2905 if (opt.find('t') != string::npos) ss << "Top";
2906 if (opt.find('b') != string::npos) ss << "Bottom";
2907 if (opt.find('B') != string::npos) ss << "Baseline";
2908 if (!ss.str().empty())
2909 os << "\trotateOrigin " << ss.str() << '\n';
2911 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2913 if (opts.find("keepaspectratio") != opts.end())
2914 os << "\tkeepAspectRatio\n";
2915 if (opts.find("clip") != opts.end())
2917 if (opts.find("draft") != opts.end())
2919 if (opts.find("bb") != opts.end())
2920 os << "\tBoundingBox "
2921 << opts["bb"] << '\n';
2922 int numberOfbbOptions = 0;
2923 if (opts.find("bbllx") != opts.end())
2924 numberOfbbOptions++;
2925 if (opts.find("bblly") != opts.end())
2926 numberOfbbOptions++;
2927 if (opts.find("bburx") != opts.end())
2928 numberOfbbOptions++;
2929 if (opts.find("bbury") != opts.end())
2930 numberOfbbOptions++;
2931 if (numberOfbbOptions == 4)
2932 os << "\tBoundingBox "
2933 << opts["bbllx"] << " " << opts["bblly"] << " "
2934 << opts["bburx"] << " " << opts["bbury"] << '\n';
2935 else if (numberOfbbOptions > 0)
2936 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2937 numberOfbbOptions = 0;
2938 if (opts.find("natwidth") != opts.end())
2939 numberOfbbOptions++;
2940 if (opts.find("natheight") != opts.end())
2941 numberOfbbOptions++;
2942 if (numberOfbbOptions == 2)
2943 os << "\tBoundingBox 0bp 0bp "
2944 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2945 else if (numberOfbbOptions > 0)
2946 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2947 ostringstream special;
2948 if (opts.find("hiresbb") != opts.end())
2949 special << "hiresbb,";
2950 if (opts.find("trim") != opts.end())
2952 if (opts.find("viewport") != opts.end())
2953 special << "viewport=" << opts["viewport"] << ',';
2954 if (opts.find("totalheight") != opts.end())
2955 special << "totalheight=" << opts["totalheight"] << ',';
2956 if (opts.find("type") != opts.end())
2957 special << "type=" << opts["type"] << ',';
2958 if (opts.find("ext") != opts.end())
2959 special << "ext=" << opts["ext"] << ',';
2960 if (opts.find("read") != opts.end())
2961 special << "read=" << opts["read"] << ',';
2962 if (opts.find("command") != opts.end())
2963 special << "command=" << opts["command"] << ',';
2964 string s_special = special.str();
2965 if (!s_special.empty()) {
2966 // We had special arguments. Remove the trailing ','.
2967 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2969 // TODO: Handle the unknown settings better.
2970 // Warn about invalid options.
2971 // Check whether some option was given twice.
2973 preamble.registerAutomaticallyLoadedPackage("graphicx");
2976 else if (t.cs() == "footnote" ||
2977 (t.cs() == "thanks" && context.layout->intitle)) {
2979 context.check_layout(os);
2980 begin_inset(os, "Foot\n");
2981 os << "status collapsed\n\n";
2982 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2986 else if (t.cs() == "marginpar") {
2988 context.check_layout(os);
2989 begin_inset(os, "Marginal\n");
2990 os << "status collapsed\n\n";
2991 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2995 else if (t.cs() == "lstinline") {
2997 parse_listings(p, os, context, true);
3000 else if (t.cs() == "ensuremath") {
3002 context.check_layout(os);
3003 string const s = p.verbatim_item();
3004 //FIXME: this never triggers in UTF8
3005 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3008 handle_ert(os, "\\ensuremath{" + s + "}",
3012 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3013 if (preamble.titleLayoutFound()) {
3015 skip_spaces_braces(p);
3017 handle_ert(os, t.asInput(), context);
3020 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3021 context.check_layout(os);
3022 begin_command_inset(os, "toc", t.cs());
3024 skip_spaces_braces(p);
3025 if (t.cs() == "lstlistoflistings")
3026 preamble.registerAutomaticallyLoadedPackage("listings");
3029 else if (t.cs() == "listoffigures") {
3030 context.check_layout(os);
3031 begin_inset(os, "FloatList figure\n");
3033 skip_spaces_braces(p);
3036 else if (t.cs() == "listoftables") {
3037 context.check_layout(os);
3038 begin_inset(os, "FloatList table\n");
3040 skip_spaces_braces(p);
3043 else if (t.cs() == "listof") {
3044 p.skip_spaces(true);
3045 string const name = p.get_token().cs();
3046 if (context.textclass.floats().typeExist(name)) {
3047 context.check_layout(os);
3048 begin_inset(os, "FloatList ");
3051 p.get_token(); // swallow second arg
3053 handle_ert(os, "\\listof{" + name + "}", context);
3056 else if ((where = is_known(t.cs(), known_text_font_families)))
3057 parse_text_attributes(p, os, FLAG_ITEM, outer,
3058 context, "\\family", context.font.family,
3059 known_coded_font_families[where - known_text_font_families]);
3061 else if ((where = is_known(t.cs(), known_text_font_series)))
3062 parse_text_attributes(p, os, FLAG_ITEM, outer,
3063 context, "\\series", context.font.series,
3064 known_coded_font_series[where - known_text_font_series]);
3066 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3067 parse_text_attributes(p, os, FLAG_ITEM, outer,
3068 context, "\\shape", context.font.shape,
3069 known_coded_font_shapes[where - known_text_font_shapes]);
3071 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3072 context.check_layout(os);
3073 TeXFont oldFont = context.font;
3074 context.font.init();
3075 context.font.size = oldFont.size;
3076 os << "\n\\family " << context.font.family << "\n";
3077 os << "\n\\series " << context.font.series << "\n";
3078 os << "\n\\shape " << context.font.shape << "\n";
3079 if (t.cs() == "textnormal") {
3080 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3081 output_font_change(os, context.font, oldFont);
3082 context.font = oldFont;
3084 eat_whitespace(p, os, context, false);
3087 else if (t.cs() == "textcolor") {
3088 // scheme is \textcolor{color name}{text}
3089 string const color = p.verbatim_item();
3090 // we only support the predefined colors of the color package
3091 if (color == "black" || color == "blue" || color == "cyan"
3092 || color == "green" || color == "magenta" || color == "red"
3093 || color == "white" || color == "yellow") {
3094 context.check_layout(os);
3095 os << "\n\\color " << color << "\n";
3096 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3097 context.check_layout(os);
3098 os << "\n\\color inherit\n";
3099 preamble.registerAutomaticallyLoadedPackage("color");
3101 // for custom defined colors
3102 handle_ert(os, t.asInput() + "{" + color + "}", context);
3105 else if (t.cs() == "underbar" || t.cs() == "uline") {
3106 // \underbar is not 100% correct (LyX outputs \uline
3107 // of ulem.sty). The difference is that \ulem allows
3108 // line breaks, and \underbar does not.
3109 // Do NOT handle \underline.
3110 // \underbar cuts through y, g, q, p etc.,
3111 // \underline does not.
3112 context.check_layout(os);
3113 os << "\n\\bar under\n";
3114 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3115 context.check_layout(os);
3116 os << "\n\\bar default\n";
3117 preamble.registerAutomaticallyLoadedPackage("ulem");
3120 else if (t.cs() == "sout") {
3121 context.check_layout(os);
3122 os << "\n\\strikeout on\n";
3123 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3124 context.check_layout(os);
3125 os << "\n\\strikeout default\n";
3126 preamble.registerAutomaticallyLoadedPackage("ulem");
3129 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3130 t.cs() == "emph" || t.cs() == "noun") {
3131 context.check_layout(os);
3132 os << "\n\\" << t.cs() << " on\n";
3133 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3134 context.check_layout(os);
3135 os << "\n\\" << t.cs() << " default\n";
3136 if (t.cs() == "uuline" || t.cs() == "uwave")
3137 preamble.registerAutomaticallyLoadedPackage("ulem");
3140 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3141 context.check_layout(os);
3142 string name = p.getArg('{', '}');
3143 string localtime = p.getArg('{', '}');
3144 preamble.registerAuthor(name);
3145 Author const & author = preamble.getAuthor(name);
3146 // from_ctime() will fail if LyX decides to output the
3147 // time in the text language. It might also use a wrong
3148 // time zone (if the original LyX document was exported
3149 // with a different time zone).
3150 time_t ptime = from_ctime(localtime);
3151 if (ptime == static_cast<time_t>(-1)) {
3152 cerr << "Warning: Could not parse time `" << localtime
3153 << "´ for change tracking, using current time instead.\n";
3154 ptime = current_time();
3156 if (t.cs() == "lyxadded")
3157 os << "\n\\change_inserted ";
3159 os << "\n\\change_deleted ";
3160 os << author.bufferId() << ' ' << ptime << '\n';
3161 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3162 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3163 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3164 LaTeXPackages::isAvailable("xcolor");
3165 // No need to test for luatex, since luatex comes in
3166 // two flavours (dvi and pdf), like latex, and those
3167 // are detected by pdflatex.
3168 if (pdflatex || xetex) {
3170 preamble.registerAutomaticallyLoadedPackage("ulem");
3171 preamble.registerAutomaticallyLoadedPackage("xcolor");
3172 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3176 preamble.registerAutomaticallyLoadedPackage("dvipost");
3177 } else if (xcolorulem) {
3178 preamble.registerAutomaticallyLoadedPackage("ulem");
3179 preamble.registerAutomaticallyLoadedPackage("xcolor");
3184 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3185 t.cs() == "vphantom") {
3186 context.check_layout(os);
3187 if (t.cs() == "phantom")
3188 begin_inset(os, "Phantom Phantom\n");
3189 if (t.cs() == "hphantom")
3190 begin_inset(os, "Phantom HPhantom\n");
3191 if (t.cs() == "vphantom")
3192 begin_inset(os, "Phantom VPhantom\n");
3193 os << "status open\n";
3194 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3199 else if (t.cs() == "href") {
3200 context.check_layout(os);
3201 string target = convert_command_inset_arg(p.verbatim_item());
3202 string name = convert_command_inset_arg(p.verbatim_item());
3204 size_t i = target.find(':');
3205 if (i != string::npos) {
3206 type = target.substr(0, i + 1);
3207 if (type == "mailto:" || type == "file:")
3208 target = target.substr(i + 1);
3209 // handle the case that name is equal to target, except of "http://"
3210 else if (target.substr(i + 3) == name && type == "http:")
3213 begin_command_inset(os, "href", "href");
3215 os << "name \"" << name << "\"\n";
3216 os << "target \"" << target << "\"\n";
3217 if (type == "mailto:" || type == "file:")
3218 os << "type \"" << type << "\"\n";
3220 skip_spaces_braces(p);
3223 else if (t.cs() == "lyxline") {
3224 // swallow size argument (it is not used anyway)
3226 if (!context.atParagraphStart()) {
3227 // so our line is in the middle of a paragraph
3228 // we need to add a new line, lest this line
3229 // follow the other content on that line and
3230 // run off the side of the page
3231 // FIXME: This may create an empty paragraph,
3232 // but without that it would not be
3233 // possible to set noindent below.
3234 // Fortunately LaTeX does not care
3235 // about the empty paragraph.
3236 context.new_paragraph(os);
3238 if (preamble.indentParagraphs()) {
3239 // we need to unindent, lest the line be too long
3240 context.add_par_extra_stuff("\\noindent\n");
3242 context.check_layout(os);
3243 begin_command_inset(os, "line", "rule");
3244 os << "offset \"0.5ex\"\n"
3245 "width \"100line%\"\n"
3250 else if (t.cs() == "rule") {
3251 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3252 string const width = p.getArg('{', '}');
3253 string const thickness = p.getArg('{', '}');
3254 context.check_layout(os);
3255 begin_command_inset(os, "line", "rule");
3256 if (!offset.empty())
3257 os << "offset \"" << translate_len(offset) << "\"\n";
3258 os << "width \"" << translate_len(width) << "\"\n"
3259 "height \"" << translate_len(thickness) << "\"\n";
3263 else if (is_known(t.cs(), known_phrases) ||
3264 (t.cs() == "protect" &&
3265 p.next_token().cat() == catEscape &&
3266 is_known(p.next_token().cs(), known_phrases))) {
3267 // LyX sometimes puts a \protect in front, so we have to ignore it
3268 // FIXME: This needs to be changed when bug 4752 is fixed.
3270 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3272 context.check_layout(os);
3273 os << known_coded_phrases[where - known_phrases];
3274 skip_spaces_braces(p);
3277 else if ((where = is_known(t.cs(), known_ref_commands))) {
3278 string const opt = p.getOpt();
3280 context.check_layout(os);
3281 begin_command_inset(os, "ref",
3282 known_coded_ref_commands[where - known_ref_commands]);
3283 os << "reference \""
3284 << convert_command_inset_arg(p.verbatim_item())
3287 if (t.cs() == "vref" || t.cs() == "vpageref")
3288 preamble.registerAutomaticallyLoadedPackage("varioref");
3291 // LyX does not support optional arguments of ref commands
3292 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3293 p.verbatim_item() + "}", context);
3297 else if (use_natbib &&
3298 is_known(t.cs(), known_natbib_commands) &&
3299 ((t.cs() != "citefullauthor" &&
3300 t.cs() != "citeyear" &&
3301 t.cs() != "citeyearpar") ||
3302 p.next_token().asInput() != "*")) {
3303 context.check_layout(os);
3304 string command = t.cs();
3305 if (p.next_token().asInput() == "*") {
3309 if (command == "citefullauthor")
3310 // alternative name for "\\citeauthor*"
3311 command = "citeauthor*";
3313 // text before the citation
3315 // text after the citation
3317 get_cite_arguments(p, true, before, after);
3319 if (command == "cite") {
3320 // \cite without optional argument means
3321 // \citet, \cite with at least one optional
3322 // argument means \citep.
3323 if (before.empty() && after.empty())
3328 if (before.empty() && after == "[]")
3329 // avoid \citet[]{a}
3331 else if (before == "[]" && after == "[]") {
3332 // avoid \citet[][]{a}
3336 // remove the brackets around after and before
3337 if (!after.empty()) {
3339 after.erase(after.length() - 1, 1);
3340 after = convert_command_inset_arg(after);
3342 if (!before.empty()) {
3344 before.erase(before.length() - 1, 1);
3345 before = convert_command_inset_arg(before);
3347 begin_command_inset(os, "citation", command);
3348 os << "after " << '"' << after << '"' << "\n";
3349 os << "before " << '"' << before << '"' << "\n";
3351 << convert_command_inset_arg(p.verbatim_item())
3356 else if (use_jurabib &&
3357 is_known(t.cs(), known_jurabib_commands) &&
3358 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3359 context.check_layout(os);
3360 string command = t.cs();
3361 if (p.next_token().asInput() == "*") {
3365 char argumentOrder = '\0';
3366 vector<string> const options =
3367 preamble.getPackageOptions("jurabib");
3368 if (find(options.begin(), options.end(),
3369 "natbiborder") != options.end())
3370 argumentOrder = 'n';
3371 else if (find(options.begin(), options.end(),
3372 "jurabiborder") != options.end())
3373 argumentOrder = 'j';
3375 // text before the citation
3377 // text after the citation
3379 get_cite_arguments(p, argumentOrder != 'j', before, after);
3381 string const citation = p.verbatim_item();
3382 if (!before.empty() && argumentOrder == '\0') {
3383 cerr << "Warning: Assuming argument order "
3384 "of jurabib version 0.6 for\n'"
3385 << command << before << after << '{'
3386 << citation << "}'.\n"
3387 "Add 'jurabiborder' to the jurabib "
3388 "package options if you used an\n"
3389 "earlier jurabib version." << endl;
3391 if (!after.empty()) {
3393 after.erase(after.length() - 1, 1);
3395 if (!before.empty()) {
3397 before.erase(before.length() - 1, 1);
3399 begin_command_inset(os, "citation", command);
3400 os << "after " << '"' << after << '"' << "\n";
3401 os << "before " << '"' << before << '"' << "\n";
3402 os << "key " << '"' << citation << '"' << "\n";
3406 else if (t.cs() == "cite"
3407 || t.cs() == "nocite") {
3408 context.check_layout(os);
3409 string after = convert_command_inset_arg(p.getArg('[', ']'));
3410 string key = convert_command_inset_arg(p.verbatim_item());
3411 // store the case that it is "\nocite{*}" to use it later for
3414 begin_command_inset(os, "citation", t.cs());
3415 os << "after " << '"' << after << '"' << "\n";
3416 os << "key " << '"' << key << '"' << "\n";
3418 } else if (t.cs() == "nocite")
3422 else if (t.cs() == "index" ||
3423 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3424 context.check_layout(os);
3425 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3426 p.getArg('[', ']') : "";
3427 string const kind = arg.empty() ? "idx" : arg;
3428 begin_inset(os, "Index ");
3429 os << kind << "\nstatus collapsed\n";
3430 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3433 preamble.registerAutomaticallyLoadedPackage("splitidx");
3436 else if (t.cs() == "nomenclature") {
3437 context.check_layout(os);
3438 begin_command_inset(os, "nomenclature", "nomenclature");
3439 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3440 if (!prefix.empty())
3441 os << "prefix " << '"' << prefix << '"' << "\n";
3442 os << "symbol " << '"'
3443 << convert_command_inset_arg(p.verbatim_item());
3444 os << "\"\ndescription \""
3445 << convert_command_inset_arg(p.verbatim_item())
3448 preamble.registerAutomaticallyLoadedPackage("nomencl");
3451 else if (t.cs() == "label") {
3452 context.check_layout(os);
3453 begin_command_inset(os, "label", "label");
3455 << convert_command_inset_arg(p.verbatim_item())
3460 else if (t.cs() == "printindex") {
3461 context.check_layout(os);
3462 begin_command_inset(os, "index_print", "printindex");
3463 os << "type \"idx\"\n";
3465 skip_spaces_braces(p);
3466 preamble.registerAutomaticallyLoadedPackage("makeidx");
3467 if (preamble.use_indices() == "true")
3468 preamble.registerAutomaticallyLoadedPackage("splitidx");
3471 else if (t.cs() == "printnomenclature") {
3473 string width_type = "";
3474 context.check_layout(os);
3475 begin_command_inset(os, "nomencl_print", "printnomenclature");
3476 // case of a custom width
3478 width = p.getArg('[', ']');
3479 width = translate_len(width);
3480 width_type = "custom";
3482 // case of no custom width
3483 // the case of no custom width but the width set
3484 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3485 // because the user could have set anything, not only the width
3486 // of the longest label (which would be width_type = "auto")
3487 string label = convert_command_inset_arg(p.getArg('{', '}'));
3488 if (label.empty() && width_type.empty())
3489 width_type = "none";
3490 os << "set_width \"" << width_type << "\"\n";
3491 if (width_type == "custom")
3492 os << "width \"" << width << '\"';
3494 skip_spaces_braces(p);
3495 preamble.registerAutomaticallyLoadedPackage("nomencl");
3498 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3499 context.check_layout(os);
3500 begin_inset(os, "script ");
3501 os << t.cs().substr(4) << '\n';
3502 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3504 if (t.cs() == "textsubscript")
3505 preamble.registerAutomaticallyLoadedPackage("subscript");
3508 else if ((where = is_known(t.cs(), known_quotes))) {
3509 context.check_layout(os);
3510 begin_inset(os, "Quotes ");
3511 os << known_coded_quotes[where - known_quotes];
3513 // LyX adds {} after the quote, so we have to eat
3514 // spaces here if there are any before a possible
3516 eat_whitespace(p, os, context, false);
3520 else if ((where = is_known(t.cs(), known_sizes)) &&
3521 context.new_layout_allowed) {
3522 context.check_layout(os);
3523 TeXFont const oldFont = context.font;
3524 context.font.size = known_coded_sizes[where - known_sizes];
3525 output_font_change(os, oldFont, context.font);
3526 eat_whitespace(p, os, context, false);
3529 else if ((where = is_known(t.cs(), known_font_families)) &&
3530 context.new_layout_allowed) {
3531 context.check_layout(os);
3532 TeXFont const oldFont = context.font;
3533 context.font.family =
3534 known_coded_font_families[where - known_font_families];
3535 output_font_change(os, oldFont, context.font);
3536 eat_whitespace(p, os, context, false);
3539 else if ((where = is_known(t.cs(), known_font_series)) &&
3540 context.new_layout_allowed) {
3541 context.check_layout(os);
3542 TeXFont const oldFont = context.font;
3543 context.font.series =
3544 known_coded_font_series[where - known_font_series];
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_shapes)) &&
3550 context.new_layout_allowed) {
3551 context.check_layout(os);
3552 TeXFont const oldFont = context.font;
3553 context.font.shape =
3554 known_coded_font_shapes[where - known_font_shapes];
3555 output_font_change(os, oldFont, context.font);
3556 eat_whitespace(p, os, context, false);
3558 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3559 context.new_layout_allowed) {
3560 context.check_layout(os);
3561 TeXFont const oldFont = context.font;
3562 context.font.init();
3563 context.font.size = oldFont.size;
3564 context.font.family =
3565 known_coded_font_families[where - known_old_font_families];
3566 output_font_change(os, oldFont, context.font);
3567 eat_whitespace(p, os, context, false);
3570 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3571 context.new_layout_allowed) {
3572 context.check_layout(os);
3573 TeXFont const oldFont = context.font;
3574 context.font.init();
3575 context.font.size = oldFont.size;
3576 context.font.series =
3577 known_coded_font_series[where - known_old_font_series];
3578 output_font_change(os, oldFont, context.font);
3579 eat_whitespace(p, os, context, false);
3582 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3583 context.new_layout_allowed) {
3584 context.check_layout(os);
3585 TeXFont const oldFont = context.font;
3586 context.font.init();
3587 context.font.size = oldFont.size;
3588 context.font.shape =
3589 known_coded_font_shapes[where - known_old_font_shapes];
3590 output_font_change(os, oldFont, context.font);
3591 eat_whitespace(p, os, context, false);
3594 else if (t.cs() == "selectlanguage") {
3595 context.check_layout(os);
3596 // save the language for the case that a
3597 // \foreignlanguage is used
3598 context.font.language = babel2lyx(p.verbatim_item());
3599 os << "\n\\lang " << context.font.language << "\n";
3602 else if (t.cs() == "foreignlanguage") {
3603 string const lang = babel2lyx(p.verbatim_item());
3604 parse_text_attributes(p, os, FLAG_ITEM, outer,
3606 context.font.language, lang);
3609 else if (prefixIs(t.cs(), "text")
3610 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3611 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3613 // We have to output the whole command if it has an option
3614 // because LyX doesn't support this yet, see bug #8214,
3615 // only if there is a single option specifying a variant, we can handle it.
3617 string langopts = p.getOpt();
3618 // check if the option contains a variant, if yes, extract it
3619 string::size_type pos_var = langopts.find("variant");
3620 string::size_type i = langopts.find(',');
3621 string::size_type k = langopts.find('=', pos_var);
3622 if (pos_var != string::npos && i == string::npos) {
3624 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3625 lang = preamble.polyglossia2lyx(variant);
3626 parse_text_attributes(p, os, FLAG_ITEM, outer,
3628 context.font.language, lang);
3630 handle_ert(os, t.asInput() + langopts, context);
3632 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3633 parse_text_attributes(p, os, FLAG_ITEM, outer,
3635 context.font.language, lang);
3639 else if (t.cs() == "inputencoding") {
3640 // nothing to write here
3641 string const enc = subst(p.verbatim_item(), "\n", " ");
3645 else if ((where = is_known(t.cs(), known_special_chars))) {
3646 context.check_layout(os);
3647 os << "\\SpecialChar \\"
3648 << known_coded_special_chars[where - known_special_chars]
3650 skip_spaces_braces(p);
3653 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3654 context.check_layout(os);
3655 os << "\\SpecialChar \\nobreakdash-\n";
3659 else if (t.cs() == "textquotedbl") {
3660 context.check_layout(os);
3665 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3666 context.check_layout(os);
3667 os << "\\SpecialChar \\@.\n";
3671 else if (t.cs() == "-") {
3672 context.check_layout(os);
3673 os << "\\SpecialChar \\-\n";
3676 else if (t.cs() == "textasciitilde") {
3677 context.check_layout(os);
3679 skip_spaces_braces(p);
3682 else if (t.cs() == "textasciicircum") {
3683 context.check_layout(os);
3685 skip_spaces_braces(p);
3688 else if (t.cs() == "textbackslash") {
3689 context.check_layout(os);
3690 os << "\n\\backslash\n";
3691 skip_spaces_braces(p);
3694 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3695 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3697 context.check_layout(os);
3701 else if (t.cs() == "char") {
3702 context.check_layout(os);
3703 if (p.next_token().character() == '`') {
3705 if (p.next_token().cs() == "\"") {
3710 handle_ert(os, "\\char`", context);
3713 handle_ert(os, "\\char", context);
3717 else if (t.cs() == "verb") {
3718 context.check_layout(os);
3719 char const delimiter = p.next_token().character();
3720 // \verb is special: The usual escaping rules do not
3721 // apply, e.g. "\verb+\+" is valid and denotes a single
3722 // backslash (bug #4468). Therefore we do not allow
3723 // escaping in getArg().
3724 string const arg = p.getArg(delimiter, delimiter, false);
3726 oss << "\\verb" << delimiter << arg << delimiter;
3727 handle_ert(os, oss.str(), context);
3730 // Problem: \= creates a tabstop inside the tabbing environment
3731 // and else an accent. In the latter case we really would want
3732 // \={o} instead of \= o.
3733 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3734 handle_ert(os, t.asInput(), context);
3736 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3737 else if (t.cs().size() == 1
3738 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3739 context.check_layout(os);
3740 // try to see whether the string is in unicodesymbols
3743 string command = t.asInput() + "{"
3744 + trimSpaceAndEol(p.verbatim_item())
3747 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3748 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3749 termination, rem, &req);
3752 cerr << "When parsing " << command
3753 << ", result is " << to_utf8(s)
3754 << "+" << to_utf8(rem) << endl;
3756 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3757 preamble.registerAutomaticallyLoadedPackage(*it);
3759 // we did not find a non-ert version
3760 handle_ert(os, command, context);
3763 else if (t.cs() == "\\") {
3764 context.check_layout(os);
3766 handle_ert(os, "\\\\" + p.getOpt(), context);
3767 else if (p.next_token().asInput() == "*") {
3769 // getOpt() eats the following space if there
3770 // is no optional argument, but that is OK
3771 // here since it has no effect in the output.
3772 handle_ert(os, "\\\\*" + p.getOpt(), context);
3775 begin_inset(os, "Newline newline");
3780 else if (t.cs() == "newline" ||
3781 (t.cs() == "linebreak" && !p.hasOpt())) {
3782 context.check_layout(os);
3783 begin_inset(os, "Newline ");
3786 skip_spaces_braces(p);
3789 else if (t.cs() == "input" || t.cs() == "include"
3790 || t.cs() == "verbatiminput") {
3791 string name = t.cs();
3792 if (t.cs() == "verbatiminput"
3793 && p.next_token().asInput() == "*")
3794 name += p.get_token().asInput();
3795 context.check_layout(os);
3796 string filename(normalize_filename(p.getArg('{', '}')));
3797 string const path = getMasterFilePath(true);
3798 // We want to preserve relative / absolute filenames,
3799 // therefore path is only used for testing
3800 if ((t.cs() == "include" || t.cs() == "input") &&
3801 !makeAbsPath(filename, path).exists()) {
3802 // The file extension is probably missing.
3803 // Now try to find it out.
3804 string const tex_name =
3805 find_file(filename, path,
3806 known_tex_extensions);
3807 if (!tex_name.empty())
3808 filename = tex_name;
3810 bool external = false;
3812 if (makeAbsPath(filename, path).exists()) {
3813 string const abstexname =
3814 makeAbsPath(filename, path).absFileName();
3815 string const absfigname =
3816 changeExtension(abstexname, ".fig");
3817 fix_child_filename(filename);
3818 string const lyxname =
3819 changeExtension(filename, ".lyx");
3820 string const abslyxname = makeAbsPath(
3821 lyxname, getParentFilePath(false)).absFileName();
3823 if (!skipChildren())
3824 external = FileName(absfigname).exists();
3825 if (t.cs() == "input" && !skipChildren()) {
3826 string const ext = getExtension(abstexname);
3828 // Combined PS/LaTeX:
3829 // x.eps, x.pstex_t (old xfig)
3830 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3831 FileName const absepsname(
3832 changeExtension(abstexname, ".eps"));
3833 FileName const abspstexname(
3834 changeExtension(abstexname, ".pstex"));
3835 bool const xfigeps =
3836 (absepsname.exists() ||
3837 abspstexname.exists()) &&
3840 // Combined PDF/LaTeX:
3841 // x.pdf, x.pdftex_t (old xfig)
3842 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3843 FileName const abspdfname(
3844 changeExtension(abstexname, ".pdf"));
3845 bool const xfigpdf =
3846 abspdfname.exists() &&
3847 (ext == "pdftex_t" || ext == "pdf_t");
3851 // Combined PS/PDF/LaTeX:
3852 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3853 string const absbase2(
3854 removeExtension(abstexname) + "_pspdftex");
3855 FileName const abseps2name(
3856 addExtension(absbase2, ".eps"));
3857 FileName const abspdf2name(
3858 addExtension(absbase2, ".pdf"));
3859 bool const xfigboth =
3860 abspdf2name.exists() &&
3861 abseps2name.exists() && ext == "pspdftex";
3863 xfig = xfigpdf || xfigeps || xfigboth;
3864 external = external && xfig;
3867 outname = changeExtension(filename, ".fig");
3868 FileName abssrc(changeExtension(abstexname, ".fig"));
3869 copy_file(abssrc, outname);
3871 // Don't try to convert, the result
3872 // would be full of ERT.
3874 FileName abssrc(abstexname);
3875 copy_file(abssrc, outname);
3876 } else if (t.cs() != "verbatiminput" &&
3878 tex2lyx(abstexname, FileName(abslyxname),
3881 // no need to call copy_file
3882 // tex2lyx creates the file
3885 FileName abssrc(abstexname);
3886 copy_file(abssrc, outname);
3889 cerr << "Warning: Could not find included file '"
3890 << filename << "'." << endl;
3894 begin_inset(os, "External\n");
3895 os << "\ttemplate XFig\n"
3896 << "\tfilename " << outname << '\n';
3897 registerExternalTemplatePackages("XFig");
3899 begin_command_inset(os, "include", name);
3900 os << "preview false\n"
3901 "filename \"" << outname << "\"\n";
3902 if (t.cs() == "verbatiminput")
3903 preamble.registerAutomaticallyLoadedPackage("verbatim");
3908 else if (t.cs() == "bibliographystyle") {
3909 // store new bibliographystyle
3910 bibliographystyle = p.verbatim_item();
3911 // If any other command than \bibliography and
3912 // \nocite{*} follows, we need to output the style
3913 // (because it might be used by that command).
3914 // Otherwise, it will automatically be output by LyX.
3917 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3918 if (t2.cat() == catBegin)
3920 if (t2.cat() != catEscape)
3922 if (t2.cs() == "nocite") {
3923 if (p.getArg('{', '}') == "*")
3925 } else if (t2.cs() == "bibliography")
3932 "\\bibliographystyle{" + bibliographystyle + '}',
3937 else if (t.cs() == "bibliography") {
3938 context.check_layout(os);
3939 begin_command_inset(os, "bibtex", "bibtex");
3940 if (!btprint.empty()) {
3941 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3942 // clear the string because the next BibTeX inset can be without the
3943 // \nocite{*} option
3946 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3947 // Do we have a bibliographystyle set?
3948 if (!bibliographystyle.empty())
3949 os << "options " << '"' << bibliographystyle << '"' << "\n";
3953 else if (t.cs() == "parbox") {
3954 // Test whether this is an outer box of a shaded box
3956 // swallow arguments
3957 while (p.hasOpt()) {
3959 p.skip_spaces(true);
3962 p.skip_spaces(true);
3964 if (p.next_token().cat() == catBegin)
3966 p.skip_spaces(true);
3967 Token to = p.get_token();
3968 bool shaded = false;
3969 if (to.asInput() == "\\begin") {
3970 p.skip_spaces(true);
3971 if (p.getArg('{', '}') == "shaded")
3976 parse_outer_box(p, os, FLAG_ITEM, outer,
3977 context, "parbox", "shaded");
3979 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3983 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3984 t.cs() == "shadowbox" || t.cs() == "doublebox")
3985 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3987 else if (t.cs() == "framebox") {
3988 if (p.next_token().character() == '(') {
3989 //the syntax is: \framebox(x,y)[position]{content}
3990 string arg = t.asInput();
3991 arg += p.getFullParentheseArg();
3992 arg += p.getFullOpt();
3993 eat_whitespace(p, os, context, false);
3994 handle_ert(os, arg + '{', context);
3995 parse_text(p, os, FLAG_ITEM, outer, context);
3996 handle_ert(os, "}", context);
3998 string special = p.getFullOpt();
3999 special += p.getOpt();
4000 // LyX does not yet support \framebox without any option
4001 if (!special.empty())
4002 parse_outer_box(p, os, FLAG_ITEM, outer,
4003 context, t.cs(), special);
4005 eat_whitespace(p, os, context, false);
4006 handle_ert(os, "\\framebox{", context);
4007 parse_text(p, os, FLAG_ITEM, outer, context);
4008 handle_ert(os, "}", context);
4013 //\makebox() is part of the picture environment and different from \makebox{}
4014 //\makebox{} will be parsed by parse_box
4015 else if (t.cs() == "makebox") {
4016 if (p.next_token().character() == '(') {
4017 //the syntax is: \makebox(x,y)[position]{content}
4018 string arg = t.asInput();
4019 arg += p.getFullParentheseArg();
4020 arg += p.getFullOpt();
4021 eat_whitespace(p, os, context, false);
4022 handle_ert(os, arg + '{', context);
4023 parse_text(p, os, FLAG_ITEM, outer, context);
4024 handle_ert(os, "}", context);
4026 //the syntax is: \makebox[width][position]{content}
4027 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4031 else if (t.cs() == "smallskip" ||
4032 t.cs() == "medskip" ||
4033 t.cs() == "bigskip" ||
4034 t.cs() == "vfill") {
4035 context.check_layout(os);
4036 begin_inset(os, "VSpace ");
4039 skip_spaces_braces(p);
4042 else if ((where = is_known(t.cs(), known_spaces))) {
4043 context.check_layout(os);
4044 begin_inset(os, "space ");
4045 os << '\\' << known_coded_spaces[where - known_spaces]
4048 // LaTeX swallows whitespace after all spaces except
4049 // "\\,". We have to do that here, too, because LyX
4050 // adds "{}" which would make the spaces significant.
4052 eat_whitespace(p, os, context, false);
4053 // LyX adds "{}" after all spaces except "\\ " and
4054 // "\\,", so we have to remove "{}".
4055 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4056 // remove the braces after "\\,", too.
4061 else if (t.cs() == "newpage" ||
4062 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4063 t.cs() == "clearpage" ||
4064 t.cs() == "cleardoublepage") {
4065 context.check_layout(os);
4066 begin_inset(os, "Newpage ");
4069 skip_spaces_braces(p);
4072 else if (t.cs() == "DeclareRobustCommand" ||
4073 t.cs() == "DeclareRobustCommandx" ||
4074 t.cs() == "newcommand" ||
4075 t.cs() == "newcommandx" ||
4076 t.cs() == "providecommand" ||
4077 t.cs() == "providecommandx" ||
4078 t.cs() == "renewcommand" ||
4079 t.cs() == "renewcommandx") {
4080 // DeclareRobustCommand, DeclareRobustCommandx,
4081 // providecommand and providecommandx could be handled
4082 // by parse_command(), but we need to call
4083 // add_known_command() here.
4084 string name = t.asInput();
4085 if (p.next_token().asInput() == "*") {
4086 // Starred form. Eat '*'
4090 string const command = p.verbatim_item();
4091 string const opt1 = p.getFullOpt();
4092 string const opt2 = p.getFullOpt();
4093 add_known_command(command, opt1, !opt2.empty());
4094 string const ert = name + '{' + command + '}' +
4096 '{' + p.verbatim_item() + '}';
4098 if (t.cs() == "DeclareRobustCommand" ||
4099 t.cs() == "DeclareRobustCommandx" ||
4100 t.cs() == "providecommand" ||
4101 t.cs() == "providecommandx" ||
4102 name[name.length()-1] == '*')
4103 handle_ert(os, ert, context);
4105 context.check_layout(os);
4106 begin_inset(os, "FormulaMacro");
4112 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4113 // let could be handled by parse_command(),
4114 // but we need to call add_known_command() here.
4115 string ert = t.asInput();
4118 if (p.next_token().cat() == catBegin) {
4119 name = p.verbatim_item();
4120 ert += '{' + name + '}';
4122 name = p.verbatim_item();
4127 if (p.next_token().cat() == catBegin) {
4128 command = p.verbatim_item();
4129 ert += '{' + command + '}';
4131 command = p.verbatim_item();
4134 // If command is known, make name known too, to parse
4135 // its arguments correctly. For this reason we also
4136 // have commands in syntax.default that are hardcoded.
4137 CommandMap::iterator it = known_commands.find(command);
4138 if (it != known_commands.end())
4139 known_commands[t.asInput()] = it->second;
4140 handle_ert(os, ert, context);
4143 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4144 bool starred = false;
4145 if (p.next_token().asInput() == "*") {
4149 string name = t.asInput();
4150 string const length = p.verbatim_item();
4153 bool valid = splitLatexLength(length, valstring, unit);
4154 bool known_hspace = false;
4155 bool known_vspace = false;
4156 bool known_unit = false;
4159 istringstream iss(valstring);
4162 if (t.cs()[0] == 'h') {
4163 if (unit == "\\fill") {
4168 known_hspace = true;
4171 if (unit == "\\smallskipamount") {
4173 known_vspace = true;
4174 } else if (unit == "\\medskipamount") {
4176 known_vspace = true;
4177 } else if (unit == "\\bigskipamount") {
4179 known_vspace = true;
4180 } else if (unit == "\\fill") {
4182 known_vspace = true;
4186 if (!known_hspace && !known_vspace) {
4187 switch (unitFromString(unit)) {
4208 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4209 // Literal horizontal length or known variable
4210 context.check_layout(os);
4211 begin_inset(os, "space ");
4219 if (known_unit && !known_hspace)
4221 << translate_len(length);
4223 } else if (known_unit || known_vspace) {
4224 // Literal vertical length or known variable
4225 context.check_layout(os);
4226 begin_inset(os, "VSpace ");
4234 // LyX can't handle other length variables in Inset VSpace/space
4239 handle_ert(os, name + '{' + unit + '}', context);
4240 else if (value == -1.0)
4241 handle_ert(os, name + "{-" + unit + '}', context);
4243 handle_ert(os, name + '{' + valstring + unit + '}', context);
4245 handle_ert(os, name + '{' + length + '}', context);
4249 // The single '=' is meant here.
4250 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4252 context.check_layout(os);
4253 begin_inset(os, "Flex ");
4254 os << to_utf8(newinsetlayout->name()) << '\n'
4255 << "status collapsed\n";
4256 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4260 else if (t.cs() == "includepdf") {
4262 string const arg = p.getArg('[', ']');
4263 map<string, string> opts;
4264 vector<string> keys;
4265 split_map(arg, opts, keys);
4266 string name = normalize_filename(p.verbatim_item());
4267 string const path = getMasterFilePath(true);
4268 // We want to preserve relative / absolute filenames,
4269 // therefore path is only used for testing
4270 if (!makeAbsPath(name, path).exists()) {
4271 // The file extension is probably missing.
4272 // Now try to find it out.
4273 char const * const pdfpages_format[] = {"pdf", 0};
4274 string const pdftex_name =
4275 find_file(name, path, pdfpages_format);
4276 if (!pdftex_name.empty()) {
4281 FileName const absname = makeAbsPath(name, path);
4282 if (absname.exists())
4284 fix_child_filename(name);
4285 copy_file(absname, name);
4287 cerr << "Warning: Could not find file '"
4288 << name << "'." << endl;
4290 context.check_layout(os);
4291 begin_inset(os, "External\n\ttemplate ");
4292 os << "PDFPages\n\tfilename "
4294 // parse the options
4295 if (opts.find("pages") != opts.end())
4296 os << "\textra LaTeX \"pages="
4297 << opts["pages"] << "\"\n";
4298 if (opts.find("angle") != opts.end())
4299 os << "\trotateAngle "
4300 << opts["angle"] << '\n';
4301 if (opts.find("origin") != opts.end()) {
4303 string const opt = opts["origin"];
4304 if (opt == "tl") ss << "topleft";
4305 if (opt == "bl") ss << "bottomleft";
4306 if (opt == "Bl") ss << "baselineleft";
4307 if (opt == "c") ss << "center";
4308 if (opt == "tc") ss << "topcenter";
4309 if (opt == "bc") ss << "bottomcenter";
4310 if (opt == "Bc") ss << "baselinecenter";
4311 if (opt == "tr") ss << "topright";
4312 if (opt == "br") ss << "bottomright";
4313 if (opt == "Br") ss << "baselineright";
4314 if (!ss.str().empty())
4315 os << "\trotateOrigin " << ss.str() << '\n';
4317 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4319 if (opts.find("width") != opts.end())
4321 << translate_len(opts["width"]) << '\n';
4322 if (opts.find("height") != opts.end())
4324 << translate_len(opts["height"]) << '\n';
4325 if (opts.find("keepaspectratio") != opts.end())
4326 os << "\tkeepAspectRatio\n";
4328 context.check_layout(os);
4329 registerExternalTemplatePackages("PDFPages");
4332 else if (t.cs() == "loadgame") {
4334 string name = normalize_filename(p.verbatim_item());
4335 string const path = getMasterFilePath(true);
4336 // We want to preserve relative / absolute filenames,
4337 // therefore path is only used for testing
4338 if (!makeAbsPath(name, path).exists()) {
4339 // The file extension is probably missing.
4340 // Now try to find it out.
4341 char const * const lyxskak_format[] = {"fen", 0};
4342 string const lyxskak_name =
4343 find_file(name, path, lyxskak_format);
4344 if (!lyxskak_name.empty())
4345 name = lyxskak_name;
4347 FileName const absname = makeAbsPath(name, path);
4348 if (absname.exists())
4350 fix_child_filename(name);
4351 copy_file(absname, name);
4353 cerr << "Warning: Could not find file '"
4354 << name << "'." << endl;
4355 context.check_layout(os);
4356 begin_inset(os, "External\n\ttemplate ");
4357 os << "ChessDiagram\n\tfilename "
4360 context.check_layout(os);
4361 // after a \loadgame follows a \showboard
4362 if (p.get_token().asInput() == "showboard")
4364 registerExternalTemplatePackages("ChessDiagram");
4368 // try to see whether the string is in unicodesymbols
4369 // Only use text mode commands, since we are in text mode here,
4370 // and math commands may be invalid (bug 6797)
4374 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4375 Encodings::TEXT_CMD, termination, rem, &req);
4378 cerr << "When parsing " << t.cs()
4379 << ", result is " << to_utf8(s)
4380 << "+" << to_utf8(rem) << endl;
4381 context.check_layout(os);
4384 skip_spaces_braces(p);
4385 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4386 preamble.registerAutomaticallyLoadedPackage(*it);
4388 //cerr << "#: " << t << " mode: " << mode << endl;
4389 // heuristic: read up to next non-nested space
4391 string s = t.asInput();
4392 string z = p.verbatim_item();
4393 while (p.good() && z != " " && !z.empty()) {
4394 //cerr << "read: " << z << endl;
4396 z = p.verbatim_item();
4398 cerr << "found ERT: " << s << endl;
4399 handle_ert(os, s + ' ', context);
4402 string name = t.asInput();
4403 if (p.next_token().asInput() == "*") {
4404 // Starred commands like \vspace*{}
4405 p.get_token(); // Eat '*'
4408 if (!parse_command(name, p, os, outer, context))
4409 handle_ert(os, name, context);
4413 if (flags & FLAG_LEAVE) {
4414 flags &= ~FLAG_LEAVE;
4421 string guessLanguage(Parser & p, string const & lang)
4423 typedef std::map<std::string, size_t> LangMap;
4424 // map from language names to number of characters
4427 for (char const * const * i = supported_CJK_languages; *i; i++)
4428 used[string(*i)] = 0;
4431 Token const t = p.get_token();
4432 // comments are not counted for any language
4433 if (t.cat() == catComment)
4435 // commands are not counted as well, but we need to detect
4436 // \begin{CJK} and switch encoding if needed
4437 if (t.cat() == catEscape) {
4438 if (t.cs() == "inputencoding") {
4439 string const enc = subst(p.verbatim_item(), "\n", " ");
4443 if (t.cs() != "begin")
4446 // Non-CJK content is counted for lang.
4447 // We do not care about the real language here:
4448 // If we have more non-CJK contents than CJK contents,
4449 // we simply use the language that was specified as
4450 // babel main language.
4451 used[lang] += t.asInput().length();
4454 // Now we are starting an environment
4456 string const name = p.getArg('{', '}');
4457 if (name != "CJK") {
4461 // It is a CJK environment
4463 /* name = */ p.getArg('{', '}');
4464 string const encoding = p.getArg('{', '}');
4465 /* mapping = */ p.getArg('{', '}');
4466 string const encoding_old = p.getEncoding();
4467 char const * const * const where =
4468 is_known(encoding, supported_CJK_encodings);
4470 p.setEncoding(encoding);
4472 p.setEncoding("utf8");
4473 string const text = p.verbatimEnvironment("CJK");
4474 p.setEncoding(encoding_old);
4477 // ignore contents in unknown CJK encoding
4480 // the language of the text
4482 supported_CJK_languages[where - supported_CJK_encodings];
4483 used[cjk] += text.length();
4485 LangMap::const_iterator use = used.begin();
4486 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4487 if (it->second > use->second)