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 unsigned int optargs = 0;
632 while (optargs < context.layout->optargs) {
633 eat_whitespace(p, os, context, false);
634 if (p.next_token().cat() == catEscape ||
635 p.next_token().character() != '[')
637 p.get_token(); // eat '['
638 begin_inset(os, "Argument\n");
639 os << "status collapsed\n\n";
640 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
642 eat_whitespace(p, os, context, false);
645 unsigned int reqargs = 0;
646 while (reqargs < context.layout->reqargs) {
647 eat_whitespace(p, os, context, false);
648 if (p.next_token().cat() != catBegin)
650 p.get_token(); // eat '{'
651 begin_inset(os, "Argument\n");
652 os << "status collapsed\n\n";
653 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
655 eat_whitespace(p, os, context, false);
658 parse_text(p, os, FLAG_ITEM, outer, context);
659 context.check_end_layout(os);
660 if (parent_context.deeper_paragraph) {
661 // We must suppress the "end deeper" because we
662 // suppressed the "begin deeper" above.
663 context.need_end_deeper = false;
665 context.check_end_deeper(os);
666 // We don't need really a new paragraph, but
667 // we must make sure that the next item gets a \begin_layout.
668 parent_context.new_paragraph(os);
669 // Set the font size to the original value. No need to output it here
670 // (Context::begin_layout() will do that if needed)
671 parent_context.font.size = size;
676 * Output a space if necessary.
677 * This function gets called for every whitespace token.
679 * We have three cases here:
680 * 1. A space must be suppressed. Example: The lyxcode case below
681 * 2. A space may be suppressed. Example: Spaces before "\par"
682 * 3. A space must not be suppressed. Example: A space between two words
684 * We currently handle only 1. and 3 and from 2. only the case of
685 * spaces before newlines as a side effect.
687 * 2. could be used to suppress as many spaces as possible. This has two effects:
688 * - Reimporting LyX generated LaTeX files changes almost no whitespace
689 * - Superflous whitespace from non LyX generated LaTeX files is removed.
690 * The drawback is that the logic inside the function becomes
691 * complicated, and that is the reason why it is not implemented.
693 void check_space(Parser & p, ostream & os, Context & context)
695 Token const next = p.next_token();
696 Token const curr = p.curr_token();
697 // A space before a single newline and vice versa must be ignored
698 // LyX emits a newline before \end{lyxcode}.
699 // This newline must be ignored,
700 // otherwise LyX will add an additional protected space.
701 if (next.cat() == catSpace ||
702 next.cat() == catNewline ||
703 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
706 context.check_layout(os);
712 * Parse all arguments of \p command
714 void parse_arguments(string const & command,
715 vector<ArgumentType> const & template_arguments,
716 Parser & p, ostream & os, bool outer, Context & context)
718 string ert = command;
719 size_t no_arguments = template_arguments.size();
720 for (size_t i = 0; i < no_arguments; ++i) {
721 switch (template_arguments[i]) {
724 // This argument contains regular LaTeX
725 handle_ert(os, ert + '{', context);
726 eat_whitespace(p, os, context, false);
727 if (template_arguments[i] == required)
728 parse_text(p, os, FLAG_ITEM, outer, context);
730 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
734 // This argument consists only of a single item.
735 // The presence of '{' or not must be preserved.
737 if (p.next_token().cat() == catBegin)
738 ert += '{' + p.verbatim_item() + '}';
740 ert += p.verbatim_item();
744 // This argument may contain special characters
745 ert += '{' + p.verbatim_item() + '}';
749 // true because we must not eat whitespace
750 // if an optional arg follows we must not strip the
751 // brackets from this one
752 if (i < no_arguments - 1 &&
753 template_arguments[i+1] == optional)
754 ert += p.getFullOpt(true);
756 ert += p.getOpt(true);
760 handle_ert(os, ert, context);
765 * Check whether \p command is a known command. If yes,
766 * handle the command with all arguments.
767 * \return true if the command was parsed, false otherwise.
769 bool parse_command(string const & command, Parser & p, ostream & os,
770 bool outer, Context & context)
772 if (known_commands.find(command) != known_commands.end()) {
773 parse_arguments(command, known_commands[command], p, os,
781 /// Parses a minipage or parbox
782 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
783 unsigned inner_flags, bool outer, Context & parent_context,
784 string const & outer_type, string const & special,
785 string const & inner_type)
789 string hor_pos = "c";
790 // We need to set the height to the LaTeX default of 1\\totalheight
791 // for the case when no height argument is given
792 string height_value = "1";
793 string height_unit = "in";
794 string height_special = "totalheight";
799 string width_special = "none";
800 if (!inner_type.empty() && p.hasOpt()) {
801 if (inner_type != "makebox")
802 position = p.getArg('[', ']');
804 latex_width = p.getArg('[', ']');
805 translate_box_len(latex_width, width_value, width_unit, width_special);
808 if (position != "t" && position != "c" && position != "b") {
809 cerr << "invalid position " << position << " for "
810 << inner_type << endl;
814 if (inner_type != "makebox") {
815 latex_height = p.getArg('[', ']');
816 translate_box_len(latex_height, height_value, height_unit, height_special);
818 string const opt = p.getArg('[', ']');
821 if (hor_pos != "l" && hor_pos != "c" &&
822 hor_pos != "r" && hor_pos != "s") {
823 cerr << "invalid hor_pos " << hor_pos
824 << " for " << inner_type << endl;
831 inner_pos = p.getArg('[', ']');
832 if (inner_pos != "c" && inner_pos != "t" &&
833 inner_pos != "b" && inner_pos != "s") {
834 cerr << "invalid inner_pos "
835 << inner_pos << " for "
836 << inner_type << endl;
837 inner_pos = position;
842 if (inner_type.empty()) {
843 if (special.empty() && outer_type != "framebox")
844 latex_width = "1\\columnwidth";
847 latex_width = p2.getArg('[', ']');
848 string const opt = p2.getArg('[', ']');
851 if (hor_pos != "l" && hor_pos != "c" &&
852 hor_pos != "r" && hor_pos != "s") {
853 cerr << "invalid hor_pos " << hor_pos
854 << " for " << outer_type << endl;
859 } else if (inner_type != "makebox")
860 latex_width = p.verbatim_item();
861 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
862 // as this is LyX's standard for such cases (except for makebox)
863 // \framebox is more special and handled below
864 if (latex_width.empty() && inner_type != "makebox"
865 && outer_type != "framebox")
866 latex_width = "1\\columnwidth";
868 translate_len(latex_width, width_value, width_unit);
870 bool shadedparbox = false;
871 if (inner_type == "shaded") {
872 eat_whitespace(p, os, parent_context, false);
873 if (outer_type == "parbox") {
875 if (p.next_token().cat() == catBegin)
877 eat_whitespace(p, os, parent_context, false);
883 // If we already read the inner box we have to push the inner env
884 if (!outer_type.empty() && !inner_type.empty() &&
885 (inner_flags & FLAG_END))
886 active_environments.push_back(inner_type);
887 // LyX can't handle length variables
888 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
889 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
890 // Look whether there is some content after the end of the
891 // inner box, but before the end of the outer box.
892 // If yes, we need to output ERT.
894 if (inner_flags & FLAG_END)
895 p.verbatimEnvironment(inner_type);
899 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
900 if ((outer_env && p.next_token().asInput() != "\\end") ||
901 (!outer_env && p.next_token().cat() != catEnd)) {
902 // something is between the end of the inner box and
903 // the end of the outer box, so we need to use ERT.
908 // if only \makebox{content} was used we can set its width to 1\width
909 // because this identic and also identic to \mbox
910 // this doesn't work for \framebox{content}, thus we have to use ERT for this
911 if (latex_width.empty() && inner_type == "makebox") {
914 width_special = "width";
915 } else if (latex_width.empty() && outer_type == "framebox") {
920 if (!outer_type.empty()) {
921 if (outer_flags & FLAG_END)
922 ss << "\\begin{" << outer_type << '}';
924 ss << '\\' << outer_type << '{';
925 if (!special.empty())
929 if (!inner_type.empty()) {
930 if (inner_type != "shaded") {
931 if (inner_flags & FLAG_END)
932 ss << "\\begin{" << inner_type << '}';
934 ss << '\\' << inner_type;
936 if (!position.empty())
937 ss << '[' << position << ']';
938 if (!latex_height.empty())
939 ss << '[' << latex_height << ']';
940 if (!inner_pos.empty())
941 ss << '[' << inner_pos << ']';
942 ss << '{' << latex_width << '}';
943 if (!(inner_flags & FLAG_END))
946 if (inner_type == "shaded")
947 ss << "\\begin{shaded}";
948 handle_ert(os, ss.str(), parent_context);
949 if (!inner_type.empty()) {
950 parse_text(p, os, inner_flags, outer, parent_context);
951 if (inner_flags & FLAG_END)
952 handle_ert(os, "\\end{" + inner_type + '}',
955 handle_ert(os, "}", parent_context);
957 if (!outer_type.empty()) {
958 // If we already read the inner box we have to pop
960 if (!inner_type.empty() && (inner_flags & FLAG_END))
961 active_environments.pop_back();
963 // Ensure that the end of the outer box is parsed correctly:
964 // The opening brace has been eaten by parse_outer_box()
965 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
966 outer_flags &= ~FLAG_ITEM;
967 outer_flags |= FLAG_BRACE_LAST;
969 parse_text(p, os, outer_flags, outer, parent_context);
970 if (outer_flags & FLAG_END)
971 handle_ert(os, "\\end{" + outer_type + '}',
973 else if (inner_type.empty() && outer_type == "framebox")
974 // in this case it is already closed later
977 handle_ert(os, "}", parent_context);
980 // LyX does not like empty positions, so we have
981 // to set them to the LaTeX default values here.
982 if (position.empty())
984 if (inner_pos.empty())
985 inner_pos = position;
986 parent_context.check_layout(os);
987 begin_inset(os, "Box ");
988 if (outer_type == "framed")
990 else if (outer_type == "framebox")
992 else if (outer_type == "shadowbox")
994 else if ((outer_type == "shaded" && inner_type.empty()) ||
995 (outer_type == "minipage" && inner_type == "shaded") ||
996 (outer_type == "parbox" && inner_type == "shaded")) {
998 preamble.registerAutomaticallyLoadedPackage("color");
999 } else if (outer_type == "doublebox")
1000 os << "Doublebox\n";
1001 else if (outer_type.empty())
1002 os << "Frameless\n";
1004 os << outer_type << '\n';
1005 os << "position \"" << position << "\"\n";
1006 os << "hor_pos \"" << hor_pos << "\"\n";
1007 os << "has_inner_box " << !inner_type.empty() << "\n";
1008 os << "inner_pos \"" << inner_pos << "\"\n";
1009 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1011 os << "use_makebox " << (inner_type == "makebox") << '\n';
1012 os << "width \"" << width_value << width_unit << "\"\n";
1013 os << "special \"" << width_special << "\"\n";
1014 os << "height \"" << height_value << height_unit << "\"\n";
1015 os << "height_special \"" << height_special << "\"\n";
1016 os << "status open\n\n";
1018 // Unfortunately we can't use parse_text_in_inset:
1019 // InsetBox::forcePlainLayout() is hard coded and does not
1020 // use the inset layout. Apart from that do we call parse_text
1021 // up to two times, but need only one check_end_layout.
1022 bool const forcePlainLayout =
1023 (!inner_type.empty() || inner_type == "makebox") &&
1024 outer_type != "shaded" && outer_type != "framed";
1025 Context context(true, parent_context.textclass);
1026 if (forcePlainLayout)
1027 context.layout = &context.textclass.plainLayout();
1029 context.font = parent_context.font;
1031 // If we have no inner box the contents will be read with the outer box
1032 if (!inner_type.empty())
1033 parse_text(p, os, inner_flags, outer, context);
1035 // Ensure that the end of the outer box is parsed correctly:
1036 // The opening brace has been eaten by parse_outer_box()
1037 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1038 outer_flags &= ~FLAG_ITEM;
1039 outer_flags |= FLAG_BRACE_LAST;
1042 // Find end of outer box, output contents if inner_type is
1043 // empty and output possible comments
1044 if (!outer_type.empty()) {
1045 // If we already read the inner box we have to pop
1047 if (!inner_type.empty() && (inner_flags & FLAG_END))
1048 active_environments.pop_back();
1049 // This does not output anything but comments if
1050 // inner_type is not empty (see use_ert)
1051 parse_text(p, os, outer_flags, outer, context);
1054 context.check_end_layout(os);
1056 #ifdef PRESERVE_LAYOUT
1057 // LyX puts a % after the end of the minipage
1058 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1060 //handle_comment(os, "%dummy", parent_context);
1063 parent_context.new_paragraph(os);
1065 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1066 //handle_comment(os, "%dummy", parent_context);
1069 // We add a protected space if something real follows
1070 if (p.good() && p.next_token().cat() != catComment) {
1071 begin_inset(os, "space ~\n");
1080 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1081 Context & parent_context, string const & outer_type,
1082 string const & special)
1084 eat_whitespace(p, os, parent_context, false);
1085 if (flags & FLAG_ITEM) {
1087 if (p.next_token().cat() == catBegin)
1090 cerr << "Warning: Ignoring missing '{' after \\"
1091 << outer_type << '.' << endl;
1092 eat_whitespace(p, os, parent_context, false);
1095 unsigned int inner_flags = 0;
1097 if (outer_type == "minipage" || outer_type == "parbox") {
1098 p.skip_spaces(true);
1099 while (p.hasOpt()) {
1101 p.skip_spaces(true);
1104 p.skip_spaces(true);
1105 if (outer_type == "parbox") {
1107 if (p.next_token().cat() == catBegin)
1109 p.skip_spaces(true);
1112 if (outer_type == "shaded") {
1113 // These boxes never have an inner box
1115 } else if (p.next_token().asInput() == "\\parbox") {
1116 inner = p.get_token().cs();
1117 inner_flags = FLAG_ITEM;
1118 } else if (p.next_token().asInput() == "\\begin") {
1119 // Is this a minipage or shaded box?
1122 inner = p.getArg('{', '}');
1124 if (inner == "minipage" || inner == "shaded")
1125 inner_flags = FLAG_END;
1130 if (inner_flags == FLAG_END) {
1131 if (inner != "shaded")
1135 eat_whitespace(p, os, parent_context, false);
1137 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1138 outer_type, special, inner);
1140 if (inner_flags == FLAG_ITEM) {
1142 eat_whitespace(p, os, parent_context, false);
1144 parse_box(p, os, flags, inner_flags, outer, parent_context,
1145 outer_type, special, inner);
1150 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1152 parent_context.check_layout(os);
1153 begin_inset(os, "listings\n");
1155 string arg = p.verbatimOption();
1156 os << "lstparams " << '"' << arg << '"' << '\n';
1157 if (arg.find("\\color") != string::npos)
1158 preamble.registerAutomaticallyLoadedPackage("color");
1161 os << "inline true\n";
1163 os << "inline false\n";
1164 os << "status collapsed\n";
1165 Context context(true, parent_context.textclass);
1166 context.layout = &parent_context.textclass.plainLayout();
1169 s = p.plainCommand('!', '!', "lstinline");
1170 context.new_paragraph(os);
1171 context.check_layout(os);
1173 s = p.plainEnvironment("lstlisting");
1174 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1176 os << "\n\\backslash\n";
1177 else if (*it == '\n') {
1178 // avoid adding an empty paragraph at the end
1180 context.new_paragraph(os);
1181 context.check_layout(os);
1186 context.check_end_layout(os);
1191 /// parse an unknown environment
1192 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1193 unsigned flags, bool outer,
1194 Context & parent_context)
1196 if (name == "tabbing")
1197 // We need to remember that we have to handle '\=' specially
1198 flags |= FLAG_TABBING;
1200 // We need to translate font changes and paragraphs inside the
1201 // environment to ERT if we have a non standard font.
1202 // Otherwise things like
1203 // \large\begin{foo}\huge bar\end{foo}
1205 bool const specialfont =
1206 (parent_context.font != parent_context.normalfont);
1207 bool const new_layout_allowed = parent_context.new_layout_allowed;
1209 parent_context.new_layout_allowed = false;
1210 handle_ert(os, "\\begin{" + name + "}", parent_context);
1211 parse_text_snippet(p, os, flags, outer, parent_context);
1212 handle_ert(os, "\\end{" + name + "}", parent_context);
1214 parent_context.new_layout_allowed = new_layout_allowed;
1218 void parse_environment(Parser & p, ostream & os, bool outer,
1219 string & last_env, Context & parent_context)
1221 Layout const * newlayout;
1222 InsetLayout const * newinsetlayout = 0;
1223 string const name = p.getArg('{', '}');
1224 const bool is_starred = suffixIs(name, '*');
1225 string const unstarred_name = rtrim(name, "*");
1226 active_environments.push_back(name);
1228 if (is_math_env(name)) {
1229 parent_context.check_layout(os);
1230 begin_inset(os, "Formula ");
1231 os << "\\begin{" << name << "}";
1232 parse_math(p, os, FLAG_END, MATH_MODE);
1233 os << "\\end{" << name << "}";
1235 if (is_display_math_env(name)) {
1236 // Prevent the conversion of a line break to a space
1237 // (bug 7668). This does not change the output, but
1238 // looks ugly in LyX.
1239 eat_whitespace(p, os, parent_context, false);
1243 else if (is_known(name, preamble.polyglossia_languages)) {
1244 // We must begin a new paragraph if not already done
1245 if (! parent_context.atParagraphStart()) {
1246 parent_context.check_end_layout(os);
1247 parent_context.new_paragraph(os);
1249 // save the language in the context so that it is
1250 // handled by parse_text
1251 parent_context.font.language = preamble.polyglossia2lyx(name);
1252 parse_text(p, os, FLAG_END, outer, parent_context);
1253 // Just in case the environment is empty
1254 parent_context.extra_stuff.erase();
1255 // We must begin a new paragraph to reset the language
1256 parent_context.new_paragraph(os);
1260 else if (unstarred_name == "tabular" || name == "longtable") {
1261 eat_whitespace(p, os, parent_context, false);
1262 string width = "0pt";
1263 if (name == "tabular*") {
1264 width = lyx::translate_len(p.getArg('{', '}'));
1265 eat_whitespace(p, os, parent_context, false);
1267 parent_context.check_layout(os);
1268 begin_inset(os, "Tabular ");
1269 handle_tabular(p, os, name, width, parent_context);
1274 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1275 eat_whitespace(p, os, parent_context, false);
1276 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1277 eat_whitespace(p, os, parent_context, false);
1278 parent_context.check_layout(os);
1279 begin_inset(os, "Float " + unstarred_name + "\n");
1280 // store the float type for subfloats
1281 // subfloats only work with figures and tables
1282 if (unstarred_name == "figure")
1283 float_type = unstarred_name;
1284 else if (unstarred_name == "table")
1285 float_type = unstarred_name;
1289 os << "placement " << opt << '\n';
1290 if (contains(opt, "H"))
1291 preamble.registerAutomaticallyLoadedPackage("float");
1293 Floating const & fl = parent_context.textclass.floats()
1294 .getType(unstarred_name);
1295 if (!fl.floattype().empty() && fl.usesFloatPkg())
1296 preamble.registerAutomaticallyLoadedPackage("float");
1299 os << "wide " << convert<string>(is_starred)
1300 << "\nsideways false"
1301 << "\nstatus open\n\n";
1302 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1304 // We don't need really a new paragraph, but
1305 // we must make sure that the next item gets a \begin_layout.
1306 parent_context.new_paragraph(os);
1308 // the float is parsed thus delete the type
1312 else if (unstarred_name == "sidewaysfigure"
1313 || unstarred_name == "sidewaystable") {
1314 eat_whitespace(p, os, parent_context, false);
1315 parent_context.check_layout(os);
1316 if (unstarred_name == "sidewaysfigure")
1317 begin_inset(os, "Float figure\n");
1319 begin_inset(os, "Float table\n");
1320 os << "wide " << convert<string>(is_starred)
1321 << "\nsideways true"
1322 << "\nstatus open\n\n";
1323 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1325 // We don't need really a new paragraph, but
1326 // we must make sure that the next item gets a \begin_layout.
1327 parent_context.new_paragraph(os);
1329 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1332 else if (name == "wrapfigure" || name == "wraptable") {
1333 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1334 eat_whitespace(p, os, parent_context, false);
1335 parent_context.check_layout(os);
1338 string overhang = "0col%";
1341 lines = p.getArg('[', ']');
1342 string const placement = p.getArg('{', '}');
1344 overhang = p.getArg('[', ']');
1345 string const width = p.getArg('{', '}');
1347 if (name == "wrapfigure")
1348 begin_inset(os, "Wrap figure\n");
1350 begin_inset(os, "Wrap table\n");
1351 os << "lines " << lines
1352 << "\nplacement " << placement
1353 << "\noverhang " << lyx::translate_len(overhang)
1354 << "\nwidth " << lyx::translate_len(width)
1355 << "\nstatus open\n\n";
1356 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1358 // We don't need really a new paragraph, but
1359 // we must make sure that the next item gets a \begin_layout.
1360 parent_context.new_paragraph(os);
1362 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1365 else if (name == "minipage") {
1366 eat_whitespace(p, os, parent_context, false);
1367 // Test whether this is an outer box of a shaded box
1369 // swallow arguments
1370 while (p.hasOpt()) {
1372 p.skip_spaces(true);
1375 p.skip_spaces(true);
1376 Token t = p.get_token();
1377 bool shaded = false;
1378 if (t.asInput() == "\\begin") {
1379 p.skip_spaces(true);
1380 if (p.getArg('{', '}') == "shaded")
1385 parse_outer_box(p, os, FLAG_END, outer,
1386 parent_context, name, "shaded");
1388 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1393 else if (name == "comment") {
1394 eat_whitespace(p, os, parent_context, false);
1395 parent_context.check_layout(os);
1396 begin_inset(os, "Note Comment\n");
1397 os << "status open\n";
1398 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1401 skip_braces(p); // eat {} that might by set by LyX behind comments
1402 preamble.registerAutomaticallyLoadedPackage("verbatim");
1405 else if (name == "verbatim") {
1406 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1407 string const s = p.plainEnvironment("verbatim");
1408 string::const_iterator it2 = s.begin();
1409 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1411 os << "\\backslash ";
1412 else if (*it == '\n') {
1414 // avoid adding an empty paragraph at the end
1415 // FIXME: if there are 2 consecutive spaces at the end ignore it
1416 // because LyX will re-add a \n
1417 // This hack must be removed once bug 8049 is fixed!
1418 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1419 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1423 os << "\n\\end_layout\n\n";
1425 // reset to Standard layout
1426 os << "\n\\begin_layout Standard\n";
1429 else if (name == "CJK") {
1430 // the scheme is \begin{CJK}{encoding}{mapping}{text}
1431 // It is impossible to decide if a CJK environment was in its own paragraph or within
1432 // a line. We therefore always assume a paragraph since the latter is a rare case.
1433 eat_whitespace(p, os, parent_context, false);
1434 parent_context.check_end_layout(os);
1435 // store the encoding to be able to reset it
1436 string const encoding_old = p.getEncoding();
1437 string const encoding = p.getArg('{', '}');
1438 // SJIS and Bg5 cannot be handled by iconv
1439 // JIS does not work with LyX's encoding conversion
1440 if (encoding != "Bg5" && encoding != "JIS" && encoding != "SJIS")
1441 p.setEncoding(encoding);
1443 p.setEncoding("utf8");
1444 // LyX doesn't support the second argument so if
1445 // this is used we need to output everything as ERT
1446 string const mapping = p.getArg('{', '}');
1447 char const * const * const where =
1448 is_known(encoding, supported_CJK_encodings);
1449 if ((!mapping.empty() && mapping != " ") || !where) {
1450 parent_context.check_layout(os);
1451 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1453 // we must parse the content as verbatim because e.g. JIS can contain
1454 // normally invalid characters
1455 string const s = p.plainEnvironment("CJK");
1456 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1458 handle_ert(os, "\\", parent_context);
1459 else if (*it == '$')
1460 handle_ert(os, "$", parent_context);
1464 handle_ert(os, "\\end{" + name + "}",
1468 supported_CJK_languages[where - supported_CJK_encodings];
1469 // store the language because we must reset it at the end
1470 string const lang_old = parent_context.font.language;
1471 parent_context.font.language = lang;
1472 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1473 parent_context.font.language = lang_old;
1474 parent_context.new_paragraph(os);
1476 p.setEncoding(encoding_old);
1480 else if (name == "lyxgreyedout") {
1481 eat_whitespace(p, os, parent_context, false);
1482 parent_context.check_layout(os);
1483 begin_inset(os, "Note Greyedout\n");
1484 os << "status open\n";
1485 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1488 if (!preamble.notefontcolor().empty())
1489 preamble.registerAutomaticallyLoadedPackage("color");
1492 else if (name == "framed" || name == "shaded") {
1493 eat_whitespace(p, os, parent_context, false);
1494 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1498 else if (name == "lstlisting") {
1499 eat_whitespace(p, os, parent_context, false);
1500 // FIXME handle the automatic color package loading
1501 // uwestoehr asks: In what case color is loaded?
1502 parse_listings(p, os, parent_context, false);
1506 else if (!parent_context.new_layout_allowed)
1507 parse_unknown_environment(p, name, os, FLAG_END, outer,
1510 // Alignment and spacing settings
1511 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1512 // therefore are totally broken!
1513 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1514 // they are commands not environments. They are furthermore switches that
1515 // can be ended by another switches, but also by commands like \footnote or
1516 // \parbox. So the only safe way is to leave them untouched.
1517 else if (name == "center" || name == "centering" ||
1518 name == "flushleft" || name == "flushright" ||
1519 name == "singlespace" || name == "onehalfspace" ||
1520 name == "doublespace" || name == "spacing") {
1521 eat_whitespace(p, os, parent_context, false);
1522 // We must begin a new paragraph if not already done
1523 if (! parent_context.atParagraphStart()) {
1524 parent_context.check_end_layout(os);
1525 parent_context.new_paragraph(os);
1527 if (name == "flushleft")
1528 parent_context.add_extra_stuff("\\align left\n");
1529 else if (name == "flushright")
1530 parent_context.add_extra_stuff("\\align right\n");
1531 else if (name == "center" || name == "centering")
1532 parent_context.add_extra_stuff("\\align center\n");
1533 else if (name == "singlespace")
1534 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1535 else if (name == "onehalfspace") {
1536 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1537 preamble.registerAutomaticallyLoadedPackage("setspace");
1538 } else if (name == "doublespace") {
1539 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1540 preamble.registerAutomaticallyLoadedPackage("setspace");
1541 } else if (name == "spacing") {
1542 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1543 preamble.registerAutomaticallyLoadedPackage("setspace");
1545 parse_text(p, os, FLAG_END, outer, parent_context);
1546 // Just in case the environment is empty
1547 parent_context.extra_stuff.erase();
1548 // We must begin a new paragraph to reset the alignment
1549 parent_context.new_paragraph(os);
1553 // The single '=' is meant here.
1554 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1555 eat_whitespace(p, os, parent_context, false);
1556 Context context(true, parent_context.textclass, newlayout,
1557 parent_context.layout, parent_context.font);
1558 if (parent_context.deeper_paragraph) {
1559 // We are beginning a nested environment after a
1560 // deeper paragraph inside the outer list environment.
1561 // Therefore we don't need to output a "begin deeper".
1562 context.need_end_deeper = true;
1564 parent_context.check_end_layout(os);
1565 if (last_env == name) {
1566 // we need to output a separator since LyX would export
1567 // the two environments as one otherwise (bug 5716)
1568 docstring const sep = from_ascii("--Separator--");
1569 TeX2LyXDocClass const & textclass(parent_context.textclass);
1570 if (textclass.hasLayout(sep)) {
1571 Context newcontext(parent_context);
1572 newcontext.layout = &(textclass[sep]);
1573 newcontext.check_layout(os);
1574 newcontext.check_end_layout(os);
1576 parent_context.check_layout(os);
1577 begin_inset(os, "Note Note\n");
1578 os << "status closed\n";
1579 Context newcontext(true, textclass,
1580 &(textclass.defaultLayout()));
1581 newcontext.check_layout(os);
1582 newcontext.check_end_layout(os);
1584 parent_context.check_end_layout(os);
1587 switch (context.layout->latextype) {
1588 case LATEX_LIST_ENVIRONMENT:
1589 context.add_par_extra_stuff("\\labelwidthstring "
1590 + p.verbatim_item() + '\n');
1593 case LATEX_BIB_ENVIRONMENT:
1594 p.verbatim_item(); // swallow next arg
1600 context.check_deeper(os);
1601 // handle known optional and required arguments
1602 // layouts require all optional arguments before the required ones
1603 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1604 // It is impossible to place anything after the environment name,
1605 // but before the first \\item.
1606 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1607 bool need_layout = true;
1608 unsigned int optargs = 0;
1609 while (optargs < context.layout->optargs) {
1610 eat_whitespace(p, os, context, false);
1611 if (p.next_token().cat() == catEscape ||
1612 p.next_token().character() != '[')
1614 p.get_token(); // eat '['
1616 context.check_layout(os);
1617 need_layout = false;
1619 begin_inset(os, "Argument\n");
1620 os << "status collapsed\n\n";
1621 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1623 eat_whitespace(p, os, context, false);
1626 unsigned int reqargs = 0;
1627 while (reqargs < context.layout->reqargs) {
1628 eat_whitespace(p, os, context, false);
1629 if (p.next_token().cat() != catBegin)
1631 p.get_token(); // eat '{'
1633 context.check_layout(os);
1634 need_layout = false;
1636 begin_inset(os, "Argument\n");
1637 os << "status collapsed\n\n";
1638 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1640 eat_whitespace(p, os, context, false);
1644 parse_text(p, os, FLAG_END, outer, context);
1645 context.check_end_layout(os);
1646 if (parent_context.deeper_paragraph) {
1647 // We must suppress the "end deeper" because we
1648 // suppressed the "begin deeper" above.
1649 context.need_end_deeper = false;
1651 context.check_end_deeper(os);
1652 parent_context.new_paragraph(os);
1654 if (!preamble.titleLayoutFound())
1655 preamble.titleLayoutFound(newlayout->intitle);
1656 set<string> const & req = newlayout->requires();
1657 set<string>::const_iterator it = req.begin();
1658 set<string>::const_iterator en = req.end();
1659 for (; it != en; ++it)
1660 preamble.registerAutomaticallyLoadedPackage(*it);
1663 // The single '=' is meant here.
1664 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1665 eat_whitespace(p, os, parent_context, false);
1666 parent_context.check_layout(os);
1667 begin_inset(os, "Flex ");
1668 os << to_utf8(newinsetlayout->name()) << '\n'
1669 << "status collapsed\n";
1670 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1674 else if (name == "appendix") {
1675 // This is no good latex style, but it works and is used in some documents...
1676 eat_whitespace(p, os, parent_context, false);
1677 parent_context.check_end_layout(os);
1678 Context context(true, parent_context.textclass, parent_context.layout,
1679 parent_context.layout, parent_context.font);
1680 context.check_layout(os);
1681 os << "\\start_of_appendix\n";
1682 parse_text(p, os, FLAG_END, outer, context);
1683 context.check_end_layout(os);
1687 else if (known_environments.find(name) != known_environments.end()) {
1688 vector<ArgumentType> arguments = known_environments[name];
1689 // The last "argument" denotes wether we may translate the
1690 // environment contents to LyX
1691 // The default required if no argument is given makes us
1692 // compatible with the reLyXre environment.
1693 ArgumentType contents = arguments.empty() ?
1696 if (!arguments.empty())
1697 arguments.pop_back();
1698 // See comment in parse_unknown_environment()
1699 bool const specialfont =
1700 (parent_context.font != parent_context.normalfont);
1701 bool const new_layout_allowed =
1702 parent_context.new_layout_allowed;
1704 parent_context.new_layout_allowed = false;
1705 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1706 outer, parent_context);
1707 if (contents == verbatim)
1708 handle_ert(os, p.verbatimEnvironment(name),
1711 parse_text_snippet(p, os, FLAG_END, outer,
1713 handle_ert(os, "\\end{" + name + "}", parent_context);
1715 parent_context.new_layout_allowed = new_layout_allowed;
1719 parse_unknown_environment(p, name, os, FLAG_END, outer,
1723 active_environments.pop_back();
1727 /// parses a comment and outputs it to \p os.
1728 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1730 LASSERT(t.cat() == catComment, return);
1731 if (!t.cs().empty()) {
1732 context.check_layout(os);
1733 handle_comment(os, '%' + t.cs(), context);
1734 if (p.next_token().cat() == catNewline) {
1735 // A newline after a comment line starts a new
1737 if (context.new_layout_allowed) {
1738 if(!context.atParagraphStart())
1739 // Only start a new paragraph if not already
1740 // done (we might get called recursively)
1741 context.new_paragraph(os);
1743 handle_ert(os, "\n", context);
1744 eat_whitespace(p, os, context, true);
1747 // "%\n" combination
1754 * Reads spaces and comments until the first non-space, non-comment token.
1755 * New paragraphs (double newlines or \\par) are handled like simple spaces
1756 * if \p eatParagraph is true.
1757 * Spaces are skipped, but comments are written to \p os.
1759 void eat_whitespace(Parser & p, ostream & os, Context & context,
1763 Token const & t = p.get_token();
1764 if (t.cat() == catComment)
1765 parse_comment(p, os, t, context);
1766 else if ((! eatParagraph && p.isParagraph()) ||
1767 (t.cat() != catSpace && t.cat() != catNewline)) {
1776 * Set a font attribute, parse text and reset the font attribute.
1777 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1778 * \param currentvalue Current value of the attribute. Is set to the new
1779 * value during parsing.
1780 * \param newvalue New value of the attribute
1782 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1783 Context & context, string const & attribute,
1784 string & currentvalue, string const & newvalue)
1786 context.check_layout(os);
1787 string const oldvalue = currentvalue;
1788 currentvalue = newvalue;
1789 os << '\n' << attribute << ' ' << newvalue << "\n";
1790 parse_text_snippet(p, os, flags, outer, context);
1791 context.check_layout(os);
1792 os << '\n' << attribute << ' ' << oldvalue << "\n";
1793 currentvalue = oldvalue;
1797 /// get the arguments of a natbib or jurabib citation command
1798 void get_cite_arguments(Parser & p, bool natbibOrder,
1799 string & before, string & after)
1801 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1803 // text before the citation
1805 // text after the citation
1806 after = p.getFullOpt();
1808 if (!after.empty()) {
1809 before = p.getFullOpt();
1810 if (natbibOrder && !before.empty())
1811 swap(before, after);
1816 /// Convert filenames with TeX macros and/or quotes to something LyX
1818 string const normalize_filename(string const & name)
1820 Parser p(trim(name, "\""));
1823 Token const & t = p.get_token();
1824 if (t.cat() != catEscape)
1826 else if (t.cs() == "lyxdot") {
1827 // This is used by LyX for simple dots in relative
1831 } else if (t.cs() == "space") {
1841 /// Convert \p name from TeX convention (relative to master file) to LyX
1842 /// convention (relative to .lyx file) if it is relative
1843 void fix_child_filename(string & name)
1845 string const absMasterTeX = getMasterFilePath(true);
1846 bool const isabs = FileName::isAbsolute(name);
1847 // convert from "relative to .tex master" to absolute original path
1849 name = makeAbsPath(name, absMasterTeX).absFileName();
1850 bool copyfile = copyFiles();
1851 string const absParentLyX = getParentFilePath(false);
1854 // convert from absolute original path to "relative to master file"
1855 string const rel = to_utf8(makeRelPath(from_utf8(name),
1856 from_utf8(absMasterTeX)));
1857 // re-interpret "relative to .tex file" as "relative to .lyx file"
1858 // (is different if the master .lyx file resides in a
1859 // different path than the master .tex file)
1860 string const absMasterLyX = getMasterFilePath(false);
1861 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1862 // Do not copy if the new path is impossible to create. Example:
1863 // absMasterTeX = "/foo/bar/"
1864 // absMasterLyX = "/bar/"
1865 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1866 if (contains(name, "/../"))
1873 // convert from absolute original path to
1874 // "relative to .lyx file"
1875 name = to_utf8(makeRelPath(from_utf8(abs),
1876 from_utf8(absParentLyX)));
1880 // convert from absolute original path to "relative to .lyx file"
1881 name = to_utf8(makeRelPath(from_utf8(name),
1882 from_utf8(absParentLyX)));
1887 void copy_file(FileName const & src, string dstname)
1891 string const absParent = getParentFilePath(false);
1893 if (FileName::isAbsolute(dstname))
1894 dst = FileName(dstname);
1896 dst = makeAbsPath(dstname, absParent);
1897 string const absMaster = getMasterFilePath(false);
1898 FileName const srcpath = src.onlyPath();
1899 FileName const dstpath = dst.onlyPath();
1900 if (equivalent(srcpath, dstpath))
1902 if (!dstpath.isDirectory()) {
1903 if (!dstpath.createPath()) {
1904 cerr << "Warning: Could not create directory for file `"
1905 << dst.absFileName() << "´." << endl;
1909 if (dst.isReadableFile()) {
1910 if (overwriteFiles())
1911 cerr << "Warning: Overwriting existing file `"
1912 << dst.absFileName() << "´." << endl;
1914 cerr << "Warning: Not overwriting existing file `"
1915 << dst.absFileName() << "´." << endl;
1919 if (!src.copyTo(dst))
1920 cerr << "Warning: Could not copy file `" << src.absFileName()
1921 << "´ to `" << dst.absFileName() << "´." << endl;
1925 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1926 void parse_noweb(Parser & p, ostream & os, Context & context)
1928 // assemble the rest of the keyword
1932 Token const & t = p.get_token();
1933 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1936 scrap = (p.good() && p.next_token().asInput() == "=");
1938 name += p.get_token().asInput();
1941 name += t.asInput();
1944 if (!scrap || !context.new_layout_allowed ||
1945 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1946 cerr << "Warning: Could not interpret '" << name
1947 << "'. Ignoring it." << endl;
1951 // We use new_paragraph instead of check_end_layout because the stuff
1952 // following the noweb chunk needs to start with a \begin_layout.
1953 // This may create a new paragraph even if there was none in the
1954 // noweb file, but the alternative is an invalid LyX file. Since
1955 // noweb code chunks are implemented with a layout style in LyX they
1956 // always must be in an own paragraph.
1957 context.new_paragraph(os);
1958 Context newcontext(true, context.textclass,
1959 &context.textclass[from_ascii("Scrap")]);
1960 newcontext.check_layout(os);
1963 Token const & t = p.get_token();
1964 // We abuse the parser a bit, because this is no TeX syntax
1966 if (t.cat() == catEscape)
1967 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1970 Context tmp(false, context.textclass,
1971 &context.textclass[from_ascii("Scrap")]);
1972 tmp.need_end_layout = true;
1973 tmp.check_layout(oss);
1974 os << subst(t.asInput(), "\n", oss.str());
1976 // The scrap chunk is ended by an @ at the beginning of a line.
1977 // After the @ the line may contain a comment and/or
1978 // whitespace, but nothing else.
1979 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1980 (p.next_token().cat() == catSpace ||
1981 p.next_token().cat() == catNewline ||
1982 p.next_token().cat() == catComment)) {
1983 while (p.good() && p.next_token().cat() == catSpace)
1984 os << p.get_token().asInput();
1985 if (p.next_token().cat() == catComment)
1986 // The comment includes a final '\n'
1987 os << p.get_token().asInput();
1989 if (p.next_token().cat() == catNewline)
1996 newcontext.check_end_layout(os);
2000 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2001 bool is_macro(Parser & p)
2003 Token first = p.curr_token();
2004 if (first.cat() != catEscape || !p.good())
2006 if (first.cs() == "def")
2008 if (first.cs() != "global" && first.cs() != "long")
2010 Token second = p.get_token();
2012 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2013 second.cat() == catNewline || second.cat() == catComment)) {
2014 second = p.get_token();
2017 bool secondvalid = second.cat() == catEscape;
2019 bool thirdvalid = false;
2020 if (p.good() && first.cs() == "global" && secondvalid &&
2021 second.cs() == "long") {
2022 third = p.get_token();
2024 while (p.good() && !p.isParagraph() &&
2025 (third.cat() == catSpace ||
2026 third.cat() == catNewline ||
2027 third.cat() == catComment)) {
2028 third = p.get_token();
2031 thirdvalid = third.cat() == catEscape;
2033 for (int i = 0; i < pos; ++i)
2038 return (first.cs() == "global" || first.cs() == "long") &&
2039 second.cs() == "def";
2040 return first.cs() == "global" && second.cs() == "long" &&
2041 third.cs() == "def";
2045 /// Parse a macro definition (assumes that is_macro() returned true)
2046 void parse_macro(Parser & p, ostream & os, Context & context)
2048 context.check_layout(os);
2049 Token first = p.curr_token();
2052 string command = first.asInput();
2053 if (first.cs() != "def") {
2055 eat_whitespace(p, os, context, false);
2056 second = p.curr_token();
2057 command += second.asInput();
2058 if (second.cs() != "def") {
2060 eat_whitespace(p, os, context, false);
2061 third = p.curr_token();
2062 command += third.asInput();
2065 eat_whitespace(p, os, context, false);
2066 string const name = p.get_token().cs();
2067 eat_whitespace(p, os, context, false);
2073 while (p.next_token().cat() != catBegin) {
2074 if (p.next_token().cat() == catParameter) {
2079 // followed by number?
2080 if (p.next_token().cat() == catOther) {
2081 char c = p.getChar();
2083 // number = current arity + 1?
2084 if (c == arity + '0' + 1)
2089 paramtext += p.get_token().cs();
2091 paramtext += p.get_token().cs();
2096 // only output simple (i.e. compatible) macro as FormulaMacros
2097 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2099 context.check_layout(os);
2100 begin_inset(os, "FormulaMacro");
2101 os << "\n\\def" << ert;
2104 handle_ert(os, command + ert, context);
2108 void registerExternalTemplatePackages(string const & name)
2110 external::TemplateManager const & etm = external::TemplateManager::get();
2111 external::Template const * const et = etm.getTemplateByName(name);
2114 external::Template::Formats::const_iterator cit = et->formats.end();
2116 cit = et->formats.find("PDFLaTeX");
2117 if (cit == et->formats.end())
2118 // If the template has not specified a PDFLaTeX output,
2119 // we try the LaTeX format.
2120 cit = et->formats.find("LaTeX");
2121 if (cit == et->formats.end())
2123 vector<string>::const_iterator qit = cit->second.requirements.begin();
2124 vector<string>::const_iterator qend = cit->second.requirements.end();
2125 for (; qit != qend; ++qit)
2126 preamble.registerAutomaticallyLoadedPackage(*qit);
2129 } // anonymous namespace
2132 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2135 Layout const * newlayout = 0;
2136 InsetLayout const * newinsetlayout = 0;
2137 char const * const * where = 0;
2138 // Store the latest bibliographystyle and nocite{*} option
2139 // (needed for bibtex inset)
2141 string bibliographystyle = "default";
2142 bool const use_natbib = preamble.isPackageUsed("natbib");
2143 bool const use_jurabib = preamble.isPackageUsed("jurabib");
2146 Token const & t = p.get_token();
2148 // it is impossible to determine the correct encoding for non-CJK Japanese.
2149 // Therefore write a note at the beginning of the document
2150 if (is_nonCJKJapanese) {
2151 context.check_layout(os);
2152 begin_inset(os, "Note Note\n");
2153 os << "status open\n\\begin_layout Plain Layout\n"
2154 << "\\series bold\n"
2155 << "Important information:\n"
2156 << "\\end_layout\n\n"
2157 << "\\begin_layout Plain Layout\n"
2158 << "This document is in Japanese (non-CJK).\n"
2159 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2160 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2161 << " encoding in the document settings.\n"
2162 << "\\end_layout\n";
2164 is_nonCJKJapanese = false;
2168 debugToken(cerr, t, flags);
2171 if (flags & FLAG_ITEM) {
2172 if (t.cat() == catSpace)
2175 flags &= ~FLAG_ITEM;
2176 if (t.cat() == catBegin) {
2177 // skip the brace and collect everything to the next matching
2179 flags |= FLAG_BRACE_LAST;
2183 // handle only this single token, leave the loop if done
2184 flags |= FLAG_LEAVE;
2187 if (t.cat() != catEscape && t.character() == ']' &&
2188 (flags & FLAG_BRACK_LAST))
2190 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2193 // If there is anything between \end{env} and \begin{env} we
2194 // don't need to output a separator.
2195 if (t.cat() != catSpace && t.cat() != catNewline &&
2196 t.asInput() != "\\begin")
2202 if (t.cat() == catMath) {
2203 // we are inside some text mode thingy, so opening new math is allowed
2204 context.check_layout(os);
2205 begin_inset(os, "Formula ");
2206 Token const & n = p.get_token();
2207 bool const display(n.cat() == catMath && outer);
2209 // TeX's $$...$$ syntax for displayed math
2211 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2213 p.get_token(); // skip the second '$' token
2215 // simple $...$ stuff
2218 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2223 // Prevent the conversion of a line break to a
2224 // space (bug 7668). This does not change the
2225 // output, but looks ugly in LyX.
2226 eat_whitespace(p, os, context, false);
2230 else if (t.cat() == catSuper || t.cat() == catSub)
2231 cerr << "catcode " << t << " illegal in text mode\n";
2233 // Basic support for english quotes. This should be
2234 // extended to other quotes, but is not so easy (a
2235 // left english quote is the same as a right german
2237 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2238 context.check_layout(os);
2239 begin_inset(os, "Quotes ");
2245 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2246 context.check_layout(os);
2247 begin_inset(os, "Quotes ");
2254 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2255 context.check_layout(os);
2256 begin_inset(os, "Quotes ");
2263 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2264 context.check_layout(os);
2265 begin_inset(os, "Quotes ");
2272 else if (t.asInput() == "<"
2273 && p.next_token().asInput() == "<" && noweb_mode) {
2275 parse_noweb(p, os, context);
2278 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2279 check_space(p, os, context);
2281 else if (t.character() == '[' && noweb_mode &&
2282 p.next_token().character() == '[') {
2283 // These can contain underscores
2285 string const s = p.getFullOpt() + ']';
2286 if (p.next_token().character() == ']')
2289 cerr << "Warning: Inserting missing ']' in '"
2290 << s << "'." << endl;
2291 handle_ert(os, s, context);
2294 else if (t.cat() == catLetter) {
2295 context.check_layout(os);
2296 // Workaround for bug 4752.
2297 // FIXME: This whole code block needs to be removed
2298 // when the bug is fixed and tex2lyx produces
2299 // the updated file format.
2300 // The replacement algorithm in LyX is so stupid that
2301 // it even translates a phrase if it is part of a word.
2302 bool handled = false;
2303 for (int const * l = known_phrase_lengths; *l; ++l) {
2304 string phrase = t.cs();
2305 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2306 phrase += p.get_token().cs();
2307 if (is_known(phrase, known_coded_phrases)) {
2308 handle_ert(os, phrase, context);
2312 for (size_t i = 1; i < phrase.length(); ++i)
2320 else if (t.cat() == catOther ||
2321 t.cat() == catAlign ||
2322 t.cat() == catParameter) {
2323 // This translates "&" to "\\&" which may be wrong...
2324 context.check_layout(os);
2328 else if (p.isParagraph()) {
2329 if (context.new_layout_allowed)
2330 context.new_paragraph(os);
2332 handle_ert(os, "\\par ", context);
2333 eat_whitespace(p, os, context, true);
2336 else if (t.cat() == catActive) {
2337 context.check_layout(os);
2338 if (t.character() == '~') {
2339 if (context.layout->free_spacing)
2342 begin_inset(os, "space ~\n");
2349 else if (t.cat() == catBegin) {
2350 Token const next = p.next_token();
2351 Token const end = p.next_next_token();
2352 if (next.cat() == catEnd) {
2354 Token const prev = p.prev_token();
2356 if (p.next_token().character() == '`' ||
2357 (prev.character() == '-' &&
2358 p.next_token().character() == '-'))
2359 ; // ignore it in {}`` or -{}-
2361 handle_ert(os, "{}", context);
2362 } else if (next.cat() == catEscape &&
2363 is_known(next.cs(), known_quotes) &&
2364 end.cat() == catEnd) {
2365 // Something like {\textquoteright} (e.g.
2366 // from writer2latex). LyX writes
2367 // \textquoteright{}, so we may skip the
2368 // braces here for better readability.
2369 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2372 context.check_layout(os);
2373 // special handling of font attribute changes
2374 Token const prev = p.prev_token();
2375 TeXFont const oldFont = context.font;
2376 if (next.character() == '[' ||
2377 next.character() == ']' ||
2378 next.character() == '*') {
2380 if (p.next_token().cat() == catEnd) {
2385 handle_ert(os, "{", context);
2386 parse_text_snippet(p, os,
2389 handle_ert(os, "}", context);
2391 } else if (! context.new_layout_allowed) {
2392 handle_ert(os, "{", context);
2393 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2395 handle_ert(os, "}", context);
2396 } else if (is_known(next.cs(), known_sizes)) {
2397 // next will change the size, so we must
2399 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2401 if (!context.atParagraphStart())
2403 << context.font.size << "\n";
2404 } else if (is_known(next.cs(), known_font_families)) {
2405 // next will change the font family, so we
2406 // must reset it here
2407 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2409 if (!context.atParagraphStart())
2411 << context.font.family << "\n";
2412 } else if (is_known(next.cs(), known_font_series)) {
2413 // next will change the font series, so we
2414 // must reset it here
2415 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2417 if (!context.atParagraphStart())
2419 << context.font.series << "\n";
2420 } else if (is_known(next.cs(), known_font_shapes)) {
2421 // next will change the font shape, so we
2422 // must reset it here
2423 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2425 if (!context.atParagraphStart())
2427 << context.font.shape << "\n";
2428 } else if (is_known(next.cs(), known_old_font_families) ||
2429 is_known(next.cs(), known_old_font_series) ||
2430 is_known(next.cs(), known_old_font_shapes)) {
2431 // next will change the font family, series
2432 // and shape, so we must reset it here
2433 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2435 if (!context.atParagraphStart())
2437 << context.font.family
2439 << context.font.series
2441 << context.font.shape << "\n";
2443 handle_ert(os, "{", context);
2444 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2446 handle_ert(os, "}", context);
2451 else if (t.cat() == catEnd) {
2452 if (flags & FLAG_BRACE_LAST) {
2455 cerr << "stray '}' in text\n";
2456 handle_ert(os, "}", context);
2459 else if (t.cat() == catComment)
2460 parse_comment(p, os, t, context);
2463 // control sequences
2466 else if (t.cs() == "(") {
2467 context.check_layout(os);
2468 begin_inset(os, "Formula");
2470 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2475 else if (t.cs() == "[") {
2476 context.check_layout(os);
2477 begin_inset(os, "Formula");
2479 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2482 // Prevent the conversion of a line break to a space
2483 // (bug 7668). This does not change the output, but
2484 // looks ugly in LyX.
2485 eat_whitespace(p, os, context, false);
2488 else if (t.cs() == "begin")
2489 parse_environment(p, os, outer, last_env,
2492 else if (t.cs() == "end") {
2493 if (flags & FLAG_END) {
2494 // eat environment name
2495 string const name = p.getArg('{', '}');
2496 if (name != active_environment())
2497 cerr << "\\end{" + name + "} does not match \\begin{"
2498 + active_environment() + "}\n";
2501 p.error("found 'end' unexpectedly");
2504 else if (t.cs() == "item") {
2506 bool const optarg = p.hasOpt();
2508 // FIXME: This swallows comments, but we cannot use
2509 // eat_whitespace() since we must not output
2510 // anything before the item.
2511 p.skip_spaces(true);
2512 s = p.verbatimOption();
2514 p.skip_spaces(false);
2516 context.check_layout(os);
2517 if (context.has_item) {
2518 // An item in an unknown list-like environment
2519 // FIXME: Do this in check_layout()!
2520 context.has_item = false;
2522 handle_ert(os, "\\item", context);
2524 handle_ert(os, "\\item ", context);
2527 if (context.layout->labeltype != LABEL_MANUAL) {
2528 // LyX does not support \item[\mybullet]
2529 // in itemize environments
2531 os << parse_text_snippet(p2,
2532 FLAG_BRACK_LAST, outer, context);
2533 } else if (!s.empty()) {
2534 // LyX adds braces around the argument,
2535 // so we need to remove them here.
2536 if (s.size() > 2 && s[0] == '{' &&
2537 s[s.size()-1] == '}')
2538 s = s.substr(1, s.size()-2);
2539 // If the argument contains a space we
2540 // must put it into ERT: Otherwise LyX
2541 // would misinterpret the space as
2542 // item delimiter (bug 7663)
2543 if (contains(s, ' ')) {
2544 handle_ert(os, s, context);
2547 os << parse_text_snippet(p2,
2551 // The space is needed to separate the
2552 // item from the rest of the sentence.
2554 eat_whitespace(p, os, context, false);
2559 else if (t.cs() == "bibitem") {
2561 context.check_layout(os);
2562 eat_whitespace(p, os, context, false);
2563 string label = convert_command_inset_arg(p.verbatimOption());
2564 string key = convert_command_inset_arg(p.verbatim_item());
2565 if (contains(label, '\\') || contains(key, '\\')) {
2566 // LyX can't handle LaTeX commands in labels or keys
2567 handle_ert(os, t.asInput() + '[' + label +
2568 "]{" + p.verbatim_item() + '}',
2571 begin_command_inset(os, "bibitem", "bibitem");
2572 os << "label \"" << label << "\"\n"
2573 "key \"" << key << "\"\n";
2578 else if (is_macro(p)) {
2579 // catch the case of \def\inputGnumericTable
2581 if (t.cs() == "def") {
2582 Token second = p.next_token();
2583 if (second.cs() == "inputGnumericTable") {
2587 Token third = p.get_token();
2589 if (third.cs() == "input") {
2593 string name = normalize_filename(p.verbatim_item());
2594 string const path = getMasterFilePath(true);
2595 // We want to preserve relative / absolute filenames,
2596 // therefore path is only used for testing
2597 // The file extension is in every case ".tex".
2598 // So we need to remove this extension and check for
2599 // the original one.
2600 name = removeExtension(name);
2601 if (!makeAbsPath(name, path).exists()) {
2602 char const * const Gnumeric_formats[] = {"gnumeric",
2604 string const Gnumeric_name =
2605 find_file(name, path, Gnumeric_formats);
2606 if (!Gnumeric_name.empty())
2607 name = Gnumeric_name;
2609 FileName const absname = makeAbsPath(name, path);
2610 if (absname.exists()) {
2611 fix_child_filename(name);
2612 copy_file(absname, name);
2614 cerr << "Warning: Could not find file '"
2615 << name << "'." << endl;
2616 context.check_layout(os);
2617 begin_inset(os, "External\n\ttemplate ");
2618 os << "GnumericSpreadsheet\n\tfilename "
2621 context.check_layout(os);
2623 // register the packages that are automatically loaded
2624 // by the Gnumeric template
2625 registerExternalTemplatePackages("GnumericSpreadsheet");
2630 parse_macro(p, os, context);
2633 else if (t.cs() == "noindent") {
2635 context.add_par_extra_stuff("\\noindent\n");
2638 else if (t.cs() == "appendix") {
2639 context.add_par_extra_stuff("\\start_of_appendix\n");
2640 // We need to start a new paragraph. Otherwise the
2641 // appendix in 'bla\appendix\chapter{' would start
2643 context.new_paragraph(os);
2644 // We need to make sure that the paragraph is
2645 // generated even if it is empty. Otherwise the
2646 // appendix in '\par\appendix\par\chapter{' would
2648 context.check_layout(os);
2649 // FIXME: This is a hack to prevent paragraph
2650 // deletion if it is empty. Handle this better!
2652 "%dummy comment inserted by tex2lyx to "
2653 "ensure that this paragraph is not empty",
2655 // Both measures above may generate an additional
2656 // empty paragraph, but that does not hurt, because
2657 // whitespace does not matter here.
2658 eat_whitespace(p, os, context, true);
2661 // Must catch empty dates before findLayout is called below
2662 else if (t.cs() == "date") {
2663 eat_whitespace(p, os, context, false);
2665 string const date = p.verbatim_item();
2668 preamble.suppressDate(true);
2671 preamble.suppressDate(false);
2672 if (context.new_layout_allowed &&
2673 (newlayout = findLayout(context.textclass,
2676 output_command_layout(os, p, outer,
2677 context, newlayout);
2678 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2679 if (!preamble.titleLayoutFound())
2680 preamble.titleLayoutFound(newlayout->intitle);
2681 set<string> const & req = newlayout->requires();
2682 set<string>::const_iterator it = req.begin();
2683 set<string>::const_iterator en = req.end();
2684 for (; it != en; ++it)
2685 preamble.registerAutomaticallyLoadedPackage(*it);
2688 "\\date{" + p.verbatim_item() + '}',
2693 // Starred section headings
2694 // Must attempt to parse "Section*" before "Section".
2695 else if ((p.next_token().asInput() == "*") &&
2696 context.new_layout_allowed &&
2697 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2700 output_command_layout(os, p, outer, context, newlayout);
2702 if (!preamble.titleLayoutFound())
2703 preamble.titleLayoutFound(newlayout->intitle);
2704 set<string> const & req = newlayout->requires();
2705 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2706 preamble.registerAutomaticallyLoadedPackage(*it);
2709 // Section headings and the like
2710 else if (context.new_layout_allowed &&
2711 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2713 output_command_layout(os, p, outer, context, newlayout);
2715 if (!preamble.titleLayoutFound())
2716 preamble.titleLayoutFound(newlayout->intitle);
2717 set<string> const & req = newlayout->requires();
2718 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2719 preamble.registerAutomaticallyLoadedPackage(*it);
2722 else if (t.cs() == "caption") {
2724 context.check_layout(os);
2726 begin_inset(os, "Caption\n");
2727 Context newcontext(true, context.textclass, 0, 0, context.font);
2728 newcontext.check_layout(os);
2729 if (p.next_token().cat() != catEscape &&
2730 p.next_token().character() == '[') {
2731 p.get_token(); // eat '['
2732 begin_inset(os, "Argument\n");
2733 os << "status collapsed\n";
2734 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2736 eat_whitespace(p, os, context, false);
2738 parse_text(p, os, FLAG_ITEM, outer, context);
2739 context.check_end_layout(os);
2740 // We don't need really a new paragraph, but
2741 // we must make sure that the next item gets a \begin_layout.
2742 context.new_paragraph(os);
2745 newcontext.check_end_layout(os);
2748 else if (t.cs() == "subfloat") {
2749 // the syntax is \subfloat[caption]{content}
2750 // if it is a table of figure depends on the surrounding float
2751 bool has_caption = false;
2753 // do nothing if there is no outer float
2754 if (!float_type.empty()) {
2755 context.check_layout(os);
2757 begin_inset(os, "Float " + float_type + "\n");
2759 << "\nsideways false"
2760 << "\nstatus collapsed\n\n";
2763 if (p.next_token().cat() != catEscape &&
2764 p.next_token().character() == '[') {
2765 p.get_token(); // eat '['
2766 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2770 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2771 // the caption comes always as the last
2773 // we must make sure that the caption gets a \begin_layout
2774 os << "\n\\begin_layout Plain Layout";
2776 begin_inset(os, "Caption\n");
2777 Context newcontext(true, context.textclass,
2778 0, 0, context.font);
2779 newcontext.check_layout(os);
2780 os << caption << "\n";
2781 newcontext.check_end_layout(os);
2782 // We don't need really a new paragraph, but
2783 // we must make sure that the next item gets a \begin_layout.
2784 //newcontext.new_paragraph(os);
2788 // We don't need really a new paragraph, but
2789 // we must make sure that the next item gets a \begin_layout.
2791 context.new_paragraph(os);
2794 context.check_end_layout(os);
2795 // close the layout we opened
2797 os << "\n\\end_layout\n";
2799 // if the float type is not supported or there is no surrounding float
2802 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2803 handle_ert(os, t.asInput() + '[' + opt_arg +
2804 "]{" + p.verbatim_item() + '}', context);
2806 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2810 else if (t.cs() == "includegraphics") {
2811 bool const clip = p.next_token().asInput() == "*";
2814 string const arg = p.getArg('[', ']');
2815 map<string, string> opts;
2816 vector<string> keys;
2817 split_map(arg, opts, keys);
2819 opts["clip"] = string();
2820 string name = normalize_filename(p.verbatim_item());
2822 string const path = getMasterFilePath(true);
2823 // We want to preserve relative / absolute filenames,
2824 // therefore path is only used for testing
2825 if (!makeAbsPath(name, path).exists()) {
2826 // The file extension is probably missing.
2827 // Now try to find it out.
2828 string const dvips_name =
2829 find_file(name, path,
2830 known_dvips_graphics_formats);
2831 string const pdftex_name =
2832 find_file(name, path,
2833 known_pdftex_graphics_formats);
2834 if (!dvips_name.empty()) {
2835 if (!pdftex_name.empty()) {
2836 cerr << "This file contains the "
2838 "\"\\includegraphics{"
2840 "However, files\n\""
2841 << dvips_name << "\" and\n\""
2842 << pdftex_name << "\"\n"
2843 "both exist, so I had to make a "
2844 "choice and took the first one.\n"
2845 "Please move the unwanted one "
2846 "someplace else and try again\n"
2847 "if my choice was wrong."
2851 } else if (!pdftex_name.empty()) {
2857 FileName const absname = makeAbsPath(name, path);
2858 if (absname.exists()) {
2859 fix_child_filename(name);
2860 copy_file(absname, name);
2862 cerr << "Warning: Could not find graphics file '"
2863 << name << "'." << endl;
2865 context.check_layout(os);
2866 begin_inset(os, "Graphics ");
2867 os << "\n\tfilename " << name << '\n';
2868 if (opts.find("width") != opts.end())
2870 << translate_len(opts["width"]) << '\n';
2871 if (opts.find("height") != opts.end())
2873 << translate_len(opts["height"]) << '\n';
2874 if (opts.find("scale") != opts.end()) {
2875 istringstream iss(opts["scale"]);
2879 os << "\tscale " << val << '\n';
2881 if (opts.find("angle") != opts.end()) {
2882 os << "\trotateAngle "
2883 << opts["angle"] << '\n';
2884 vector<string>::const_iterator a =
2885 find(keys.begin(), keys.end(), "angle");
2886 vector<string>::const_iterator s =
2887 find(keys.begin(), keys.end(), "width");
2888 if (s == keys.end())
2889 s = find(keys.begin(), keys.end(), "height");
2890 if (s == keys.end())
2891 s = find(keys.begin(), keys.end(), "scale");
2892 if (s != keys.end() && distance(s, a) > 0)
2893 os << "\tscaleBeforeRotation\n";
2895 if (opts.find("origin") != opts.end()) {
2897 string const opt = opts["origin"];
2898 if (opt.find('l') != string::npos) ss << "left";
2899 if (opt.find('r') != string::npos) ss << "right";
2900 if (opt.find('c') != string::npos) ss << "center";
2901 if (opt.find('t') != string::npos) ss << "Top";
2902 if (opt.find('b') != string::npos) ss << "Bottom";
2903 if (opt.find('B') != string::npos) ss << "Baseline";
2904 if (!ss.str().empty())
2905 os << "\trotateOrigin " << ss.str() << '\n';
2907 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2909 if (opts.find("keepaspectratio") != opts.end())
2910 os << "\tkeepAspectRatio\n";
2911 if (opts.find("clip") != opts.end())
2913 if (opts.find("draft") != opts.end())
2915 if (opts.find("bb") != opts.end())
2916 os << "\tBoundingBox "
2917 << opts["bb"] << '\n';
2918 int numberOfbbOptions = 0;
2919 if (opts.find("bbllx") != opts.end())
2920 numberOfbbOptions++;
2921 if (opts.find("bblly") != opts.end())
2922 numberOfbbOptions++;
2923 if (opts.find("bburx") != opts.end())
2924 numberOfbbOptions++;
2925 if (opts.find("bbury") != opts.end())
2926 numberOfbbOptions++;
2927 if (numberOfbbOptions == 4)
2928 os << "\tBoundingBox "
2929 << opts["bbllx"] << " " << opts["bblly"] << " "
2930 << opts["bburx"] << " " << opts["bbury"] << '\n';
2931 else if (numberOfbbOptions > 0)
2932 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2933 numberOfbbOptions = 0;
2934 if (opts.find("natwidth") != opts.end())
2935 numberOfbbOptions++;
2936 if (opts.find("natheight") != opts.end())
2937 numberOfbbOptions++;
2938 if (numberOfbbOptions == 2)
2939 os << "\tBoundingBox 0bp 0bp "
2940 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2941 else if (numberOfbbOptions > 0)
2942 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2943 ostringstream special;
2944 if (opts.find("hiresbb") != opts.end())
2945 special << "hiresbb,";
2946 if (opts.find("trim") != opts.end())
2948 if (opts.find("viewport") != opts.end())
2949 special << "viewport=" << opts["viewport"] << ',';
2950 if (opts.find("totalheight") != opts.end())
2951 special << "totalheight=" << opts["totalheight"] << ',';
2952 if (opts.find("type") != opts.end())
2953 special << "type=" << opts["type"] << ',';
2954 if (opts.find("ext") != opts.end())
2955 special << "ext=" << opts["ext"] << ',';
2956 if (opts.find("read") != opts.end())
2957 special << "read=" << opts["read"] << ',';
2958 if (opts.find("command") != opts.end())
2959 special << "command=" << opts["command"] << ',';
2960 string s_special = special.str();
2961 if (!s_special.empty()) {
2962 // We had special arguments. Remove the trailing ','.
2963 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2965 // TODO: Handle the unknown settings better.
2966 // Warn about invalid options.
2967 // Check whether some option was given twice.
2969 preamble.registerAutomaticallyLoadedPackage("graphicx");
2972 else if (t.cs() == "footnote" ||
2973 (t.cs() == "thanks" && context.layout->intitle)) {
2975 context.check_layout(os);
2976 begin_inset(os, "Foot\n");
2977 os << "status collapsed\n\n";
2978 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2982 else if (t.cs() == "marginpar") {
2984 context.check_layout(os);
2985 begin_inset(os, "Marginal\n");
2986 os << "status collapsed\n\n";
2987 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2991 else if (t.cs() == "lstinline") {
2993 parse_listings(p, os, context, true);
2996 else if (t.cs() == "ensuremath") {
2998 context.check_layout(os);
2999 string const s = p.verbatim_item();
3000 //FIXME: this never triggers in UTF8
3001 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3004 handle_ert(os, "\\ensuremath{" + s + "}",
3008 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3009 if (preamble.titleLayoutFound()) {
3011 skip_spaces_braces(p);
3013 handle_ert(os, t.asInput(), context);
3016 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3017 context.check_layout(os);
3018 begin_command_inset(os, "toc", t.cs());
3020 skip_spaces_braces(p);
3021 if (t.cs() == "lstlistoflistings")
3022 preamble.registerAutomaticallyLoadedPackage("listings");
3025 else if (t.cs() == "listoffigures") {
3026 context.check_layout(os);
3027 begin_inset(os, "FloatList figure\n");
3029 skip_spaces_braces(p);
3032 else if (t.cs() == "listoftables") {
3033 context.check_layout(os);
3034 begin_inset(os, "FloatList table\n");
3036 skip_spaces_braces(p);
3039 else if (t.cs() == "listof") {
3040 p.skip_spaces(true);
3041 string const name = p.get_token().cs();
3042 if (context.textclass.floats().typeExist(name)) {
3043 context.check_layout(os);
3044 begin_inset(os, "FloatList ");
3047 p.get_token(); // swallow second arg
3049 handle_ert(os, "\\listof{" + name + "}", context);
3052 else if ((where = is_known(t.cs(), known_text_font_families)))
3053 parse_text_attributes(p, os, FLAG_ITEM, outer,
3054 context, "\\family", context.font.family,
3055 known_coded_font_families[where - known_text_font_families]);
3057 else if ((where = is_known(t.cs(), known_text_font_series)))
3058 parse_text_attributes(p, os, FLAG_ITEM, outer,
3059 context, "\\series", context.font.series,
3060 known_coded_font_series[where - known_text_font_series]);
3062 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3063 parse_text_attributes(p, os, FLAG_ITEM, outer,
3064 context, "\\shape", context.font.shape,
3065 known_coded_font_shapes[where - known_text_font_shapes]);
3067 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3068 context.check_layout(os);
3069 TeXFont oldFont = context.font;
3070 context.font.init();
3071 context.font.size = oldFont.size;
3072 os << "\n\\family " << context.font.family << "\n";
3073 os << "\n\\series " << context.font.series << "\n";
3074 os << "\n\\shape " << context.font.shape << "\n";
3075 if (t.cs() == "textnormal") {
3076 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3077 output_font_change(os, context.font, oldFont);
3078 context.font = oldFont;
3080 eat_whitespace(p, os, context, false);
3083 else if (t.cs() == "textcolor") {
3084 // scheme is \textcolor{color name}{text}
3085 string const color = p.verbatim_item();
3086 // we only support the predefined colors of the color package
3087 if (color == "black" || color == "blue" || color == "cyan"
3088 || color == "green" || color == "magenta" || color == "red"
3089 || color == "white" || color == "yellow") {
3090 context.check_layout(os);
3091 os << "\n\\color " << color << "\n";
3092 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3093 context.check_layout(os);
3094 os << "\n\\color inherit\n";
3095 preamble.registerAutomaticallyLoadedPackage("color");
3097 // for custom defined colors
3098 handle_ert(os, t.asInput() + "{" + color + "}", context);
3101 else if (t.cs() == "underbar" || t.cs() == "uline") {
3102 // \underbar is not 100% correct (LyX outputs \uline
3103 // of ulem.sty). The difference is that \ulem allows
3104 // line breaks, and \underbar does not.
3105 // Do NOT handle \underline.
3106 // \underbar cuts through y, g, q, p etc.,
3107 // \underline does not.
3108 context.check_layout(os);
3109 os << "\n\\bar under\n";
3110 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3111 context.check_layout(os);
3112 os << "\n\\bar default\n";
3113 preamble.registerAutomaticallyLoadedPackage("ulem");
3116 else if (t.cs() == "sout") {
3117 context.check_layout(os);
3118 os << "\n\\strikeout on\n";
3119 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3120 context.check_layout(os);
3121 os << "\n\\strikeout default\n";
3122 preamble.registerAutomaticallyLoadedPackage("ulem");
3125 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3126 t.cs() == "emph" || t.cs() == "noun") {
3127 context.check_layout(os);
3128 os << "\n\\" << t.cs() << " on\n";
3129 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3130 context.check_layout(os);
3131 os << "\n\\" << t.cs() << " default\n";
3132 if (t.cs() == "uuline" || t.cs() == "uwave")
3133 preamble.registerAutomaticallyLoadedPackage("ulem");
3136 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3137 context.check_layout(os);
3138 string name = p.getArg('{', '}');
3139 string localtime = p.getArg('{', '}');
3140 preamble.registerAuthor(name);
3141 Author const & author = preamble.getAuthor(name);
3142 // from_ctime() will fail if LyX decides to output the
3143 // time in the text language. It might also use a wrong
3144 // time zone (if the original LyX document was exported
3145 // with a different time zone).
3146 time_t ptime = from_ctime(localtime);
3147 if (ptime == static_cast<time_t>(-1)) {
3148 cerr << "Warning: Could not parse time `" << localtime
3149 << "´ for change tracking, using current time instead.\n";
3150 ptime = current_time();
3152 if (t.cs() == "lyxadded")
3153 os << "\n\\change_inserted ";
3155 os << "\n\\change_deleted ";
3156 os << author.bufferId() << ' ' << ptime << '\n';
3157 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3158 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3159 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3160 LaTeXPackages::isAvailable("xcolor");
3161 // No need to test for luatex, since luatex comes in
3162 // two flavours (dvi and pdf), like latex, and those
3163 // are detected by pdflatex.
3164 if (pdflatex || xetex) {
3166 preamble.registerAutomaticallyLoadedPackage("ulem");
3167 preamble.registerAutomaticallyLoadedPackage("xcolor");
3168 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3172 preamble.registerAutomaticallyLoadedPackage("dvipost");
3173 } else if (xcolorulem) {
3174 preamble.registerAutomaticallyLoadedPackage("ulem");
3175 preamble.registerAutomaticallyLoadedPackage("xcolor");
3180 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3181 t.cs() == "vphantom") {
3182 context.check_layout(os);
3183 if (t.cs() == "phantom")
3184 begin_inset(os, "Phantom Phantom\n");
3185 if (t.cs() == "hphantom")
3186 begin_inset(os, "Phantom HPhantom\n");
3187 if (t.cs() == "vphantom")
3188 begin_inset(os, "Phantom VPhantom\n");
3189 os << "status open\n";
3190 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3195 else if (t.cs() == "href") {
3196 context.check_layout(os);
3197 string target = convert_command_inset_arg(p.verbatim_item());
3198 string name = convert_command_inset_arg(p.verbatim_item());
3200 size_t i = target.find(':');
3201 if (i != string::npos) {
3202 type = target.substr(0, i + 1);
3203 if (type == "mailto:" || type == "file:")
3204 target = target.substr(i + 1);
3205 // handle the case that name is equal to target, except of "http://"
3206 else if (target.substr(i + 3) == name && type == "http:")
3209 begin_command_inset(os, "href", "href");
3211 os << "name \"" << name << "\"\n";
3212 os << "target \"" << target << "\"\n";
3213 if (type == "mailto:" || type == "file:")
3214 os << "type \"" << type << "\"\n";
3216 skip_spaces_braces(p);
3219 else if (t.cs() == "lyxline") {
3220 // swallow size argument (it is not used anyway)
3222 if (!context.atParagraphStart()) {
3223 // so our line is in the middle of a paragraph
3224 // we need to add a new line, lest this line
3225 // follow the other content on that line and
3226 // run off the side of the page
3227 // FIXME: This may create an empty paragraph,
3228 // but without that it would not be
3229 // possible to set noindent below.
3230 // Fortunately LaTeX does not care
3231 // about the empty paragraph.
3232 context.new_paragraph(os);
3234 if (preamble.indentParagraphs()) {
3235 // we need to unindent, lest the line be too long
3236 context.add_par_extra_stuff("\\noindent\n");
3238 context.check_layout(os);
3239 begin_command_inset(os, "line", "rule");
3240 os << "offset \"0.5ex\"\n"
3241 "width \"100line%\"\n"
3246 else if (t.cs() == "rule") {
3247 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3248 string const width = p.getArg('{', '}');
3249 string const thickness = p.getArg('{', '}');
3250 context.check_layout(os);
3251 begin_command_inset(os, "line", "rule");
3252 if (!offset.empty())
3253 os << "offset \"" << translate_len(offset) << "\"\n";
3254 os << "width \"" << translate_len(width) << "\"\n"
3255 "height \"" << translate_len(thickness) << "\"\n";
3259 else if (is_known(t.cs(), known_phrases) ||
3260 (t.cs() == "protect" &&
3261 p.next_token().cat() == catEscape &&
3262 is_known(p.next_token().cs(), known_phrases))) {
3263 // LyX sometimes puts a \protect in front, so we have to ignore it
3264 // FIXME: This needs to be changed when bug 4752 is fixed.
3266 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3268 context.check_layout(os);
3269 os << known_coded_phrases[where - known_phrases];
3270 skip_spaces_braces(p);
3273 else if ((where = is_known(t.cs(), known_ref_commands))) {
3274 string const opt = p.getOpt();
3276 context.check_layout(os);
3277 begin_command_inset(os, "ref",
3278 known_coded_ref_commands[where - known_ref_commands]);
3279 os << "reference \""
3280 << convert_command_inset_arg(p.verbatim_item())
3283 if (t.cs() == "vref" || t.cs() == "vpageref")
3284 preamble.registerAutomaticallyLoadedPackage("varioref");
3287 // LyX does not support optional arguments of ref commands
3288 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3289 p.verbatim_item() + "}", context);
3293 else if (use_natbib &&
3294 is_known(t.cs(), known_natbib_commands) &&
3295 ((t.cs() != "citefullauthor" &&
3296 t.cs() != "citeyear" &&
3297 t.cs() != "citeyearpar") ||
3298 p.next_token().asInput() != "*")) {
3299 context.check_layout(os);
3300 string command = t.cs();
3301 if (p.next_token().asInput() == "*") {
3305 if (command == "citefullauthor")
3306 // alternative name for "\\citeauthor*"
3307 command = "citeauthor*";
3309 // text before the citation
3311 // text after the citation
3313 get_cite_arguments(p, true, before, after);
3315 if (command == "cite") {
3316 // \cite without optional argument means
3317 // \citet, \cite with at least one optional
3318 // argument means \citep.
3319 if (before.empty() && after.empty())
3324 if (before.empty() && after == "[]")
3325 // avoid \citet[]{a}
3327 else if (before == "[]" && after == "[]") {
3328 // avoid \citet[][]{a}
3332 // remove the brackets around after and before
3333 if (!after.empty()) {
3335 after.erase(after.length() - 1, 1);
3336 after = convert_command_inset_arg(after);
3338 if (!before.empty()) {
3340 before.erase(before.length() - 1, 1);
3341 before = convert_command_inset_arg(before);
3343 begin_command_inset(os, "citation", command);
3344 os << "after " << '"' << after << '"' << "\n";
3345 os << "before " << '"' << before << '"' << "\n";
3347 << convert_command_inset_arg(p.verbatim_item())
3352 else if (use_jurabib &&
3353 is_known(t.cs(), known_jurabib_commands) &&
3354 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3355 context.check_layout(os);
3356 string command = t.cs();
3357 if (p.next_token().asInput() == "*") {
3361 char argumentOrder = '\0';
3362 vector<string> const options =
3363 preamble.getPackageOptions("jurabib");
3364 if (find(options.begin(), options.end(),
3365 "natbiborder") != options.end())
3366 argumentOrder = 'n';
3367 else if (find(options.begin(), options.end(),
3368 "jurabiborder") != options.end())
3369 argumentOrder = 'j';
3371 // text before the citation
3373 // text after the citation
3375 get_cite_arguments(p, argumentOrder != 'j', before, after);
3377 string const citation = p.verbatim_item();
3378 if (!before.empty() && argumentOrder == '\0') {
3379 cerr << "Warning: Assuming argument order "
3380 "of jurabib version 0.6 for\n'"
3381 << command << before << after << '{'
3382 << citation << "}'.\n"
3383 "Add 'jurabiborder' to the jurabib "
3384 "package options if you used an\n"
3385 "earlier jurabib version." << endl;
3387 if (!after.empty()) {
3389 after.erase(after.length() - 1, 1);
3391 if (!before.empty()) {
3393 before.erase(before.length() - 1, 1);
3395 begin_command_inset(os, "citation", command);
3396 os << "after " << '"' << after << '"' << "\n";
3397 os << "before " << '"' << before << '"' << "\n";
3398 os << "key " << '"' << citation << '"' << "\n";
3402 else if (t.cs() == "cite"
3403 || t.cs() == "nocite") {
3404 context.check_layout(os);
3405 string after = convert_command_inset_arg(p.getArg('[', ']'));
3406 string key = convert_command_inset_arg(p.verbatim_item());
3407 // store the case that it is "\nocite{*}" to use it later for
3410 begin_command_inset(os, "citation", t.cs());
3411 os << "after " << '"' << after << '"' << "\n";
3412 os << "key " << '"' << key << '"' << "\n";
3414 } else if (t.cs() == "nocite")
3418 else if (t.cs() == "index" ||
3419 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3420 context.check_layout(os);
3421 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3422 p.getArg('[', ']') : "";
3423 string const kind = arg.empty() ? "idx" : arg;
3424 begin_inset(os, "Index ");
3425 os << kind << "\nstatus collapsed\n";
3426 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3429 preamble.registerAutomaticallyLoadedPackage("splitidx");
3432 else if (t.cs() == "nomenclature") {
3433 context.check_layout(os);
3434 begin_command_inset(os, "nomenclature", "nomenclature");
3435 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3436 if (!prefix.empty())
3437 os << "prefix " << '"' << prefix << '"' << "\n";
3438 os << "symbol " << '"'
3439 << convert_command_inset_arg(p.verbatim_item());
3440 os << "\"\ndescription \""
3441 << convert_command_inset_arg(p.verbatim_item())
3444 preamble.registerAutomaticallyLoadedPackage("nomencl");
3447 else if (t.cs() == "label") {
3448 context.check_layout(os);
3449 begin_command_inset(os, "label", "label");
3451 << convert_command_inset_arg(p.verbatim_item())
3456 else if (t.cs() == "printindex") {
3457 context.check_layout(os);
3458 begin_command_inset(os, "index_print", "printindex");
3459 os << "type \"idx\"\n";
3461 skip_spaces_braces(p);
3462 preamble.registerAutomaticallyLoadedPackage("makeidx");
3463 if (preamble.use_indices() == "true")
3464 preamble.registerAutomaticallyLoadedPackage("splitidx");
3467 else if (t.cs() == "printnomenclature") {
3469 string width_type = "";
3470 context.check_layout(os);
3471 begin_command_inset(os, "nomencl_print", "printnomenclature");
3472 // case of a custom width
3474 width = p.getArg('[', ']');
3475 width = translate_len(width);
3476 width_type = "custom";
3478 // case of no custom width
3479 // the case of no custom width but the width set
3480 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3481 // because the user could have set anything, not only the width
3482 // of the longest label (which would be width_type = "auto")
3483 string label = convert_command_inset_arg(p.getArg('{', '}'));
3484 if (label.empty() && width_type.empty())
3485 width_type = "none";
3486 os << "set_width \"" << width_type << "\"\n";
3487 if (width_type == "custom")
3488 os << "width \"" << width << '\"';
3490 skip_spaces_braces(p);
3491 preamble.registerAutomaticallyLoadedPackage("nomencl");
3494 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3495 context.check_layout(os);
3496 begin_inset(os, "script ");
3497 os << t.cs().substr(4) << '\n';
3498 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3500 if (t.cs() == "textsubscript")
3501 preamble.registerAutomaticallyLoadedPackage("subscript");
3504 else if ((where = is_known(t.cs(), known_quotes))) {
3505 context.check_layout(os);
3506 begin_inset(os, "Quotes ");
3507 os << known_coded_quotes[where - known_quotes];
3509 // LyX adds {} after the quote, so we have to eat
3510 // spaces here if there are any before a possible
3512 eat_whitespace(p, os, context, false);
3516 else if ((where = is_known(t.cs(), known_sizes)) &&
3517 context.new_layout_allowed) {
3518 context.check_layout(os);
3519 TeXFont const oldFont = context.font;
3520 context.font.size = known_coded_sizes[where - known_sizes];
3521 output_font_change(os, oldFont, context.font);
3522 eat_whitespace(p, os, context, false);
3525 else if ((where = is_known(t.cs(), known_font_families)) &&
3526 context.new_layout_allowed) {
3527 context.check_layout(os);
3528 TeXFont const oldFont = context.font;
3529 context.font.family =
3530 known_coded_font_families[where - known_font_families];
3531 output_font_change(os, oldFont, context.font);
3532 eat_whitespace(p, os, context, false);
3535 else if ((where = is_known(t.cs(), known_font_series)) &&
3536 context.new_layout_allowed) {
3537 context.check_layout(os);
3538 TeXFont const oldFont = context.font;
3539 context.font.series =
3540 known_coded_font_series[where - known_font_series];
3541 output_font_change(os, oldFont, context.font);
3542 eat_whitespace(p, os, context, false);
3545 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3546 context.new_layout_allowed) {
3547 context.check_layout(os);
3548 TeXFont const oldFont = context.font;
3549 context.font.shape =
3550 known_coded_font_shapes[where - known_font_shapes];
3551 output_font_change(os, oldFont, context.font);
3552 eat_whitespace(p, os, context, false);
3554 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3555 context.new_layout_allowed) {
3556 context.check_layout(os);
3557 TeXFont const oldFont = context.font;
3558 context.font.init();
3559 context.font.size = oldFont.size;
3560 context.font.family =
3561 known_coded_font_families[where - known_old_font_families];
3562 output_font_change(os, oldFont, context.font);
3563 eat_whitespace(p, os, context, false);
3566 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3567 context.new_layout_allowed) {
3568 context.check_layout(os);
3569 TeXFont const oldFont = context.font;
3570 context.font.init();
3571 context.font.size = oldFont.size;
3572 context.font.series =
3573 known_coded_font_series[where - known_old_font_series];
3574 output_font_change(os, oldFont, context.font);
3575 eat_whitespace(p, os, context, false);
3578 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3579 context.new_layout_allowed) {
3580 context.check_layout(os);
3581 TeXFont const oldFont = context.font;
3582 context.font.init();
3583 context.font.size = oldFont.size;
3584 context.font.shape =
3585 known_coded_font_shapes[where - known_old_font_shapes];
3586 output_font_change(os, oldFont, context.font);
3587 eat_whitespace(p, os, context, false);
3590 else if (t.cs() == "selectlanguage") {
3591 context.check_layout(os);
3592 // save the language for the case that a
3593 // \foreignlanguage is used
3594 context.font.language = babel2lyx(p.verbatim_item());
3595 os << "\n\\lang " << context.font.language << "\n";
3598 else if (t.cs() == "foreignlanguage") {
3599 string const lang = babel2lyx(p.verbatim_item());
3600 parse_text_attributes(p, os, FLAG_ITEM, outer,
3602 context.font.language, lang);
3605 else if (prefixIs(t.cs(), "text")
3606 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3607 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3609 // We have to output the whole command if it has an option
3610 // because LyX doesn't support this yet, see bug #8214,
3611 // only if there is a single option specifying a variant, we can handle it.
3613 string langopts = p.getOpt();
3614 // check if the option contains a variant, if yes, extract it
3615 string::size_type pos_var = langopts.find("variant");
3616 string::size_type i = langopts.find(',');
3617 string::size_type k = langopts.find('=', pos_var);
3618 if (pos_var != string::npos && i == string::npos) {
3620 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3621 lang = preamble.polyglossia2lyx(variant);
3622 parse_text_attributes(p, os, FLAG_ITEM, outer,
3624 context.font.language, lang);
3626 handle_ert(os, t.asInput() + langopts, context);
3628 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3629 parse_text_attributes(p, os, FLAG_ITEM, outer,
3631 context.font.language, lang);
3635 else if (t.cs() == "inputencoding") {
3636 // nothing to write here
3637 string const enc = subst(p.verbatim_item(), "\n", " ");
3641 else if ((where = is_known(t.cs(), known_special_chars))) {
3642 context.check_layout(os);
3643 os << "\\SpecialChar \\"
3644 << known_coded_special_chars[where - known_special_chars]
3646 skip_spaces_braces(p);
3649 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3650 context.check_layout(os);
3651 os << "\\SpecialChar \\nobreakdash-\n";
3655 else if (t.cs() == "textquotedbl") {
3656 context.check_layout(os);
3661 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3662 context.check_layout(os);
3663 os << "\\SpecialChar \\@.\n";
3667 else if (t.cs() == "-") {
3668 context.check_layout(os);
3669 os << "\\SpecialChar \\-\n";
3672 else if (t.cs() == "textasciitilde") {
3673 context.check_layout(os);
3675 skip_spaces_braces(p);
3678 else if (t.cs() == "textasciicircum") {
3679 context.check_layout(os);
3681 skip_spaces_braces(p);
3684 else if (t.cs() == "textbackslash") {
3685 context.check_layout(os);
3686 os << "\n\\backslash\n";
3687 skip_spaces_braces(p);
3690 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3691 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3693 context.check_layout(os);
3697 else if (t.cs() == "char") {
3698 context.check_layout(os);
3699 if (p.next_token().character() == '`') {
3701 if (p.next_token().cs() == "\"") {
3706 handle_ert(os, "\\char`", context);
3709 handle_ert(os, "\\char", context);
3713 else if (t.cs() == "verb") {
3714 context.check_layout(os);
3715 char const delimiter = p.next_token().character();
3716 // \verb is special: The usual escaping rules do not
3717 // apply, e.g. "\verb+\+" is valid and denotes a single
3718 // backslash (bug #4468). Therefore we do not allow
3719 // escaping in getArg().
3720 string const arg = p.getArg(delimiter, delimiter, false);
3722 oss << "\\verb" << delimiter << arg << delimiter;
3723 handle_ert(os, oss.str(), context);
3726 // Problem: \= creates a tabstop inside the tabbing environment
3727 // and else an accent. In the latter case we really would want
3728 // \={o} instead of \= o.
3729 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3730 handle_ert(os, t.asInput(), context);
3732 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3733 else if (t.cs().size() == 1
3734 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3735 context.check_layout(os);
3736 // try to see whether the string is in unicodesymbols
3739 string command = t.asInput() + "{"
3740 + trimSpaceAndEol(p.verbatim_item())
3743 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3744 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3745 termination, rem, &req);
3748 cerr << "When parsing " << command
3749 << ", result is " << to_utf8(s)
3750 << "+" << to_utf8(rem) << endl;
3752 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3753 preamble.registerAutomaticallyLoadedPackage(*it);
3755 // we did not find a non-ert version
3756 handle_ert(os, command, context);
3759 else if (t.cs() == "\\") {
3760 context.check_layout(os);
3762 handle_ert(os, "\\\\" + p.getOpt(), context);
3763 else if (p.next_token().asInput() == "*") {
3765 // getOpt() eats the following space if there
3766 // is no optional argument, but that is OK
3767 // here since it has no effect in the output.
3768 handle_ert(os, "\\\\*" + p.getOpt(), context);
3771 begin_inset(os, "Newline newline");
3776 else if (t.cs() == "newline" ||
3777 (t.cs() == "linebreak" && !p.hasOpt())) {
3778 context.check_layout(os);
3779 begin_inset(os, "Newline ");
3782 skip_spaces_braces(p);
3785 else if (t.cs() == "input" || t.cs() == "include"
3786 || t.cs() == "verbatiminput") {
3787 string name = t.cs();
3788 if (t.cs() == "verbatiminput"
3789 && p.next_token().asInput() == "*")
3790 name += p.get_token().asInput();
3791 context.check_layout(os);
3792 string filename(normalize_filename(p.getArg('{', '}')));
3793 string const path = getMasterFilePath(true);
3794 // We want to preserve relative / absolute filenames,
3795 // therefore path is only used for testing
3796 if ((t.cs() == "include" || t.cs() == "input") &&
3797 !makeAbsPath(filename, path).exists()) {
3798 // The file extension is probably missing.
3799 // Now try to find it out.
3800 string const tex_name =
3801 find_file(filename, path,
3802 known_tex_extensions);
3803 if (!tex_name.empty())
3804 filename = tex_name;
3806 bool external = false;
3808 if (makeAbsPath(filename, path).exists()) {
3809 string const abstexname =
3810 makeAbsPath(filename, path).absFileName();
3811 string const absfigname =
3812 changeExtension(abstexname, ".fig");
3813 fix_child_filename(filename);
3814 string const lyxname =
3815 changeExtension(filename, ".lyx");
3816 string const abslyxname = makeAbsPath(
3817 lyxname, getParentFilePath(false)).absFileName();
3819 external = FileName(absfigname).exists();
3820 if (t.cs() == "input") {
3821 string const ext = getExtension(abstexname);
3823 // Combined PS/LaTeX:
3824 // x.eps, x.pstex_t (old xfig)
3825 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3826 FileName const absepsname(
3827 changeExtension(abstexname, ".eps"));
3828 FileName const abspstexname(
3829 changeExtension(abstexname, ".pstex"));
3830 bool const xfigeps =
3831 (absepsname.exists() ||
3832 abspstexname.exists()) &&
3835 // Combined PDF/LaTeX:
3836 // x.pdf, x.pdftex_t (old xfig)
3837 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3838 FileName const abspdfname(
3839 changeExtension(abstexname, ".pdf"));
3840 bool const xfigpdf =
3841 abspdfname.exists() &&
3842 (ext == "pdftex_t" || ext == "pdf_t");
3846 // Combined PS/PDF/LaTeX:
3847 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3848 string const absbase2(
3849 removeExtension(abstexname) + "_pspdftex");
3850 FileName const abseps2name(
3851 addExtension(absbase2, ".eps"));
3852 FileName const abspdf2name(
3853 addExtension(absbase2, ".pdf"));
3854 bool const xfigboth =
3855 abspdf2name.exists() &&
3856 abseps2name.exists() && ext == "pspdftex";
3858 xfig = xfigpdf || xfigeps || xfigboth;
3859 external = external && xfig;
3862 outname = changeExtension(filename, ".fig");
3863 FileName abssrc(changeExtension(abstexname, ".fig"));
3864 copy_file(abssrc, outname);
3866 // Don't try to convert, the result
3867 // would be full of ERT.
3869 FileName abssrc(abstexname);
3870 copy_file(abssrc, outname);
3871 } else if (t.cs() != "verbatiminput" &&
3872 tex2lyx(abstexname, FileName(abslyxname),
3875 // no need to call copy_file
3876 // tex2lyx creates the file
3879 FileName abssrc(abstexname);
3880 copy_file(abssrc, outname);
3883 cerr << "Warning: Could not find included file '"
3884 << filename << "'." << endl;
3888 begin_inset(os, "External\n");
3889 os << "\ttemplate XFig\n"
3890 << "\tfilename " << outname << '\n';
3891 registerExternalTemplatePackages("XFig");
3893 begin_command_inset(os, "include", name);
3894 os << "preview false\n"
3895 "filename \"" << outname << "\"\n";
3896 if (t.cs() == "verbatiminput")
3897 preamble.registerAutomaticallyLoadedPackage("verbatim");
3902 else if (t.cs() == "bibliographystyle") {
3903 // store new bibliographystyle
3904 bibliographystyle = p.verbatim_item();
3905 // If any other command than \bibliography and
3906 // \nocite{*} follows, we need to output the style
3907 // (because it might be used by that command).
3908 // Otherwise, it will automatically be output by LyX.
3911 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3912 if (t2.cat() == catBegin)
3914 if (t2.cat() != catEscape)
3916 if (t2.cs() == "nocite") {
3917 if (p.getArg('{', '}') == "*")
3919 } else if (t2.cs() == "bibliography")
3926 "\\bibliographystyle{" + bibliographystyle + '}',
3931 else if (t.cs() == "bibliography") {
3932 context.check_layout(os);
3933 begin_command_inset(os, "bibtex", "bibtex");
3934 if (!btprint.empty()) {
3935 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3936 // clear the string because the next BibTeX inset can be without the
3937 // \nocite{*} option
3940 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3941 // Do we have a bibliographystyle set?
3942 if (!bibliographystyle.empty())
3943 os << "options " << '"' << bibliographystyle << '"' << "\n";
3947 else if (t.cs() == "parbox") {
3948 // Test whether this is an outer box of a shaded box
3950 // swallow arguments
3951 while (p.hasOpt()) {
3953 p.skip_spaces(true);
3956 p.skip_spaces(true);
3958 if (p.next_token().cat() == catBegin)
3960 p.skip_spaces(true);
3961 Token to = p.get_token();
3962 bool shaded = false;
3963 if (to.asInput() == "\\begin") {
3964 p.skip_spaces(true);
3965 if (p.getArg('{', '}') == "shaded")
3970 parse_outer_box(p, os, FLAG_ITEM, outer,
3971 context, "parbox", "shaded");
3973 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3977 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3978 t.cs() == "shadowbox" || t.cs() == "doublebox")
3979 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3981 else if (t.cs() == "framebox") {
3982 if (p.next_token().character() == '(') {
3983 //the syntax is: \framebox(x,y)[position]{content}
3984 string arg = t.asInput();
3985 arg += p.getFullParentheseArg();
3986 arg += p.getFullOpt();
3987 eat_whitespace(p, os, context, false);
3988 handle_ert(os, arg + '{', context);
3989 parse_text(p, os, FLAG_ITEM, outer, context);
3990 handle_ert(os, "}", context);
3992 string special = p.getFullOpt();
3993 special += p.getOpt();
3994 // LyX does not yet support \framebox without any option
3995 if (!special.empty())
3996 parse_outer_box(p, os, FLAG_ITEM, outer,
3997 context, t.cs(), special);
3999 eat_whitespace(p, os, context, false);
4000 handle_ert(os, "\\framebox{", context);
4001 parse_text(p, os, FLAG_ITEM, outer, context);
4002 handle_ert(os, "}", context);
4007 //\makebox() is part of the picture environment and different from \makebox{}
4008 //\makebox{} will be parsed by parse_box
4009 else if (t.cs() == "makebox") {
4010 if (p.next_token().character() == '(') {
4011 //the syntax is: \makebox(x,y)[position]{content}
4012 string arg = t.asInput();
4013 arg += p.getFullParentheseArg();
4014 arg += p.getFullOpt();
4015 eat_whitespace(p, os, context, false);
4016 handle_ert(os, arg + '{', context);
4017 parse_text(p, os, FLAG_ITEM, outer, context);
4018 handle_ert(os, "}", context);
4020 //the syntax is: \makebox[width][position]{content}
4021 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4025 else if (t.cs() == "smallskip" ||
4026 t.cs() == "medskip" ||
4027 t.cs() == "bigskip" ||
4028 t.cs() == "vfill") {
4029 context.check_layout(os);
4030 begin_inset(os, "VSpace ");
4033 skip_spaces_braces(p);
4036 else if ((where = is_known(t.cs(), known_spaces))) {
4037 context.check_layout(os);
4038 begin_inset(os, "space ");
4039 os << '\\' << known_coded_spaces[where - known_spaces]
4042 // LaTeX swallows whitespace after all spaces except
4043 // "\\,". We have to do that here, too, because LyX
4044 // adds "{}" which would make the spaces significant.
4046 eat_whitespace(p, os, context, false);
4047 // LyX adds "{}" after all spaces except "\\ " and
4048 // "\\,", so we have to remove "{}".
4049 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4050 // remove the braces after "\\,", too.
4055 else if (t.cs() == "newpage" ||
4056 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4057 t.cs() == "clearpage" ||
4058 t.cs() == "cleardoublepage") {
4059 context.check_layout(os);
4060 begin_inset(os, "Newpage ");
4063 skip_spaces_braces(p);
4066 else if (t.cs() == "DeclareRobustCommand" ||
4067 t.cs() == "DeclareRobustCommandx" ||
4068 t.cs() == "newcommand" ||
4069 t.cs() == "newcommandx" ||
4070 t.cs() == "providecommand" ||
4071 t.cs() == "providecommandx" ||
4072 t.cs() == "renewcommand" ||
4073 t.cs() == "renewcommandx") {
4074 // DeclareRobustCommand, DeclareRobustCommandx,
4075 // providecommand and providecommandx could be handled
4076 // by parse_command(), but we need to call
4077 // add_known_command() here.
4078 string name = t.asInput();
4079 if (p.next_token().asInput() == "*") {
4080 // Starred form. Eat '*'
4084 string const command = p.verbatim_item();
4085 string const opt1 = p.getFullOpt();
4086 string const opt2 = p.getFullOpt();
4087 add_known_command(command, opt1, !opt2.empty());
4088 string const ert = name + '{' + command + '}' +
4090 '{' + p.verbatim_item() + '}';
4092 if (t.cs() == "DeclareRobustCommand" ||
4093 t.cs() == "DeclareRobustCommandx" ||
4094 t.cs() == "providecommand" ||
4095 t.cs() == "providecommandx" ||
4096 name[name.length()-1] == '*')
4097 handle_ert(os, ert, context);
4099 context.check_layout(os);
4100 begin_inset(os, "FormulaMacro");
4106 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4107 // let could be handled by parse_command(),
4108 // but we need to call add_known_command() here.
4109 string ert = t.asInput();
4112 if (p.next_token().cat() == catBegin) {
4113 name = p.verbatim_item();
4114 ert += '{' + name + '}';
4116 name = p.verbatim_item();
4121 if (p.next_token().cat() == catBegin) {
4122 command = p.verbatim_item();
4123 ert += '{' + command + '}';
4125 command = p.verbatim_item();
4128 // If command is known, make name known too, to parse
4129 // its arguments correctly. For this reason we also
4130 // have commands in syntax.default that are hardcoded.
4131 CommandMap::iterator it = known_commands.find(command);
4132 if (it != known_commands.end())
4133 known_commands[t.asInput()] = it->second;
4134 handle_ert(os, ert, context);
4137 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4138 bool starred = false;
4139 if (p.next_token().asInput() == "*") {
4143 string name = t.asInput();
4144 string const length = p.verbatim_item();
4147 bool valid = splitLatexLength(length, valstring, unit);
4148 bool known_hspace = false;
4149 bool known_vspace = false;
4150 bool known_unit = false;
4153 istringstream iss(valstring);
4156 if (t.cs()[0] == 'h') {
4157 if (unit == "\\fill") {
4162 known_hspace = true;
4165 if (unit == "\\smallskipamount") {
4167 known_vspace = true;
4168 } else if (unit == "\\medskipamount") {
4170 known_vspace = true;
4171 } else if (unit == "\\bigskipamount") {
4173 known_vspace = true;
4174 } else if (unit == "\\fill") {
4176 known_vspace = true;
4180 if (!known_hspace && !known_vspace) {
4181 switch (unitFromString(unit)) {
4202 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4203 // Literal horizontal length or known variable
4204 context.check_layout(os);
4205 begin_inset(os, "space ");
4213 if (known_unit && !known_hspace)
4215 << translate_len(length);
4217 } else if (known_unit || known_vspace) {
4218 // Literal vertical length or known variable
4219 context.check_layout(os);
4220 begin_inset(os, "VSpace ");
4228 // LyX can't handle other length variables in Inset VSpace/space
4233 handle_ert(os, name + '{' + unit + '}', context);
4234 else if (value == -1.0)
4235 handle_ert(os, name + "{-" + unit + '}', context);
4237 handle_ert(os, name + '{' + valstring + unit + '}', context);
4239 handle_ert(os, name + '{' + length + '}', context);
4243 // The single '=' is meant here.
4244 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4246 context.check_layout(os);
4247 begin_inset(os, "Flex ");
4248 os << to_utf8(newinsetlayout->name()) << '\n'
4249 << "status collapsed\n";
4250 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4254 else if (t.cs() == "includepdf") {
4256 string const arg = p.getArg('[', ']');
4257 map<string, string> opts;
4258 vector<string> keys;
4259 split_map(arg, opts, keys);
4260 string name = normalize_filename(p.verbatim_item());
4261 string const path = getMasterFilePath(true);
4262 // We want to preserve relative / absolute filenames,
4263 // therefore path is only used for testing
4264 if (!makeAbsPath(name, path).exists()) {
4265 // The file extension is probably missing.
4266 // Now try to find it out.
4267 char const * const pdfpages_format[] = {"pdf", 0};
4268 string const pdftex_name =
4269 find_file(name, path, pdfpages_format);
4270 if (!pdftex_name.empty()) {
4275 FileName const absname = makeAbsPath(name, path);
4276 if (absname.exists())
4278 fix_child_filename(name);
4279 copy_file(absname, name);
4281 cerr << "Warning: Could not find file '"
4282 << name << "'." << endl;
4284 context.check_layout(os);
4285 begin_inset(os, "External\n\ttemplate ");
4286 os << "PDFPages\n\tfilename "
4288 // parse the options
4289 if (opts.find("pages") != opts.end())
4290 os << "\textra LaTeX \"pages="
4291 << opts["pages"] << "\"\n";
4292 if (opts.find("angle") != opts.end())
4293 os << "\trotateAngle "
4294 << opts["angle"] << '\n';
4295 if (opts.find("origin") != opts.end()) {
4297 string const opt = opts["origin"];
4298 if (opt == "tl") ss << "topleft";
4299 if (opt == "bl") ss << "bottomleft";
4300 if (opt == "Bl") ss << "baselineleft";
4301 if (opt == "c") ss << "center";
4302 if (opt == "tc") ss << "topcenter";
4303 if (opt == "bc") ss << "bottomcenter";
4304 if (opt == "Bc") ss << "baselinecenter";
4305 if (opt == "tr") ss << "topright";
4306 if (opt == "br") ss << "bottomright";
4307 if (opt == "Br") ss << "baselineright";
4308 if (!ss.str().empty())
4309 os << "\trotateOrigin " << ss.str() << '\n';
4311 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4313 if (opts.find("width") != opts.end())
4315 << translate_len(opts["width"]) << '\n';
4316 if (opts.find("height") != opts.end())
4318 << translate_len(opts["height"]) << '\n';
4319 if (opts.find("keepaspectratio") != opts.end())
4320 os << "\tkeepAspectRatio\n";
4322 context.check_layout(os);
4323 registerExternalTemplatePackages("PDFPages");
4326 else if (t.cs() == "loadgame") {
4328 string name = normalize_filename(p.verbatim_item());
4329 string const path = getMasterFilePath(true);
4330 // We want to preserve relative / absolute filenames,
4331 // therefore path is only used for testing
4332 if (!makeAbsPath(name, path).exists()) {
4333 // The file extension is probably missing.
4334 // Now try to find it out.
4335 char const * const lyxskak_format[] = {"fen", 0};
4336 string const lyxskak_name =
4337 find_file(name, path, lyxskak_format);
4338 if (!lyxskak_name.empty())
4339 name = lyxskak_name;
4341 FileName const absname = makeAbsPath(name, path);
4342 if (absname.exists())
4344 fix_child_filename(name);
4345 copy_file(absname, name);
4347 cerr << "Warning: Could not find file '"
4348 << name << "'." << endl;
4349 context.check_layout(os);
4350 begin_inset(os, "External\n\ttemplate ");
4351 os << "ChessDiagram\n\tfilename "
4354 context.check_layout(os);
4355 // after a \loadgame follows a \showboard
4356 if (p.get_token().asInput() == "showboard")
4358 registerExternalTemplatePackages("ChessDiagram");
4362 // try to see whether the string is in unicodesymbols
4363 // Only use text mode commands, since we are in text mode here,
4364 // and math commands may be invalid (bug 6797)
4368 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4369 Encodings::TEXT_CMD, termination, rem, &req);
4372 cerr << "When parsing " << t.cs()
4373 << ", result is " << to_utf8(s)
4374 << "+" << to_utf8(rem) << endl;
4375 context.check_layout(os);
4378 skip_spaces_braces(p);
4379 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4380 preamble.registerAutomaticallyLoadedPackage(*it);
4382 //cerr << "#: " << t << " mode: " << mode << endl;
4383 // heuristic: read up to next non-nested space
4385 string s = t.asInput();
4386 string z = p.verbatim_item();
4387 while (p.good() && z != " " && z.size()) {
4388 //cerr << "read: " << z << endl;
4390 z = p.verbatim_item();
4392 cerr << "found ERT: " << s << endl;
4393 handle_ert(os, s + ' ', context);
4396 string name = t.asInput();
4397 if (p.next_token().asInput() == "*") {
4398 // Starred commands like \vspace*{}
4399 p.get_token(); // Eat '*'
4402 if (!parse_command(name, p, os, outer, context))
4403 handle_ert(os, name, context);
4407 if (flags & FLAG_LEAVE) {
4408 flags &= ~FLAG_LEAVE;
4415 string guessLanguage(Parser & p, string const & lang)
4417 typedef std::map<std::string, size_t> LangMap;
4418 // map from language names to number of characters
4421 for (char const * const * i = supported_CJK_languages; *i; i++)
4422 used[string(*i)] = 0;
4425 Token const t = p.get_token();
4426 // comments are not counted for any language
4427 if (t.cat() == catComment)
4429 // commands are not counted as well, but we need to detect
4430 // \begin{CJK} and switch encoding if needed
4431 if (t.cat() == catEscape) {
4432 if (t.cs() == "inputencoding") {
4433 string const enc = subst(p.verbatim_item(), "\n", " ");
4437 if (t.cs() != "begin")
4440 // Non-CJK content is counted for lang.
4441 // We do not care about the real language here:
4442 // If we have more non-CJK contents than CJK contents,
4443 // we simply use the language that was specified as
4444 // babel main language.
4445 used[lang] += t.asInput().length();
4448 // Now we are starting an environment
4450 string const name = p.getArg('{', '}');
4451 if (name != "CJK") {
4455 // It is a CJK environment
4457 /* name = */ p.getArg('{', '}');
4458 string const encoding = p.getArg('{', '}');
4459 /* mapping = */ p.getArg('{', '}');
4460 string const encoding_old = p.getEncoding();
4461 char const * const * const where =
4462 is_known(encoding, supported_CJK_encodings);
4464 p.setEncoding(encoding);
4466 p.setEncoding("utf8");
4467 string const text = p.verbatimEnvironment("CJK");
4468 p.setEncoding(encoding_old);
4471 // ignore contents in unknown CJK encoding
4474 // the language of the text
4476 supported_CJK_languages[where - supported_CJK_encodings];
4477 used[cjk] += text.length();
4479 LangMap::const_iterator use = used.begin();
4480 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4481 if (it->second > use->second)