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 hor_pos = p.getArg('[', ']');
821 inner_pos = p.getArg('[', ']');
822 if (inner_pos != "c" && inner_pos != "t" &&
823 inner_pos != "b" && inner_pos != "s") {
824 cerr << "invalid inner_pos "
825 << inner_pos << " for "
826 << inner_type << endl;
827 inner_pos = position;
832 if (inner_type.empty()) {
833 if (special.empty() && outer_type != "framebox")
834 latex_width = "1\\columnwidth";
837 latex_width = p2.getArg('[', ']');
838 string const opt = p2.getArg('[', ']');
841 if (hor_pos != "l" && hor_pos != "c" &&
843 cerr << "invalid hor_pos " << hor_pos
844 << " for " << outer_type << endl;
849 } else if (inner_type != "makebox")
850 latex_width = p.verbatim_item();
851 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
852 // as this is LyX's standard for such cases (except for makebox)
853 // \framebox is more special and handled below
854 if (latex_width.empty() && inner_type != "makebox"
855 && outer_type != "framebox")
856 latex_width = "1\\columnwidth";
858 translate_len(latex_width, width_value, width_unit);
860 bool shadedparbox = false;
861 if (inner_type == "shaded") {
862 eat_whitespace(p, os, parent_context, false);
863 if (outer_type == "parbox") {
865 if (p.next_token().cat() == catBegin)
867 eat_whitespace(p, os, parent_context, false);
873 // If we already read the inner box we have to push the inner env
874 if (!outer_type.empty() && !inner_type.empty() &&
875 (inner_flags & FLAG_END))
876 active_environments.push_back(inner_type);
877 // LyX can't handle length variables
878 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
879 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
880 // Look whether there is some content after the end of the
881 // inner box, but before the end of the outer box.
882 // If yes, we need to output ERT.
884 if (inner_flags & FLAG_END)
885 p.verbatimEnvironment(inner_type);
889 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
890 if ((outer_env && p.next_token().asInput() != "\\end") ||
891 (!outer_env && p.next_token().cat() != catEnd)) {
892 // something is between the end of the inner box and
893 // the end of the outer box, so we need to use ERT.
898 // if only \makebox{content} was used we can set its width to 1\width
899 // because this identic and also identic to \mbox
900 // this doesn't work for \framebox{content}, thus we have to use ERT for this
901 if (latex_width.empty() && inner_type == "makebox") {
904 width_special = "width";
905 } else if (latex_width.empty() && outer_type == "framebox") {
910 if (!outer_type.empty()) {
911 if (outer_flags & FLAG_END)
912 ss << "\\begin{" << outer_type << '}';
914 ss << '\\' << outer_type << '{';
915 if (!special.empty())
919 if (!inner_type.empty()) {
920 if (inner_type != "shaded") {
921 if (inner_flags & FLAG_END)
922 ss << "\\begin{" << inner_type << '}';
924 ss << '\\' << inner_type;
926 if (!position.empty())
927 ss << '[' << position << ']';
928 if (!latex_height.empty())
929 ss << '[' << latex_height << ']';
930 if (!inner_pos.empty())
931 ss << '[' << inner_pos << ']';
932 ss << '{' << latex_width << '}';
933 if (!(inner_flags & FLAG_END))
936 if (inner_type == "shaded")
937 ss << "\\begin{shaded}";
938 handle_ert(os, ss.str(), parent_context);
939 if (!inner_type.empty()) {
940 parse_text(p, os, inner_flags, outer, parent_context);
941 if (inner_flags & FLAG_END)
942 handle_ert(os, "\\end{" + inner_type + '}',
945 handle_ert(os, "}", parent_context);
947 if (!outer_type.empty()) {
948 // If we already read the inner box we have to pop
950 if (!inner_type.empty() && (inner_flags & FLAG_END))
951 active_environments.pop_back();
953 // Ensure that the end of the outer box is parsed correctly:
954 // The opening brace has been eaten by parse_outer_box()
955 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
956 outer_flags &= ~FLAG_ITEM;
957 outer_flags |= FLAG_BRACE_LAST;
959 parse_text(p, os, outer_flags, outer, parent_context);
960 if (outer_flags & FLAG_END)
961 handle_ert(os, "\\end{" + outer_type + '}',
963 else if (inner_type.empty() && outer_type == "framebox")
964 // in this case it is already closed later
967 handle_ert(os, "}", parent_context);
970 // LyX does not like empty positions, so we have
971 // to set them to the LaTeX default values here.
972 if (position.empty())
974 if (inner_pos.empty())
975 inner_pos = position;
976 parent_context.check_layout(os);
977 begin_inset(os, "Box ");
978 if (outer_type == "framed")
980 else if (outer_type == "framebox")
982 else if (outer_type == "shadowbox")
984 else if ((outer_type == "shaded" && inner_type.empty()) ||
985 (outer_type == "minipage" && inner_type == "shaded") ||
986 (outer_type == "parbox" && inner_type == "shaded")) {
988 preamble.registerAutomaticallyLoadedPackage("color");
989 } else if (outer_type == "doublebox")
991 else if (outer_type.empty())
994 os << outer_type << '\n';
995 os << "position \"" << position << "\"\n";
996 os << "hor_pos \"" << hor_pos << "\"\n";
997 os << "has_inner_box " << !inner_type.empty() << "\n";
998 os << "inner_pos \"" << inner_pos << "\"\n";
999 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1001 os << "use_makebox " << (inner_type == "makebox") << '\n';
1002 os << "width \"" << width_value << width_unit << "\"\n";
1003 os << "special \"" << width_special << "\"\n";
1004 os << "height \"" << height_value << height_unit << "\"\n";
1005 os << "height_special \"" << height_special << "\"\n";
1006 os << "status open\n\n";
1008 // Unfortunately we can't use parse_text_in_inset:
1009 // InsetBox::forcePlainLayout() is hard coded and does not
1010 // use the inset layout. Apart from that do we call parse_text
1011 // up to two times, but need only one check_end_layout.
1012 bool const forcePlainLayout =
1013 (!inner_type.empty() || inner_type == "makebox") &&
1014 outer_type != "shaded" && outer_type != "framed";
1015 Context context(true, parent_context.textclass);
1016 if (forcePlainLayout)
1017 context.layout = &context.textclass.plainLayout();
1019 context.font = parent_context.font;
1021 // If we have no inner box the contents will be read with the outer box
1022 if (!inner_type.empty())
1023 parse_text(p, os, inner_flags, outer, context);
1025 // Ensure that the end of the outer box is parsed correctly:
1026 // The opening brace has been eaten by parse_outer_box()
1027 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1028 outer_flags &= ~FLAG_ITEM;
1029 outer_flags |= FLAG_BRACE_LAST;
1032 // Find end of outer box, output contents if inner_type is
1033 // empty and output possible comments
1034 if (!outer_type.empty()) {
1035 // If we already read the inner box we have to pop
1037 if (!inner_type.empty() && (inner_flags & FLAG_END))
1038 active_environments.pop_back();
1039 // This does not output anything but comments if
1040 // inner_type is not empty (see use_ert)
1041 parse_text(p, os, outer_flags, outer, context);
1044 context.check_end_layout(os);
1046 #ifdef PRESERVE_LAYOUT
1047 // LyX puts a % after the end of the minipage
1048 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1050 //handle_comment(os, "%dummy", parent_context);
1053 parent_context.new_paragraph(os);
1055 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1056 //handle_comment(os, "%dummy", parent_context);
1059 // We add a protected space if something real follows
1060 if (p.good() && p.next_token().cat() != catComment) {
1061 begin_inset(os, "space ~\n");
1070 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1071 Context & parent_context, string const & outer_type,
1072 string const & special)
1074 eat_whitespace(p, os, parent_context, false);
1075 if (flags & FLAG_ITEM) {
1077 if (p.next_token().cat() == catBegin)
1080 cerr << "Warning: Ignoring missing '{' after \\"
1081 << outer_type << '.' << endl;
1082 eat_whitespace(p, os, parent_context, false);
1085 unsigned int inner_flags = 0;
1087 if (outer_type == "minipage" || outer_type == "parbox") {
1088 p.skip_spaces(true);
1089 while (p.hasOpt()) {
1091 p.skip_spaces(true);
1094 p.skip_spaces(true);
1095 if (outer_type == "parbox") {
1097 if (p.next_token().cat() == catBegin)
1099 p.skip_spaces(true);
1102 if (outer_type == "shaded") {
1103 // These boxes never have an inner box
1105 } else if (p.next_token().asInput() == "\\parbox") {
1106 inner = p.get_token().cs();
1107 inner_flags = FLAG_ITEM;
1108 } else if (p.next_token().asInput() == "\\begin") {
1109 // Is this a minipage or shaded box?
1112 inner = p.getArg('{', '}');
1114 if (inner == "minipage" || inner == "shaded")
1115 inner_flags = FLAG_END;
1120 if (inner_flags == FLAG_END) {
1121 if (inner != "shaded")
1125 eat_whitespace(p, os, parent_context, false);
1127 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1128 outer_type, special, inner);
1130 if (inner_flags == FLAG_ITEM) {
1132 eat_whitespace(p, os, parent_context, false);
1134 parse_box(p, os, flags, inner_flags, outer, parent_context,
1135 outer_type, special, inner);
1140 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1142 parent_context.check_layout(os);
1143 begin_inset(os, "listings\n");
1145 string arg = p.verbatimOption();
1146 os << "lstparams " << '"' << arg << '"' << '\n';
1149 os << "inline true\n";
1151 os << "inline false\n";
1152 os << "status collapsed\n";
1153 Context context(true, parent_context.textclass);
1154 context.layout = &parent_context.textclass.plainLayout();
1157 s = p.plainCommand('!', '!', "lstinline");
1158 context.new_paragraph(os);
1159 context.check_layout(os);
1161 s = p.plainEnvironment("lstlisting");
1162 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1164 os << "\n\\backslash\n";
1165 else if (*it == '\n') {
1166 // avoid adding an empty paragraph at the end
1168 context.new_paragraph(os);
1169 context.check_layout(os);
1174 context.check_end_layout(os);
1179 /// parse an unknown environment
1180 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1181 unsigned flags, bool outer,
1182 Context & parent_context)
1184 if (name == "tabbing")
1185 // We need to remember that we have to handle '\=' specially
1186 flags |= FLAG_TABBING;
1188 // We need to translate font changes and paragraphs inside the
1189 // environment to ERT if we have a non standard font.
1190 // Otherwise things like
1191 // \large\begin{foo}\huge bar\end{foo}
1193 bool const specialfont =
1194 (parent_context.font != parent_context.normalfont);
1195 bool const new_layout_allowed = parent_context.new_layout_allowed;
1197 parent_context.new_layout_allowed = false;
1198 handle_ert(os, "\\begin{" + name + "}", parent_context);
1199 parse_text_snippet(p, os, flags, outer, parent_context);
1200 handle_ert(os, "\\end{" + name + "}", parent_context);
1202 parent_context.new_layout_allowed = new_layout_allowed;
1206 void parse_environment(Parser & p, ostream & os, bool outer,
1207 string & last_env, Context & parent_context)
1209 Layout const * newlayout;
1210 InsetLayout const * newinsetlayout = 0;
1211 string const name = p.getArg('{', '}');
1212 const bool is_starred = suffixIs(name, '*');
1213 string const unstarred_name = rtrim(name, "*");
1214 active_environments.push_back(name);
1216 if (is_math_env(name)) {
1217 parent_context.check_layout(os);
1218 begin_inset(os, "Formula ");
1219 os << "\\begin{" << name << "}";
1220 parse_math(p, os, FLAG_END, MATH_MODE);
1221 os << "\\end{" << name << "}";
1223 if (is_display_math_env(name)) {
1224 // Prevent the conversion of a line break to a space
1225 // (bug 7668). This does not change the output, but
1226 // looks ugly in LyX.
1227 eat_whitespace(p, os, parent_context, false);
1231 else if (is_known(name, preamble.polyglossia_languages)) {
1232 // We must begin a new paragraph if not already done
1233 if (! parent_context.atParagraphStart()) {
1234 parent_context.check_end_layout(os);
1235 parent_context.new_paragraph(os);
1237 // save the language in the context so that it is
1238 // handled by parse_text
1239 parent_context.font.language = preamble.polyglossia2lyx(name);
1240 parse_text(p, os, FLAG_END, outer, parent_context);
1241 // Just in case the environment is empty
1242 parent_context.extra_stuff.erase();
1243 // We must begin a new paragraph to reset the language
1244 parent_context.new_paragraph(os);
1248 else if (unstarred_name == "tabular" || name == "longtable") {
1249 eat_whitespace(p, os, parent_context, false);
1250 string width = "0pt";
1251 if (name == "tabular*") {
1252 width = lyx::translate_len(p.getArg('{', '}'));
1253 eat_whitespace(p, os, parent_context, false);
1255 parent_context.check_layout(os);
1256 begin_inset(os, "Tabular ");
1257 handle_tabular(p, os, name, width, parent_context);
1262 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1263 eat_whitespace(p, os, parent_context, false);
1264 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1265 eat_whitespace(p, os, parent_context, false);
1266 parent_context.check_layout(os);
1267 begin_inset(os, "Float " + unstarred_name + "\n");
1268 // store the float type for subfloats
1269 // subfloats only work with figures and tables
1270 if (unstarred_name == "figure")
1271 float_type = unstarred_name;
1272 else if (unstarred_name == "table")
1273 float_type = unstarred_name;
1277 os << "placement " << opt << '\n';
1278 if (contains(opt, "H"))
1279 preamble.registerAutomaticallyLoadedPackage("float");
1281 Floating const & fl = parent_context.textclass.floats()
1282 .getType(unstarred_name);
1283 if (!fl.floattype().empty() && fl.usesFloatPkg())
1284 preamble.registerAutomaticallyLoadedPackage("float");
1287 os << "wide " << convert<string>(is_starred)
1288 << "\nsideways false"
1289 << "\nstatus open\n\n";
1290 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1292 // We don't need really a new paragraph, but
1293 // we must make sure that the next item gets a \begin_layout.
1294 parent_context.new_paragraph(os);
1296 // the float is parsed thus delete the type
1300 else if (unstarred_name == "sidewaysfigure"
1301 || unstarred_name == "sidewaystable") {
1302 eat_whitespace(p, os, parent_context, false);
1303 parent_context.check_layout(os);
1304 if (unstarred_name == "sidewaysfigure")
1305 begin_inset(os, "Float figure\n");
1307 begin_inset(os, "Float table\n");
1308 os << "wide " << convert<string>(is_starred)
1309 << "\nsideways true"
1310 << "\nstatus open\n\n";
1311 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1313 // We don't need really a new paragraph, but
1314 // we must make sure that the next item gets a \begin_layout.
1315 parent_context.new_paragraph(os);
1317 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1320 else if (name == "wrapfigure" || name == "wraptable") {
1321 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1322 eat_whitespace(p, os, parent_context, false);
1323 parent_context.check_layout(os);
1326 string overhang = "0col%";
1329 lines = p.getArg('[', ']');
1330 string const placement = p.getArg('{', '}');
1332 overhang = p.getArg('[', ']');
1333 string const width = p.getArg('{', '}');
1335 if (name == "wrapfigure")
1336 begin_inset(os, "Wrap figure\n");
1338 begin_inset(os, "Wrap table\n");
1339 os << "lines " << lines
1340 << "\nplacement " << placement
1341 << "\noverhang " << lyx::translate_len(overhang)
1342 << "\nwidth " << lyx::translate_len(width)
1343 << "\nstatus open\n\n";
1344 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1346 // We don't need really a new paragraph, but
1347 // we must make sure that the next item gets a \begin_layout.
1348 parent_context.new_paragraph(os);
1350 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1353 else if (name == "minipage") {
1354 eat_whitespace(p, os, parent_context, false);
1355 // Test whether this is an outer box of a shaded box
1357 // swallow arguments
1358 while (p.hasOpt()) {
1360 p.skip_spaces(true);
1363 p.skip_spaces(true);
1364 Token t = p.get_token();
1365 bool shaded = false;
1366 if (t.asInput() == "\\begin") {
1367 p.skip_spaces(true);
1368 if (p.getArg('{', '}') == "shaded")
1373 parse_outer_box(p, os, FLAG_END, outer,
1374 parent_context, name, "shaded");
1376 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1381 else if (name == "comment") {
1382 eat_whitespace(p, os, parent_context, false);
1383 parent_context.check_layout(os);
1384 begin_inset(os, "Note Comment\n");
1385 os << "status open\n";
1386 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1389 skip_braces(p); // eat {} that might by set by LyX behind comments
1390 preamble.registerAutomaticallyLoadedPackage("verbatim");
1393 else if (name == "verbatim") {
1394 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1395 string const s = p.plainEnvironment("verbatim");
1396 string::const_iterator it2 = s.begin();
1397 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1399 os << "\\backslash ";
1400 else if (*it == '\n') {
1402 // avoid adding an empty paragraph at the end
1403 // FIXME: if there are 2 consecutive spaces at the end ignore it
1404 // because LyX will re-add a \n
1405 // This hack must be removed once bug 8049 is fixed!
1406 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1407 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1411 os << "\n\\end_layout\n\n";
1413 // reset to Standard layout
1414 os << "\n\\begin_layout Standard\n";
1417 else if (name == "CJK") {
1418 // the scheme is \begin{CJK}{encoding}{mapping}{text}
1419 // It is impossible to decide if a CJK environment was in its own paragraph or within
1420 // a line. We therefore always assume a paragraph since the latter is a rare case.
1421 eat_whitespace(p, os, parent_context, false);
1422 parent_context.check_end_layout(os);
1423 // store the encoding to be able to reset it
1424 string const encoding_old = p.getEncoding();
1425 string const encoding = p.getArg('{', '}');
1426 // SJIS and Bg5 cannot be handled by iconv
1427 // JIS does not work with LyX's encoding conversion
1428 if (encoding != "Bg5" && encoding != "JIS" && encoding != "SJIS")
1429 p.setEncoding(encoding);
1431 p.setEncoding("utf8");
1432 // LyX doesn't support the second argument so if
1433 // this is used we need to output everything as ERT
1434 string const mapping = p.getArg('{', '}');
1435 char const * const * const where =
1436 is_known(encoding, supported_CJK_encodings);
1437 if ((!mapping.empty() && mapping != " ") || !where) {
1438 parent_context.check_layout(os);
1439 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1441 // we must parse the content as verbatim because e.g. JIS can contain
1442 // normally invalid characters
1443 string const s = p.plainEnvironment("CJK");
1444 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1446 handle_ert(os, "\\", parent_context);
1447 else if (*it == '$')
1448 handle_ert(os, "$", parent_context);
1452 handle_ert(os, "\\end{" + name + "}",
1456 supported_CJK_languages[where - supported_CJK_encodings];
1457 // store the language because we must reset it at the end
1458 string const lang_old = parent_context.font.language;
1459 parent_context.font.language = lang;
1460 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1461 parent_context.font.language = lang_old;
1462 parent_context.new_paragraph(os);
1464 p.setEncoding(encoding_old);
1468 else if (name == "lyxgreyedout") {
1469 eat_whitespace(p, os, parent_context, false);
1470 parent_context.check_layout(os);
1471 begin_inset(os, "Note Greyedout\n");
1472 os << "status open\n";
1473 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1476 if (!preamble.notefontcolor().empty())
1477 preamble.registerAutomaticallyLoadedPackage("color");
1480 else if (name == "framed" || name == "shaded") {
1481 eat_whitespace(p, os, parent_context, false);
1482 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1486 else if (name == "lstlisting") {
1487 eat_whitespace(p, os, parent_context, false);
1488 // FIXME handle the automatic color package loading
1489 // uwestoehr asks: In what case color is loaded?
1490 parse_listings(p, os, parent_context, false);
1494 else if (!parent_context.new_layout_allowed)
1495 parse_unknown_environment(p, name, os, FLAG_END, outer,
1498 // Alignment and spacing settings
1499 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1500 // therefore are totally broken!
1501 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1502 // they are commands not environments. They are furthermore switches that
1503 // can be ended by another switches, but also by commands like \footnote or
1504 // \parbox. So the only safe way is to leave them untouched.
1505 else if (name == "center" || name == "centering" ||
1506 name == "flushleft" || name == "flushright" ||
1507 name == "singlespace" || name == "onehalfspace" ||
1508 name == "doublespace" || name == "spacing") {
1509 eat_whitespace(p, os, parent_context, false);
1510 // We must begin a new paragraph if not already done
1511 if (! parent_context.atParagraphStart()) {
1512 parent_context.check_end_layout(os);
1513 parent_context.new_paragraph(os);
1515 if (name == "flushleft")
1516 parent_context.add_extra_stuff("\\align left\n");
1517 else if (name == "flushright")
1518 parent_context.add_extra_stuff("\\align right\n");
1519 else if (name == "center" || name == "centering")
1520 parent_context.add_extra_stuff("\\align center\n");
1521 else if (name == "singlespace")
1522 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1523 else if (name == "onehalfspace") {
1524 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1525 preamble.registerAutomaticallyLoadedPackage("setspace");
1526 } else if (name == "doublespace") {
1527 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1528 preamble.registerAutomaticallyLoadedPackage("setspace");
1529 } else if (name == "spacing") {
1530 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1531 preamble.registerAutomaticallyLoadedPackage("setspace");
1533 parse_text(p, os, FLAG_END, outer, parent_context);
1534 // Just in case the environment is empty
1535 parent_context.extra_stuff.erase();
1536 // We must begin a new paragraph to reset the alignment
1537 parent_context.new_paragraph(os);
1541 // The single '=' is meant here.
1542 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1543 eat_whitespace(p, os, parent_context, false);
1544 Context context(true, parent_context.textclass, newlayout,
1545 parent_context.layout, parent_context.font);
1546 if (parent_context.deeper_paragraph) {
1547 // We are beginning a nested environment after a
1548 // deeper paragraph inside the outer list environment.
1549 // Therefore we don't need to output a "begin deeper".
1550 context.need_end_deeper = true;
1552 parent_context.check_end_layout(os);
1553 if (last_env == name) {
1554 // we need to output a separator since LyX would export
1555 // the two environments as one otherwise (bug 5716)
1556 docstring const sep = from_ascii("--Separator--");
1557 TeX2LyXDocClass const & textclass(parent_context.textclass);
1558 if (textclass.hasLayout(sep)) {
1559 Context newcontext(parent_context);
1560 newcontext.layout = &(textclass[sep]);
1561 newcontext.check_layout(os);
1562 newcontext.check_end_layout(os);
1564 parent_context.check_layout(os);
1565 begin_inset(os, "Note Note\n");
1566 os << "status closed\n";
1567 Context newcontext(true, textclass,
1568 &(textclass.defaultLayout()));
1569 newcontext.check_layout(os);
1570 newcontext.check_end_layout(os);
1572 parent_context.check_end_layout(os);
1575 switch (context.layout->latextype) {
1576 case LATEX_LIST_ENVIRONMENT:
1577 context.add_par_extra_stuff("\\labelwidthstring "
1578 + p.verbatim_item() + '\n');
1581 case LATEX_BIB_ENVIRONMENT:
1582 p.verbatim_item(); // swallow next arg
1588 context.check_deeper(os);
1589 // handle known optional and required arguments
1590 // layouts require all optional arguments before the required ones
1591 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1592 // It is impossible to place anything after the environment name,
1593 // but before the first \\item.
1594 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1595 bool need_layout = true;
1596 unsigned int optargs = 0;
1597 while (optargs < context.layout->optargs) {
1598 eat_whitespace(p, os, context, false);
1599 if (p.next_token().cat() == catEscape ||
1600 p.next_token().character() != '[')
1602 p.get_token(); // eat '['
1604 context.check_layout(os);
1605 need_layout = false;
1607 begin_inset(os, "Argument\n");
1608 os << "status collapsed\n\n";
1609 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1611 eat_whitespace(p, os, context, false);
1614 unsigned int reqargs = 0;
1615 while (reqargs < context.layout->reqargs) {
1616 eat_whitespace(p, os, context, false);
1617 if (p.next_token().cat() != catBegin)
1619 p.get_token(); // eat '{'
1621 context.check_layout(os);
1622 need_layout = false;
1624 begin_inset(os, "Argument\n");
1625 os << "status collapsed\n\n";
1626 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1628 eat_whitespace(p, os, context, false);
1632 parse_text(p, os, FLAG_END, outer, context);
1633 context.check_end_layout(os);
1634 if (parent_context.deeper_paragraph) {
1635 // We must suppress the "end deeper" because we
1636 // suppressed the "begin deeper" above.
1637 context.need_end_deeper = false;
1639 context.check_end_deeper(os);
1640 parent_context.new_paragraph(os);
1642 if (!preamble.titleLayoutFound())
1643 preamble.titleLayoutFound(newlayout->intitle);
1644 set<string> const & req = newlayout->requires();
1645 set<string>::const_iterator it = req.begin();
1646 set<string>::const_iterator en = req.end();
1647 for (; it != en; ++it)
1648 preamble.registerAutomaticallyLoadedPackage(*it);
1651 // The single '=' is meant here.
1652 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1653 eat_whitespace(p, os, parent_context, false);
1654 parent_context.check_layout(os);
1655 begin_inset(os, "Flex ");
1656 os << to_utf8(newinsetlayout->name()) << '\n'
1657 << "status collapsed\n";
1658 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1662 else if (name == "appendix") {
1663 // This is no good latex style, but it works and is used in some documents...
1664 eat_whitespace(p, os, parent_context, false);
1665 parent_context.check_end_layout(os);
1666 Context context(true, parent_context.textclass, parent_context.layout,
1667 parent_context.layout, parent_context.font);
1668 context.check_layout(os);
1669 os << "\\start_of_appendix\n";
1670 parse_text(p, os, FLAG_END, outer, context);
1671 context.check_end_layout(os);
1675 else if (known_environments.find(name) != known_environments.end()) {
1676 vector<ArgumentType> arguments = known_environments[name];
1677 // The last "argument" denotes wether we may translate the
1678 // environment contents to LyX
1679 // The default required if no argument is given makes us
1680 // compatible with the reLyXre environment.
1681 ArgumentType contents = arguments.empty() ?
1684 if (!arguments.empty())
1685 arguments.pop_back();
1686 // See comment in parse_unknown_environment()
1687 bool const specialfont =
1688 (parent_context.font != parent_context.normalfont);
1689 bool const new_layout_allowed =
1690 parent_context.new_layout_allowed;
1692 parent_context.new_layout_allowed = false;
1693 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1694 outer, parent_context);
1695 if (contents == verbatim)
1696 handle_ert(os, p.verbatimEnvironment(name),
1699 parse_text_snippet(p, os, FLAG_END, outer,
1701 handle_ert(os, "\\end{" + name + "}", parent_context);
1703 parent_context.new_layout_allowed = new_layout_allowed;
1707 parse_unknown_environment(p, name, os, FLAG_END, outer,
1711 active_environments.pop_back();
1715 /// parses a comment and outputs it to \p os.
1716 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1718 LASSERT(t.cat() == catComment, return);
1719 if (!t.cs().empty()) {
1720 context.check_layout(os);
1721 handle_comment(os, '%' + t.cs(), context);
1722 if (p.next_token().cat() == catNewline) {
1723 // A newline after a comment line starts a new
1725 if (context.new_layout_allowed) {
1726 if(!context.atParagraphStart())
1727 // Only start a new paragraph if not already
1728 // done (we might get called recursively)
1729 context.new_paragraph(os);
1731 handle_ert(os, "\n", context);
1732 eat_whitespace(p, os, context, true);
1735 // "%\n" combination
1742 * Reads spaces and comments until the first non-space, non-comment token.
1743 * New paragraphs (double newlines or \\par) are handled like simple spaces
1744 * if \p eatParagraph is true.
1745 * Spaces are skipped, but comments are written to \p os.
1747 void eat_whitespace(Parser & p, ostream & os, Context & context,
1751 Token const & t = p.get_token();
1752 if (t.cat() == catComment)
1753 parse_comment(p, os, t, context);
1754 else if ((! eatParagraph && p.isParagraph()) ||
1755 (t.cat() != catSpace && t.cat() != catNewline)) {
1764 * Set a font attribute, parse text and reset the font attribute.
1765 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1766 * \param currentvalue Current value of the attribute. Is set to the new
1767 * value during parsing.
1768 * \param newvalue New value of the attribute
1770 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1771 Context & context, string const & attribute,
1772 string & currentvalue, string const & newvalue)
1774 context.check_layout(os);
1775 string const oldvalue = currentvalue;
1776 currentvalue = newvalue;
1777 os << '\n' << attribute << ' ' << newvalue << "\n";
1778 parse_text_snippet(p, os, flags, outer, context);
1779 context.check_layout(os);
1780 os << '\n' << attribute << ' ' << oldvalue << "\n";
1781 currentvalue = oldvalue;
1785 /// get the arguments of a natbib or jurabib citation command
1786 void get_cite_arguments(Parser & p, bool natbibOrder,
1787 string & before, string & after)
1789 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1791 // text before the citation
1793 // text after the citation
1794 after = p.getFullOpt();
1796 if (!after.empty()) {
1797 before = p.getFullOpt();
1798 if (natbibOrder && !before.empty())
1799 swap(before, after);
1804 /// Convert filenames with TeX macros and/or quotes to something LyX
1806 string const normalize_filename(string const & name)
1808 Parser p(trim(name, "\""));
1811 Token const & t = p.get_token();
1812 if (t.cat() != catEscape)
1814 else if (t.cs() == "lyxdot") {
1815 // This is used by LyX for simple dots in relative
1819 } else if (t.cs() == "space") {
1829 /// Convert \p name from TeX convention (relative to master file) to LyX
1830 /// convention (relative to .lyx file) if it is relative
1831 void fix_child_filename(string & name)
1833 string const absMasterTeX = getMasterFilePath(true);
1834 bool const isabs = FileName::isAbsolute(name);
1835 // convert from "relative to .tex master" to absolute original path
1837 name = makeAbsPath(name, absMasterTeX).absFileName();
1838 bool copyfile = copyFiles();
1839 string const absParentLyX = getParentFilePath(false);
1842 // convert from absolute original path to "relative to master file"
1843 string const rel = to_utf8(makeRelPath(from_utf8(name),
1844 from_utf8(absMasterTeX)));
1845 // re-interpret "relative to .tex file" as "relative to .lyx file"
1846 // (is different if the master .lyx file resides in a
1847 // different path than the master .tex file)
1848 string const absMasterLyX = getMasterFilePath(false);
1849 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1850 // Do not copy if the new path is impossible to create. Example:
1851 // absMasterTeX = "/foo/bar/"
1852 // absMasterLyX = "/bar/"
1853 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1854 if (contains(name, "/../"))
1861 // convert from absolute original path to
1862 // "relative to .lyx file"
1863 name = to_utf8(makeRelPath(from_utf8(abs),
1864 from_utf8(absParentLyX)));
1868 // convert from absolute original path to "relative to .lyx file"
1869 name = to_utf8(makeRelPath(from_utf8(name),
1870 from_utf8(absParentLyX)));
1875 void copy_file(FileName const & src, string dstname)
1879 string const absParent = getParentFilePath(false);
1881 if (FileName::isAbsolute(dstname))
1882 dst = FileName(dstname);
1884 dst = makeAbsPath(dstname, absParent);
1885 string const absMaster = getMasterFilePath(false);
1886 FileName const srcpath = src.onlyPath();
1887 FileName const dstpath = dst.onlyPath();
1888 if (equivalent(srcpath, dstpath))
1890 if (!dstpath.isDirectory()) {
1891 if (!dstpath.createPath()) {
1892 cerr << "Warning: Could not create directory for file `"
1893 << dst.absFileName() << "´." << endl;
1897 if (dst.isReadableFile()) {
1898 if (overwriteFiles())
1899 cerr << "Warning: Overwriting existing file `"
1900 << dst.absFileName() << "´." << endl;
1902 cerr << "Warning: Not overwriting existing file `"
1903 << dst.absFileName() << "´." << endl;
1907 if (!src.copyTo(dst))
1908 cerr << "Warning: Could not copy file `" << src.absFileName()
1909 << "´ to `" << dst.absFileName() << "´." << endl;
1913 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1914 void parse_noweb(Parser & p, ostream & os, Context & context)
1916 // assemble the rest of the keyword
1920 Token const & t = p.get_token();
1921 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1924 scrap = (p.good() && p.next_token().asInput() == "=");
1926 name += p.get_token().asInput();
1929 name += t.asInput();
1932 if (!scrap || !context.new_layout_allowed ||
1933 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1934 cerr << "Warning: Could not interpret '" << name
1935 << "'. Ignoring it." << endl;
1939 // We use new_paragraph instead of check_end_layout because the stuff
1940 // following the noweb chunk needs to start with a \begin_layout.
1941 // This may create a new paragraph even if there was none in the
1942 // noweb file, but the alternative is an invalid LyX file. Since
1943 // noweb code chunks are implemented with a layout style in LyX they
1944 // always must be in an own paragraph.
1945 context.new_paragraph(os);
1946 Context newcontext(true, context.textclass,
1947 &context.textclass[from_ascii("Scrap")]);
1948 newcontext.check_layout(os);
1951 Token const & t = p.get_token();
1952 // We abuse the parser a bit, because this is no TeX syntax
1954 if (t.cat() == catEscape)
1955 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1958 Context tmp(false, context.textclass,
1959 &context.textclass[from_ascii("Scrap")]);
1960 tmp.need_end_layout = true;
1961 tmp.check_layout(oss);
1962 os << subst(t.asInput(), "\n", oss.str());
1964 // The scrap chunk is ended by an @ at the beginning of a line.
1965 // After the @ the line may contain a comment and/or
1966 // whitespace, but nothing else.
1967 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1968 (p.next_token().cat() == catSpace ||
1969 p.next_token().cat() == catNewline ||
1970 p.next_token().cat() == catComment)) {
1971 while (p.good() && p.next_token().cat() == catSpace)
1972 os << p.get_token().asInput();
1973 if (p.next_token().cat() == catComment)
1974 // The comment includes a final '\n'
1975 os << p.get_token().asInput();
1977 if (p.next_token().cat() == catNewline)
1984 newcontext.check_end_layout(os);
1988 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1989 bool is_macro(Parser & p)
1991 Token first = p.curr_token();
1992 if (first.cat() != catEscape || !p.good())
1994 if (first.cs() == "def")
1996 if (first.cs() != "global" && first.cs() != "long")
1998 Token second = p.get_token();
2000 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2001 second.cat() == catNewline || second.cat() == catComment)) {
2002 second = p.get_token();
2005 bool secondvalid = second.cat() == catEscape;
2007 bool thirdvalid = false;
2008 if (p.good() && first.cs() == "global" && secondvalid &&
2009 second.cs() == "long") {
2010 third = p.get_token();
2012 while (p.good() && !p.isParagraph() &&
2013 (third.cat() == catSpace ||
2014 third.cat() == catNewline ||
2015 third.cat() == catComment)) {
2016 third = p.get_token();
2019 thirdvalid = third.cat() == catEscape;
2021 for (int i = 0; i < pos; ++i)
2026 return (first.cs() == "global" || first.cs() == "long") &&
2027 second.cs() == "def";
2028 return first.cs() == "global" && second.cs() == "long" &&
2029 third.cs() == "def";
2033 /// Parse a macro definition (assumes that is_macro() returned true)
2034 void parse_macro(Parser & p, ostream & os, Context & context)
2036 context.check_layout(os);
2037 Token first = p.curr_token();
2040 string command = first.asInput();
2041 if (first.cs() != "def") {
2043 eat_whitespace(p, os, context, false);
2044 second = p.curr_token();
2045 command += second.asInput();
2046 if (second.cs() != "def") {
2048 eat_whitespace(p, os, context, false);
2049 third = p.curr_token();
2050 command += third.asInput();
2053 eat_whitespace(p, os, context, false);
2054 string const name = p.get_token().cs();
2055 eat_whitespace(p, os, context, false);
2061 while (p.next_token().cat() != catBegin) {
2062 if (p.next_token().cat() == catParameter) {
2067 // followed by number?
2068 if (p.next_token().cat() == catOther) {
2069 char c = p.getChar();
2071 // number = current arity + 1?
2072 if (c == arity + '0' + 1)
2077 paramtext += p.get_token().cs();
2079 paramtext += p.get_token().cs();
2084 // only output simple (i.e. compatible) macro as FormulaMacros
2085 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2087 context.check_layout(os);
2088 begin_inset(os, "FormulaMacro");
2089 os << "\n\\def" << ert;
2092 handle_ert(os, command + ert, context);
2096 void registerExternalTemplatePackages(string const & name)
2098 external::TemplateManager const & etm = external::TemplateManager::get();
2099 external::Template const * const et = etm.getTemplateByName(name);
2102 external::Template::Formats::const_iterator cit = et->formats.end();
2104 cit = et->formats.find("PDFLaTeX");
2105 if (cit == et->formats.end())
2106 // If the template has not specified a PDFLaTeX output,
2107 // we try the LaTeX format.
2108 cit = et->formats.find("LaTeX");
2109 if (cit == et->formats.end())
2111 vector<string>::const_iterator qit = cit->second.requirements.begin();
2112 vector<string>::const_iterator qend = cit->second.requirements.end();
2113 for (; qit != qend; ++qit)
2114 preamble.registerAutomaticallyLoadedPackage(*qit);
2117 } // anonymous namespace
2120 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2123 Layout const * newlayout = 0;
2124 InsetLayout const * newinsetlayout = 0;
2125 char const * const * where = 0;
2126 // Store the latest bibliographystyle and nocite{*} option
2127 // (needed for bibtex inset)
2129 string bibliographystyle = "default";
2130 bool const use_natbib = preamble.isPackageUsed("natbib");
2131 bool const use_jurabib = preamble.isPackageUsed("jurabib");
2134 Token const & t = p.get_token();
2136 // it is impossible to determine the correct encoding for non-CJK Japanese.
2137 // Therefore write a note at the beginning of the document
2138 if (is_nonCJKJapanese) {
2139 context.check_layout(os);
2140 begin_inset(os, "Note Note\n");
2141 os << "status open\n\\begin_layout Plain Layout\n"
2142 << "\\series bold\n"
2143 << "Important information:\n"
2144 << "\\end_layout\n\n"
2145 << "\\begin_layout Plain Layout\n"
2146 << "This document is in Japanese (non-CJK).\n"
2147 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2148 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2149 << " encoding in the document settings.\n"
2150 << "\\end_layout\n";
2152 is_nonCJKJapanese = false;
2156 debugToken(cerr, t, flags);
2159 if (flags & FLAG_ITEM) {
2160 if (t.cat() == catSpace)
2163 flags &= ~FLAG_ITEM;
2164 if (t.cat() == catBegin) {
2165 // skip the brace and collect everything to the next matching
2167 flags |= FLAG_BRACE_LAST;
2171 // handle only this single token, leave the loop if done
2172 flags |= FLAG_LEAVE;
2175 if (t.cat() != catEscape && t.character() == ']' &&
2176 (flags & FLAG_BRACK_LAST))
2178 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2181 // If there is anything between \end{env} and \begin{env} we
2182 // don't need to output a separator.
2183 if (t.cat() != catSpace && t.cat() != catNewline &&
2184 t.asInput() != "\\begin")
2190 if (t.cat() == catMath) {
2191 // we are inside some text mode thingy, so opening new math is allowed
2192 context.check_layout(os);
2193 begin_inset(os, "Formula ");
2194 Token const & n = p.get_token();
2195 bool const display(n.cat() == catMath && outer);
2197 // TeX's $$...$$ syntax for displayed math
2199 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2201 p.get_token(); // skip the second '$' token
2203 // simple $...$ stuff
2206 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2211 // Prevent the conversion of a line break to a
2212 // space (bug 7668). This does not change the
2213 // output, but looks ugly in LyX.
2214 eat_whitespace(p, os, context, false);
2218 else if (t.cat() == catSuper || t.cat() == catSub)
2219 cerr << "catcode " << t << " illegal in text mode\n";
2221 // Basic support for english quotes. This should be
2222 // extended to other quotes, but is not so easy (a
2223 // left english quote is the same as a right german
2225 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2226 context.check_layout(os);
2227 begin_inset(os, "Quotes ");
2233 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2234 context.check_layout(os);
2235 begin_inset(os, "Quotes ");
2242 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2243 context.check_layout(os);
2244 begin_inset(os, "Quotes ");
2251 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2252 context.check_layout(os);
2253 begin_inset(os, "Quotes ");
2260 else if (t.asInput() == "<"
2261 && p.next_token().asInput() == "<" && noweb_mode) {
2263 parse_noweb(p, os, context);
2266 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2267 check_space(p, os, context);
2269 else if (t.character() == '[' && noweb_mode &&
2270 p.next_token().character() == '[') {
2271 // These can contain underscores
2273 string const s = p.getFullOpt() + ']';
2274 if (p.next_token().character() == ']')
2277 cerr << "Warning: Inserting missing ']' in '"
2278 << s << "'." << endl;
2279 handle_ert(os, s, context);
2282 else if (t.cat() == catLetter) {
2283 context.check_layout(os);
2284 // Workaround for bug 4752.
2285 // FIXME: This whole code block needs to be removed
2286 // when the bug is fixed and tex2lyx produces
2287 // the updated file format.
2288 // The replacement algorithm in LyX is so stupid that
2289 // it even translates a phrase if it is part of a word.
2290 bool handled = false;
2291 for (int const * l = known_phrase_lengths; *l; ++l) {
2292 string phrase = t.cs();
2293 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2294 phrase += p.get_token().cs();
2295 if (is_known(phrase, known_coded_phrases)) {
2296 handle_ert(os, phrase, context);
2300 for (size_t i = 1; i < phrase.length(); ++i)
2308 else if (t.cat() == catOther ||
2309 t.cat() == catAlign ||
2310 t.cat() == catParameter) {
2311 // This translates "&" to "\\&" which may be wrong...
2312 context.check_layout(os);
2316 else if (p.isParagraph()) {
2317 if (context.new_layout_allowed)
2318 context.new_paragraph(os);
2320 handle_ert(os, "\\par ", context);
2321 eat_whitespace(p, os, context, true);
2324 else if (t.cat() == catActive) {
2325 context.check_layout(os);
2326 if (t.character() == '~') {
2327 if (context.layout->free_spacing)
2330 begin_inset(os, "space ~\n");
2337 else if (t.cat() == catBegin) {
2338 Token const next = p.next_token();
2339 Token const end = p.next_next_token();
2340 if (next.cat() == catEnd) {
2342 Token const prev = p.prev_token();
2344 if (p.next_token().character() == '`' ||
2345 (prev.character() == '-' &&
2346 p.next_token().character() == '-'))
2347 ; // ignore it in {}`` or -{}-
2349 handle_ert(os, "{}", context);
2350 } else if (next.cat() == catEscape &&
2351 is_known(next.cs(), known_quotes) &&
2352 end.cat() == catEnd) {
2353 // Something like {\textquoteright} (e.g.
2354 // from writer2latex). LyX writes
2355 // \textquoteright{}, so we may skip the
2356 // braces here for better readability.
2357 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2360 context.check_layout(os);
2361 // special handling of font attribute changes
2362 Token const prev = p.prev_token();
2363 TeXFont const oldFont = context.font;
2364 if (next.character() == '[' ||
2365 next.character() == ']' ||
2366 next.character() == '*') {
2368 if (p.next_token().cat() == catEnd) {
2373 handle_ert(os, "{", context);
2374 parse_text_snippet(p, os,
2377 handle_ert(os, "}", context);
2379 } else if (! context.new_layout_allowed) {
2380 handle_ert(os, "{", context);
2381 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2383 handle_ert(os, "}", context);
2384 } else if (is_known(next.cs(), known_sizes)) {
2385 // next will change the size, so we must
2387 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2389 if (!context.atParagraphStart())
2391 << context.font.size << "\n";
2392 } else if (is_known(next.cs(), known_font_families)) {
2393 // next will change the font family, so we
2394 // must reset it here
2395 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2397 if (!context.atParagraphStart())
2399 << context.font.family << "\n";
2400 } else if (is_known(next.cs(), known_font_series)) {
2401 // next will change the font series, so we
2402 // must reset it here
2403 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2405 if (!context.atParagraphStart())
2407 << context.font.series << "\n";
2408 } else if (is_known(next.cs(), known_font_shapes)) {
2409 // next will change the font shape, so we
2410 // must reset it here
2411 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2413 if (!context.atParagraphStart())
2415 << context.font.shape << "\n";
2416 } else if (is_known(next.cs(), known_old_font_families) ||
2417 is_known(next.cs(), known_old_font_series) ||
2418 is_known(next.cs(), known_old_font_shapes)) {
2419 // next will change the font family, series
2420 // and shape, so we must reset it here
2421 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2423 if (!context.atParagraphStart())
2425 << context.font.family
2427 << context.font.series
2429 << context.font.shape << "\n";
2431 handle_ert(os, "{", context);
2432 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2434 handle_ert(os, "}", context);
2439 else if (t.cat() == catEnd) {
2440 if (flags & FLAG_BRACE_LAST) {
2443 cerr << "stray '}' in text\n";
2444 handle_ert(os, "}", context);
2447 else if (t.cat() == catComment)
2448 parse_comment(p, os, t, context);
2451 // control sequences
2454 else if (t.cs() == "(") {
2455 context.check_layout(os);
2456 begin_inset(os, "Formula");
2458 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2463 else if (t.cs() == "[") {
2464 context.check_layout(os);
2465 begin_inset(os, "Formula");
2467 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2470 // Prevent the conversion of a line break to a space
2471 // (bug 7668). This does not change the output, but
2472 // looks ugly in LyX.
2473 eat_whitespace(p, os, context, false);
2476 else if (t.cs() == "begin")
2477 parse_environment(p, os, outer, last_env,
2480 else if (t.cs() == "end") {
2481 if (flags & FLAG_END) {
2482 // eat environment name
2483 string const name = p.getArg('{', '}');
2484 if (name != active_environment())
2485 cerr << "\\end{" + name + "} does not match \\begin{"
2486 + active_environment() + "}\n";
2489 p.error("found 'end' unexpectedly");
2492 else if (t.cs() == "item") {
2494 bool const optarg = p.hasOpt();
2496 // FIXME: This swallows comments, but we cannot use
2497 // eat_whitespace() since we must not output
2498 // anything before the item.
2499 p.skip_spaces(true);
2500 s = p.verbatimOption();
2502 p.skip_spaces(false);
2504 context.check_layout(os);
2505 if (context.has_item) {
2506 // An item in an unknown list-like environment
2507 // FIXME: Do this in check_layout()!
2508 context.has_item = false;
2510 handle_ert(os, "\\item", context);
2512 handle_ert(os, "\\item ", context);
2515 if (context.layout->labeltype != LABEL_MANUAL) {
2516 // LyX does not support \item[\mybullet]
2517 // in itemize environments
2519 os << parse_text_snippet(p2,
2520 FLAG_BRACK_LAST, outer, context);
2521 } else if (!s.empty()) {
2522 // LyX adds braces around the argument,
2523 // so we need to remove them here.
2524 if (s.size() > 2 && s[0] == '{' &&
2525 s[s.size()-1] == '}')
2526 s = s.substr(1, s.size()-2);
2527 // If the argument contains a space we
2528 // must put it into ERT: Otherwise LyX
2529 // would misinterpret the space as
2530 // item delimiter (bug 7663)
2531 if (contains(s, ' ')) {
2532 handle_ert(os, s, context);
2535 os << parse_text_snippet(p2,
2539 // The space is needed to separate the
2540 // item from the rest of the sentence.
2542 eat_whitespace(p, os, context, false);
2547 else if (t.cs() == "bibitem") {
2549 context.check_layout(os);
2550 eat_whitespace(p, os, context, false);
2551 string label = convert_command_inset_arg(p.verbatimOption());
2552 string key = convert_command_inset_arg(p.verbatim_item());
2553 if (contains(label, '\\') || contains(key, '\\')) {
2554 // LyX can't handle LaTeX commands in labels or keys
2555 handle_ert(os, t.asInput() + '[' + label +
2556 "]{" + p.verbatim_item() + '}',
2559 begin_command_inset(os, "bibitem", "bibitem");
2560 os << "label \"" << label << "\"\n"
2561 "key \"" << key << "\"\n";
2566 else if (is_macro(p)) {
2567 // catch the case of \def\inputGnumericTable
2569 if (t.cs() == "def") {
2570 Token second = p.next_token();
2571 if (second.cs() == "inputGnumericTable") {
2575 Token third = p.get_token();
2577 if (third.cs() == "input") {
2581 string name = normalize_filename(p.verbatim_item());
2582 string const path = getMasterFilePath(true);
2583 // We want to preserve relative / absolute filenames,
2584 // therefore path is only used for testing
2585 // The file extension is in every case ".tex".
2586 // So we need to remove this extension and check for
2587 // the original one.
2588 name = removeExtension(name);
2589 if (!makeAbsPath(name, path).exists()) {
2590 char const * const Gnumeric_formats[] = {"gnumeric",
2592 string const Gnumeric_name =
2593 find_file(name, path, Gnumeric_formats);
2594 if (!Gnumeric_name.empty())
2595 name = Gnumeric_name;
2597 FileName const absname = makeAbsPath(name, path);
2598 if (absname.exists()) {
2599 fix_child_filename(name);
2600 copy_file(absname, name);
2602 cerr << "Warning: Could not find file '"
2603 << name << "'." << endl;
2604 context.check_layout(os);
2605 begin_inset(os, "External\n\ttemplate ");
2606 os << "GnumericSpreadsheet\n\tfilename "
2609 context.check_layout(os);
2611 // register the packages that are automatically loaded
2612 // by the Gnumeric template
2613 registerExternalTemplatePackages("GnumericSpreadsheet");
2618 parse_macro(p, os, context);
2621 else if (t.cs() == "noindent") {
2623 context.add_par_extra_stuff("\\noindent\n");
2626 else if (t.cs() == "appendix") {
2627 context.add_par_extra_stuff("\\start_of_appendix\n");
2628 // We need to start a new paragraph. Otherwise the
2629 // appendix in 'bla\appendix\chapter{' would start
2631 context.new_paragraph(os);
2632 // We need to make sure that the paragraph is
2633 // generated even if it is empty. Otherwise the
2634 // appendix in '\par\appendix\par\chapter{' would
2636 context.check_layout(os);
2637 // FIXME: This is a hack to prevent paragraph
2638 // deletion if it is empty. Handle this better!
2640 "%dummy comment inserted by tex2lyx to "
2641 "ensure that this paragraph is not empty",
2643 // Both measures above may generate an additional
2644 // empty paragraph, but that does not hurt, because
2645 // whitespace does not matter here.
2646 eat_whitespace(p, os, context, true);
2649 // Must catch empty dates before findLayout is called below
2650 else if (t.cs() == "date") {
2651 eat_whitespace(p, os, context, false);
2653 string const date = p.verbatim_item();
2656 preamble.suppressDate(true);
2659 preamble.suppressDate(false);
2660 if (context.new_layout_allowed &&
2661 (newlayout = findLayout(context.textclass,
2664 output_command_layout(os, p, outer,
2665 context, newlayout);
2666 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2667 if (!preamble.titleLayoutFound())
2668 preamble.titleLayoutFound(newlayout->intitle);
2669 set<string> const & req = newlayout->requires();
2670 set<string>::const_iterator it = req.begin();
2671 set<string>::const_iterator en = req.end();
2672 for (; it != en; ++it)
2673 preamble.registerAutomaticallyLoadedPackage(*it);
2676 "\\date{" + p.verbatim_item() + '}',
2681 // Starred section headings
2682 // Must attempt to parse "Section*" before "Section".
2683 else if ((p.next_token().asInput() == "*") &&
2684 context.new_layout_allowed &&
2685 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2688 output_command_layout(os, p, outer, context, newlayout);
2690 if (!preamble.titleLayoutFound())
2691 preamble.titleLayoutFound(newlayout->intitle);
2692 set<string> const & req = newlayout->requires();
2693 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2694 preamble.registerAutomaticallyLoadedPackage(*it);
2697 // Section headings and the like
2698 else if (context.new_layout_allowed &&
2699 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2701 output_command_layout(os, p, outer, context, newlayout);
2703 if (!preamble.titleLayoutFound())
2704 preamble.titleLayoutFound(newlayout->intitle);
2705 set<string> const & req = newlayout->requires();
2706 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2707 preamble.registerAutomaticallyLoadedPackage(*it);
2710 else if (t.cs() == "caption") {
2712 context.check_layout(os);
2714 begin_inset(os, "Caption\n");
2715 Context newcontext(true, context.textclass, 0, 0, context.font);
2716 newcontext.check_layout(os);
2717 if (p.next_token().cat() != catEscape &&
2718 p.next_token().character() == '[') {
2719 p.get_token(); // eat '['
2720 begin_inset(os, "Argument\n");
2721 os << "status collapsed\n";
2722 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2724 eat_whitespace(p, os, context, false);
2726 parse_text(p, os, FLAG_ITEM, outer, context);
2727 context.check_end_layout(os);
2728 // We don't need really a new paragraph, but
2729 // we must make sure that the next item gets a \begin_layout.
2730 context.new_paragraph(os);
2733 newcontext.check_end_layout(os);
2736 else if (t.cs() == "subfloat") {
2737 // the syntax is \subfloat[caption]{content}
2738 // if it is a table of figure depends on the surrounding float
2739 bool has_caption = false;
2741 // do nothing if there is no outer float
2742 if (!float_type.empty()) {
2743 context.check_layout(os);
2745 begin_inset(os, "Float " + float_type + "\n");
2747 << "\nsideways false"
2748 << "\nstatus collapsed\n\n";
2751 if (p.next_token().cat() != catEscape &&
2752 p.next_token().character() == '[') {
2753 p.get_token(); // eat '['
2754 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2758 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2759 // the caption comes always as the last
2761 // we must make sure that the caption gets a \begin_layout
2762 os << "\n\\begin_layout Plain Layout";
2764 begin_inset(os, "Caption\n");
2765 Context newcontext(true, context.textclass,
2766 0, 0, context.font);
2767 newcontext.check_layout(os);
2768 os << caption << "\n";
2769 newcontext.check_end_layout(os);
2770 // We don't need really a new paragraph, but
2771 // we must make sure that the next item gets a \begin_layout.
2772 //newcontext.new_paragraph(os);
2776 // We don't need really a new paragraph, but
2777 // we must make sure that the next item gets a \begin_layout.
2779 context.new_paragraph(os);
2782 context.check_end_layout(os);
2783 // close the layout we opened
2785 os << "\n\\end_layout\n";
2787 // if the float type is not supported or there is no surrounding float
2790 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2791 handle_ert(os, t.asInput() + '[' + opt_arg +
2792 "]{" + p.verbatim_item() + '}', context);
2794 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2798 else if (t.cs() == "includegraphics") {
2799 bool const clip = p.next_token().asInput() == "*";
2802 string const arg = p.getArg('[', ']');
2803 map<string, string> opts;
2804 vector<string> keys;
2805 split_map(arg, opts, keys);
2807 opts["clip"] = string();
2808 string name = normalize_filename(p.verbatim_item());
2810 string const path = getMasterFilePath(true);
2811 // We want to preserve relative / absolute filenames,
2812 // therefore path is only used for testing
2813 if (!makeAbsPath(name, path).exists()) {
2814 // The file extension is probably missing.
2815 // Now try to find it out.
2816 string const dvips_name =
2817 find_file(name, path,
2818 known_dvips_graphics_formats);
2819 string const pdftex_name =
2820 find_file(name, path,
2821 known_pdftex_graphics_formats);
2822 if (!dvips_name.empty()) {
2823 if (!pdftex_name.empty()) {
2824 cerr << "This file contains the "
2826 "\"\\includegraphics{"
2828 "However, files\n\""
2829 << dvips_name << "\" and\n\""
2830 << pdftex_name << "\"\n"
2831 "both exist, so I had to make a "
2832 "choice and took the first one.\n"
2833 "Please move the unwanted one "
2834 "someplace else and try again\n"
2835 "if my choice was wrong."
2839 } else if (!pdftex_name.empty()) {
2845 FileName const absname = makeAbsPath(name, path);
2846 if (absname.exists()) {
2847 fix_child_filename(name);
2848 copy_file(absname, name);
2850 cerr << "Warning: Could not find graphics file '"
2851 << name << "'." << endl;
2853 context.check_layout(os);
2854 begin_inset(os, "Graphics ");
2855 os << "\n\tfilename " << name << '\n';
2856 if (opts.find("width") != opts.end())
2858 << translate_len(opts["width"]) << '\n';
2859 if (opts.find("height") != opts.end())
2861 << translate_len(opts["height"]) << '\n';
2862 if (opts.find("scale") != opts.end()) {
2863 istringstream iss(opts["scale"]);
2867 os << "\tscale " << val << '\n';
2869 if (opts.find("angle") != opts.end()) {
2870 os << "\trotateAngle "
2871 << opts["angle"] << '\n';
2872 vector<string>::const_iterator a =
2873 find(keys.begin(), keys.end(), "angle");
2874 vector<string>::const_iterator s =
2875 find(keys.begin(), keys.end(), "width");
2876 if (s == keys.end())
2877 s = find(keys.begin(), keys.end(), "height");
2878 if (s == keys.end())
2879 s = find(keys.begin(), keys.end(), "scale");
2880 if (s != keys.end() && distance(s, a) > 0)
2881 os << "\tscaleBeforeRotation\n";
2883 if (opts.find("origin") != opts.end()) {
2885 string const opt = opts["origin"];
2886 if (opt.find('l') != string::npos) ss << "left";
2887 if (opt.find('r') != string::npos) ss << "right";
2888 if (opt.find('c') != string::npos) ss << "center";
2889 if (opt.find('t') != string::npos) ss << "Top";
2890 if (opt.find('b') != string::npos) ss << "Bottom";
2891 if (opt.find('B') != string::npos) ss << "Baseline";
2892 if (!ss.str().empty())
2893 os << "\trotateOrigin " << ss.str() << '\n';
2895 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2897 if (opts.find("keepaspectratio") != opts.end())
2898 os << "\tkeepAspectRatio\n";
2899 if (opts.find("clip") != opts.end())
2901 if (opts.find("draft") != opts.end())
2903 if (opts.find("bb") != opts.end())
2904 os << "\tBoundingBox "
2905 << opts["bb"] << '\n';
2906 int numberOfbbOptions = 0;
2907 if (opts.find("bbllx") != opts.end())
2908 numberOfbbOptions++;
2909 if (opts.find("bblly") != opts.end())
2910 numberOfbbOptions++;
2911 if (opts.find("bburx") != opts.end())
2912 numberOfbbOptions++;
2913 if (opts.find("bbury") != opts.end())
2914 numberOfbbOptions++;
2915 if (numberOfbbOptions == 4)
2916 os << "\tBoundingBox "
2917 << opts["bbllx"] << " " << opts["bblly"] << " "
2918 << opts["bburx"] << " " << opts["bbury"] << '\n';
2919 else if (numberOfbbOptions > 0)
2920 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2921 numberOfbbOptions = 0;
2922 if (opts.find("natwidth") != opts.end())
2923 numberOfbbOptions++;
2924 if (opts.find("natheight") != opts.end())
2925 numberOfbbOptions++;
2926 if (numberOfbbOptions == 2)
2927 os << "\tBoundingBox 0bp 0bp "
2928 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2929 else if (numberOfbbOptions > 0)
2930 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2931 ostringstream special;
2932 if (opts.find("hiresbb") != opts.end())
2933 special << "hiresbb,";
2934 if (opts.find("trim") != opts.end())
2936 if (opts.find("viewport") != opts.end())
2937 special << "viewport=" << opts["viewport"] << ',';
2938 if (opts.find("totalheight") != opts.end())
2939 special << "totalheight=" << opts["totalheight"] << ',';
2940 if (opts.find("type") != opts.end())
2941 special << "type=" << opts["type"] << ',';
2942 if (opts.find("ext") != opts.end())
2943 special << "ext=" << opts["ext"] << ',';
2944 if (opts.find("read") != opts.end())
2945 special << "read=" << opts["read"] << ',';
2946 if (opts.find("command") != opts.end())
2947 special << "command=" << opts["command"] << ',';
2948 string s_special = special.str();
2949 if (!s_special.empty()) {
2950 // We had special arguments. Remove the trailing ','.
2951 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2953 // TODO: Handle the unknown settings better.
2954 // Warn about invalid options.
2955 // Check whether some option was given twice.
2957 preamble.registerAutomaticallyLoadedPackage("graphicx");
2960 else if (t.cs() == "footnote" ||
2961 (t.cs() == "thanks" && context.layout->intitle)) {
2963 context.check_layout(os);
2964 begin_inset(os, "Foot\n");
2965 os << "status collapsed\n\n";
2966 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2970 else if (t.cs() == "marginpar") {
2972 context.check_layout(os);
2973 begin_inset(os, "Marginal\n");
2974 os << "status collapsed\n\n";
2975 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2979 else if (t.cs() == "lstinline") {
2981 parse_listings(p, os, context, true);
2984 else if (t.cs() == "ensuremath") {
2986 context.check_layout(os);
2987 string const s = p.verbatim_item();
2988 //FIXME: this never triggers in UTF8
2989 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2992 handle_ert(os, "\\ensuremath{" + s + "}",
2996 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2997 if (preamble.titleLayoutFound()) {
2999 skip_spaces_braces(p);
3001 handle_ert(os, t.asInput(), context);
3004 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3005 context.check_layout(os);
3006 begin_command_inset(os, "toc", t.cs());
3008 skip_spaces_braces(p);
3009 if (t.cs() == "lstlistoflistings")
3010 preamble.registerAutomaticallyLoadedPackage("listings");
3013 else if (t.cs() == "listoffigures") {
3014 context.check_layout(os);
3015 begin_inset(os, "FloatList figure\n");
3017 skip_spaces_braces(p);
3020 else if (t.cs() == "listoftables") {
3021 context.check_layout(os);
3022 begin_inset(os, "FloatList table\n");
3024 skip_spaces_braces(p);
3027 else if (t.cs() == "listof") {
3028 p.skip_spaces(true);
3029 string const name = p.get_token().cs();
3030 if (context.textclass.floats().typeExist(name)) {
3031 context.check_layout(os);
3032 begin_inset(os, "FloatList ");
3035 p.get_token(); // swallow second arg
3037 handle_ert(os, "\\listof{" + name + "}", context);
3040 else if ((where = is_known(t.cs(), known_text_font_families)))
3041 parse_text_attributes(p, os, FLAG_ITEM, outer,
3042 context, "\\family", context.font.family,
3043 known_coded_font_families[where - known_text_font_families]);
3045 else if ((where = is_known(t.cs(), known_text_font_series)))
3046 parse_text_attributes(p, os, FLAG_ITEM, outer,
3047 context, "\\series", context.font.series,
3048 known_coded_font_series[where - known_text_font_series]);
3050 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3051 parse_text_attributes(p, os, FLAG_ITEM, outer,
3052 context, "\\shape", context.font.shape,
3053 known_coded_font_shapes[where - known_text_font_shapes]);
3055 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3056 context.check_layout(os);
3057 TeXFont oldFont = context.font;
3058 context.font.init();
3059 context.font.size = oldFont.size;
3060 os << "\n\\family " << context.font.family << "\n";
3061 os << "\n\\series " << context.font.series << "\n";
3062 os << "\n\\shape " << context.font.shape << "\n";
3063 if (t.cs() == "textnormal") {
3064 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3065 output_font_change(os, context.font, oldFont);
3066 context.font = oldFont;
3068 eat_whitespace(p, os, context, false);
3071 else if (t.cs() == "textcolor") {
3072 // scheme is \textcolor{color name}{text}
3073 string const color = p.verbatim_item();
3074 // we only support the predefined colors of the color package
3075 if (color == "black" || color == "blue" || color == "cyan"
3076 || color == "green" || color == "magenta" || color == "red"
3077 || color == "white" || color == "yellow") {
3078 context.check_layout(os);
3079 os << "\n\\color " << color << "\n";
3080 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3081 context.check_layout(os);
3082 os << "\n\\color inherit\n";
3083 preamble.registerAutomaticallyLoadedPackage("color");
3085 // for custom defined colors
3086 handle_ert(os, t.asInput() + "{" + color + "}", context);
3089 else if (t.cs() == "underbar" || t.cs() == "uline") {
3090 // \underbar is not 100% correct (LyX outputs \uline
3091 // of ulem.sty). The difference is that \ulem allows
3092 // line breaks, and \underbar does not.
3093 // Do NOT handle \underline.
3094 // \underbar cuts through y, g, q, p etc.,
3095 // \underline does not.
3096 context.check_layout(os);
3097 os << "\n\\bar under\n";
3098 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3099 context.check_layout(os);
3100 os << "\n\\bar default\n";
3101 preamble.registerAutomaticallyLoadedPackage("ulem");
3104 else if (t.cs() == "sout") {
3105 context.check_layout(os);
3106 os << "\n\\strikeout on\n";
3107 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3108 context.check_layout(os);
3109 os << "\n\\strikeout default\n";
3110 preamble.registerAutomaticallyLoadedPackage("ulem");
3113 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3114 t.cs() == "emph" || t.cs() == "noun") {
3115 context.check_layout(os);
3116 os << "\n\\" << t.cs() << " on\n";
3117 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3118 context.check_layout(os);
3119 os << "\n\\" << t.cs() << " default\n";
3120 if (t.cs() == "uuline" || t.cs() == "uwave")
3121 preamble.registerAutomaticallyLoadedPackage("ulem");
3124 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3125 context.check_layout(os);
3126 string name = p.getArg('{', '}');
3127 string localtime = p.getArg('{', '}');
3128 preamble.registerAuthor(name);
3129 Author const & author = preamble.getAuthor(name);
3130 // from_ctime() will fail if LyX decides to output the
3131 // time in the text language. It might also use a wrong
3132 // time zone (if the original LyX document was exported
3133 // with a different time zone).
3134 time_t ptime = from_ctime(localtime);
3135 if (ptime == static_cast<time_t>(-1)) {
3136 cerr << "Warning: Could not parse time `" << localtime
3137 << "´ for change tracking, using current time instead.\n";
3138 ptime = current_time();
3140 if (t.cs() == "lyxadded")
3141 os << "\n\\change_inserted ";
3143 os << "\n\\change_deleted ";
3144 os << author.bufferId() << ' ' << ptime << '\n';
3145 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3146 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3147 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3148 LaTeXPackages::isAvailable("xcolor");
3149 // No need to test for luatex, since luatex comes in
3150 // two flavours (dvi and pdf), like latex, and those
3151 // are detected by pdflatex.
3152 if (pdflatex || xetex) {
3154 preamble.registerAutomaticallyLoadedPackage("ulem");
3155 preamble.registerAutomaticallyLoadedPackage("xcolor");
3156 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3160 preamble.registerAutomaticallyLoadedPackage("dvipost");
3161 } else if (xcolorulem) {
3162 preamble.registerAutomaticallyLoadedPackage("ulem");
3163 preamble.registerAutomaticallyLoadedPackage("xcolor");
3168 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3169 t.cs() == "vphantom") {
3170 context.check_layout(os);
3171 if (t.cs() == "phantom")
3172 begin_inset(os, "Phantom Phantom\n");
3173 if (t.cs() == "hphantom")
3174 begin_inset(os, "Phantom HPhantom\n");
3175 if (t.cs() == "vphantom")
3176 begin_inset(os, "Phantom VPhantom\n");
3177 os << "status open\n";
3178 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3183 else if (t.cs() == "href") {
3184 context.check_layout(os);
3185 string target = convert_command_inset_arg(p.verbatim_item());
3186 string name = convert_command_inset_arg(p.verbatim_item());
3188 size_t i = target.find(':');
3189 if (i != string::npos) {
3190 type = target.substr(0, i + 1);
3191 if (type == "mailto:" || type == "file:")
3192 target = target.substr(i + 1);
3193 // handle the case that name is equal to target, except of "http://"
3194 else if (target.substr(i + 3) == name && type == "http:")
3197 begin_command_inset(os, "href", "href");
3199 os << "name \"" << name << "\"\n";
3200 os << "target \"" << target << "\"\n";
3201 if (type == "mailto:" || type == "file:")
3202 os << "type \"" << type << "\"\n";
3204 skip_spaces_braces(p);
3207 else if (t.cs() == "lyxline") {
3208 // swallow size argument (it is not used anyway)
3210 if (!context.atParagraphStart()) {
3211 // so our line is in the middle of a paragraph
3212 // we need to add a new line, lest this line
3213 // follow the other content on that line and
3214 // run off the side of the page
3215 // FIXME: This may create an empty paragraph,
3216 // but without that it would not be
3217 // possible to set noindent below.
3218 // Fortunately LaTeX does not care
3219 // about the empty paragraph.
3220 context.new_paragraph(os);
3222 if (preamble.indentParagraphs()) {
3223 // we need to unindent, lest the line be too long
3224 context.add_par_extra_stuff("\\noindent\n");
3226 context.check_layout(os);
3227 begin_command_inset(os, "line", "rule");
3228 os << "offset \"0.5ex\"\n"
3229 "width \"100line%\"\n"
3234 else if (t.cs() == "rule") {
3235 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3236 string const width = p.getArg('{', '}');
3237 string const thickness = p.getArg('{', '}');
3238 context.check_layout(os);
3239 begin_command_inset(os, "line", "rule");
3240 if (!offset.empty())
3241 os << "offset \"" << translate_len(offset) << "\"\n";
3242 os << "width \"" << translate_len(width) << "\"\n"
3243 "height \"" << translate_len(thickness) << "\"\n";
3247 else if (is_known(t.cs(), known_phrases) ||
3248 (t.cs() == "protect" &&
3249 p.next_token().cat() == catEscape &&
3250 is_known(p.next_token().cs(), known_phrases))) {
3251 // LyX sometimes puts a \protect in front, so we have to ignore it
3252 // FIXME: This needs to be changed when bug 4752 is fixed.
3254 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3256 context.check_layout(os);
3257 os << known_coded_phrases[where - known_phrases];
3258 skip_spaces_braces(p);
3261 else if ((where = is_known(t.cs(), known_ref_commands))) {
3262 string const opt = p.getOpt();
3264 context.check_layout(os);
3265 begin_command_inset(os, "ref",
3266 known_coded_ref_commands[where - known_ref_commands]);
3267 os << "reference \""
3268 << convert_command_inset_arg(p.verbatim_item())
3271 if (t.cs() == "vref" || t.cs() == "vpageref")
3272 preamble.registerAutomaticallyLoadedPackage("varioref");
3275 // LyX does not support optional arguments of ref commands
3276 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3277 p.verbatim_item() + "}", context);
3281 else if (use_natbib &&
3282 is_known(t.cs(), known_natbib_commands) &&
3283 ((t.cs() != "citefullauthor" &&
3284 t.cs() != "citeyear" &&
3285 t.cs() != "citeyearpar") ||
3286 p.next_token().asInput() != "*")) {
3287 context.check_layout(os);
3288 string command = t.cs();
3289 if (p.next_token().asInput() == "*") {
3293 if (command == "citefullauthor")
3294 // alternative name for "\\citeauthor*"
3295 command = "citeauthor*";
3297 // text before the citation
3299 // text after the citation
3301 get_cite_arguments(p, true, before, after);
3303 if (command == "cite") {
3304 // \cite without optional argument means
3305 // \citet, \cite with at least one optional
3306 // argument means \citep.
3307 if (before.empty() && after.empty())
3312 if (before.empty() && after == "[]")
3313 // avoid \citet[]{a}
3315 else if (before == "[]" && after == "[]") {
3316 // avoid \citet[][]{a}
3320 // remove the brackets around after and before
3321 if (!after.empty()) {
3323 after.erase(after.length() - 1, 1);
3324 after = convert_command_inset_arg(after);
3326 if (!before.empty()) {
3328 before.erase(before.length() - 1, 1);
3329 before = convert_command_inset_arg(before);
3331 begin_command_inset(os, "citation", command);
3332 os << "after " << '"' << after << '"' << "\n";
3333 os << "before " << '"' << before << '"' << "\n";
3335 << convert_command_inset_arg(p.verbatim_item())
3340 else if (use_jurabib &&
3341 is_known(t.cs(), known_jurabib_commands) &&
3342 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3343 context.check_layout(os);
3344 string command = t.cs();
3345 if (p.next_token().asInput() == "*") {
3349 char argumentOrder = '\0';
3350 vector<string> const options =
3351 preamble.getPackageOptions("jurabib");
3352 if (find(options.begin(), options.end(),
3353 "natbiborder") != options.end())
3354 argumentOrder = 'n';
3355 else if (find(options.begin(), options.end(),
3356 "jurabiborder") != options.end())
3357 argumentOrder = 'j';
3359 // text before the citation
3361 // text after the citation
3363 get_cite_arguments(p, argumentOrder != 'j', before, after);
3365 string const citation = p.verbatim_item();
3366 if (!before.empty() && argumentOrder == '\0') {
3367 cerr << "Warning: Assuming argument order "
3368 "of jurabib version 0.6 for\n'"
3369 << command << before << after << '{'
3370 << citation << "}'.\n"
3371 "Add 'jurabiborder' to the jurabib "
3372 "package options if you used an\n"
3373 "earlier jurabib version." << endl;
3375 if (!after.empty()) {
3377 after.erase(after.length() - 1, 1);
3379 if (!before.empty()) {
3381 before.erase(before.length() - 1, 1);
3383 begin_command_inset(os, "citation", command);
3384 os << "after " << '"' << after << '"' << "\n";
3385 os << "before " << '"' << before << '"' << "\n";
3386 os << "key " << '"' << citation << '"' << "\n";
3390 else if (t.cs() == "cite"
3391 || t.cs() == "nocite") {
3392 context.check_layout(os);
3393 string after = convert_command_inset_arg(p.getArg('[', ']'));
3394 string key = convert_command_inset_arg(p.verbatim_item());
3395 // store the case that it is "\nocite{*}" to use it later for
3398 begin_command_inset(os, "citation", t.cs());
3399 os << "after " << '"' << after << '"' << "\n";
3400 os << "key " << '"' << key << '"' << "\n";
3402 } else if (t.cs() == "nocite")
3406 else if (t.cs() == "index" ||
3407 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3408 context.check_layout(os);
3409 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3410 p.getArg('[', ']') : "";
3411 string const kind = arg.empty() ? "idx" : arg;
3412 begin_inset(os, "Index ");
3413 os << kind << "\nstatus collapsed\n";
3414 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3417 preamble.registerAutomaticallyLoadedPackage("splitidx");
3420 else if (t.cs() == "nomenclature") {
3421 context.check_layout(os);
3422 begin_command_inset(os, "nomenclature", "nomenclature");
3423 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3424 if (!prefix.empty())
3425 os << "prefix " << '"' << prefix << '"' << "\n";
3426 os << "symbol " << '"'
3427 << convert_command_inset_arg(p.verbatim_item());
3428 os << "\"\ndescription \""
3429 << convert_command_inset_arg(p.verbatim_item())
3432 preamble.registerAutomaticallyLoadedPackage("nomencl");
3435 else if (t.cs() == "label") {
3436 context.check_layout(os);
3437 begin_command_inset(os, "label", "label");
3439 << convert_command_inset_arg(p.verbatim_item())
3444 else if (t.cs() == "printindex") {
3445 context.check_layout(os);
3446 begin_command_inset(os, "index_print", "printindex");
3447 os << "type \"idx\"\n";
3449 skip_spaces_braces(p);
3450 preamble.registerAutomaticallyLoadedPackage("makeidx");
3451 if (preamble.use_indices() == "true")
3452 preamble.registerAutomaticallyLoadedPackage("splitidx");
3455 else if (t.cs() == "printnomenclature") {
3457 string width_type = "";
3458 context.check_layout(os);
3459 begin_command_inset(os, "nomencl_print", "printnomenclature");
3460 // case of a custom width
3462 width = p.getArg('[', ']');
3463 width = translate_len(width);
3464 width_type = "custom";
3466 // case of no custom width
3467 // the case of no custom width but the width set
3468 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3469 // because the user could have set anything, not only the width
3470 // of the longest label (which would be width_type = "auto")
3471 string label = convert_command_inset_arg(p.getArg('{', '}'));
3472 if (label.empty() && width_type.empty())
3473 width_type = "none";
3474 os << "set_width \"" << width_type << "\"\n";
3475 if (width_type == "custom")
3476 os << "width \"" << width << '\"';
3478 skip_spaces_braces(p);
3479 preamble.registerAutomaticallyLoadedPackage("nomencl");
3482 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3483 context.check_layout(os);
3484 begin_inset(os, "script ");
3485 os << t.cs().substr(4) << '\n';
3486 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3488 if (t.cs() == "textsubscript")
3489 preamble.registerAutomaticallyLoadedPackage("subscript");
3492 else if ((where = is_known(t.cs(), known_quotes))) {
3493 context.check_layout(os);
3494 begin_inset(os, "Quotes ");
3495 os << known_coded_quotes[where - known_quotes];
3497 // LyX adds {} after the quote, so we have to eat
3498 // spaces here if there are any before a possible
3500 eat_whitespace(p, os, context, false);
3504 else if ((where = is_known(t.cs(), known_sizes)) &&
3505 context.new_layout_allowed) {
3506 context.check_layout(os);
3507 TeXFont const oldFont = context.font;
3508 context.font.size = known_coded_sizes[where - known_sizes];
3509 output_font_change(os, oldFont, context.font);
3510 eat_whitespace(p, os, context, false);
3513 else if ((where = is_known(t.cs(), known_font_families)) &&
3514 context.new_layout_allowed) {
3515 context.check_layout(os);
3516 TeXFont const oldFont = context.font;
3517 context.font.family =
3518 known_coded_font_families[where - known_font_families];
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_series)) &&
3524 context.new_layout_allowed) {
3525 context.check_layout(os);
3526 TeXFont const oldFont = context.font;
3527 context.font.series =
3528 known_coded_font_series[where - known_font_series];
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_shapes)) &&
3534 context.new_layout_allowed) {
3535 context.check_layout(os);
3536 TeXFont const oldFont = context.font;
3537 context.font.shape =
3538 known_coded_font_shapes[where - known_font_shapes];
3539 output_font_change(os, oldFont, context.font);
3540 eat_whitespace(p, os, context, false);
3542 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3543 context.new_layout_allowed) {
3544 context.check_layout(os);
3545 TeXFont const oldFont = context.font;
3546 context.font.init();
3547 context.font.size = oldFont.size;
3548 context.font.family =
3549 known_coded_font_families[where - known_old_font_families];
3550 output_font_change(os, oldFont, context.font);
3551 eat_whitespace(p, os, context, false);
3554 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3555 context.new_layout_allowed) {
3556 context.check_layout(os);
3557 TeXFont const oldFont = context.font;
3558 context.font.init();
3559 context.font.size = oldFont.size;
3560 context.font.series =
3561 known_coded_font_series[where - known_old_font_series];
3562 output_font_change(os, oldFont, context.font);
3563 eat_whitespace(p, os, context, false);
3566 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3567 context.new_layout_allowed) {
3568 context.check_layout(os);
3569 TeXFont const oldFont = context.font;
3570 context.font.init();
3571 context.font.size = oldFont.size;
3572 context.font.shape =
3573 known_coded_font_shapes[where - known_old_font_shapes];
3574 output_font_change(os, oldFont, context.font);
3575 eat_whitespace(p, os, context, false);
3578 else if (t.cs() == "selectlanguage") {
3579 context.check_layout(os);
3580 // save the language for the case that a
3581 // \foreignlanguage is used
3582 context.font.language = babel2lyx(p.verbatim_item());
3583 os << "\n\\lang " << context.font.language << "\n";
3586 else if (t.cs() == "foreignlanguage") {
3587 string const lang = babel2lyx(p.verbatim_item());
3588 parse_text_attributes(p, os, FLAG_ITEM, outer,
3590 context.font.language, lang);
3593 else if (prefixIs(t.cs(), "text")
3594 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3595 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3597 // We have to output the whole command if it has an option
3598 // because LyX doesn't support this yet, see bug #8214,
3599 // only if there is a single option specifying a variant, we can handle it.
3601 string langopts = p.getOpt();
3602 // check if the option contains a variant, if yes, extract it
3603 string::size_type pos_var = langopts.find("variant");
3604 string::size_type i = langopts.find(',');
3605 string::size_type k = langopts.find('=', pos_var);
3606 if (pos_var != string::npos && i == string::npos) {
3608 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3609 lang = preamble.polyglossia2lyx(variant);
3610 parse_text_attributes(p, os, FLAG_ITEM, outer,
3612 context.font.language, lang);
3614 handle_ert(os, t.asInput() + langopts, context);
3616 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3617 parse_text_attributes(p, os, FLAG_ITEM, outer,
3619 context.font.language, lang);
3623 else if (t.cs() == "inputencoding") {
3624 // nothing to write here
3625 string const enc = subst(p.verbatim_item(), "\n", " ");
3629 else if ((where = is_known(t.cs(), known_special_chars))) {
3630 context.check_layout(os);
3631 os << "\\SpecialChar \\"
3632 << known_coded_special_chars[where - known_special_chars]
3634 skip_spaces_braces(p);
3637 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3638 context.check_layout(os);
3639 os << "\\SpecialChar \\nobreakdash-\n";
3643 else if (t.cs() == "textquotedbl") {
3644 context.check_layout(os);
3649 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3650 context.check_layout(os);
3651 os << "\\SpecialChar \\@.\n";
3655 else if (t.cs() == "-") {
3656 context.check_layout(os);
3657 os << "\\SpecialChar \\-\n";
3660 else if (t.cs() == "textasciitilde") {
3661 context.check_layout(os);
3663 skip_spaces_braces(p);
3666 else if (t.cs() == "textasciicircum") {
3667 context.check_layout(os);
3669 skip_spaces_braces(p);
3672 else if (t.cs() == "textbackslash") {
3673 context.check_layout(os);
3674 os << "\n\\backslash\n";
3675 skip_spaces_braces(p);
3678 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3679 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3681 context.check_layout(os);
3685 else if (t.cs() == "char") {
3686 context.check_layout(os);
3687 if (p.next_token().character() == '`') {
3689 if (p.next_token().cs() == "\"") {
3694 handle_ert(os, "\\char`", context);
3697 handle_ert(os, "\\char", context);
3701 else if (t.cs() == "verb") {
3702 context.check_layout(os);
3703 char const delimiter = p.next_token().character();
3704 // \verb is special: The usual escaping rules do not
3705 // apply, e.g. "\verb+\+" is valid and denotes a single
3706 // backslash (bug #4468). Therefore we do not allow
3707 // escaping in getArg().
3708 string const arg = p.getArg(delimiter, delimiter, false);
3710 oss << "\\verb" << delimiter << arg << delimiter;
3711 handle_ert(os, oss.str(), context);
3714 // Problem: \= creates a tabstop inside the tabbing environment
3715 // and else an accent. In the latter case we really would want
3716 // \={o} instead of \= o.
3717 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3718 handle_ert(os, t.asInput(), context);
3720 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3721 else if (t.cs().size() == 1
3722 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3723 context.check_layout(os);
3724 // try to see whether the string is in unicodesymbols
3727 string command = t.asInput() + "{"
3728 + trimSpaceAndEol(p.verbatim_item())
3731 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3732 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3733 termination, rem, &req);
3736 cerr << "When parsing " << command
3737 << ", result is " << to_utf8(s)
3738 << "+" << to_utf8(rem) << endl;
3740 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3741 preamble.registerAutomaticallyLoadedPackage(*it);
3743 // we did not find a non-ert version
3744 handle_ert(os, command, context);
3747 else if (t.cs() == "\\") {
3748 context.check_layout(os);
3750 handle_ert(os, "\\\\" + p.getOpt(), context);
3751 else if (p.next_token().asInput() == "*") {
3753 // getOpt() eats the following space if there
3754 // is no optional argument, but that is OK
3755 // here since it has no effect in the output.
3756 handle_ert(os, "\\\\*" + p.getOpt(), context);
3759 begin_inset(os, "Newline newline");
3764 else if (t.cs() == "newline" ||
3765 (t.cs() == "linebreak" && !p.hasOpt())) {
3766 context.check_layout(os);
3767 begin_inset(os, "Newline ");
3770 skip_spaces_braces(p);
3773 else if (t.cs() == "input" || t.cs() == "include"
3774 || t.cs() == "verbatiminput") {
3775 string name = t.cs();
3776 if (t.cs() == "verbatiminput"
3777 && p.next_token().asInput() == "*")
3778 name += p.get_token().asInput();
3779 context.check_layout(os);
3780 string filename(normalize_filename(p.getArg('{', '}')));
3781 string const path = getMasterFilePath(true);
3782 // We want to preserve relative / absolute filenames,
3783 // therefore path is only used for testing
3784 if ((t.cs() == "include" || t.cs() == "input") &&
3785 !makeAbsPath(filename, path).exists()) {
3786 // The file extension is probably missing.
3787 // Now try to find it out.
3788 string const tex_name =
3789 find_file(filename, path,
3790 known_tex_extensions);
3791 if (!tex_name.empty())
3792 filename = tex_name;
3794 bool external = false;
3796 if (makeAbsPath(filename, path).exists()) {
3797 string const abstexname =
3798 makeAbsPath(filename, path).absFileName();
3799 string const absfigname =
3800 changeExtension(abstexname, ".fig");
3801 fix_child_filename(filename);
3802 string const lyxname =
3803 changeExtension(filename, ".lyx");
3804 string const abslyxname = makeAbsPath(
3805 lyxname, getParentFilePath(false)).absFileName();
3807 external = FileName(absfigname).exists();
3808 if (t.cs() == "input") {
3809 string const ext = getExtension(abstexname);
3811 // Combined PS/LaTeX:
3812 // x.eps, x.pstex_t (old xfig)
3813 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3814 FileName const absepsname(
3815 changeExtension(abstexname, ".eps"));
3816 FileName const abspstexname(
3817 changeExtension(abstexname, ".pstex"));
3818 bool const xfigeps =
3819 (absepsname.exists() ||
3820 abspstexname.exists()) &&
3823 // Combined PDF/LaTeX:
3824 // x.pdf, x.pdftex_t (old xfig)
3825 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3826 FileName const abspdfname(
3827 changeExtension(abstexname, ".pdf"));
3828 bool const xfigpdf =
3829 abspdfname.exists() &&
3830 (ext == "pdftex_t" || ext == "pdf_t");
3834 // Combined PS/PDF/LaTeX:
3835 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3836 string const absbase2(
3837 removeExtension(abstexname) + "_pspdftex");
3838 FileName const abseps2name(
3839 addExtension(absbase2, ".eps"));
3840 FileName const abspdf2name(
3841 addExtension(absbase2, ".pdf"));
3842 bool const xfigboth =
3843 abspdf2name.exists() &&
3844 abseps2name.exists() && ext == "pspdftex";
3846 xfig = xfigpdf || xfigeps || xfigboth;
3847 external = external && xfig;
3850 outname = changeExtension(filename, ".fig");
3851 FileName abssrc(changeExtension(abstexname, ".fig"));
3852 copy_file(abssrc, outname);
3854 // Don't try to convert, the result
3855 // would be full of ERT.
3857 FileName abssrc(abstexname);
3858 copy_file(abssrc, outname);
3859 } else if (t.cs() != "verbatiminput" &&
3860 tex2lyx(abstexname, FileName(abslyxname),
3863 // no need to call copy_file
3864 // tex2lyx creates the file
3867 FileName abssrc(abstexname);
3868 copy_file(abssrc, outname);
3871 cerr << "Warning: Could not find included file '"
3872 << filename << "'." << endl;
3876 begin_inset(os, "External\n");
3877 os << "\ttemplate XFig\n"
3878 << "\tfilename " << outname << '\n';
3879 registerExternalTemplatePackages("XFig");
3881 begin_command_inset(os, "include", name);
3882 os << "preview false\n"
3883 "filename \"" << outname << "\"\n";
3884 if (t.cs() == "verbatiminput")
3885 preamble.registerAutomaticallyLoadedPackage("verbatim");
3890 else if (t.cs() == "bibliographystyle") {
3891 // store new bibliographystyle
3892 bibliographystyle = p.verbatim_item();
3893 // If any other command than \bibliography and
3894 // \nocite{*} follows, we need to output the style
3895 // (because it might be used by that command).
3896 // Otherwise, it will automatically be output by LyX.
3899 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3900 if (t2.cat() == catBegin)
3902 if (t2.cat() != catEscape)
3904 if (t2.cs() == "nocite") {
3905 if (p.getArg('{', '}') == "*")
3907 } else if (t2.cs() == "bibliography")
3914 "\\bibliographystyle{" + bibliographystyle + '}',
3919 else if (t.cs() == "bibliography") {
3920 context.check_layout(os);
3921 begin_command_inset(os, "bibtex", "bibtex");
3922 if (!btprint.empty()) {
3923 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3924 // clear the string because the next BibTeX inset can be without the
3925 // \nocite{*} option
3928 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3929 // Do we have a bibliographystyle set?
3930 if (!bibliographystyle.empty())
3931 os << "options " << '"' << bibliographystyle << '"' << "\n";
3935 else if (t.cs() == "parbox") {
3936 // Test whether this is an outer box of a shaded box
3938 // swallow arguments
3939 while (p.hasOpt()) {
3941 p.skip_spaces(true);
3944 p.skip_spaces(true);
3946 if (p.next_token().cat() == catBegin)
3948 p.skip_spaces(true);
3949 Token to = p.get_token();
3950 bool shaded = false;
3951 if (to.asInput() == "\\begin") {
3952 p.skip_spaces(true);
3953 if (p.getArg('{', '}') == "shaded")
3958 parse_outer_box(p, os, FLAG_ITEM, outer,
3959 context, "parbox", "shaded");
3961 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3965 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3966 t.cs() == "shadowbox" || t.cs() == "doublebox")
3967 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3969 else if (t.cs() == "framebox") {
3970 if (p.next_token().character() == '(') {
3971 //the syntax is: \framebox(x,y)[position]{content}
3972 string arg = t.asInput();
3973 arg += p.getFullParentheseArg();
3974 arg += p.getFullOpt();
3975 eat_whitespace(p, os, context, false);
3976 handle_ert(os, arg + '{', context);
3977 parse_text(p, os, FLAG_ITEM, outer, context);
3978 handle_ert(os, "}", context);
3980 string special = p.getFullOpt();
3981 special += p.getOpt();
3982 // LyX does not yet support \framebox without any option
3983 if (!special.empty())
3984 parse_outer_box(p, os, FLAG_ITEM, outer,
3985 context, t.cs(), special);
3987 eat_whitespace(p, os, context, false);
3988 handle_ert(os, "\\framebox{", context);
3989 parse_text(p, os, FLAG_ITEM, outer, context);
3990 handle_ert(os, "}", context);
3995 //\makebox() is part of the picture environment and different from \makebox{}
3996 //\makebox{} will be parsed by parse_box
3997 else if (t.cs() == "makebox") {
3998 if (p.next_token().character() == '(') {
3999 //the syntax is: \makebox(x,y)[position]{content}
4000 string arg = t.asInput();
4001 arg += p.getFullParentheseArg();
4002 arg += p.getFullOpt();
4003 eat_whitespace(p, os, context, false);
4004 handle_ert(os, arg + '{', context);
4005 parse_text(p, os, FLAG_ITEM, outer, context);
4006 handle_ert(os, "}", context);
4008 //the syntax is: \makebox[width][position]{content}
4009 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4013 else if (t.cs() == "smallskip" ||
4014 t.cs() == "medskip" ||
4015 t.cs() == "bigskip" ||
4016 t.cs() == "vfill") {
4017 context.check_layout(os);
4018 begin_inset(os, "VSpace ");
4021 skip_spaces_braces(p);
4024 else if ((where = is_known(t.cs(), known_spaces))) {
4025 context.check_layout(os);
4026 begin_inset(os, "space ");
4027 os << '\\' << known_coded_spaces[where - known_spaces]
4030 // LaTeX swallows whitespace after all spaces except
4031 // "\\,". We have to do that here, too, because LyX
4032 // adds "{}" which would make the spaces significant.
4034 eat_whitespace(p, os, context, false);
4035 // LyX adds "{}" after all spaces except "\\ " and
4036 // "\\,", so we have to remove "{}".
4037 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4038 // remove the braces after "\\,", too.
4043 else if (t.cs() == "newpage" ||
4044 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4045 t.cs() == "clearpage" ||
4046 t.cs() == "cleardoublepage") {
4047 context.check_layout(os);
4048 begin_inset(os, "Newpage ");
4051 skip_spaces_braces(p);
4054 else if (t.cs() == "DeclareRobustCommand" ||
4055 t.cs() == "DeclareRobustCommandx" ||
4056 t.cs() == "newcommand" ||
4057 t.cs() == "newcommandx" ||
4058 t.cs() == "providecommand" ||
4059 t.cs() == "providecommandx" ||
4060 t.cs() == "renewcommand" ||
4061 t.cs() == "renewcommandx") {
4062 // DeclareRobustCommand, DeclareRobustCommandx,
4063 // providecommand and providecommandx could be handled
4064 // by parse_command(), but we need to call
4065 // add_known_command() here.
4066 string name = t.asInput();
4067 if (p.next_token().asInput() == "*") {
4068 // Starred form. Eat '*'
4072 string const command = p.verbatim_item();
4073 string const opt1 = p.getFullOpt();
4074 string const opt2 = p.getFullOpt();
4075 add_known_command(command, opt1, !opt2.empty());
4076 string const ert = name + '{' + command + '}' +
4078 '{' + p.verbatim_item() + '}';
4080 if (t.cs() == "DeclareRobustCommand" ||
4081 t.cs() == "DeclareRobustCommandx" ||
4082 t.cs() == "providecommand" ||
4083 t.cs() == "providecommandx" ||
4084 name[name.length()-1] == '*')
4085 handle_ert(os, ert, context);
4087 context.check_layout(os);
4088 begin_inset(os, "FormulaMacro");
4094 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4095 // let could be handled by parse_command(),
4096 // but we need to call add_known_command() here.
4097 string ert = t.asInput();
4100 if (p.next_token().cat() == catBegin) {
4101 name = p.verbatim_item();
4102 ert += '{' + name + '}';
4104 name = p.verbatim_item();
4109 if (p.next_token().cat() == catBegin) {
4110 command = p.verbatim_item();
4111 ert += '{' + command + '}';
4113 command = p.verbatim_item();
4116 // If command is known, make name known too, to parse
4117 // its arguments correctly. For this reason we also
4118 // have commands in syntax.default that are hardcoded.
4119 CommandMap::iterator it = known_commands.find(command);
4120 if (it != known_commands.end())
4121 known_commands[t.asInput()] = it->second;
4122 handle_ert(os, ert, context);
4125 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4126 bool starred = false;
4127 if (p.next_token().asInput() == "*") {
4131 string name = t.asInput();
4132 string const length = p.verbatim_item();
4135 bool valid = splitLatexLength(length, valstring, unit);
4136 bool known_hspace = false;
4137 bool known_vspace = false;
4138 bool known_unit = false;
4141 istringstream iss(valstring);
4144 if (t.cs()[0] == 'h') {
4145 if (unit == "\\fill") {
4150 known_hspace = true;
4153 if (unit == "\\smallskipamount") {
4155 known_vspace = true;
4156 } else if (unit == "\\medskipamount") {
4158 known_vspace = true;
4159 } else if (unit == "\\bigskipamount") {
4161 known_vspace = true;
4162 } else if (unit == "\\fill") {
4164 known_vspace = true;
4168 if (!known_hspace && !known_vspace) {
4169 switch (unitFromString(unit)) {
4190 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4191 // Literal horizontal length or known variable
4192 context.check_layout(os);
4193 begin_inset(os, "space ");
4201 if (known_unit && !known_hspace)
4203 << translate_len(length);
4205 } else if (known_unit || known_vspace) {
4206 // Literal vertical length or known variable
4207 context.check_layout(os);
4208 begin_inset(os, "VSpace ");
4216 // LyX can't handle other length variables in Inset VSpace/space
4221 handle_ert(os, name + '{' + unit + '}', context);
4222 else if (value == -1.0)
4223 handle_ert(os, name + "{-" + unit + '}', context);
4225 handle_ert(os, name + '{' + valstring + unit + '}', context);
4227 handle_ert(os, name + '{' + length + '}', context);
4231 // The single '=' is meant here.
4232 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4234 context.check_layout(os);
4235 begin_inset(os, "Flex ");
4236 os << to_utf8(newinsetlayout->name()) << '\n'
4237 << "status collapsed\n";
4238 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4242 else if (t.cs() == "includepdf") {
4244 string const arg = p.getArg('[', ']');
4245 map<string, string> opts;
4246 vector<string> keys;
4247 split_map(arg, opts, keys);
4248 string name = normalize_filename(p.verbatim_item());
4249 string const path = getMasterFilePath(true);
4250 // We want to preserve relative / absolute filenames,
4251 // therefore path is only used for testing
4252 if (!makeAbsPath(name, path).exists()) {
4253 // The file extension is probably missing.
4254 // Now try to find it out.
4255 char const * const pdfpages_format[] = {"pdf", 0};
4256 string const pdftex_name =
4257 find_file(name, path, pdfpages_format);
4258 if (!pdftex_name.empty()) {
4263 FileName const absname = makeAbsPath(name, path);
4264 if (absname.exists())
4266 fix_child_filename(name);
4267 copy_file(absname, name);
4269 cerr << "Warning: Could not find file '"
4270 << name << "'." << endl;
4272 context.check_layout(os);
4273 begin_inset(os, "External\n\ttemplate ");
4274 os << "PDFPages\n\tfilename "
4276 // parse the options
4277 if (opts.find("pages") != opts.end())
4278 os << "\textra LaTeX \"pages="
4279 << opts["pages"] << "\"\n";
4280 if (opts.find("angle") != opts.end())
4281 os << "\trotateAngle "
4282 << opts["angle"] << '\n';
4283 if (opts.find("origin") != opts.end()) {
4285 string const opt = opts["origin"];
4286 if (opt == "tl") ss << "topleft";
4287 if (opt == "bl") ss << "bottomleft";
4288 if (opt == "Bl") ss << "baselineleft";
4289 if (opt == "c") ss << "center";
4290 if (opt == "tc") ss << "topcenter";
4291 if (opt == "bc") ss << "bottomcenter";
4292 if (opt == "Bc") ss << "baselinecenter";
4293 if (opt == "tr") ss << "topright";
4294 if (opt == "br") ss << "bottomright";
4295 if (opt == "Br") ss << "baselineright";
4296 if (!ss.str().empty())
4297 os << "\trotateOrigin " << ss.str() << '\n';
4299 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4301 if (opts.find("width") != opts.end())
4303 << translate_len(opts["width"]) << '\n';
4304 if (opts.find("height") != opts.end())
4306 << translate_len(opts["height"]) << '\n';
4307 if (opts.find("keepaspectratio") != opts.end())
4308 os << "\tkeepAspectRatio\n";
4310 context.check_layout(os);
4311 registerExternalTemplatePackages("PDFPages");
4314 else if (t.cs() == "loadgame") {
4316 string name = normalize_filename(p.verbatim_item());
4317 string const path = getMasterFilePath(true);
4318 // We want to preserve relative / absolute filenames,
4319 // therefore path is only used for testing
4320 if (!makeAbsPath(name, path).exists()) {
4321 // The file extension is probably missing.
4322 // Now try to find it out.
4323 char const * const lyxskak_format[] = {"fen", 0};
4324 string const lyxskak_name =
4325 find_file(name, path, lyxskak_format);
4326 if (!lyxskak_name.empty())
4327 name = lyxskak_name;
4329 FileName const absname = makeAbsPath(name, path);
4330 if (absname.exists())
4332 fix_child_filename(name);
4333 copy_file(absname, name);
4335 cerr << "Warning: Could not find file '"
4336 << name << "'." << endl;
4337 context.check_layout(os);
4338 begin_inset(os, "External\n\ttemplate ");
4339 os << "ChessDiagram\n\tfilename "
4342 context.check_layout(os);
4343 // after a \loadgame follows a \showboard
4344 if (p.get_token().asInput() == "showboard")
4346 registerExternalTemplatePackages("ChessDiagram");
4350 // try to see whether the string is in unicodesymbols
4351 // Only use text mode commands, since we are in text mode here,
4352 // and math commands may be invalid (bug 6797)
4356 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4357 Encodings::TEXT_CMD, termination, rem, &req);
4360 cerr << "When parsing " << t.cs()
4361 << ", result is " << to_utf8(s)
4362 << "+" << to_utf8(rem) << endl;
4363 context.check_layout(os);
4366 skip_spaces_braces(p);
4367 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4368 preamble.registerAutomaticallyLoadedPackage(*it);
4370 //cerr << "#: " << t << " mode: " << mode << endl;
4371 // heuristic: read up to next non-nested space
4373 string s = t.asInput();
4374 string z = p.verbatim_item();
4375 while (p.good() && z != " " && z.size()) {
4376 //cerr << "read: " << z << endl;
4378 z = p.verbatim_item();
4380 cerr << "found ERT: " << s << endl;
4381 handle_ert(os, s + ' ', context);
4384 string name = t.asInput();
4385 if (p.next_token().asInput() == "*") {
4386 // Starred commands like \vspace*{}
4387 p.get_token(); // Eat '*'
4390 if (!parse_command(name, p, os, outer, context))
4391 handle_ert(os, name, context);
4395 if (flags & FLAG_LEAVE) {
4396 flags &= ~FLAG_LEAVE;
4403 string guessLanguage(Parser & p, string const & lang)
4405 typedef std::map<std::string, size_t> LangMap;
4406 // map from language names to number of characters
4409 for (char const * const * i = supported_CJK_languages; *i; i++)
4410 used[string(*i)] = 0;
4413 Token const t = p.get_token();
4414 // comments are not counted for any language
4415 if (t.cat() == catComment)
4417 // commands are not counted as well, but we need to detect
4418 // \begin{CJK} and switch encoding if needed
4419 if (t.cat() == catEscape) {
4420 if (t.cs() == "inputencoding") {
4421 string const enc = subst(p.verbatim_item(), "\n", " ");
4425 if (t.cs() != "begin")
4428 // Non-CJK content is counted for lang.
4429 // We do not care about the real language here:
4430 // If we have more non-CJK contents than CJK contents,
4431 // we simply use the language that was specified as
4432 // babel main language.
4433 used[lang] += t.asInput().length();
4436 // Now we are starting an environment
4438 string const name = p.getArg('{', '}');
4439 if (name != "CJK") {
4443 // It is a CJK environment
4445 /* name = */ p.getArg('{', '}');
4446 string const encoding = p.getArg('{', '}');
4447 /* mapping = */ p.getArg('{', '}');
4448 string const encoding_old = p.getEncoding();
4449 char const * const * const where =
4450 is_known(encoding, supported_CJK_encodings);
4452 p.setEncoding(encoding);
4454 p.setEncoding("utf8");
4455 string const text = p.verbatimEnvironment("CJK");
4456 p.setEncoding(encoding_old);
4459 // ignore contents in unknown CJK encoding
4462 // the language of the text
4464 supported_CJK_languages[where - supported_CJK_encodings];
4465 used[cjk] += text.length();
4467 LangMap::const_iterator use = used.begin();
4468 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4469 if (it->second > use->second)