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';
1159 os << "inline true\n";
1161 os << "inline false\n";
1162 os << "status collapsed\n";
1163 Context context(true, parent_context.textclass);
1164 context.layout = &parent_context.textclass.plainLayout();
1167 s = p.plainCommand('!', '!', "lstinline");
1168 context.new_paragraph(os);
1169 context.check_layout(os);
1171 s = p.plainEnvironment("lstlisting");
1172 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1174 os << "\n\\backslash\n";
1175 else if (*it == '\n') {
1176 // avoid adding an empty paragraph at the end
1178 context.new_paragraph(os);
1179 context.check_layout(os);
1184 context.check_end_layout(os);
1189 /// parse an unknown environment
1190 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1191 unsigned flags, bool outer,
1192 Context & parent_context)
1194 if (name == "tabbing")
1195 // We need to remember that we have to handle '\=' specially
1196 flags |= FLAG_TABBING;
1198 // We need to translate font changes and paragraphs inside the
1199 // environment to ERT if we have a non standard font.
1200 // Otherwise things like
1201 // \large\begin{foo}\huge bar\end{foo}
1203 bool const specialfont =
1204 (parent_context.font != parent_context.normalfont);
1205 bool const new_layout_allowed = parent_context.new_layout_allowed;
1207 parent_context.new_layout_allowed = false;
1208 handle_ert(os, "\\begin{" + name + "}", parent_context);
1209 parse_text_snippet(p, os, flags, outer, parent_context);
1210 handle_ert(os, "\\end{" + name + "}", parent_context);
1212 parent_context.new_layout_allowed = new_layout_allowed;
1216 void parse_environment(Parser & p, ostream & os, bool outer,
1217 string & last_env, Context & parent_context)
1219 Layout const * newlayout;
1220 InsetLayout const * newinsetlayout = 0;
1221 string const name = p.getArg('{', '}');
1222 const bool is_starred = suffixIs(name, '*');
1223 string const unstarred_name = rtrim(name, "*");
1224 active_environments.push_back(name);
1226 if (is_math_env(name)) {
1227 parent_context.check_layout(os);
1228 begin_inset(os, "Formula ");
1229 os << "\\begin{" << name << "}";
1230 parse_math(p, os, FLAG_END, MATH_MODE);
1231 os << "\\end{" << name << "}";
1233 if (is_display_math_env(name)) {
1234 // Prevent the conversion of a line break to a space
1235 // (bug 7668). This does not change the output, but
1236 // looks ugly in LyX.
1237 eat_whitespace(p, os, parent_context, false);
1241 else if (is_known(name, preamble.polyglossia_languages)) {
1242 // We must begin a new paragraph if not already done
1243 if (! parent_context.atParagraphStart()) {
1244 parent_context.check_end_layout(os);
1245 parent_context.new_paragraph(os);
1247 // save the language in the context so that it is
1248 // handled by parse_text
1249 parent_context.font.language = preamble.polyglossia2lyx(name);
1250 parse_text(p, os, FLAG_END, outer, parent_context);
1251 // Just in case the environment is empty
1252 parent_context.extra_stuff.erase();
1253 // We must begin a new paragraph to reset the language
1254 parent_context.new_paragraph(os);
1258 else if (unstarred_name == "tabular" || name == "longtable") {
1259 eat_whitespace(p, os, parent_context, false);
1260 string width = "0pt";
1261 if (name == "tabular*") {
1262 width = lyx::translate_len(p.getArg('{', '}'));
1263 eat_whitespace(p, os, parent_context, false);
1265 parent_context.check_layout(os);
1266 begin_inset(os, "Tabular ");
1267 handle_tabular(p, os, name, width, parent_context);
1272 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1273 eat_whitespace(p, os, parent_context, false);
1274 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1275 eat_whitespace(p, os, parent_context, false);
1276 parent_context.check_layout(os);
1277 begin_inset(os, "Float " + unstarred_name + "\n");
1278 // store the float type for subfloats
1279 // subfloats only work with figures and tables
1280 if (unstarred_name == "figure")
1281 float_type = unstarred_name;
1282 else if (unstarred_name == "table")
1283 float_type = unstarred_name;
1287 os << "placement " << opt << '\n';
1288 if (contains(opt, "H"))
1289 preamble.registerAutomaticallyLoadedPackage("float");
1291 Floating const & fl = parent_context.textclass.floats()
1292 .getType(unstarred_name);
1293 if (!fl.floattype().empty() && fl.usesFloatPkg())
1294 preamble.registerAutomaticallyLoadedPackage("float");
1297 os << "wide " << convert<string>(is_starred)
1298 << "\nsideways false"
1299 << "\nstatus open\n\n";
1300 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1302 // We don't need really a new paragraph, but
1303 // we must make sure that the next item gets a \begin_layout.
1304 parent_context.new_paragraph(os);
1306 // the float is parsed thus delete the type
1310 else if (unstarred_name == "sidewaysfigure"
1311 || unstarred_name == "sidewaystable") {
1312 eat_whitespace(p, os, parent_context, false);
1313 parent_context.check_layout(os);
1314 if (unstarred_name == "sidewaysfigure")
1315 begin_inset(os, "Float figure\n");
1317 begin_inset(os, "Float table\n");
1318 os << "wide " << convert<string>(is_starred)
1319 << "\nsideways true"
1320 << "\nstatus open\n\n";
1321 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1323 // We don't need really a new paragraph, but
1324 // we must make sure that the next item gets a \begin_layout.
1325 parent_context.new_paragraph(os);
1327 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1330 else if (name == "wrapfigure" || name == "wraptable") {
1331 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1332 eat_whitespace(p, os, parent_context, false);
1333 parent_context.check_layout(os);
1336 string overhang = "0col%";
1339 lines = p.getArg('[', ']');
1340 string const placement = p.getArg('{', '}');
1342 overhang = p.getArg('[', ']');
1343 string const width = p.getArg('{', '}');
1345 if (name == "wrapfigure")
1346 begin_inset(os, "Wrap figure\n");
1348 begin_inset(os, "Wrap table\n");
1349 os << "lines " << lines
1350 << "\nplacement " << placement
1351 << "\noverhang " << lyx::translate_len(overhang)
1352 << "\nwidth " << lyx::translate_len(width)
1353 << "\nstatus open\n\n";
1354 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1356 // We don't need really a new paragraph, but
1357 // we must make sure that the next item gets a \begin_layout.
1358 parent_context.new_paragraph(os);
1360 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1363 else if (name == "minipage") {
1364 eat_whitespace(p, os, parent_context, false);
1365 // Test whether this is an outer box of a shaded box
1367 // swallow arguments
1368 while (p.hasOpt()) {
1370 p.skip_spaces(true);
1373 p.skip_spaces(true);
1374 Token t = p.get_token();
1375 bool shaded = false;
1376 if (t.asInput() == "\\begin") {
1377 p.skip_spaces(true);
1378 if (p.getArg('{', '}') == "shaded")
1383 parse_outer_box(p, os, FLAG_END, outer,
1384 parent_context, name, "shaded");
1386 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1391 else if (name == "comment") {
1392 eat_whitespace(p, os, parent_context, false);
1393 parent_context.check_layout(os);
1394 begin_inset(os, "Note Comment\n");
1395 os << "status open\n";
1396 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1399 skip_braces(p); // eat {} that might by set by LyX behind comments
1400 preamble.registerAutomaticallyLoadedPackage("verbatim");
1403 else if (name == "verbatim") {
1404 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1405 string const s = p.plainEnvironment("verbatim");
1406 string::const_iterator it2 = s.begin();
1407 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1409 os << "\\backslash ";
1410 else if (*it == '\n') {
1412 // avoid adding an empty paragraph at the end
1413 // FIXME: if there are 2 consecutive spaces at the end ignore it
1414 // because LyX will re-add a \n
1415 // This hack must be removed once bug 8049 is fixed!
1416 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1417 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1421 os << "\n\\end_layout\n\n";
1423 // reset to Standard layout
1424 os << "\n\\begin_layout Standard\n";
1427 else if (name == "CJK") {
1428 // the scheme is \begin{CJK}{encoding}{mapping}{text}
1429 // It is impossible to decide if a CJK environment was in its own paragraph or within
1430 // a line. We therefore always assume a paragraph since the latter is a rare case.
1431 eat_whitespace(p, os, parent_context, false);
1432 parent_context.check_end_layout(os);
1433 // store the encoding to be able to reset it
1434 string const encoding_old = p.getEncoding();
1435 string const encoding = p.getArg('{', '}');
1436 // SJIS and Bg5 cannot be handled by iconv
1437 // JIS does not work with LyX's encoding conversion
1438 if (encoding != "Bg5" && encoding != "JIS" && encoding != "SJIS")
1439 p.setEncoding(encoding);
1441 p.setEncoding("utf8");
1442 // LyX doesn't support the second argument so if
1443 // this is used we need to output everything as ERT
1444 string const mapping = p.getArg('{', '}');
1445 char const * const * const where =
1446 is_known(encoding, supported_CJK_encodings);
1447 if ((!mapping.empty() && mapping != " ") || !where) {
1448 parent_context.check_layout(os);
1449 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1451 // we must parse the content as verbatim because e.g. JIS can contain
1452 // normally invalid characters
1453 string const s = p.plainEnvironment("CJK");
1454 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1456 handle_ert(os, "\\", parent_context);
1457 else if (*it == '$')
1458 handle_ert(os, "$", parent_context);
1462 handle_ert(os, "\\end{" + name + "}",
1466 supported_CJK_languages[where - supported_CJK_encodings];
1467 // store the language because we must reset it at the end
1468 string const lang_old = parent_context.font.language;
1469 parent_context.font.language = lang;
1470 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1471 parent_context.font.language = lang_old;
1472 parent_context.new_paragraph(os);
1474 p.setEncoding(encoding_old);
1478 else if (name == "lyxgreyedout") {
1479 eat_whitespace(p, os, parent_context, false);
1480 parent_context.check_layout(os);
1481 begin_inset(os, "Note Greyedout\n");
1482 os << "status open\n";
1483 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1486 if (!preamble.notefontcolor().empty())
1487 preamble.registerAutomaticallyLoadedPackage("color");
1490 else if (name == "framed" || name == "shaded") {
1491 eat_whitespace(p, os, parent_context, false);
1492 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1496 else if (name == "lstlisting") {
1497 eat_whitespace(p, os, parent_context, false);
1498 // FIXME handle the automatic color package loading
1499 // uwestoehr asks: In what case color is loaded?
1500 parse_listings(p, os, parent_context, false);
1504 else if (!parent_context.new_layout_allowed)
1505 parse_unknown_environment(p, name, os, FLAG_END, outer,
1508 // Alignment and spacing settings
1509 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1510 // therefore are totally broken!
1511 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1512 // they are commands not environments. They are furthermore switches that
1513 // can be ended by another switches, but also by commands like \footnote or
1514 // \parbox. So the only safe way is to leave them untouched.
1515 else if (name == "center" || name == "centering" ||
1516 name == "flushleft" || name == "flushright" ||
1517 name == "singlespace" || name == "onehalfspace" ||
1518 name == "doublespace" || name == "spacing") {
1519 eat_whitespace(p, os, parent_context, false);
1520 // We must begin a new paragraph if not already done
1521 if (! parent_context.atParagraphStart()) {
1522 parent_context.check_end_layout(os);
1523 parent_context.new_paragraph(os);
1525 if (name == "flushleft")
1526 parent_context.add_extra_stuff("\\align left\n");
1527 else if (name == "flushright")
1528 parent_context.add_extra_stuff("\\align right\n");
1529 else if (name == "center" || name == "centering")
1530 parent_context.add_extra_stuff("\\align center\n");
1531 else if (name == "singlespace")
1532 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1533 else if (name == "onehalfspace") {
1534 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1535 preamble.registerAutomaticallyLoadedPackage("setspace");
1536 } else if (name == "doublespace") {
1537 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1538 preamble.registerAutomaticallyLoadedPackage("setspace");
1539 } else if (name == "spacing") {
1540 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1541 preamble.registerAutomaticallyLoadedPackage("setspace");
1543 parse_text(p, os, FLAG_END, outer, parent_context);
1544 // Just in case the environment is empty
1545 parent_context.extra_stuff.erase();
1546 // We must begin a new paragraph to reset the alignment
1547 parent_context.new_paragraph(os);
1551 // The single '=' is meant here.
1552 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1553 eat_whitespace(p, os, parent_context, false);
1554 Context context(true, parent_context.textclass, newlayout,
1555 parent_context.layout, parent_context.font);
1556 if (parent_context.deeper_paragraph) {
1557 // We are beginning a nested environment after a
1558 // deeper paragraph inside the outer list environment.
1559 // Therefore we don't need to output a "begin deeper".
1560 context.need_end_deeper = true;
1562 parent_context.check_end_layout(os);
1563 if (last_env == name) {
1564 // we need to output a separator since LyX would export
1565 // the two environments as one otherwise (bug 5716)
1566 docstring const sep = from_ascii("--Separator--");
1567 TeX2LyXDocClass const & textclass(parent_context.textclass);
1568 if (textclass.hasLayout(sep)) {
1569 Context newcontext(parent_context);
1570 newcontext.layout = &(textclass[sep]);
1571 newcontext.check_layout(os);
1572 newcontext.check_end_layout(os);
1574 parent_context.check_layout(os);
1575 begin_inset(os, "Note Note\n");
1576 os << "status closed\n";
1577 Context newcontext(true, textclass,
1578 &(textclass.defaultLayout()));
1579 newcontext.check_layout(os);
1580 newcontext.check_end_layout(os);
1582 parent_context.check_end_layout(os);
1585 switch (context.layout->latextype) {
1586 case LATEX_LIST_ENVIRONMENT:
1587 context.add_par_extra_stuff("\\labelwidthstring "
1588 + p.verbatim_item() + '\n');
1591 case LATEX_BIB_ENVIRONMENT:
1592 p.verbatim_item(); // swallow next arg
1598 context.check_deeper(os);
1599 // handle known optional and required arguments
1600 // layouts require all optional arguments before the required ones
1601 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1602 // It is impossible to place anything after the environment name,
1603 // but before the first \\item.
1604 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1605 bool need_layout = true;
1606 unsigned int optargs = 0;
1607 while (optargs < context.layout->optargs) {
1608 eat_whitespace(p, os, context, false);
1609 if (p.next_token().cat() == catEscape ||
1610 p.next_token().character() != '[')
1612 p.get_token(); // eat '['
1614 context.check_layout(os);
1615 need_layout = false;
1617 begin_inset(os, "Argument\n");
1618 os << "status collapsed\n\n";
1619 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1621 eat_whitespace(p, os, context, false);
1624 unsigned int reqargs = 0;
1625 while (reqargs < context.layout->reqargs) {
1626 eat_whitespace(p, os, context, false);
1627 if (p.next_token().cat() != catBegin)
1629 p.get_token(); // eat '{'
1631 context.check_layout(os);
1632 need_layout = false;
1634 begin_inset(os, "Argument\n");
1635 os << "status collapsed\n\n";
1636 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1638 eat_whitespace(p, os, context, false);
1642 parse_text(p, os, FLAG_END, outer, context);
1643 context.check_end_layout(os);
1644 if (parent_context.deeper_paragraph) {
1645 // We must suppress the "end deeper" because we
1646 // suppressed the "begin deeper" above.
1647 context.need_end_deeper = false;
1649 context.check_end_deeper(os);
1650 parent_context.new_paragraph(os);
1652 if (!preamble.titleLayoutFound())
1653 preamble.titleLayoutFound(newlayout->intitle);
1654 set<string> const & req = newlayout->requires();
1655 set<string>::const_iterator it = req.begin();
1656 set<string>::const_iterator en = req.end();
1657 for (; it != en; ++it)
1658 preamble.registerAutomaticallyLoadedPackage(*it);
1661 // The single '=' is meant here.
1662 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1663 eat_whitespace(p, os, parent_context, false);
1664 parent_context.check_layout(os);
1665 begin_inset(os, "Flex ");
1666 os << to_utf8(newinsetlayout->name()) << '\n'
1667 << "status collapsed\n";
1668 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1672 else if (name == "appendix") {
1673 // This is no good latex style, but it works and is used in some documents...
1674 eat_whitespace(p, os, parent_context, false);
1675 parent_context.check_end_layout(os);
1676 Context context(true, parent_context.textclass, parent_context.layout,
1677 parent_context.layout, parent_context.font);
1678 context.check_layout(os);
1679 os << "\\start_of_appendix\n";
1680 parse_text(p, os, FLAG_END, outer, context);
1681 context.check_end_layout(os);
1685 else if (known_environments.find(name) != known_environments.end()) {
1686 vector<ArgumentType> arguments = known_environments[name];
1687 // The last "argument" denotes wether we may translate the
1688 // environment contents to LyX
1689 // The default required if no argument is given makes us
1690 // compatible with the reLyXre environment.
1691 ArgumentType contents = arguments.empty() ?
1694 if (!arguments.empty())
1695 arguments.pop_back();
1696 // See comment in parse_unknown_environment()
1697 bool const specialfont =
1698 (parent_context.font != parent_context.normalfont);
1699 bool const new_layout_allowed =
1700 parent_context.new_layout_allowed;
1702 parent_context.new_layout_allowed = false;
1703 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1704 outer, parent_context);
1705 if (contents == verbatim)
1706 handle_ert(os, p.verbatimEnvironment(name),
1709 parse_text_snippet(p, os, FLAG_END, outer,
1711 handle_ert(os, "\\end{" + name + "}", parent_context);
1713 parent_context.new_layout_allowed = new_layout_allowed;
1717 parse_unknown_environment(p, name, os, FLAG_END, outer,
1721 active_environments.pop_back();
1725 /// parses a comment and outputs it to \p os.
1726 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1728 LASSERT(t.cat() == catComment, return);
1729 if (!t.cs().empty()) {
1730 context.check_layout(os);
1731 handle_comment(os, '%' + t.cs(), context);
1732 if (p.next_token().cat() == catNewline) {
1733 // A newline after a comment line starts a new
1735 if (context.new_layout_allowed) {
1736 if(!context.atParagraphStart())
1737 // Only start a new paragraph if not already
1738 // done (we might get called recursively)
1739 context.new_paragraph(os);
1741 handle_ert(os, "\n", context);
1742 eat_whitespace(p, os, context, true);
1745 // "%\n" combination
1752 * Reads spaces and comments until the first non-space, non-comment token.
1753 * New paragraphs (double newlines or \\par) are handled like simple spaces
1754 * if \p eatParagraph is true.
1755 * Spaces are skipped, but comments are written to \p os.
1757 void eat_whitespace(Parser & p, ostream & os, Context & context,
1761 Token const & t = p.get_token();
1762 if (t.cat() == catComment)
1763 parse_comment(p, os, t, context);
1764 else if ((! eatParagraph && p.isParagraph()) ||
1765 (t.cat() != catSpace && t.cat() != catNewline)) {
1774 * Set a font attribute, parse text and reset the font attribute.
1775 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1776 * \param currentvalue Current value of the attribute. Is set to the new
1777 * value during parsing.
1778 * \param newvalue New value of the attribute
1780 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1781 Context & context, string const & attribute,
1782 string & currentvalue, string const & newvalue)
1784 context.check_layout(os);
1785 string const oldvalue = currentvalue;
1786 currentvalue = newvalue;
1787 os << '\n' << attribute << ' ' << newvalue << "\n";
1788 parse_text_snippet(p, os, flags, outer, context);
1789 context.check_layout(os);
1790 os << '\n' << attribute << ' ' << oldvalue << "\n";
1791 currentvalue = oldvalue;
1795 /// get the arguments of a natbib or jurabib citation command
1796 void get_cite_arguments(Parser & p, bool natbibOrder,
1797 string & before, string & after)
1799 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1801 // text before the citation
1803 // text after the citation
1804 after = p.getFullOpt();
1806 if (!after.empty()) {
1807 before = p.getFullOpt();
1808 if (natbibOrder && !before.empty())
1809 swap(before, after);
1814 /// Convert filenames with TeX macros and/or quotes to something LyX
1816 string const normalize_filename(string const & name)
1818 Parser p(trim(name, "\""));
1821 Token const & t = p.get_token();
1822 if (t.cat() != catEscape)
1824 else if (t.cs() == "lyxdot") {
1825 // This is used by LyX for simple dots in relative
1829 } else if (t.cs() == "space") {
1839 /// Convert \p name from TeX convention (relative to master file) to LyX
1840 /// convention (relative to .lyx file) if it is relative
1841 void fix_child_filename(string & name)
1843 string const absMasterTeX = getMasterFilePath(true);
1844 bool const isabs = FileName::isAbsolute(name);
1845 // convert from "relative to .tex master" to absolute original path
1847 name = makeAbsPath(name, absMasterTeX).absFileName();
1848 bool copyfile = copyFiles();
1849 string const absParentLyX = getParentFilePath(false);
1852 // convert from absolute original path to "relative to master file"
1853 string const rel = to_utf8(makeRelPath(from_utf8(name),
1854 from_utf8(absMasterTeX)));
1855 // re-interpret "relative to .tex file" as "relative to .lyx file"
1856 // (is different if the master .lyx file resides in a
1857 // different path than the master .tex file)
1858 string const absMasterLyX = getMasterFilePath(false);
1859 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1860 // Do not copy if the new path is impossible to create. Example:
1861 // absMasterTeX = "/foo/bar/"
1862 // absMasterLyX = "/bar/"
1863 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1864 if (contains(name, "/../"))
1871 // convert from absolute original path to
1872 // "relative to .lyx file"
1873 name = to_utf8(makeRelPath(from_utf8(abs),
1874 from_utf8(absParentLyX)));
1878 // convert from absolute original path to "relative to .lyx file"
1879 name = to_utf8(makeRelPath(from_utf8(name),
1880 from_utf8(absParentLyX)));
1885 void copy_file(FileName const & src, string dstname)
1889 string const absParent = getParentFilePath(false);
1891 if (FileName::isAbsolute(dstname))
1892 dst = FileName(dstname);
1894 dst = makeAbsPath(dstname, absParent);
1895 string const absMaster = getMasterFilePath(false);
1896 FileName const srcpath = src.onlyPath();
1897 FileName const dstpath = dst.onlyPath();
1898 if (equivalent(srcpath, dstpath))
1900 if (!dstpath.isDirectory()) {
1901 if (!dstpath.createPath()) {
1902 cerr << "Warning: Could not create directory for file `"
1903 << dst.absFileName() << "´." << endl;
1907 if (dst.isReadableFile()) {
1908 if (overwriteFiles())
1909 cerr << "Warning: Overwriting existing file `"
1910 << dst.absFileName() << "´." << endl;
1912 cerr << "Warning: Not overwriting existing file `"
1913 << dst.absFileName() << "´." << endl;
1917 if (!src.copyTo(dst))
1918 cerr << "Warning: Could not copy file `" << src.absFileName()
1919 << "´ to `" << dst.absFileName() << "´." << endl;
1923 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1924 void parse_noweb(Parser & p, ostream & os, Context & context)
1926 // assemble the rest of the keyword
1930 Token const & t = p.get_token();
1931 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1934 scrap = (p.good() && p.next_token().asInput() == "=");
1936 name += p.get_token().asInput();
1939 name += t.asInput();
1942 if (!scrap || !context.new_layout_allowed ||
1943 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1944 cerr << "Warning: Could not interpret '" << name
1945 << "'. Ignoring it." << endl;
1949 // We use new_paragraph instead of check_end_layout because the stuff
1950 // following the noweb chunk needs to start with a \begin_layout.
1951 // This may create a new paragraph even if there was none in the
1952 // noweb file, but the alternative is an invalid LyX file. Since
1953 // noweb code chunks are implemented with a layout style in LyX they
1954 // always must be in an own paragraph.
1955 context.new_paragraph(os);
1956 Context newcontext(true, context.textclass,
1957 &context.textclass[from_ascii("Scrap")]);
1958 newcontext.check_layout(os);
1961 Token const & t = p.get_token();
1962 // We abuse the parser a bit, because this is no TeX syntax
1964 if (t.cat() == catEscape)
1965 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1968 Context tmp(false, context.textclass,
1969 &context.textclass[from_ascii("Scrap")]);
1970 tmp.need_end_layout = true;
1971 tmp.check_layout(oss);
1972 os << subst(t.asInput(), "\n", oss.str());
1974 // The scrap chunk is ended by an @ at the beginning of a line.
1975 // After the @ the line may contain a comment and/or
1976 // whitespace, but nothing else.
1977 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1978 (p.next_token().cat() == catSpace ||
1979 p.next_token().cat() == catNewline ||
1980 p.next_token().cat() == catComment)) {
1981 while (p.good() && p.next_token().cat() == catSpace)
1982 os << p.get_token().asInput();
1983 if (p.next_token().cat() == catComment)
1984 // The comment includes a final '\n'
1985 os << p.get_token().asInput();
1987 if (p.next_token().cat() == catNewline)
1994 newcontext.check_end_layout(os);
1998 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1999 bool is_macro(Parser & p)
2001 Token first = p.curr_token();
2002 if (first.cat() != catEscape || !p.good())
2004 if (first.cs() == "def")
2006 if (first.cs() != "global" && first.cs() != "long")
2008 Token second = p.get_token();
2010 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2011 second.cat() == catNewline || second.cat() == catComment)) {
2012 second = p.get_token();
2015 bool secondvalid = second.cat() == catEscape;
2017 bool thirdvalid = false;
2018 if (p.good() && first.cs() == "global" && secondvalid &&
2019 second.cs() == "long") {
2020 third = p.get_token();
2022 while (p.good() && !p.isParagraph() &&
2023 (third.cat() == catSpace ||
2024 third.cat() == catNewline ||
2025 third.cat() == catComment)) {
2026 third = p.get_token();
2029 thirdvalid = third.cat() == catEscape;
2031 for (int i = 0; i < pos; ++i)
2036 return (first.cs() == "global" || first.cs() == "long") &&
2037 second.cs() == "def";
2038 return first.cs() == "global" && second.cs() == "long" &&
2039 third.cs() == "def";
2043 /// Parse a macro definition (assumes that is_macro() returned true)
2044 void parse_macro(Parser & p, ostream & os, Context & context)
2046 context.check_layout(os);
2047 Token first = p.curr_token();
2050 string command = first.asInput();
2051 if (first.cs() != "def") {
2053 eat_whitespace(p, os, context, false);
2054 second = p.curr_token();
2055 command += second.asInput();
2056 if (second.cs() != "def") {
2058 eat_whitespace(p, os, context, false);
2059 third = p.curr_token();
2060 command += third.asInput();
2063 eat_whitespace(p, os, context, false);
2064 string const name = p.get_token().cs();
2065 eat_whitespace(p, os, context, false);
2071 while (p.next_token().cat() != catBegin) {
2072 if (p.next_token().cat() == catParameter) {
2077 // followed by number?
2078 if (p.next_token().cat() == catOther) {
2079 char c = p.getChar();
2081 // number = current arity + 1?
2082 if (c == arity + '0' + 1)
2087 paramtext += p.get_token().cs();
2089 paramtext += p.get_token().cs();
2094 // only output simple (i.e. compatible) macro as FormulaMacros
2095 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2097 context.check_layout(os);
2098 begin_inset(os, "FormulaMacro");
2099 os << "\n\\def" << ert;
2102 handle_ert(os, command + ert, context);
2106 void registerExternalTemplatePackages(string const & name)
2108 external::TemplateManager const & etm = external::TemplateManager::get();
2109 external::Template const * const et = etm.getTemplateByName(name);
2112 external::Template::Formats::const_iterator cit = et->formats.end();
2114 cit = et->formats.find("PDFLaTeX");
2115 if (cit == et->formats.end())
2116 // If the template has not specified a PDFLaTeX output,
2117 // we try the LaTeX format.
2118 cit = et->formats.find("LaTeX");
2119 if (cit == et->formats.end())
2121 vector<string>::const_iterator qit = cit->second.requirements.begin();
2122 vector<string>::const_iterator qend = cit->second.requirements.end();
2123 for (; qit != qend; ++qit)
2124 preamble.registerAutomaticallyLoadedPackage(*qit);
2127 } // anonymous namespace
2130 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2133 Layout const * newlayout = 0;
2134 InsetLayout const * newinsetlayout = 0;
2135 char const * const * where = 0;
2136 // Store the latest bibliographystyle and nocite{*} option
2137 // (needed for bibtex inset)
2139 string bibliographystyle = "default";
2140 bool const use_natbib = preamble.isPackageUsed("natbib");
2141 bool const use_jurabib = preamble.isPackageUsed("jurabib");
2144 Token const & t = p.get_token();
2146 // it is impossible to determine the correct encoding for non-CJK Japanese.
2147 // Therefore write a note at the beginning of the document
2148 if (is_nonCJKJapanese) {
2149 context.check_layout(os);
2150 begin_inset(os, "Note Note\n");
2151 os << "status open\n\\begin_layout Plain Layout\n"
2152 << "\\series bold\n"
2153 << "Important information:\n"
2154 << "\\end_layout\n\n"
2155 << "\\begin_layout Plain Layout\n"
2156 << "This document is in Japanese (non-CJK).\n"
2157 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2158 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2159 << " encoding in the document settings.\n"
2160 << "\\end_layout\n";
2162 is_nonCJKJapanese = false;
2166 debugToken(cerr, t, flags);
2169 if (flags & FLAG_ITEM) {
2170 if (t.cat() == catSpace)
2173 flags &= ~FLAG_ITEM;
2174 if (t.cat() == catBegin) {
2175 // skip the brace and collect everything to the next matching
2177 flags |= FLAG_BRACE_LAST;
2181 // handle only this single token, leave the loop if done
2182 flags |= FLAG_LEAVE;
2185 if (t.cat() != catEscape && t.character() == ']' &&
2186 (flags & FLAG_BRACK_LAST))
2188 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2191 // If there is anything between \end{env} and \begin{env} we
2192 // don't need to output a separator.
2193 if (t.cat() != catSpace && t.cat() != catNewline &&
2194 t.asInput() != "\\begin")
2200 if (t.cat() == catMath) {
2201 // we are inside some text mode thingy, so opening new math is allowed
2202 context.check_layout(os);
2203 begin_inset(os, "Formula ");
2204 Token const & n = p.get_token();
2205 bool const display(n.cat() == catMath && outer);
2207 // TeX's $$...$$ syntax for displayed math
2209 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2211 p.get_token(); // skip the second '$' token
2213 // simple $...$ stuff
2216 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2221 // Prevent the conversion of a line break to a
2222 // space (bug 7668). This does not change the
2223 // output, but looks ugly in LyX.
2224 eat_whitespace(p, os, context, false);
2228 else if (t.cat() == catSuper || t.cat() == catSub)
2229 cerr << "catcode " << t << " illegal in text mode\n";
2231 // Basic support for english quotes. This should be
2232 // extended to other quotes, but is not so easy (a
2233 // left english quote is the same as a right german
2235 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2236 context.check_layout(os);
2237 begin_inset(os, "Quotes ");
2243 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2244 context.check_layout(os);
2245 begin_inset(os, "Quotes ");
2252 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2253 context.check_layout(os);
2254 begin_inset(os, "Quotes ");
2261 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2262 context.check_layout(os);
2263 begin_inset(os, "Quotes ");
2270 else if (t.asInput() == "<"
2271 && p.next_token().asInput() == "<" && noweb_mode) {
2273 parse_noweb(p, os, context);
2276 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2277 check_space(p, os, context);
2279 else if (t.character() == '[' && noweb_mode &&
2280 p.next_token().character() == '[') {
2281 // These can contain underscores
2283 string const s = p.getFullOpt() + ']';
2284 if (p.next_token().character() == ']')
2287 cerr << "Warning: Inserting missing ']' in '"
2288 << s << "'." << endl;
2289 handle_ert(os, s, context);
2292 else if (t.cat() == catLetter) {
2293 context.check_layout(os);
2294 // Workaround for bug 4752.
2295 // FIXME: This whole code block needs to be removed
2296 // when the bug is fixed and tex2lyx produces
2297 // the updated file format.
2298 // The replacement algorithm in LyX is so stupid that
2299 // it even translates a phrase if it is part of a word.
2300 bool handled = false;
2301 for (int const * l = known_phrase_lengths; *l; ++l) {
2302 string phrase = t.cs();
2303 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2304 phrase += p.get_token().cs();
2305 if (is_known(phrase, known_coded_phrases)) {
2306 handle_ert(os, phrase, context);
2310 for (size_t i = 1; i < phrase.length(); ++i)
2318 else if (t.cat() == catOther ||
2319 t.cat() == catAlign ||
2320 t.cat() == catParameter) {
2321 // This translates "&" to "\\&" which may be wrong...
2322 context.check_layout(os);
2326 else if (p.isParagraph()) {
2327 if (context.new_layout_allowed)
2328 context.new_paragraph(os);
2330 handle_ert(os, "\\par ", context);
2331 eat_whitespace(p, os, context, true);
2334 else if (t.cat() == catActive) {
2335 context.check_layout(os);
2336 if (t.character() == '~') {
2337 if (context.layout->free_spacing)
2340 begin_inset(os, "space ~\n");
2347 else if (t.cat() == catBegin) {
2348 Token const next = p.next_token();
2349 Token const end = p.next_next_token();
2350 if (next.cat() == catEnd) {
2352 Token const prev = p.prev_token();
2354 if (p.next_token().character() == '`' ||
2355 (prev.character() == '-' &&
2356 p.next_token().character() == '-'))
2357 ; // ignore it in {}`` or -{}-
2359 handle_ert(os, "{}", context);
2360 } else if (next.cat() == catEscape &&
2361 is_known(next.cs(), known_quotes) &&
2362 end.cat() == catEnd) {
2363 // Something like {\textquoteright} (e.g.
2364 // from writer2latex). LyX writes
2365 // \textquoteright{}, so we may skip the
2366 // braces here for better readability.
2367 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2370 context.check_layout(os);
2371 // special handling of font attribute changes
2372 Token const prev = p.prev_token();
2373 TeXFont const oldFont = context.font;
2374 if (next.character() == '[' ||
2375 next.character() == ']' ||
2376 next.character() == '*') {
2378 if (p.next_token().cat() == catEnd) {
2383 handle_ert(os, "{", context);
2384 parse_text_snippet(p, os,
2387 handle_ert(os, "}", context);
2389 } else if (! context.new_layout_allowed) {
2390 handle_ert(os, "{", context);
2391 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2393 handle_ert(os, "}", context);
2394 } else if (is_known(next.cs(), known_sizes)) {
2395 // next will change the size, so we must
2397 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2399 if (!context.atParagraphStart())
2401 << context.font.size << "\n";
2402 } else if (is_known(next.cs(), known_font_families)) {
2403 // next will change the font family, so we
2404 // must reset it here
2405 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2407 if (!context.atParagraphStart())
2409 << context.font.family << "\n";
2410 } else if (is_known(next.cs(), known_font_series)) {
2411 // next will change the font series, so we
2412 // must reset it here
2413 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2415 if (!context.atParagraphStart())
2417 << context.font.series << "\n";
2418 } else if (is_known(next.cs(), known_font_shapes)) {
2419 // next will change the font shape, so we
2420 // must reset it here
2421 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2423 if (!context.atParagraphStart())
2425 << context.font.shape << "\n";
2426 } else if (is_known(next.cs(), known_old_font_families) ||
2427 is_known(next.cs(), known_old_font_series) ||
2428 is_known(next.cs(), known_old_font_shapes)) {
2429 // next will change the font family, series
2430 // and shape, so we must reset it here
2431 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2433 if (!context.atParagraphStart())
2435 << context.font.family
2437 << context.font.series
2439 << context.font.shape << "\n";
2441 handle_ert(os, "{", context);
2442 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2444 handle_ert(os, "}", context);
2449 else if (t.cat() == catEnd) {
2450 if (flags & FLAG_BRACE_LAST) {
2453 cerr << "stray '}' in text\n";
2454 handle_ert(os, "}", context);
2457 else if (t.cat() == catComment)
2458 parse_comment(p, os, t, context);
2461 // control sequences
2464 else if (t.cs() == "(") {
2465 context.check_layout(os);
2466 begin_inset(os, "Formula");
2468 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2473 else if (t.cs() == "[") {
2474 context.check_layout(os);
2475 begin_inset(os, "Formula");
2477 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2480 // Prevent the conversion of a line break to a space
2481 // (bug 7668). This does not change the output, but
2482 // looks ugly in LyX.
2483 eat_whitespace(p, os, context, false);
2486 else if (t.cs() == "begin")
2487 parse_environment(p, os, outer, last_env,
2490 else if (t.cs() == "end") {
2491 if (flags & FLAG_END) {
2492 // eat environment name
2493 string const name = p.getArg('{', '}');
2494 if (name != active_environment())
2495 cerr << "\\end{" + name + "} does not match \\begin{"
2496 + active_environment() + "}\n";
2499 p.error("found 'end' unexpectedly");
2502 else if (t.cs() == "item") {
2504 bool const optarg = p.hasOpt();
2506 // FIXME: This swallows comments, but we cannot use
2507 // eat_whitespace() since we must not output
2508 // anything before the item.
2509 p.skip_spaces(true);
2510 s = p.verbatimOption();
2512 p.skip_spaces(false);
2514 context.check_layout(os);
2515 if (context.has_item) {
2516 // An item in an unknown list-like environment
2517 // FIXME: Do this in check_layout()!
2518 context.has_item = false;
2520 handle_ert(os, "\\item", context);
2522 handle_ert(os, "\\item ", context);
2525 if (context.layout->labeltype != LABEL_MANUAL) {
2526 // LyX does not support \item[\mybullet]
2527 // in itemize environments
2529 os << parse_text_snippet(p2,
2530 FLAG_BRACK_LAST, outer, context);
2531 } else if (!s.empty()) {
2532 // LyX adds braces around the argument,
2533 // so we need to remove them here.
2534 if (s.size() > 2 && s[0] == '{' &&
2535 s[s.size()-1] == '}')
2536 s = s.substr(1, s.size()-2);
2537 // If the argument contains a space we
2538 // must put it into ERT: Otherwise LyX
2539 // would misinterpret the space as
2540 // item delimiter (bug 7663)
2541 if (contains(s, ' ')) {
2542 handle_ert(os, s, context);
2545 os << parse_text_snippet(p2,
2549 // The space is needed to separate the
2550 // item from the rest of the sentence.
2552 eat_whitespace(p, os, context, false);
2557 else if (t.cs() == "bibitem") {
2559 context.check_layout(os);
2560 eat_whitespace(p, os, context, false);
2561 string label = convert_command_inset_arg(p.verbatimOption());
2562 string key = convert_command_inset_arg(p.verbatim_item());
2563 if (contains(label, '\\') || contains(key, '\\')) {
2564 // LyX can't handle LaTeX commands in labels or keys
2565 handle_ert(os, t.asInput() + '[' + label +
2566 "]{" + p.verbatim_item() + '}',
2569 begin_command_inset(os, "bibitem", "bibitem");
2570 os << "label \"" << label << "\"\n"
2571 "key \"" << key << "\"\n";
2576 else if (is_macro(p)) {
2577 // catch the case of \def\inputGnumericTable
2579 if (t.cs() == "def") {
2580 Token second = p.next_token();
2581 if (second.cs() == "inputGnumericTable") {
2585 Token third = p.get_token();
2587 if (third.cs() == "input") {
2591 string name = normalize_filename(p.verbatim_item());
2592 string const path = getMasterFilePath(true);
2593 // We want to preserve relative / absolute filenames,
2594 // therefore path is only used for testing
2595 // The file extension is in every case ".tex".
2596 // So we need to remove this extension and check for
2597 // the original one.
2598 name = removeExtension(name);
2599 if (!makeAbsPath(name, path).exists()) {
2600 char const * const Gnumeric_formats[] = {"gnumeric",
2602 string const Gnumeric_name =
2603 find_file(name, path, Gnumeric_formats);
2604 if (!Gnumeric_name.empty())
2605 name = Gnumeric_name;
2607 FileName const absname = makeAbsPath(name, path);
2608 if (absname.exists()) {
2609 fix_child_filename(name);
2610 copy_file(absname, name);
2612 cerr << "Warning: Could not find file '"
2613 << name << "'." << endl;
2614 context.check_layout(os);
2615 begin_inset(os, "External\n\ttemplate ");
2616 os << "GnumericSpreadsheet\n\tfilename "
2619 context.check_layout(os);
2621 // register the packages that are automatically loaded
2622 // by the Gnumeric template
2623 registerExternalTemplatePackages("GnumericSpreadsheet");
2628 parse_macro(p, os, context);
2631 else if (t.cs() == "noindent") {
2633 context.add_par_extra_stuff("\\noindent\n");
2636 else if (t.cs() == "appendix") {
2637 context.add_par_extra_stuff("\\start_of_appendix\n");
2638 // We need to start a new paragraph. Otherwise the
2639 // appendix in 'bla\appendix\chapter{' would start
2641 context.new_paragraph(os);
2642 // We need to make sure that the paragraph is
2643 // generated even if it is empty. Otherwise the
2644 // appendix in '\par\appendix\par\chapter{' would
2646 context.check_layout(os);
2647 // FIXME: This is a hack to prevent paragraph
2648 // deletion if it is empty. Handle this better!
2650 "%dummy comment inserted by tex2lyx to "
2651 "ensure that this paragraph is not empty",
2653 // Both measures above may generate an additional
2654 // empty paragraph, but that does not hurt, because
2655 // whitespace does not matter here.
2656 eat_whitespace(p, os, context, true);
2659 // Must catch empty dates before findLayout is called below
2660 else if (t.cs() == "date") {
2661 eat_whitespace(p, os, context, false);
2663 string const date = p.verbatim_item();
2666 preamble.suppressDate(true);
2669 preamble.suppressDate(false);
2670 if (context.new_layout_allowed &&
2671 (newlayout = findLayout(context.textclass,
2674 output_command_layout(os, p, outer,
2675 context, newlayout);
2676 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2677 if (!preamble.titleLayoutFound())
2678 preamble.titleLayoutFound(newlayout->intitle);
2679 set<string> const & req = newlayout->requires();
2680 set<string>::const_iterator it = req.begin();
2681 set<string>::const_iterator en = req.end();
2682 for (; it != en; ++it)
2683 preamble.registerAutomaticallyLoadedPackage(*it);
2686 "\\date{" + p.verbatim_item() + '}',
2691 // Starred section headings
2692 // Must attempt to parse "Section*" before "Section".
2693 else if ((p.next_token().asInput() == "*") &&
2694 context.new_layout_allowed &&
2695 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2698 output_command_layout(os, p, outer, context, newlayout);
2700 if (!preamble.titleLayoutFound())
2701 preamble.titleLayoutFound(newlayout->intitle);
2702 set<string> const & req = newlayout->requires();
2703 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2704 preamble.registerAutomaticallyLoadedPackage(*it);
2707 // Section headings and the like
2708 else if (context.new_layout_allowed &&
2709 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2711 output_command_layout(os, p, outer, context, newlayout);
2713 if (!preamble.titleLayoutFound())
2714 preamble.titleLayoutFound(newlayout->intitle);
2715 set<string> const & req = newlayout->requires();
2716 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2717 preamble.registerAutomaticallyLoadedPackage(*it);
2720 else if (t.cs() == "caption") {
2722 context.check_layout(os);
2724 begin_inset(os, "Caption\n");
2725 Context newcontext(true, context.textclass, 0, 0, context.font);
2726 newcontext.check_layout(os);
2727 if (p.next_token().cat() != catEscape &&
2728 p.next_token().character() == '[') {
2729 p.get_token(); // eat '['
2730 begin_inset(os, "Argument\n");
2731 os << "status collapsed\n";
2732 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2734 eat_whitespace(p, os, context, false);
2736 parse_text(p, os, FLAG_ITEM, outer, context);
2737 context.check_end_layout(os);
2738 // We don't need really a new paragraph, but
2739 // we must make sure that the next item gets a \begin_layout.
2740 context.new_paragraph(os);
2743 newcontext.check_end_layout(os);
2746 else if (t.cs() == "subfloat") {
2747 // the syntax is \subfloat[caption]{content}
2748 // if it is a table of figure depends on the surrounding float
2749 bool has_caption = false;
2751 // do nothing if there is no outer float
2752 if (!float_type.empty()) {
2753 context.check_layout(os);
2755 begin_inset(os, "Float " + float_type + "\n");
2757 << "\nsideways false"
2758 << "\nstatus collapsed\n\n";
2761 if (p.next_token().cat() != catEscape &&
2762 p.next_token().character() == '[') {
2763 p.get_token(); // eat '['
2764 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2768 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2769 // the caption comes always as the last
2771 // we must make sure that the caption gets a \begin_layout
2772 os << "\n\\begin_layout Plain Layout";
2774 begin_inset(os, "Caption\n");
2775 Context newcontext(true, context.textclass,
2776 0, 0, context.font);
2777 newcontext.check_layout(os);
2778 os << caption << "\n";
2779 newcontext.check_end_layout(os);
2780 // We don't need really a new paragraph, but
2781 // we must make sure that the next item gets a \begin_layout.
2782 //newcontext.new_paragraph(os);
2786 // We don't need really a new paragraph, but
2787 // we must make sure that the next item gets a \begin_layout.
2789 context.new_paragraph(os);
2792 context.check_end_layout(os);
2793 // close the layout we opened
2795 os << "\n\\end_layout\n";
2797 // if the float type is not supported or there is no surrounding float
2800 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2801 handle_ert(os, t.asInput() + '[' + opt_arg +
2802 "]{" + p.verbatim_item() + '}', context);
2804 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2808 else if (t.cs() == "includegraphics") {
2809 bool const clip = p.next_token().asInput() == "*";
2812 string const arg = p.getArg('[', ']');
2813 map<string, string> opts;
2814 vector<string> keys;
2815 split_map(arg, opts, keys);
2817 opts["clip"] = string();
2818 string name = normalize_filename(p.verbatim_item());
2820 string const path = getMasterFilePath(true);
2821 // We want to preserve relative / absolute filenames,
2822 // therefore path is only used for testing
2823 if (!makeAbsPath(name, path).exists()) {
2824 // The file extension is probably missing.
2825 // Now try to find it out.
2826 string const dvips_name =
2827 find_file(name, path,
2828 known_dvips_graphics_formats);
2829 string const pdftex_name =
2830 find_file(name, path,
2831 known_pdftex_graphics_formats);
2832 if (!dvips_name.empty()) {
2833 if (!pdftex_name.empty()) {
2834 cerr << "This file contains the "
2836 "\"\\includegraphics{"
2838 "However, files\n\""
2839 << dvips_name << "\" and\n\""
2840 << pdftex_name << "\"\n"
2841 "both exist, so I had to make a "
2842 "choice and took the first one.\n"
2843 "Please move the unwanted one "
2844 "someplace else and try again\n"
2845 "if my choice was wrong."
2849 } else if (!pdftex_name.empty()) {
2855 FileName const absname = makeAbsPath(name, path);
2856 if (absname.exists()) {
2857 fix_child_filename(name);
2858 copy_file(absname, name);
2860 cerr << "Warning: Could not find graphics file '"
2861 << name << "'." << endl;
2863 context.check_layout(os);
2864 begin_inset(os, "Graphics ");
2865 os << "\n\tfilename " << name << '\n';
2866 if (opts.find("width") != opts.end())
2868 << translate_len(opts["width"]) << '\n';
2869 if (opts.find("height") != opts.end())
2871 << translate_len(opts["height"]) << '\n';
2872 if (opts.find("scale") != opts.end()) {
2873 istringstream iss(opts["scale"]);
2877 os << "\tscale " << val << '\n';
2879 if (opts.find("angle") != opts.end()) {
2880 os << "\trotateAngle "
2881 << opts["angle"] << '\n';
2882 vector<string>::const_iterator a =
2883 find(keys.begin(), keys.end(), "angle");
2884 vector<string>::const_iterator s =
2885 find(keys.begin(), keys.end(), "width");
2886 if (s == keys.end())
2887 s = find(keys.begin(), keys.end(), "height");
2888 if (s == keys.end())
2889 s = find(keys.begin(), keys.end(), "scale");
2890 if (s != keys.end() && distance(s, a) > 0)
2891 os << "\tscaleBeforeRotation\n";
2893 if (opts.find("origin") != opts.end()) {
2895 string const opt = opts["origin"];
2896 if (opt.find('l') != string::npos) ss << "left";
2897 if (opt.find('r') != string::npos) ss << "right";
2898 if (opt.find('c') != string::npos) ss << "center";
2899 if (opt.find('t') != string::npos) ss << "Top";
2900 if (opt.find('b') != string::npos) ss << "Bottom";
2901 if (opt.find('B') != string::npos) ss << "Baseline";
2902 if (!ss.str().empty())
2903 os << "\trotateOrigin " << ss.str() << '\n';
2905 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2907 if (opts.find("keepaspectratio") != opts.end())
2908 os << "\tkeepAspectRatio\n";
2909 if (opts.find("clip") != opts.end())
2911 if (opts.find("draft") != opts.end())
2913 if (opts.find("bb") != opts.end())
2914 os << "\tBoundingBox "
2915 << opts["bb"] << '\n';
2916 int numberOfbbOptions = 0;
2917 if (opts.find("bbllx") != opts.end())
2918 numberOfbbOptions++;
2919 if (opts.find("bblly") != opts.end())
2920 numberOfbbOptions++;
2921 if (opts.find("bburx") != opts.end())
2922 numberOfbbOptions++;
2923 if (opts.find("bbury") != opts.end())
2924 numberOfbbOptions++;
2925 if (numberOfbbOptions == 4)
2926 os << "\tBoundingBox "
2927 << opts["bbllx"] << " " << opts["bblly"] << " "
2928 << opts["bburx"] << " " << opts["bbury"] << '\n';
2929 else if (numberOfbbOptions > 0)
2930 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2931 numberOfbbOptions = 0;
2932 if (opts.find("natwidth") != opts.end())
2933 numberOfbbOptions++;
2934 if (opts.find("natheight") != opts.end())
2935 numberOfbbOptions++;
2936 if (numberOfbbOptions == 2)
2937 os << "\tBoundingBox 0bp 0bp "
2938 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2939 else if (numberOfbbOptions > 0)
2940 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2941 ostringstream special;
2942 if (opts.find("hiresbb") != opts.end())
2943 special << "hiresbb,";
2944 if (opts.find("trim") != opts.end())
2946 if (opts.find("viewport") != opts.end())
2947 special << "viewport=" << opts["viewport"] << ',';
2948 if (opts.find("totalheight") != opts.end())
2949 special << "totalheight=" << opts["totalheight"] << ',';
2950 if (opts.find("type") != opts.end())
2951 special << "type=" << opts["type"] << ',';
2952 if (opts.find("ext") != opts.end())
2953 special << "ext=" << opts["ext"] << ',';
2954 if (opts.find("read") != opts.end())
2955 special << "read=" << opts["read"] << ',';
2956 if (opts.find("command") != opts.end())
2957 special << "command=" << opts["command"] << ',';
2958 string s_special = special.str();
2959 if (!s_special.empty()) {
2960 // We had special arguments. Remove the trailing ','.
2961 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2963 // TODO: Handle the unknown settings better.
2964 // Warn about invalid options.
2965 // Check whether some option was given twice.
2967 preamble.registerAutomaticallyLoadedPackage("graphicx");
2970 else if (t.cs() == "footnote" ||
2971 (t.cs() == "thanks" && context.layout->intitle)) {
2973 context.check_layout(os);
2974 begin_inset(os, "Foot\n");
2975 os << "status collapsed\n\n";
2976 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2980 else if (t.cs() == "marginpar") {
2982 context.check_layout(os);
2983 begin_inset(os, "Marginal\n");
2984 os << "status collapsed\n\n";
2985 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2989 else if (t.cs() == "lstinline") {
2991 parse_listings(p, os, context, true);
2994 else if (t.cs() == "ensuremath") {
2996 context.check_layout(os);
2997 string const s = p.verbatim_item();
2998 //FIXME: this never triggers in UTF8
2999 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3002 handle_ert(os, "\\ensuremath{" + s + "}",
3006 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3007 if (preamble.titleLayoutFound()) {
3009 skip_spaces_braces(p);
3011 handle_ert(os, t.asInput(), context);
3014 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3015 context.check_layout(os);
3016 begin_command_inset(os, "toc", t.cs());
3018 skip_spaces_braces(p);
3019 if (t.cs() == "lstlistoflistings")
3020 preamble.registerAutomaticallyLoadedPackage("listings");
3023 else if (t.cs() == "listoffigures") {
3024 context.check_layout(os);
3025 begin_inset(os, "FloatList figure\n");
3027 skip_spaces_braces(p);
3030 else if (t.cs() == "listoftables") {
3031 context.check_layout(os);
3032 begin_inset(os, "FloatList table\n");
3034 skip_spaces_braces(p);
3037 else if (t.cs() == "listof") {
3038 p.skip_spaces(true);
3039 string const name = p.get_token().cs();
3040 if (context.textclass.floats().typeExist(name)) {
3041 context.check_layout(os);
3042 begin_inset(os, "FloatList ");
3045 p.get_token(); // swallow second arg
3047 handle_ert(os, "\\listof{" + name + "}", context);
3050 else if ((where = is_known(t.cs(), known_text_font_families)))
3051 parse_text_attributes(p, os, FLAG_ITEM, outer,
3052 context, "\\family", context.font.family,
3053 known_coded_font_families[where - known_text_font_families]);
3055 else if ((where = is_known(t.cs(), known_text_font_series)))
3056 parse_text_attributes(p, os, FLAG_ITEM, outer,
3057 context, "\\series", context.font.series,
3058 known_coded_font_series[where - known_text_font_series]);
3060 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3061 parse_text_attributes(p, os, FLAG_ITEM, outer,
3062 context, "\\shape", context.font.shape,
3063 known_coded_font_shapes[where - known_text_font_shapes]);
3065 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3066 context.check_layout(os);
3067 TeXFont oldFont = context.font;
3068 context.font.init();
3069 context.font.size = oldFont.size;
3070 os << "\n\\family " << context.font.family << "\n";
3071 os << "\n\\series " << context.font.series << "\n";
3072 os << "\n\\shape " << context.font.shape << "\n";
3073 if (t.cs() == "textnormal") {
3074 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3075 output_font_change(os, context.font, oldFont);
3076 context.font = oldFont;
3078 eat_whitespace(p, os, context, false);
3081 else if (t.cs() == "textcolor") {
3082 // scheme is \textcolor{color name}{text}
3083 string const color = p.verbatim_item();
3084 // we only support the predefined colors of the color package
3085 if (color == "black" || color == "blue" || color == "cyan"
3086 || color == "green" || color == "magenta" || color == "red"
3087 || color == "white" || color == "yellow") {
3088 context.check_layout(os);
3089 os << "\n\\color " << color << "\n";
3090 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3091 context.check_layout(os);
3092 os << "\n\\color inherit\n";
3093 preamble.registerAutomaticallyLoadedPackage("color");
3095 // for custom defined colors
3096 handle_ert(os, t.asInput() + "{" + color + "}", context);
3099 else if (t.cs() == "underbar" || t.cs() == "uline") {
3100 // \underbar is not 100% correct (LyX outputs \uline
3101 // of ulem.sty). The difference is that \ulem allows
3102 // line breaks, and \underbar does not.
3103 // Do NOT handle \underline.
3104 // \underbar cuts through y, g, q, p etc.,
3105 // \underline does not.
3106 context.check_layout(os);
3107 os << "\n\\bar under\n";
3108 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3109 context.check_layout(os);
3110 os << "\n\\bar default\n";
3111 preamble.registerAutomaticallyLoadedPackage("ulem");
3114 else if (t.cs() == "sout") {
3115 context.check_layout(os);
3116 os << "\n\\strikeout on\n";
3117 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3118 context.check_layout(os);
3119 os << "\n\\strikeout default\n";
3120 preamble.registerAutomaticallyLoadedPackage("ulem");
3123 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3124 t.cs() == "emph" || t.cs() == "noun") {
3125 context.check_layout(os);
3126 os << "\n\\" << t.cs() << " on\n";
3127 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3128 context.check_layout(os);
3129 os << "\n\\" << t.cs() << " default\n";
3130 if (t.cs() == "uuline" || t.cs() == "uwave")
3131 preamble.registerAutomaticallyLoadedPackage("ulem");
3134 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3135 context.check_layout(os);
3136 string name = p.getArg('{', '}');
3137 string localtime = p.getArg('{', '}');
3138 preamble.registerAuthor(name);
3139 Author const & author = preamble.getAuthor(name);
3140 // from_ctime() will fail if LyX decides to output the
3141 // time in the text language. It might also use a wrong
3142 // time zone (if the original LyX document was exported
3143 // with a different time zone).
3144 time_t ptime = from_ctime(localtime);
3145 if (ptime == static_cast<time_t>(-1)) {
3146 cerr << "Warning: Could not parse time `" << localtime
3147 << "´ for change tracking, using current time instead.\n";
3148 ptime = current_time();
3150 if (t.cs() == "lyxadded")
3151 os << "\n\\change_inserted ";
3153 os << "\n\\change_deleted ";
3154 os << author.bufferId() << ' ' << ptime << '\n';
3155 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3156 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3157 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3158 LaTeXPackages::isAvailable("xcolor");
3159 // No need to test for luatex, since luatex comes in
3160 // two flavours (dvi and pdf), like latex, and those
3161 // are detected by pdflatex.
3162 if (pdflatex || xetex) {
3164 preamble.registerAutomaticallyLoadedPackage("ulem");
3165 preamble.registerAutomaticallyLoadedPackage("xcolor");
3166 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3170 preamble.registerAutomaticallyLoadedPackage("dvipost");
3171 } else if (xcolorulem) {
3172 preamble.registerAutomaticallyLoadedPackage("ulem");
3173 preamble.registerAutomaticallyLoadedPackage("xcolor");
3178 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3179 t.cs() == "vphantom") {
3180 context.check_layout(os);
3181 if (t.cs() == "phantom")
3182 begin_inset(os, "Phantom Phantom\n");
3183 if (t.cs() == "hphantom")
3184 begin_inset(os, "Phantom HPhantom\n");
3185 if (t.cs() == "vphantom")
3186 begin_inset(os, "Phantom VPhantom\n");
3187 os << "status open\n";
3188 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3193 else if (t.cs() == "href") {
3194 context.check_layout(os);
3195 string target = convert_command_inset_arg(p.verbatim_item());
3196 string name = convert_command_inset_arg(p.verbatim_item());
3198 size_t i = target.find(':');
3199 if (i != string::npos) {
3200 type = target.substr(0, i + 1);
3201 if (type == "mailto:" || type == "file:")
3202 target = target.substr(i + 1);
3203 // handle the case that name is equal to target, except of "http://"
3204 else if (target.substr(i + 3) == name && type == "http:")
3207 begin_command_inset(os, "href", "href");
3209 os << "name \"" << name << "\"\n";
3210 os << "target \"" << target << "\"\n";
3211 if (type == "mailto:" || type == "file:")
3212 os << "type \"" << type << "\"\n";
3214 skip_spaces_braces(p);
3217 else if (t.cs() == "lyxline") {
3218 // swallow size argument (it is not used anyway)
3220 if (!context.atParagraphStart()) {
3221 // so our line is in the middle of a paragraph
3222 // we need to add a new line, lest this line
3223 // follow the other content on that line and
3224 // run off the side of the page
3225 // FIXME: This may create an empty paragraph,
3226 // but without that it would not be
3227 // possible to set noindent below.
3228 // Fortunately LaTeX does not care
3229 // about the empty paragraph.
3230 context.new_paragraph(os);
3232 if (preamble.indentParagraphs()) {
3233 // we need to unindent, lest the line be too long
3234 context.add_par_extra_stuff("\\noindent\n");
3236 context.check_layout(os);
3237 begin_command_inset(os, "line", "rule");
3238 os << "offset \"0.5ex\"\n"
3239 "width \"100line%\"\n"
3244 else if (t.cs() == "rule") {
3245 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3246 string const width = p.getArg('{', '}');
3247 string const thickness = p.getArg('{', '}');
3248 context.check_layout(os);
3249 begin_command_inset(os, "line", "rule");
3250 if (!offset.empty())
3251 os << "offset \"" << translate_len(offset) << "\"\n";
3252 os << "width \"" << translate_len(width) << "\"\n"
3253 "height \"" << translate_len(thickness) << "\"\n";
3257 else if (is_known(t.cs(), known_phrases) ||
3258 (t.cs() == "protect" &&
3259 p.next_token().cat() == catEscape &&
3260 is_known(p.next_token().cs(), known_phrases))) {
3261 // LyX sometimes puts a \protect in front, so we have to ignore it
3262 // FIXME: This needs to be changed when bug 4752 is fixed.
3264 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3266 context.check_layout(os);
3267 os << known_coded_phrases[where - known_phrases];
3268 skip_spaces_braces(p);
3271 else if ((where = is_known(t.cs(), known_ref_commands))) {
3272 string const opt = p.getOpt();
3274 context.check_layout(os);
3275 begin_command_inset(os, "ref",
3276 known_coded_ref_commands[where - known_ref_commands]);
3277 os << "reference \""
3278 << convert_command_inset_arg(p.verbatim_item())
3281 if (t.cs() == "vref" || t.cs() == "vpageref")
3282 preamble.registerAutomaticallyLoadedPackage("varioref");
3285 // LyX does not support optional arguments of ref commands
3286 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3287 p.verbatim_item() + "}", context);
3291 else if (use_natbib &&
3292 is_known(t.cs(), known_natbib_commands) &&
3293 ((t.cs() != "citefullauthor" &&
3294 t.cs() != "citeyear" &&
3295 t.cs() != "citeyearpar") ||
3296 p.next_token().asInput() != "*")) {
3297 context.check_layout(os);
3298 string command = t.cs();
3299 if (p.next_token().asInput() == "*") {
3303 if (command == "citefullauthor")
3304 // alternative name for "\\citeauthor*"
3305 command = "citeauthor*";
3307 // text before the citation
3309 // text after the citation
3311 get_cite_arguments(p, true, before, after);
3313 if (command == "cite") {
3314 // \cite without optional argument means
3315 // \citet, \cite with at least one optional
3316 // argument means \citep.
3317 if (before.empty() && after.empty())
3322 if (before.empty() && after == "[]")
3323 // avoid \citet[]{a}
3325 else if (before == "[]" && after == "[]") {
3326 // avoid \citet[][]{a}
3330 // remove the brackets around after and before
3331 if (!after.empty()) {
3333 after.erase(after.length() - 1, 1);
3334 after = convert_command_inset_arg(after);
3336 if (!before.empty()) {
3338 before.erase(before.length() - 1, 1);
3339 before = convert_command_inset_arg(before);
3341 begin_command_inset(os, "citation", command);
3342 os << "after " << '"' << after << '"' << "\n";
3343 os << "before " << '"' << before << '"' << "\n";
3345 << convert_command_inset_arg(p.verbatim_item())
3350 else if (use_jurabib &&
3351 is_known(t.cs(), known_jurabib_commands) &&
3352 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3353 context.check_layout(os);
3354 string command = t.cs();
3355 if (p.next_token().asInput() == "*") {
3359 char argumentOrder = '\0';
3360 vector<string> const options =
3361 preamble.getPackageOptions("jurabib");
3362 if (find(options.begin(), options.end(),
3363 "natbiborder") != options.end())
3364 argumentOrder = 'n';
3365 else if (find(options.begin(), options.end(),
3366 "jurabiborder") != options.end())
3367 argumentOrder = 'j';
3369 // text before the citation
3371 // text after the citation
3373 get_cite_arguments(p, argumentOrder != 'j', before, after);
3375 string const citation = p.verbatim_item();
3376 if (!before.empty() && argumentOrder == '\0') {
3377 cerr << "Warning: Assuming argument order "
3378 "of jurabib version 0.6 for\n'"
3379 << command << before << after << '{'
3380 << citation << "}'.\n"
3381 "Add 'jurabiborder' to the jurabib "
3382 "package options if you used an\n"
3383 "earlier jurabib version." << endl;
3385 if (!after.empty()) {
3387 after.erase(after.length() - 1, 1);
3389 if (!before.empty()) {
3391 before.erase(before.length() - 1, 1);
3393 begin_command_inset(os, "citation", command);
3394 os << "after " << '"' << after << '"' << "\n";
3395 os << "before " << '"' << before << '"' << "\n";
3396 os << "key " << '"' << citation << '"' << "\n";
3400 else if (t.cs() == "cite"
3401 || t.cs() == "nocite") {
3402 context.check_layout(os);
3403 string after = convert_command_inset_arg(p.getArg('[', ']'));
3404 string key = convert_command_inset_arg(p.verbatim_item());
3405 // store the case that it is "\nocite{*}" to use it later for
3408 begin_command_inset(os, "citation", t.cs());
3409 os << "after " << '"' << after << '"' << "\n";
3410 os << "key " << '"' << key << '"' << "\n";
3412 } else if (t.cs() == "nocite")
3416 else if (t.cs() == "index" ||
3417 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3418 context.check_layout(os);
3419 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3420 p.getArg('[', ']') : "";
3421 string const kind = arg.empty() ? "idx" : arg;
3422 begin_inset(os, "Index ");
3423 os << kind << "\nstatus collapsed\n";
3424 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3427 preamble.registerAutomaticallyLoadedPackage("splitidx");
3430 else if (t.cs() == "nomenclature") {
3431 context.check_layout(os);
3432 begin_command_inset(os, "nomenclature", "nomenclature");
3433 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3434 if (!prefix.empty())
3435 os << "prefix " << '"' << prefix << '"' << "\n";
3436 os << "symbol " << '"'
3437 << convert_command_inset_arg(p.verbatim_item());
3438 os << "\"\ndescription \""
3439 << convert_command_inset_arg(p.verbatim_item())
3442 preamble.registerAutomaticallyLoadedPackage("nomencl");
3445 else if (t.cs() == "label") {
3446 context.check_layout(os);
3447 begin_command_inset(os, "label", "label");
3449 << convert_command_inset_arg(p.verbatim_item())
3454 else if (t.cs() == "printindex") {
3455 context.check_layout(os);
3456 begin_command_inset(os, "index_print", "printindex");
3457 os << "type \"idx\"\n";
3459 skip_spaces_braces(p);
3460 preamble.registerAutomaticallyLoadedPackage("makeidx");
3461 if (preamble.use_indices() == "true")
3462 preamble.registerAutomaticallyLoadedPackage("splitidx");
3465 else if (t.cs() == "printnomenclature") {
3467 string width_type = "";
3468 context.check_layout(os);
3469 begin_command_inset(os, "nomencl_print", "printnomenclature");
3470 // case of a custom width
3472 width = p.getArg('[', ']');
3473 width = translate_len(width);
3474 width_type = "custom";
3476 // case of no custom width
3477 // the case of no custom width but the width set
3478 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3479 // because the user could have set anything, not only the width
3480 // of the longest label (which would be width_type = "auto")
3481 string label = convert_command_inset_arg(p.getArg('{', '}'));
3482 if (label.empty() && width_type.empty())
3483 width_type = "none";
3484 os << "set_width \"" << width_type << "\"\n";
3485 if (width_type == "custom")
3486 os << "width \"" << width << '\"';
3488 skip_spaces_braces(p);
3489 preamble.registerAutomaticallyLoadedPackage("nomencl");
3492 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3493 context.check_layout(os);
3494 begin_inset(os, "script ");
3495 os << t.cs().substr(4) << '\n';
3496 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3498 if (t.cs() == "textsubscript")
3499 preamble.registerAutomaticallyLoadedPackage("subscript");
3502 else if ((where = is_known(t.cs(), known_quotes))) {
3503 context.check_layout(os);
3504 begin_inset(os, "Quotes ");
3505 os << known_coded_quotes[where - known_quotes];
3507 // LyX adds {} after the quote, so we have to eat
3508 // spaces here if there are any before a possible
3510 eat_whitespace(p, os, context, false);
3514 else if ((where = is_known(t.cs(), known_sizes)) &&
3515 context.new_layout_allowed) {
3516 context.check_layout(os);
3517 TeXFont const oldFont = context.font;
3518 context.font.size = known_coded_sizes[where - known_sizes];
3519 output_font_change(os, oldFont, context.font);
3520 eat_whitespace(p, os, context, false);
3523 else if ((where = is_known(t.cs(), known_font_families)) &&
3524 context.new_layout_allowed) {
3525 context.check_layout(os);
3526 TeXFont const oldFont = context.font;
3527 context.font.family =
3528 known_coded_font_families[where - known_font_families];
3529 output_font_change(os, oldFont, context.font);
3530 eat_whitespace(p, os, context, false);
3533 else if ((where = is_known(t.cs(), known_font_series)) &&
3534 context.new_layout_allowed) {
3535 context.check_layout(os);
3536 TeXFont const oldFont = context.font;
3537 context.font.series =
3538 known_coded_font_series[where - known_font_series];
3539 output_font_change(os, oldFont, context.font);
3540 eat_whitespace(p, os, context, false);
3543 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3544 context.new_layout_allowed) {
3545 context.check_layout(os);
3546 TeXFont const oldFont = context.font;
3547 context.font.shape =
3548 known_coded_font_shapes[where - known_font_shapes];
3549 output_font_change(os, oldFont, context.font);
3550 eat_whitespace(p, os, context, false);
3552 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3553 context.new_layout_allowed) {
3554 context.check_layout(os);
3555 TeXFont const oldFont = context.font;
3556 context.font.init();
3557 context.font.size = oldFont.size;
3558 context.font.family =
3559 known_coded_font_families[where - known_old_font_families];
3560 output_font_change(os, oldFont, context.font);
3561 eat_whitespace(p, os, context, false);
3564 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3565 context.new_layout_allowed) {
3566 context.check_layout(os);
3567 TeXFont const oldFont = context.font;
3568 context.font.init();
3569 context.font.size = oldFont.size;
3570 context.font.series =
3571 known_coded_font_series[where - known_old_font_series];
3572 output_font_change(os, oldFont, context.font);
3573 eat_whitespace(p, os, context, false);
3576 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3577 context.new_layout_allowed) {
3578 context.check_layout(os);
3579 TeXFont const oldFont = context.font;
3580 context.font.init();
3581 context.font.size = oldFont.size;
3582 context.font.shape =
3583 known_coded_font_shapes[where - known_old_font_shapes];
3584 output_font_change(os, oldFont, context.font);
3585 eat_whitespace(p, os, context, false);
3588 else if (t.cs() == "selectlanguage") {
3589 context.check_layout(os);
3590 // save the language for the case that a
3591 // \foreignlanguage is used
3592 context.font.language = babel2lyx(p.verbatim_item());
3593 os << "\n\\lang " << context.font.language << "\n";
3596 else if (t.cs() == "foreignlanguage") {
3597 string const lang = babel2lyx(p.verbatim_item());
3598 parse_text_attributes(p, os, FLAG_ITEM, outer,
3600 context.font.language, lang);
3603 else if (prefixIs(t.cs(), "text")
3604 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3605 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3607 // We have to output the whole command if it has an option
3608 // because LyX doesn't support this yet, see bug #8214,
3609 // only if there is a single option specifying a variant, we can handle it.
3611 string langopts = p.getOpt();
3612 // check if the option contains a variant, if yes, extract it
3613 string::size_type pos_var = langopts.find("variant");
3614 string::size_type i = langopts.find(',');
3615 string::size_type k = langopts.find('=', pos_var);
3616 if (pos_var != string::npos && i == string::npos) {
3618 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3619 lang = preamble.polyglossia2lyx(variant);
3620 parse_text_attributes(p, os, FLAG_ITEM, outer,
3622 context.font.language, lang);
3624 handle_ert(os, t.asInput() + langopts, context);
3626 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3627 parse_text_attributes(p, os, FLAG_ITEM, outer,
3629 context.font.language, lang);
3633 else if (t.cs() == "inputencoding") {
3634 // nothing to write here
3635 string const enc = subst(p.verbatim_item(), "\n", " ");
3639 else if ((where = is_known(t.cs(), known_special_chars))) {
3640 context.check_layout(os);
3641 os << "\\SpecialChar \\"
3642 << known_coded_special_chars[where - known_special_chars]
3644 skip_spaces_braces(p);
3647 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3648 context.check_layout(os);
3649 os << "\\SpecialChar \\nobreakdash-\n";
3653 else if (t.cs() == "textquotedbl") {
3654 context.check_layout(os);
3659 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3660 context.check_layout(os);
3661 os << "\\SpecialChar \\@.\n";
3665 else if (t.cs() == "-") {
3666 context.check_layout(os);
3667 os << "\\SpecialChar \\-\n";
3670 else if (t.cs() == "textasciitilde") {
3671 context.check_layout(os);
3673 skip_spaces_braces(p);
3676 else if (t.cs() == "textasciicircum") {
3677 context.check_layout(os);
3679 skip_spaces_braces(p);
3682 else if (t.cs() == "textbackslash") {
3683 context.check_layout(os);
3684 os << "\n\\backslash\n";
3685 skip_spaces_braces(p);
3688 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3689 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3691 context.check_layout(os);
3695 else if (t.cs() == "char") {
3696 context.check_layout(os);
3697 if (p.next_token().character() == '`') {
3699 if (p.next_token().cs() == "\"") {
3704 handle_ert(os, "\\char`", context);
3707 handle_ert(os, "\\char", context);
3711 else if (t.cs() == "verb") {
3712 context.check_layout(os);
3713 char const delimiter = p.next_token().character();
3714 // \verb is special: The usual escaping rules do not
3715 // apply, e.g. "\verb+\+" is valid and denotes a single
3716 // backslash (bug #4468). Therefore we do not allow
3717 // escaping in getArg().
3718 string const arg = p.getArg(delimiter, delimiter, false);
3720 oss << "\\verb" << delimiter << arg << delimiter;
3721 handle_ert(os, oss.str(), context);
3724 // Problem: \= creates a tabstop inside the tabbing environment
3725 // and else an accent. In the latter case we really would want
3726 // \={o} instead of \= o.
3727 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3728 handle_ert(os, t.asInput(), context);
3730 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3731 else if (t.cs().size() == 1
3732 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3733 context.check_layout(os);
3734 // try to see whether the string is in unicodesymbols
3737 string command = t.asInput() + "{"
3738 + trimSpaceAndEol(p.verbatim_item())
3741 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3742 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3743 termination, rem, &req);
3746 cerr << "When parsing " << command
3747 << ", result is " << to_utf8(s)
3748 << "+" << to_utf8(rem) << endl;
3750 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3751 preamble.registerAutomaticallyLoadedPackage(*it);
3753 // we did not find a non-ert version
3754 handle_ert(os, command, context);
3757 else if (t.cs() == "\\") {
3758 context.check_layout(os);
3760 handle_ert(os, "\\\\" + p.getOpt(), context);
3761 else if (p.next_token().asInput() == "*") {
3763 // getOpt() eats the following space if there
3764 // is no optional argument, but that is OK
3765 // here since it has no effect in the output.
3766 handle_ert(os, "\\\\*" + p.getOpt(), context);
3769 begin_inset(os, "Newline newline");
3774 else if (t.cs() == "newline" ||
3775 (t.cs() == "linebreak" && !p.hasOpt())) {
3776 context.check_layout(os);
3777 begin_inset(os, "Newline ");
3780 skip_spaces_braces(p);
3783 else if (t.cs() == "input" || t.cs() == "include"
3784 || t.cs() == "verbatiminput") {
3785 string name = t.cs();
3786 if (t.cs() == "verbatiminput"
3787 && p.next_token().asInput() == "*")
3788 name += p.get_token().asInput();
3789 context.check_layout(os);
3790 string filename(normalize_filename(p.getArg('{', '}')));
3791 string const path = getMasterFilePath(true);
3792 // We want to preserve relative / absolute filenames,
3793 // therefore path is only used for testing
3794 if ((t.cs() == "include" || t.cs() == "input") &&
3795 !makeAbsPath(filename, path).exists()) {
3796 // The file extension is probably missing.
3797 // Now try to find it out.
3798 string const tex_name =
3799 find_file(filename, path,
3800 known_tex_extensions);
3801 if (!tex_name.empty())
3802 filename = tex_name;
3804 bool external = false;
3806 if (makeAbsPath(filename, path).exists()) {
3807 string const abstexname =
3808 makeAbsPath(filename, path).absFileName();
3809 string const absfigname =
3810 changeExtension(abstexname, ".fig");
3811 fix_child_filename(filename);
3812 string const lyxname =
3813 changeExtension(filename, ".lyx");
3814 string const abslyxname = makeAbsPath(
3815 lyxname, getParentFilePath(false)).absFileName();
3817 external = FileName(absfigname).exists();
3818 if (t.cs() == "input") {
3819 string const ext = getExtension(abstexname);
3821 // Combined PS/LaTeX:
3822 // x.eps, x.pstex_t (old xfig)
3823 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3824 FileName const absepsname(
3825 changeExtension(abstexname, ".eps"));
3826 FileName const abspstexname(
3827 changeExtension(abstexname, ".pstex"));
3828 bool const xfigeps =
3829 (absepsname.exists() ||
3830 abspstexname.exists()) &&
3833 // Combined PDF/LaTeX:
3834 // x.pdf, x.pdftex_t (old xfig)
3835 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3836 FileName const abspdfname(
3837 changeExtension(abstexname, ".pdf"));
3838 bool const xfigpdf =
3839 abspdfname.exists() &&
3840 (ext == "pdftex_t" || ext == "pdf_t");
3844 // Combined PS/PDF/LaTeX:
3845 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3846 string const absbase2(
3847 removeExtension(abstexname) + "_pspdftex");
3848 FileName const abseps2name(
3849 addExtension(absbase2, ".eps"));
3850 FileName const abspdf2name(
3851 addExtension(absbase2, ".pdf"));
3852 bool const xfigboth =
3853 abspdf2name.exists() &&
3854 abseps2name.exists() && ext == "pspdftex";
3856 xfig = xfigpdf || xfigeps || xfigboth;
3857 external = external && xfig;
3860 outname = changeExtension(filename, ".fig");
3861 FileName abssrc(changeExtension(abstexname, ".fig"));
3862 copy_file(abssrc, outname);
3864 // Don't try to convert, the result
3865 // would be full of ERT.
3867 FileName abssrc(abstexname);
3868 copy_file(abssrc, outname);
3869 } else if (t.cs() != "verbatiminput" &&
3870 tex2lyx(abstexname, FileName(abslyxname),
3873 // no need to call copy_file
3874 // tex2lyx creates the file
3877 FileName abssrc(abstexname);
3878 copy_file(abssrc, outname);
3881 cerr << "Warning: Could not find included file '"
3882 << filename << "'." << endl;
3886 begin_inset(os, "External\n");
3887 os << "\ttemplate XFig\n"
3888 << "\tfilename " << outname << '\n';
3889 registerExternalTemplatePackages("XFig");
3891 begin_command_inset(os, "include", name);
3892 os << "preview false\n"
3893 "filename \"" << outname << "\"\n";
3894 if (t.cs() == "verbatiminput")
3895 preamble.registerAutomaticallyLoadedPackage("verbatim");
3900 else if (t.cs() == "bibliographystyle") {
3901 // store new bibliographystyle
3902 bibliographystyle = p.verbatim_item();
3903 // If any other command than \bibliography and
3904 // \nocite{*} follows, we need to output the style
3905 // (because it might be used by that command).
3906 // Otherwise, it will automatically be output by LyX.
3909 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3910 if (t2.cat() == catBegin)
3912 if (t2.cat() != catEscape)
3914 if (t2.cs() == "nocite") {
3915 if (p.getArg('{', '}') == "*")
3917 } else if (t2.cs() == "bibliography")
3924 "\\bibliographystyle{" + bibliographystyle + '}',
3929 else if (t.cs() == "bibliography") {
3930 context.check_layout(os);
3931 begin_command_inset(os, "bibtex", "bibtex");
3932 if (!btprint.empty()) {
3933 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3934 // clear the string because the next BibTeX inset can be without the
3935 // \nocite{*} option
3938 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3939 // Do we have a bibliographystyle set?
3940 if (!bibliographystyle.empty())
3941 os << "options " << '"' << bibliographystyle << '"' << "\n";
3945 else if (t.cs() == "parbox") {
3946 // Test whether this is an outer box of a shaded box
3948 // swallow arguments
3949 while (p.hasOpt()) {
3951 p.skip_spaces(true);
3954 p.skip_spaces(true);
3956 if (p.next_token().cat() == catBegin)
3958 p.skip_spaces(true);
3959 Token to = p.get_token();
3960 bool shaded = false;
3961 if (to.asInput() == "\\begin") {
3962 p.skip_spaces(true);
3963 if (p.getArg('{', '}') == "shaded")
3968 parse_outer_box(p, os, FLAG_ITEM, outer,
3969 context, "parbox", "shaded");
3971 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3975 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3976 t.cs() == "shadowbox" || t.cs() == "doublebox")
3977 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3979 else if (t.cs() == "framebox") {
3980 if (p.next_token().character() == '(') {
3981 //the syntax is: \framebox(x,y)[position]{content}
3982 string arg = t.asInput();
3983 arg += p.getFullParentheseArg();
3984 arg += p.getFullOpt();
3985 eat_whitespace(p, os, context, false);
3986 handle_ert(os, arg + '{', context);
3987 parse_text(p, os, FLAG_ITEM, outer, context);
3988 handle_ert(os, "}", context);
3990 string special = p.getFullOpt();
3991 special += p.getOpt();
3992 // LyX does not yet support \framebox without any option
3993 if (!special.empty())
3994 parse_outer_box(p, os, FLAG_ITEM, outer,
3995 context, t.cs(), special);
3997 eat_whitespace(p, os, context, false);
3998 handle_ert(os, "\\framebox{", context);
3999 parse_text(p, os, FLAG_ITEM, outer, context);
4000 handle_ert(os, "}", context);
4005 //\makebox() is part of the picture environment and different from \makebox{}
4006 //\makebox{} will be parsed by parse_box
4007 else if (t.cs() == "makebox") {
4008 if (p.next_token().character() == '(') {
4009 //the syntax is: \makebox(x,y)[position]{content}
4010 string arg = t.asInput();
4011 arg += p.getFullParentheseArg();
4012 arg += p.getFullOpt();
4013 eat_whitespace(p, os, context, false);
4014 handle_ert(os, arg + '{', context);
4015 parse_text(p, os, FLAG_ITEM, outer, context);
4016 handle_ert(os, "}", context);
4018 //the syntax is: \makebox[width][position]{content}
4019 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4023 else if (t.cs() == "smallskip" ||
4024 t.cs() == "medskip" ||
4025 t.cs() == "bigskip" ||
4026 t.cs() == "vfill") {
4027 context.check_layout(os);
4028 begin_inset(os, "VSpace ");
4031 skip_spaces_braces(p);
4034 else if ((where = is_known(t.cs(), known_spaces))) {
4035 context.check_layout(os);
4036 begin_inset(os, "space ");
4037 os << '\\' << known_coded_spaces[where - known_spaces]
4040 // LaTeX swallows whitespace after all spaces except
4041 // "\\,". We have to do that here, too, because LyX
4042 // adds "{}" which would make the spaces significant.
4044 eat_whitespace(p, os, context, false);
4045 // LyX adds "{}" after all spaces except "\\ " and
4046 // "\\,", so we have to remove "{}".
4047 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4048 // remove the braces after "\\,", too.
4053 else if (t.cs() == "newpage" ||
4054 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4055 t.cs() == "clearpage" ||
4056 t.cs() == "cleardoublepage") {
4057 context.check_layout(os);
4058 begin_inset(os, "Newpage ");
4061 skip_spaces_braces(p);
4064 else if (t.cs() == "DeclareRobustCommand" ||
4065 t.cs() == "DeclareRobustCommandx" ||
4066 t.cs() == "newcommand" ||
4067 t.cs() == "newcommandx" ||
4068 t.cs() == "providecommand" ||
4069 t.cs() == "providecommandx" ||
4070 t.cs() == "renewcommand" ||
4071 t.cs() == "renewcommandx") {
4072 // DeclareRobustCommand, DeclareRobustCommandx,
4073 // providecommand and providecommandx could be handled
4074 // by parse_command(), but we need to call
4075 // add_known_command() here.
4076 string name = t.asInput();
4077 if (p.next_token().asInput() == "*") {
4078 // Starred form. Eat '*'
4082 string const command = p.verbatim_item();
4083 string const opt1 = p.getFullOpt();
4084 string const opt2 = p.getFullOpt();
4085 add_known_command(command, opt1, !opt2.empty());
4086 string const ert = name + '{' + command + '}' +
4088 '{' + p.verbatim_item() + '}';
4090 if (t.cs() == "DeclareRobustCommand" ||
4091 t.cs() == "DeclareRobustCommandx" ||
4092 t.cs() == "providecommand" ||
4093 t.cs() == "providecommandx" ||
4094 name[name.length()-1] == '*')
4095 handle_ert(os, ert, context);
4097 context.check_layout(os);
4098 begin_inset(os, "FormulaMacro");
4104 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4105 // let could be handled by parse_command(),
4106 // but we need to call add_known_command() here.
4107 string ert = t.asInput();
4110 if (p.next_token().cat() == catBegin) {
4111 name = p.verbatim_item();
4112 ert += '{' + name + '}';
4114 name = p.verbatim_item();
4119 if (p.next_token().cat() == catBegin) {
4120 command = p.verbatim_item();
4121 ert += '{' + command + '}';
4123 command = p.verbatim_item();
4126 // If command is known, make name known too, to parse
4127 // its arguments correctly. For this reason we also
4128 // have commands in syntax.default that are hardcoded.
4129 CommandMap::iterator it = known_commands.find(command);
4130 if (it != known_commands.end())
4131 known_commands[t.asInput()] = it->second;
4132 handle_ert(os, ert, context);
4135 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4136 bool starred = false;
4137 if (p.next_token().asInput() == "*") {
4141 string name = t.asInput();
4142 string const length = p.verbatim_item();
4145 bool valid = splitLatexLength(length, valstring, unit);
4146 bool known_hspace = false;
4147 bool known_vspace = false;
4148 bool known_unit = false;
4151 istringstream iss(valstring);
4154 if (t.cs()[0] == 'h') {
4155 if (unit == "\\fill") {
4160 known_hspace = true;
4163 if (unit == "\\smallskipamount") {
4165 known_vspace = true;
4166 } else if (unit == "\\medskipamount") {
4168 known_vspace = true;
4169 } else if (unit == "\\bigskipamount") {
4171 known_vspace = true;
4172 } else if (unit == "\\fill") {
4174 known_vspace = true;
4178 if (!known_hspace && !known_vspace) {
4179 switch (unitFromString(unit)) {
4200 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4201 // Literal horizontal length or known variable
4202 context.check_layout(os);
4203 begin_inset(os, "space ");
4211 if (known_unit && !known_hspace)
4213 << translate_len(length);
4215 } else if (known_unit || known_vspace) {
4216 // Literal vertical length or known variable
4217 context.check_layout(os);
4218 begin_inset(os, "VSpace ");
4226 // LyX can't handle other length variables in Inset VSpace/space
4231 handle_ert(os, name + '{' + unit + '}', context);
4232 else if (value == -1.0)
4233 handle_ert(os, name + "{-" + unit + '}', context);
4235 handle_ert(os, name + '{' + valstring + unit + '}', context);
4237 handle_ert(os, name + '{' + length + '}', context);
4241 // The single '=' is meant here.
4242 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4244 context.check_layout(os);
4245 begin_inset(os, "Flex ");
4246 os << to_utf8(newinsetlayout->name()) << '\n'
4247 << "status collapsed\n";
4248 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4252 else if (t.cs() == "includepdf") {
4254 string const arg = p.getArg('[', ']');
4255 map<string, string> opts;
4256 vector<string> keys;
4257 split_map(arg, opts, keys);
4258 string name = normalize_filename(p.verbatim_item());
4259 string const path = getMasterFilePath(true);
4260 // We want to preserve relative / absolute filenames,
4261 // therefore path is only used for testing
4262 if (!makeAbsPath(name, path).exists()) {
4263 // The file extension is probably missing.
4264 // Now try to find it out.
4265 char const * const pdfpages_format[] = {"pdf", 0};
4266 string const pdftex_name =
4267 find_file(name, path, pdfpages_format);
4268 if (!pdftex_name.empty()) {
4273 FileName const absname = makeAbsPath(name, path);
4274 if (absname.exists())
4276 fix_child_filename(name);
4277 copy_file(absname, name);
4279 cerr << "Warning: Could not find file '"
4280 << name << "'." << endl;
4282 context.check_layout(os);
4283 begin_inset(os, "External\n\ttemplate ");
4284 os << "PDFPages\n\tfilename "
4286 // parse the options
4287 if (opts.find("pages") != opts.end())
4288 os << "\textra LaTeX \"pages="
4289 << opts["pages"] << "\"\n";
4290 if (opts.find("angle") != opts.end())
4291 os << "\trotateAngle "
4292 << opts["angle"] << '\n';
4293 if (opts.find("origin") != opts.end()) {
4295 string const opt = opts["origin"];
4296 if (opt == "tl") ss << "topleft";
4297 if (opt == "bl") ss << "bottomleft";
4298 if (opt == "Bl") ss << "baselineleft";
4299 if (opt == "c") ss << "center";
4300 if (opt == "tc") ss << "topcenter";
4301 if (opt == "bc") ss << "bottomcenter";
4302 if (opt == "Bc") ss << "baselinecenter";
4303 if (opt == "tr") ss << "topright";
4304 if (opt == "br") ss << "bottomright";
4305 if (opt == "Br") ss << "baselineright";
4306 if (!ss.str().empty())
4307 os << "\trotateOrigin " << ss.str() << '\n';
4309 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4311 if (opts.find("width") != opts.end())
4313 << translate_len(opts["width"]) << '\n';
4314 if (opts.find("height") != opts.end())
4316 << translate_len(opts["height"]) << '\n';
4317 if (opts.find("keepaspectratio") != opts.end())
4318 os << "\tkeepAspectRatio\n";
4320 context.check_layout(os);
4321 registerExternalTemplatePackages("PDFPages");
4324 else if (t.cs() == "loadgame") {
4326 string name = normalize_filename(p.verbatim_item());
4327 string const path = getMasterFilePath(true);
4328 // We want to preserve relative / absolute filenames,
4329 // therefore path is only used for testing
4330 if (!makeAbsPath(name, path).exists()) {
4331 // The file extension is probably missing.
4332 // Now try to find it out.
4333 char const * const lyxskak_format[] = {"fen", 0};
4334 string const lyxskak_name =
4335 find_file(name, path, lyxskak_format);
4336 if (!lyxskak_name.empty())
4337 name = lyxskak_name;
4339 FileName const absname = makeAbsPath(name, path);
4340 if (absname.exists())
4342 fix_child_filename(name);
4343 copy_file(absname, name);
4345 cerr << "Warning: Could not find file '"
4346 << name << "'." << endl;
4347 context.check_layout(os);
4348 begin_inset(os, "External\n\ttemplate ");
4349 os << "ChessDiagram\n\tfilename "
4352 context.check_layout(os);
4353 // after a \loadgame follows a \showboard
4354 if (p.get_token().asInput() == "showboard")
4356 registerExternalTemplatePackages("ChessDiagram");
4360 // try to see whether the string is in unicodesymbols
4361 // Only use text mode commands, since we are in text mode here,
4362 // and math commands may be invalid (bug 6797)
4366 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4367 Encodings::TEXT_CMD, termination, rem, &req);
4370 cerr << "When parsing " << t.cs()
4371 << ", result is " << to_utf8(s)
4372 << "+" << to_utf8(rem) << endl;
4373 context.check_layout(os);
4376 skip_spaces_braces(p);
4377 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4378 preamble.registerAutomaticallyLoadedPackage(*it);
4380 //cerr << "#: " << t << " mode: " << mode << endl;
4381 // heuristic: read up to next non-nested space
4383 string s = t.asInput();
4384 string z = p.verbatim_item();
4385 while (p.good() && z != " " && z.size()) {
4386 //cerr << "read: " << z << endl;
4388 z = p.verbatim_item();
4390 cerr << "found ERT: " << s << endl;
4391 handle_ert(os, s + ' ', context);
4394 string name = t.asInput();
4395 if (p.next_token().asInput() == "*") {
4396 // Starred commands like \vspace*{}
4397 p.get_token(); // Eat '*'
4400 if (!parse_command(name, p, os, outer, context))
4401 handle_ert(os, name, context);
4405 if (flags & FLAG_LEAVE) {
4406 flags &= ~FLAG_LEAVE;
4413 string guessLanguage(Parser & p, string const & lang)
4415 typedef std::map<std::string, size_t> LangMap;
4416 // map from language names to number of characters
4419 for (char const * const * i = supported_CJK_languages; *i; i++)
4420 used[string(*i)] = 0;
4423 Token const t = p.get_token();
4424 // comments are not counted for any language
4425 if (t.cat() == catComment)
4427 // commands are not counted as well, but we need to detect
4428 // \begin{CJK} and switch encoding if needed
4429 if (t.cat() == catEscape) {
4430 if (t.cs() == "inputencoding") {
4431 string const enc = subst(p.verbatim_item(), "\n", " ");
4435 if (t.cs() != "begin")
4438 // Non-CJK content is counted for lang.
4439 // We do not care about the real language here:
4440 // If we have more non-CJK contents than CJK contents,
4441 // we simply use the language that was specified as
4442 // babel main language.
4443 used[lang] += t.asInput().length();
4446 // Now we are starting an environment
4448 string const name = p.getArg('{', '}');
4449 if (name != "CJK") {
4453 // It is a CJK environment
4455 /* name = */ p.getArg('{', '}');
4456 string const encoding = p.getArg('{', '}');
4457 /* mapping = */ p.getArg('{', '}');
4458 string const encoding_old = p.getEncoding();
4459 char const * const * const where =
4460 is_known(encoding, supported_CJK_encodings);
4462 p.setEncoding(encoding);
4464 p.setEncoding("utf8");
4465 string const text = p.verbatimEnvironment("CJK");
4466 p.setEncoding(encoding_old);
4469 // ignore contents in unknown CJK encoding
4472 // the language of the text
4474 supported_CJK_languages[where - supported_CJK_encodings];
4475 used[cjk] += text.length();
4477 LangMap::const_iterator use = used.begin();
4478 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4479 if (it->second > use->second)