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 // convert from absolute original path to "relative to master file"
1840 string const rel = to_utf8(makeRelPath(from_utf8(name),
1841 from_utf8(absMasterTeX)));
1842 // Do not copy if the file is not in or below the directory of the
1843 // master, since in this case the new path might be impossible to
1845 // absMasterTeX = "/foo/bar/"
1846 // absMasterLyX = "/bar/"
1847 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1848 if (copyfile && rel.substr(0, 3) == "../")
1850 string const absParentLyX = getParentFilePath(false);
1852 // re-interpret "relative to .tex file" as "relative to .lyx file"
1853 // (is different if the master .lyx file resides in a
1854 // different path than the master .tex file)
1855 string const absMasterLyX = getMasterFilePath(false);
1856 name = makeAbsPath(rel, absMasterLyX).absFileName();
1858 // convert from absolute original path to
1859 // "relative to .lyx file"
1860 name = to_utf8(makeRelPath(from_utf8(name),
1861 from_utf8(absParentLyX)));
1865 // convert from absolute original path to "relative to .lyx file"
1866 name = to_utf8(makeRelPath(from_utf8(name),
1867 from_utf8(absParentLyX)));
1872 void copy_file(FileName const & src, string dstname)
1876 string const absParent = getParentFilePath(false);
1878 if (FileName::isAbsolute(dstname))
1879 dst = FileName(dstname);
1881 dst = makeAbsPath(dstname, absParent);
1882 string const absMaster = getMasterFilePath(false);
1883 string const rel = to_utf8(makeRelPath(from_utf8(dst.absFileName()),
1884 from_utf8(absMaster)));
1885 // Do not copy if the file is not in or below the directory of the
1886 // master (see above)
1887 if (rel.substr(0, 3) == "../")
1889 FileName const srcpath = src.onlyPath();
1890 FileName const dstpath = dst.onlyPath();
1891 if (equivalent(srcpath, dstpath))
1893 if (!dstpath.isDirectory()) {
1894 if (!dstpath.createPath()) {
1895 cerr << "Warning: Could not create directory for file `"
1896 << dst.absFileName() << "´." << endl;
1900 if (dst.isReadableFile()) {
1901 if (overwriteFiles())
1902 cerr << "Warning: Overwriting existing file `"
1903 << dst.absFileName() << "´." << endl;
1905 cerr << "Warning: Not overwriting existing file `"
1906 << dst.absFileName() << "´." << endl;
1910 if (!src.copyTo(dst))
1911 cerr << "Warning: Could not copy file `" << src.absFileName()
1912 << "´ to `" << dst.absFileName() << "´." << endl;
1916 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1917 void parse_noweb(Parser & p, ostream & os, Context & context)
1919 // assemble the rest of the keyword
1923 Token const & t = p.get_token();
1924 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1927 scrap = (p.good() && p.next_token().asInput() == "=");
1929 name += p.get_token().asInput();
1932 name += t.asInput();
1935 if (!scrap || !context.new_layout_allowed ||
1936 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1937 cerr << "Warning: Could not interpret '" << name
1938 << "'. Ignoring it." << endl;
1942 // We use new_paragraph instead of check_end_layout because the stuff
1943 // following the noweb chunk needs to start with a \begin_layout.
1944 // This may create a new paragraph even if there was none in the
1945 // noweb file, but the alternative is an invalid LyX file. Since
1946 // noweb code chunks are implemented with a layout style in LyX they
1947 // always must be in an own paragraph.
1948 context.new_paragraph(os);
1949 Context newcontext(true, context.textclass,
1950 &context.textclass[from_ascii("Scrap")]);
1951 newcontext.check_layout(os);
1954 Token const & t = p.get_token();
1955 // We abuse the parser a bit, because this is no TeX syntax
1957 if (t.cat() == catEscape)
1958 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1961 Context tmp(false, context.textclass,
1962 &context.textclass[from_ascii("Scrap")]);
1963 tmp.need_end_layout = true;
1964 tmp.check_layout(oss);
1965 os << subst(t.asInput(), "\n", oss.str());
1967 // The scrap chunk is ended by an @ at the beginning of a line.
1968 // After the @ the line may contain a comment and/or
1969 // whitespace, but nothing else.
1970 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1971 (p.next_token().cat() == catSpace ||
1972 p.next_token().cat() == catNewline ||
1973 p.next_token().cat() == catComment)) {
1974 while (p.good() && p.next_token().cat() == catSpace)
1975 os << p.get_token().asInput();
1976 if (p.next_token().cat() == catComment)
1977 // The comment includes a final '\n'
1978 os << p.get_token().asInput();
1980 if (p.next_token().cat() == catNewline)
1987 newcontext.check_end_layout(os);
1991 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1992 bool is_macro(Parser & p)
1994 Token first = p.curr_token();
1995 if (first.cat() != catEscape || !p.good())
1997 if (first.cs() == "def")
1999 if (first.cs() != "global" && first.cs() != "long")
2001 Token second = p.get_token();
2003 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2004 second.cat() == catNewline || second.cat() == catComment)) {
2005 second = p.get_token();
2008 bool secondvalid = second.cat() == catEscape;
2010 bool thirdvalid = false;
2011 if (p.good() && first.cs() == "global" && secondvalid &&
2012 second.cs() == "long") {
2013 third = p.get_token();
2015 while (p.good() && !p.isParagraph() &&
2016 (third.cat() == catSpace ||
2017 third.cat() == catNewline ||
2018 third.cat() == catComment)) {
2019 third = p.get_token();
2022 thirdvalid = third.cat() == catEscape;
2024 for (int i = 0; i < pos; ++i)
2029 return (first.cs() == "global" || first.cs() == "long") &&
2030 second.cs() == "def";
2031 return first.cs() == "global" && second.cs() == "long" &&
2032 third.cs() == "def";
2036 /// Parse a macro definition (assumes that is_macro() returned true)
2037 void parse_macro(Parser & p, ostream & os, Context & context)
2039 context.check_layout(os);
2040 Token first = p.curr_token();
2043 string command = first.asInput();
2044 if (first.cs() != "def") {
2046 eat_whitespace(p, os, context, false);
2047 second = p.curr_token();
2048 command += second.asInput();
2049 if (second.cs() != "def") {
2051 eat_whitespace(p, os, context, false);
2052 third = p.curr_token();
2053 command += third.asInput();
2056 eat_whitespace(p, os, context, false);
2057 string const name = p.get_token().cs();
2058 eat_whitespace(p, os, context, false);
2064 while (p.next_token().cat() != catBegin) {
2065 if (p.next_token().cat() == catParameter) {
2070 // followed by number?
2071 if (p.next_token().cat() == catOther) {
2072 char c = p.getChar();
2074 // number = current arity + 1?
2075 if (c == arity + '0' + 1)
2080 paramtext += p.get_token().cs();
2082 paramtext += p.get_token().cs();
2087 // only output simple (i.e. compatible) macro as FormulaMacros
2088 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2090 context.check_layout(os);
2091 begin_inset(os, "FormulaMacro");
2092 os << "\n\\def" << ert;
2095 handle_ert(os, command + ert, context);
2099 void registerExternalTemplatePackages(string const & name)
2101 external::TemplateManager const & etm = external::TemplateManager::get();
2102 external::Template const * const et = etm.getTemplateByName(name);
2105 external::Template::Formats::const_iterator cit = et->formats.end();
2107 cit = et->formats.find("PDFLaTeX");
2108 if (cit == et->formats.end())
2109 // If the template has not specified a PDFLaTeX output,
2110 // we try the LaTeX format.
2111 cit = et->formats.find("LaTeX");
2112 if (cit == et->formats.end())
2114 vector<string>::const_iterator qit = cit->second.requirements.begin();
2115 vector<string>::const_iterator qend = cit->second.requirements.end();
2116 for (; qit != qend; ++qit)
2117 preamble.registerAutomaticallyLoadedPackage(*qit);
2120 } // anonymous namespace
2123 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2126 Layout const * newlayout = 0;
2127 InsetLayout const * newinsetlayout = 0;
2128 char const * const * where = 0;
2129 // Store the latest bibliographystyle and nocite{*} option
2130 // (needed for bibtex inset)
2132 string bibliographystyle = "default";
2133 bool const use_natbib = preamble.isPackageUsed("natbib");
2134 bool const use_jurabib = preamble.isPackageUsed("jurabib");
2137 Token const & t = p.get_token();
2139 // it is impossible to determine the correct encoding for non-CJK Japanese.
2140 // Therefore write a note at the beginning of the document
2141 if (is_nonCJKJapanese) {
2142 context.check_layout(os);
2143 begin_inset(os, "Note Note\n");
2144 os << "status open\n\\begin_layout Plain Layout\n"
2145 << "\\series bold\n"
2146 << "Important information:\n"
2147 << "\\end_layout\n\n"
2148 << "\\begin_layout Plain Layout\n"
2149 << "This document is in Japanese (non-CJK).\n"
2150 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2151 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2152 << " encoding in the document settings.\n"
2153 << "\\end_layout\n";
2155 is_nonCJKJapanese = false;
2159 debugToken(cerr, t, flags);
2162 if (flags & FLAG_ITEM) {
2163 if (t.cat() == catSpace)
2166 flags &= ~FLAG_ITEM;
2167 if (t.cat() == catBegin) {
2168 // skip the brace and collect everything to the next matching
2170 flags |= FLAG_BRACE_LAST;
2174 // handle only this single token, leave the loop if done
2175 flags |= FLAG_LEAVE;
2178 if (t.cat() != catEscape && t.character() == ']' &&
2179 (flags & FLAG_BRACK_LAST))
2181 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2184 // If there is anything between \end{env} and \begin{env} we
2185 // don't need to output a separator.
2186 if (t.cat() != catSpace && t.cat() != catNewline &&
2187 t.asInput() != "\\begin")
2193 if (t.cat() == catMath) {
2194 // we are inside some text mode thingy, so opening new math is allowed
2195 context.check_layout(os);
2196 begin_inset(os, "Formula ");
2197 Token const & n = p.get_token();
2198 bool const display(n.cat() == catMath && outer);
2200 // TeX's $$...$$ syntax for displayed math
2202 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2204 p.get_token(); // skip the second '$' token
2206 // simple $...$ stuff
2209 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2214 // Prevent the conversion of a line break to a
2215 // space (bug 7668). This does not change the
2216 // output, but looks ugly in LyX.
2217 eat_whitespace(p, os, context, false);
2221 else if (t.cat() == catSuper || t.cat() == catSub)
2222 cerr << "catcode " << t << " illegal in text mode\n";
2224 // Basic support for english quotes. This should be
2225 // extended to other quotes, but is not so easy (a
2226 // left english quote is the same as a right german
2228 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2229 context.check_layout(os);
2230 begin_inset(os, "Quotes ");
2236 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2237 context.check_layout(os);
2238 begin_inset(os, "Quotes ");
2245 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2246 context.check_layout(os);
2247 begin_inset(os, "Quotes ");
2254 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2255 context.check_layout(os);
2256 begin_inset(os, "Quotes ");
2263 else if (t.asInput() == "<"
2264 && p.next_token().asInput() == "<" && noweb_mode) {
2266 parse_noweb(p, os, context);
2269 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2270 check_space(p, os, context);
2272 else if (t.character() == '[' && noweb_mode &&
2273 p.next_token().character() == '[') {
2274 // These can contain underscores
2276 string const s = p.getFullOpt() + ']';
2277 if (p.next_token().character() == ']')
2280 cerr << "Warning: Inserting missing ']' in '"
2281 << s << "'." << endl;
2282 handle_ert(os, s, context);
2285 else if (t.cat() == catLetter) {
2286 context.check_layout(os);
2287 // Workaround for bug 4752.
2288 // FIXME: This whole code block needs to be removed
2289 // when the bug is fixed and tex2lyx produces
2290 // the updated file format.
2291 // The replacement algorithm in LyX is so stupid that
2292 // it even translates a phrase if it is part of a word.
2293 bool handled = false;
2294 for (int const * l = known_phrase_lengths; *l; ++l) {
2295 string phrase = t.cs();
2296 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2297 phrase += p.get_token().cs();
2298 if (is_known(phrase, known_coded_phrases)) {
2299 handle_ert(os, phrase, context);
2303 for (size_t i = 1; i < phrase.length(); ++i)
2311 else if (t.cat() == catOther ||
2312 t.cat() == catAlign ||
2313 t.cat() == catParameter) {
2314 // This translates "&" to "\\&" which may be wrong...
2315 context.check_layout(os);
2319 else if (p.isParagraph()) {
2320 if (context.new_layout_allowed)
2321 context.new_paragraph(os);
2323 handle_ert(os, "\\par ", context);
2324 eat_whitespace(p, os, context, true);
2327 else if (t.cat() == catActive) {
2328 context.check_layout(os);
2329 if (t.character() == '~') {
2330 if (context.layout->free_spacing)
2333 begin_inset(os, "space ~\n");
2340 else if (t.cat() == catBegin) {
2341 Token const next = p.next_token();
2342 Token const end = p.next_next_token();
2343 if (next.cat() == catEnd) {
2345 Token const prev = p.prev_token();
2347 if (p.next_token().character() == '`' ||
2348 (prev.character() == '-' &&
2349 p.next_token().character() == '-'))
2350 ; // ignore it in {}`` or -{}-
2352 handle_ert(os, "{}", context);
2353 } else if (next.cat() == catEscape &&
2354 is_known(next.cs(), known_quotes) &&
2355 end.cat() == catEnd) {
2356 // Something like {\textquoteright} (e.g.
2357 // from writer2latex). LyX writes
2358 // \textquoteright{}, so we may skip the
2359 // braces here for better readability.
2360 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2363 context.check_layout(os);
2364 // special handling of font attribute changes
2365 Token const prev = p.prev_token();
2366 TeXFont const oldFont = context.font;
2367 if (next.character() == '[' ||
2368 next.character() == ']' ||
2369 next.character() == '*') {
2371 if (p.next_token().cat() == catEnd) {
2376 handle_ert(os, "{", context);
2377 parse_text_snippet(p, os,
2380 handle_ert(os, "}", context);
2382 } else if (! context.new_layout_allowed) {
2383 handle_ert(os, "{", context);
2384 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2386 handle_ert(os, "}", context);
2387 } else if (is_known(next.cs(), known_sizes)) {
2388 // next will change the size, so we must
2390 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2392 if (!context.atParagraphStart())
2394 << context.font.size << "\n";
2395 } else if (is_known(next.cs(), known_font_families)) {
2396 // next will change the font family, so we
2397 // must reset it here
2398 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2400 if (!context.atParagraphStart())
2402 << context.font.family << "\n";
2403 } else if (is_known(next.cs(), known_font_series)) {
2404 // next will change the font series, so we
2405 // must reset it here
2406 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2408 if (!context.atParagraphStart())
2410 << context.font.series << "\n";
2411 } else if (is_known(next.cs(), known_font_shapes)) {
2412 // next will change the font shape, so we
2413 // must reset it here
2414 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2416 if (!context.atParagraphStart())
2418 << context.font.shape << "\n";
2419 } else if (is_known(next.cs(), known_old_font_families) ||
2420 is_known(next.cs(), known_old_font_series) ||
2421 is_known(next.cs(), known_old_font_shapes)) {
2422 // next will change the font family, series
2423 // and shape, so we must reset it here
2424 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2426 if (!context.atParagraphStart())
2428 << context.font.family
2430 << context.font.series
2432 << context.font.shape << "\n";
2434 handle_ert(os, "{", context);
2435 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2437 handle_ert(os, "}", context);
2442 else if (t.cat() == catEnd) {
2443 if (flags & FLAG_BRACE_LAST) {
2446 cerr << "stray '}' in text\n";
2447 handle_ert(os, "}", context);
2450 else if (t.cat() == catComment)
2451 parse_comment(p, os, t, context);
2454 // control sequences
2457 else if (t.cs() == "(") {
2458 context.check_layout(os);
2459 begin_inset(os, "Formula");
2461 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2466 else if (t.cs() == "[") {
2467 context.check_layout(os);
2468 begin_inset(os, "Formula");
2470 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2473 // Prevent the conversion of a line break to a space
2474 // (bug 7668). This does not change the output, but
2475 // looks ugly in LyX.
2476 eat_whitespace(p, os, context, false);
2479 else if (t.cs() == "begin")
2480 parse_environment(p, os, outer, last_env,
2483 else if (t.cs() == "end") {
2484 if (flags & FLAG_END) {
2485 // eat environment name
2486 string const name = p.getArg('{', '}');
2487 if (name != active_environment())
2488 cerr << "\\end{" + name + "} does not match \\begin{"
2489 + active_environment() + "}\n";
2492 p.error("found 'end' unexpectedly");
2495 else if (t.cs() == "item") {
2497 bool const optarg = p.hasOpt();
2499 // FIXME: This swallows comments, but we cannot use
2500 // eat_whitespace() since we must not output
2501 // anything before the item.
2502 p.skip_spaces(true);
2503 s = p.verbatimOption();
2505 p.skip_spaces(false);
2507 context.check_layout(os);
2508 if (context.has_item) {
2509 // An item in an unknown list-like environment
2510 // FIXME: Do this in check_layout()!
2511 context.has_item = false;
2513 handle_ert(os, "\\item", context);
2515 handle_ert(os, "\\item ", context);
2518 if (context.layout->labeltype != LABEL_MANUAL) {
2519 // LyX does not support \item[\mybullet]
2520 // in itemize environments
2522 os << parse_text_snippet(p2,
2523 FLAG_BRACK_LAST, outer, context);
2524 } else if (!s.empty()) {
2525 // LyX adds braces around the argument,
2526 // so we need to remove them here.
2527 if (s.size() > 2 && s[0] == '{' &&
2528 s[s.size()-1] == '}')
2529 s = s.substr(1, s.size()-2);
2530 // If the argument contains a space we
2531 // must put it into ERT: Otherwise LyX
2532 // would misinterpret the space as
2533 // item delimiter (bug 7663)
2534 if (contains(s, ' ')) {
2535 handle_ert(os, s, context);
2538 os << parse_text_snippet(p2,
2542 // The space is needed to separate the
2543 // item from the rest of the sentence.
2545 eat_whitespace(p, os, context, false);
2550 else if (t.cs() == "bibitem") {
2552 context.check_layout(os);
2553 eat_whitespace(p, os, context, false);
2554 string label = convert_command_inset_arg(p.verbatimOption());
2555 string key = convert_command_inset_arg(p.verbatim_item());
2556 if (contains(label, '\\') || contains(key, '\\')) {
2557 // LyX can't handle LaTeX commands in labels or keys
2558 handle_ert(os, t.asInput() + '[' + label +
2559 "]{" + p.verbatim_item() + '}',
2562 begin_command_inset(os, "bibitem", "bibitem");
2563 os << "label \"" << label << "\"\n"
2564 "key \"" << key << "\"\n";
2569 else if (is_macro(p)) {
2570 // catch the case of \def\inputGnumericTable
2572 if (t.cs() == "def") {
2573 Token second = p.next_token();
2574 if (second.cs() == "inputGnumericTable") {
2578 Token third = p.get_token();
2580 if (third.cs() == "input") {
2584 string name = normalize_filename(p.verbatim_item());
2585 string const path = getMasterFilePath(true);
2586 // We want to preserve relative / absolute filenames,
2587 // therefore path is only used for testing
2588 // The file extension is in every case ".tex".
2589 // So we need to remove this extension and check for
2590 // the original one.
2591 name = removeExtension(name);
2592 if (!makeAbsPath(name, path).exists()) {
2593 char const * const Gnumeric_formats[] = {"gnumeric",
2595 string const Gnumeric_name =
2596 find_file(name, path, Gnumeric_formats);
2597 if (!Gnumeric_name.empty())
2598 name = Gnumeric_name;
2600 FileName const absname = makeAbsPath(name, path);
2601 if (absname.exists()) {
2602 fix_child_filename(name);
2603 copy_file(absname, name);
2605 cerr << "Warning: Could not find file '"
2606 << name << "'." << endl;
2607 context.check_layout(os);
2608 begin_inset(os, "External\n\ttemplate ");
2609 os << "GnumericSpreadsheet\n\tfilename "
2612 context.check_layout(os);
2614 // register the packages that are automatically loaded
2615 // by the Gnumeric template
2616 registerExternalTemplatePackages("GnumericSpreadsheet");
2621 parse_macro(p, os, context);
2624 else if (t.cs() == "noindent") {
2626 context.add_par_extra_stuff("\\noindent\n");
2629 else if (t.cs() == "appendix") {
2630 context.add_par_extra_stuff("\\start_of_appendix\n");
2631 // We need to start a new paragraph. Otherwise the
2632 // appendix in 'bla\appendix\chapter{' would start
2634 context.new_paragraph(os);
2635 // We need to make sure that the paragraph is
2636 // generated even if it is empty. Otherwise the
2637 // appendix in '\par\appendix\par\chapter{' would
2639 context.check_layout(os);
2640 // FIXME: This is a hack to prevent paragraph
2641 // deletion if it is empty. Handle this better!
2643 "%dummy comment inserted by tex2lyx to "
2644 "ensure that this paragraph is not empty",
2646 // Both measures above may generate an additional
2647 // empty paragraph, but that does not hurt, because
2648 // whitespace does not matter here.
2649 eat_whitespace(p, os, context, true);
2652 // Must catch empty dates before findLayout is called below
2653 else if (t.cs() == "date") {
2654 eat_whitespace(p, os, context, false);
2656 string const date = p.verbatim_item();
2659 preamble.suppressDate(true);
2662 preamble.suppressDate(false);
2663 if (context.new_layout_allowed &&
2664 (newlayout = findLayout(context.textclass,
2667 output_command_layout(os, p, outer,
2668 context, newlayout);
2669 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2670 if (!preamble.titleLayoutFound())
2671 preamble.titleLayoutFound(newlayout->intitle);
2672 set<string> const & req = newlayout->requires();
2673 set<string>::const_iterator it = req.begin();
2674 set<string>::const_iterator en = req.end();
2675 for (; it != en; ++it)
2676 preamble.registerAutomaticallyLoadedPackage(*it);
2679 "\\date{" + p.verbatim_item() + '}',
2684 // Starred section headings
2685 // Must attempt to parse "Section*" before "Section".
2686 else if ((p.next_token().asInput() == "*") &&
2687 context.new_layout_allowed &&
2688 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2691 output_command_layout(os, p, outer, context, newlayout);
2693 if (!preamble.titleLayoutFound())
2694 preamble.titleLayoutFound(newlayout->intitle);
2695 set<string> const & req = newlayout->requires();
2696 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2697 preamble.registerAutomaticallyLoadedPackage(*it);
2700 // Section headings and the like
2701 else if (context.new_layout_allowed &&
2702 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2704 output_command_layout(os, p, outer, context, newlayout);
2706 if (!preamble.titleLayoutFound())
2707 preamble.titleLayoutFound(newlayout->intitle);
2708 set<string> const & req = newlayout->requires();
2709 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2710 preamble.registerAutomaticallyLoadedPackage(*it);
2713 else if (t.cs() == "caption") {
2715 context.check_layout(os);
2717 begin_inset(os, "Caption\n");
2718 Context newcontext(true, context.textclass, 0, 0, context.font);
2719 newcontext.check_layout(os);
2720 if (p.next_token().cat() != catEscape &&
2721 p.next_token().character() == '[') {
2722 p.get_token(); // eat '['
2723 begin_inset(os, "Argument\n");
2724 os << "status collapsed\n";
2725 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2727 eat_whitespace(p, os, context, false);
2729 parse_text(p, os, FLAG_ITEM, outer, context);
2730 context.check_end_layout(os);
2731 // We don't need really a new paragraph, but
2732 // we must make sure that the next item gets a \begin_layout.
2733 context.new_paragraph(os);
2736 newcontext.check_end_layout(os);
2739 else if (t.cs() == "subfloat") {
2740 // the syntax is \subfloat[caption]{content}
2741 // if it is a table of figure depends on the surrounding float
2742 bool has_caption = false;
2744 // do nothing if there is no outer float
2745 if (!float_type.empty()) {
2746 context.check_layout(os);
2748 begin_inset(os, "Float " + float_type + "\n");
2750 << "\nsideways false"
2751 << "\nstatus collapsed\n\n";
2754 if (p.next_token().cat() != catEscape &&
2755 p.next_token().character() == '[') {
2756 p.get_token(); // eat '['
2757 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2761 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2762 // the caption comes always as the last
2764 // we must make sure that the caption gets a \begin_layout
2765 os << "\n\\begin_layout Plain Layout";
2767 begin_inset(os, "Caption\n");
2768 Context newcontext(true, context.textclass,
2769 0, 0, context.font);
2770 newcontext.check_layout(os);
2771 os << caption << "\n";
2772 newcontext.check_end_layout(os);
2773 // We don't need really a new paragraph, but
2774 // we must make sure that the next item gets a \begin_layout.
2775 //newcontext.new_paragraph(os);
2779 // We don't need really a new paragraph, but
2780 // we must make sure that the next item gets a \begin_layout.
2782 context.new_paragraph(os);
2785 context.check_end_layout(os);
2786 // close the layout we opened
2788 os << "\n\\end_layout\n";
2790 // if the float type is not supported or there is no surrounding float
2793 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2794 handle_ert(os, t.asInput() + '[' + opt_arg +
2795 "]{" + p.verbatim_item() + '}', context);
2797 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2801 else if (t.cs() == "includegraphics") {
2802 bool const clip = p.next_token().asInput() == "*";
2805 string const arg = p.getArg('[', ']');
2806 map<string, string> opts;
2807 vector<string> keys;
2808 split_map(arg, opts, keys);
2810 opts["clip"] = string();
2811 string name = normalize_filename(p.verbatim_item());
2813 string const path = getMasterFilePath(true);
2814 // We want to preserve relative / absolute filenames,
2815 // therefore path is only used for testing
2816 if (!makeAbsPath(name, path).exists()) {
2817 // The file extension is probably missing.
2818 // Now try to find it out.
2819 string const dvips_name =
2820 find_file(name, path,
2821 known_dvips_graphics_formats);
2822 string const pdftex_name =
2823 find_file(name, path,
2824 known_pdftex_graphics_formats);
2825 if (!dvips_name.empty()) {
2826 if (!pdftex_name.empty()) {
2827 cerr << "This file contains the "
2829 "\"\\includegraphics{"
2831 "However, files\n\""
2832 << dvips_name << "\" and\n\""
2833 << pdftex_name << "\"\n"
2834 "both exist, so I had to make a "
2835 "choice and took the first one.\n"
2836 "Please move the unwanted one "
2837 "someplace else and try again\n"
2838 "if my choice was wrong."
2842 } else if (!pdftex_name.empty()) {
2848 FileName const absname = makeAbsPath(name, path);
2849 if (absname.exists()) {
2850 fix_child_filename(name);
2851 copy_file(absname, name);
2853 cerr << "Warning: Could not find graphics file '"
2854 << name << "'." << endl;
2856 context.check_layout(os);
2857 begin_inset(os, "Graphics ");
2858 os << "\n\tfilename " << name << '\n';
2859 if (opts.find("width") != opts.end())
2861 << translate_len(opts["width"]) << '\n';
2862 if (opts.find("height") != opts.end())
2864 << translate_len(opts["height"]) << '\n';
2865 if (opts.find("scale") != opts.end()) {
2866 istringstream iss(opts["scale"]);
2870 os << "\tscale " << val << '\n';
2872 if (opts.find("angle") != opts.end()) {
2873 os << "\trotateAngle "
2874 << opts["angle"] << '\n';
2875 vector<string>::const_iterator a =
2876 find(keys.begin(), keys.end(), "angle");
2877 vector<string>::const_iterator s =
2878 find(keys.begin(), keys.end(), "width");
2879 if (s == keys.end())
2880 s = find(keys.begin(), keys.end(), "height");
2881 if (s == keys.end())
2882 s = find(keys.begin(), keys.end(), "scale");
2883 if (s != keys.end() && distance(s, a) > 0)
2884 os << "\tscaleBeforeRotation\n";
2886 if (opts.find("origin") != opts.end()) {
2888 string const opt = opts["origin"];
2889 if (opt.find('l') != string::npos) ss << "left";
2890 if (opt.find('r') != string::npos) ss << "right";
2891 if (opt.find('c') != string::npos) ss << "center";
2892 if (opt.find('t') != string::npos) ss << "Top";
2893 if (opt.find('b') != string::npos) ss << "Bottom";
2894 if (opt.find('B') != string::npos) ss << "Baseline";
2895 if (!ss.str().empty())
2896 os << "\trotateOrigin " << ss.str() << '\n';
2898 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2900 if (opts.find("keepaspectratio") != opts.end())
2901 os << "\tkeepAspectRatio\n";
2902 if (opts.find("clip") != opts.end())
2904 if (opts.find("draft") != opts.end())
2906 if (opts.find("bb") != opts.end())
2907 os << "\tBoundingBox "
2908 << opts["bb"] << '\n';
2909 int numberOfbbOptions = 0;
2910 if (opts.find("bbllx") != opts.end())
2911 numberOfbbOptions++;
2912 if (opts.find("bblly") != opts.end())
2913 numberOfbbOptions++;
2914 if (opts.find("bburx") != opts.end())
2915 numberOfbbOptions++;
2916 if (opts.find("bbury") != opts.end())
2917 numberOfbbOptions++;
2918 if (numberOfbbOptions == 4)
2919 os << "\tBoundingBox "
2920 << opts["bbllx"] << " " << opts["bblly"] << " "
2921 << opts["bburx"] << " " << opts["bbury"] << '\n';
2922 else if (numberOfbbOptions > 0)
2923 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2924 numberOfbbOptions = 0;
2925 if (opts.find("natwidth") != opts.end())
2926 numberOfbbOptions++;
2927 if (opts.find("natheight") != opts.end())
2928 numberOfbbOptions++;
2929 if (numberOfbbOptions == 2)
2930 os << "\tBoundingBox 0bp 0bp "
2931 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2932 else if (numberOfbbOptions > 0)
2933 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2934 ostringstream special;
2935 if (opts.find("hiresbb") != opts.end())
2936 special << "hiresbb,";
2937 if (opts.find("trim") != opts.end())
2939 if (opts.find("viewport") != opts.end())
2940 special << "viewport=" << opts["viewport"] << ',';
2941 if (opts.find("totalheight") != opts.end())
2942 special << "totalheight=" << opts["totalheight"] << ',';
2943 if (opts.find("type") != opts.end())
2944 special << "type=" << opts["type"] << ',';
2945 if (opts.find("ext") != opts.end())
2946 special << "ext=" << opts["ext"] << ',';
2947 if (opts.find("read") != opts.end())
2948 special << "read=" << opts["read"] << ',';
2949 if (opts.find("command") != opts.end())
2950 special << "command=" << opts["command"] << ',';
2951 string s_special = special.str();
2952 if (!s_special.empty()) {
2953 // We had special arguments. Remove the trailing ','.
2954 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2956 // TODO: Handle the unknown settings better.
2957 // Warn about invalid options.
2958 // Check whether some option was given twice.
2960 preamble.registerAutomaticallyLoadedPackage("graphicx");
2963 else if (t.cs() == "footnote" ||
2964 (t.cs() == "thanks" && context.layout->intitle)) {
2966 context.check_layout(os);
2967 begin_inset(os, "Foot\n");
2968 os << "status collapsed\n\n";
2969 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2973 else if (t.cs() == "marginpar") {
2975 context.check_layout(os);
2976 begin_inset(os, "Marginal\n");
2977 os << "status collapsed\n\n";
2978 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2982 else if (t.cs() == "lstinline") {
2984 parse_listings(p, os, context, true);
2987 else if (t.cs() == "ensuremath") {
2989 context.check_layout(os);
2990 string const s = p.verbatim_item();
2991 //FIXME: this never triggers in UTF8
2992 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2995 handle_ert(os, "\\ensuremath{" + s + "}",
2999 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3000 if (preamble.titleLayoutFound()) {
3002 skip_spaces_braces(p);
3004 handle_ert(os, t.asInput(), context);
3007 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3008 context.check_layout(os);
3009 begin_command_inset(os, "toc", t.cs());
3011 skip_spaces_braces(p);
3012 if (t.cs() == "lstlistoflistings")
3013 preamble.registerAutomaticallyLoadedPackage("listings");
3016 else if (t.cs() == "listoffigures") {
3017 context.check_layout(os);
3018 begin_inset(os, "FloatList figure\n");
3020 skip_spaces_braces(p);
3023 else if (t.cs() == "listoftables") {
3024 context.check_layout(os);
3025 begin_inset(os, "FloatList table\n");
3027 skip_spaces_braces(p);
3030 else if (t.cs() == "listof") {
3031 p.skip_spaces(true);
3032 string const name = p.get_token().cs();
3033 if (context.textclass.floats().typeExist(name)) {
3034 context.check_layout(os);
3035 begin_inset(os, "FloatList ");
3038 p.get_token(); // swallow second arg
3040 handle_ert(os, "\\listof{" + name + "}", context);
3043 else if ((where = is_known(t.cs(), known_text_font_families)))
3044 parse_text_attributes(p, os, FLAG_ITEM, outer,
3045 context, "\\family", context.font.family,
3046 known_coded_font_families[where - known_text_font_families]);
3048 else if ((where = is_known(t.cs(), known_text_font_series)))
3049 parse_text_attributes(p, os, FLAG_ITEM, outer,
3050 context, "\\series", context.font.series,
3051 known_coded_font_series[where - known_text_font_series]);
3053 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3054 parse_text_attributes(p, os, FLAG_ITEM, outer,
3055 context, "\\shape", context.font.shape,
3056 known_coded_font_shapes[where - known_text_font_shapes]);
3058 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3059 context.check_layout(os);
3060 TeXFont oldFont = context.font;
3061 context.font.init();
3062 context.font.size = oldFont.size;
3063 os << "\n\\family " << context.font.family << "\n";
3064 os << "\n\\series " << context.font.series << "\n";
3065 os << "\n\\shape " << context.font.shape << "\n";
3066 if (t.cs() == "textnormal") {
3067 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3068 output_font_change(os, context.font, oldFont);
3069 context.font = oldFont;
3071 eat_whitespace(p, os, context, false);
3074 else if (t.cs() == "textcolor") {
3075 // scheme is \textcolor{color name}{text}
3076 string const color = p.verbatim_item();
3077 // we only support the predefined colors of the color package
3078 if (color == "black" || color == "blue" || color == "cyan"
3079 || color == "green" || color == "magenta" || color == "red"
3080 || color == "white" || color == "yellow") {
3081 context.check_layout(os);
3082 os << "\n\\color " << color << "\n";
3083 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3084 context.check_layout(os);
3085 os << "\n\\color inherit\n";
3086 preamble.registerAutomaticallyLoadedPackage("color");
3088 // for custom defined colors
3089 handle_ert(os, t.asInput() + "{" + color + "}", context);
3092 else if (t.cs() == "underbar" || t.cs() == "uline") {
3093 // \underbar is not 100% correct (LyX outputs \uline
3094 // of ulem.sty). The difference is that \ulem allows
3095 // line breaks, and \underbar does not.
3096 // Do NOT handle \underline.
3097 // \underbar cuts through y, g, q, p etc.,
3098 // \underline does not.
3099 context.check_layout(os);
3100 os << "\n\\bar under\n";
3101 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3102 context.check_layout(os);
3103 os << "\n\\bar default\n";
3104 preamble.registerAutomaticallyLoadedPackage("ulem");
3107 else if (t.cs() == "sout") {
3108 context.check_layout(os);
3109 os << "\n\\strikeout on\n";
3110 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3111 context.check_layout(os);
3112 os << "\n\\strikeout default\n";
3113 preamble.registerAutomaticallyLoadedPackage("ulem");
3116 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3117 t.cs() == "emph" || t.cs() == "noun") {
3118 context.check_layout(os);
3119 os << "\n\\" << t.cs() << " on\n";
3120 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3121 context.check_layout(os);
3122 os << "\n\\" << t.cs() << " default\n";
3123 if (t.cs() == "uuline" || t.cs() == "uwave")
3124 preamble.registerAutomaticallyLoadedPackage("ulem");
3127 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3128 context.check_layout(os);
3129 string name = p.getArg('{', '}');
3130 string localtime = p.getArg('{', '}');
3131 preamble.registerAuthor(name);
3132 Author const & author = preamble.getAuthor(name);
3133 // from_ctime() will fail if LyX decides to output the
3134 // time in the text language. It might also use a wrong
3135 // time zone (if the original LyX document was exported
3136 // with a different time zone).
3137 time_t ptime = from_ctime(localtime);
3138 if (ptime == static_cast<time_t>(-1)) {
3139 cerr << "Warning: Could not parse time `" << localtime
3140 << "´ for change tracking, using current time instead.\n";
3141 ptime = current_time();
3143 if (t.cs() == "lyxadded")
3144 os << "\n\\change_inserted ";
3146 os << "\n\\change_deleted ";
3147 os << author.bufferId() << ' ' << ptime << '\n';
3148 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3149 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3150 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3151 LaTeXPackages::isAvailable("xcolor");
3152 // No need to test for luatex, since luatex comes in
3153 // two flavours (dvi and pdf), like latex, and those
3154 // are detected by pdflatex.
3155 if (pdflatex || xetex) {
3157 preamble.registerAutomaticallyLoadedPackage("ulem");
3158 preamble.registerAutomaticallyLoadedPackage("xcolor");
3159 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3163 preamble.registerAutomaticallyLoadedPackage("dvipost");
3164 } else if (xcolorulem) {
3165 preamble.registerAutomaticallyLoadedPackage("ulem");
3166 preamble.registerAutomaticallyLoadedPackage("xcolor");
3171 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3172 t.cs() == "vphantom") {
3173 context.check_layout(os);
3174 if (t.cs() == "phantom")
3175 begin_inset(os, "Phantom Phantom\n");
3176 if (t.cs() == "hphantom")
3177 begin_inset(os, "Phantom HPhantom\n");
3178 if (t.cs() == "vphantom")
3179 begin_inset(os, "Phantom VPhantom\n");
3180 os << "status open\n";
3181 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3186 else if (t.cs() == "href") {
3187 context.check_layout(os);
3188 string target = convert_command_inset_arg(p.verbatim_item());
3189 string name = convert_command_inset_arg(p.verbatim_item());
3191 size_t i = target.find(':');
3192 if (i != string::npos) {
3193 type = target.substr(0, i + 1);
3194 if (type == "mailto:" || type == "file:")
3195 target = target.substr(i + 1);
3196 // handle the case that name is equal to target, except of "http://"
3197 else if (target.substr(i + 3) == name && type == "http:")
3200 begin_command_inset(os, "href", "href");
3202 os << "name \"" << name << "\"\n";
3203 os << "target \"" << target << "\"\n";
3204 if (type == "mailto:" || type == "file:")
3205 os << "type \"" << type << "\"\n";
3207 skip_spaces_braces(p);
3210 else if (t.cs() == "lyxline") {
3211 // swallow size argument (it is not used anyway)
3213 if (!context.atParagraphStart()) {
3214 // so our line is in the middle of a paragraph
3215 // we need to add a new line, lest this line
3216 // follow the other content on that line and
3217 // run off the side of the page
3218 // FIXME: This may create an empty paragraph,
3219 // but without that it would not be
3220 // possible to set noindent below.
3221 // Fortunately LaTeX does not care
3222 // about the empty paragraph.
3223 context.new_paragraph(os);
3225 if (preamble.indentParagraphs()) {
3226 // we need to unindent, lest the line be too long
3227 context.add_par_extra_stuff("\\noindent\n");
3229 context.check_layout(os);
3230 begin_command_inset(os, "line", "rule");
3231 os << "offset \"0.5ex\"\n"
3232 "width \"100line%\"\n"
3237 else if (t.cs() == "rule") {
3238 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3239 string const width = p.getArg('{', '}');
3240 string const thickness = p.getArg('{', '}');
3241 context.check_layout(os);
3242 begin_command_inset(os, "line", "rule");
3243 if (!offset.empty())
3244 os << "offset \"" << translate_len(offset) << "\"\n";
3245 os << "width \"" << translate_len(width) << "\"\n"
3246 "height \"" << translate_len(thickness) << "\"\n";
3250 else if (is_known(t.cs(), known_phrases) ||
3251 (t.cs() == "protect" &&
3252 p.next_token().cat() == catEscape &&
3253 is_known(p.next_token().cs(), known_phrases))) {
3254 // LyX sometimes puts a \protect in front, so we have to ignore it
3255 // FIXME: This needs to be changed when bug 4752 is fixed.
3257 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3259 context.check_layout(os);
3260 os << known_coded_phrases[where - known_phrases];
3261 skip_spaces_braces(p);
3264 else if ((where = is_known(t.cs(), known_ref_commands))) {
3265 string const opt = p.getOpt();
3267 context.check_layout(os);
3268 begin_command_inset(os, "ref",
3269 known_coded_ref_commands[where - known_ref_commands]);
3270 os << "reference \""
3271 << convert_command_inset_arg(p.verbatim_item())
3274 if (t.cs() == "vref" || t.cs() == "vpageref")
3275 preamble.registerAutomaticallyLoadedPackage("varioref");
3278 // LyX does not support optional arguments of ref commands
3279 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3280 p.verbatim_item() + "}", context);
3284 else if (use_natbib &&
3285 is_known(t.cs(), known_natbib_commands) &&
3286 ((t.cs() != "citefullauthor" &&
3287 t.cs() != "citeyear" &&
3288 t.cs() != "citeyearpar") ||
3289 p.next_token().asInput() != "*")) {
3290 context.check_layout(os);
3291 string command = t.cs();
3292 if (p.next_token().asInput() == "*") {
3296 if (command == "citefullauthor")
3297 // alternative name for "\\citeauthor*"
3298 command = "citeauthor*";
3300 // text before the citation
3302 // text after the citation
3304 get_cite_arguments(p, true, before, after);
3306 if (command == "cite") {
3307 // \cite without optional argument means
3308 // \citet, \cite with at least one optional
3309 // argument means \citep.
3310 if (before.empty() && after.empty())
3315 if (before.empty() && after == "[]")
3316 // avoid \citet[]{a}
3318 else if (before == "[]" && after == "[]") {
3319 // avoid \citet[][]{a}
3323 // remove the brackets around after and before
3324 if (!after.empty()) {
3326 after.erase(after.length() - 1, 1);
3327 after = convert_command_inset_arg(after);
3329 if (!before.empty()) {
3331 before.erase(before.length() - 1, 1);
3332 before = convert_command_inset_arg(before);
3334 begin_command_inset(os, "citation", command);
3335 os << "after " << '"' << after << '"' << "\n";
3336 os << "before " << '"' << before << '"' << "\n";
3338 << convert_command_inset_arg(p.verbatim_item())
3343 else if (use_jurabib &&
3344 is_known(t.cs(), known_jurabib_commands) &&
3345 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3346 context.check_layout(os);
3347 string command = t.cs();
3348 if (p.next_token().asInput() == "*") {
3352 char argumentOrder = '\0';
3353 vector<string> const options =
3354 preamble.getPackageOptions("jurabib");
3355 if (find(options.begin(), options.end(),
3356 "natbiborder") != options.end())
3357 argumentOrder = 'n';
3358 else if (find(options.begin(), options.end(),
3359 "jurabiborder") != options.end())
3360 argumentOrder = 'j';
3362 // text before the citation
3364 // text after the citation
3366 get_cite_arguments(p, argumentOrder != 'j', before, after);
3368 string const citation = p.verbatim_item();
3369 if (!before.empty() && argumentOrder == '\0') {
3370 cerr << "Warning: Assuming argument order "
3371 "of jurabib version 0.6 for\n'"
3372 << command << before << after << '{'
3373 << citation << "}'.\n"
3374 "Add 'jurabiborder' to the jurabib "
3375 "package options if you used an\n"
3376 "earlier jurabib version." << endl;
3378 if (!after.empty()) {
3380 after.erase(after.length() - 1, 1);
3382 if (!before.empty()) {
3384 before.erase(before.length() - 1, 1);
3386 begin_command_inset(os, "citation", command);
3387 os << "after " << '"' << after << '"' << "\n";
3388 os << "before " << '"' << before << '"' << "\n";
3389 os << "key " << '"' << citation << '"' << "\n";
3393 else if (t.cs() == "cite"
3394 || t.cs() == "nocite") {
3395 context.check_layout(os);
3396 string after = convert_command_inset_arg(p.getArg('[', ']'));
3397 string key = convert_command_inset_arg(p.verbatim_item());
3398 // store the case that it is "\nocite{*}" to use it later for
3401 begin_command_inset(os, "citation", t.cs());
3402 os << "after " << '"' << after << '"' << "\n";
3403 os << "key " << '"' << key << '"' << "\n";
3405 } else if (t.cs() == "nocite")
3409 else if (t.cs() == "index" ||
3410 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3411 context.check_layout(os);
3412 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3413 p.getArg('[', ']') : "";
3414 string const kind = arg.empty() ? "idx" : arg;
3415 begin_inset(os, "Index ");
3416 os << kind << "\nstatus collapsed\n";
3417 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3420 preamble.registerAutomaticallyLoadedPackage("splitidx");
3423 else if (t.cs() == "nomenclature") {
3424 context.check_layout(os);
3425 begin_command_inset(os, "nomenclature", "nomenclature");
3426 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3427 if (!prefix.empty())
3428 os << "prefix " << '"' << prefix << '"' << "\n";
3429 os << "symbol " << '"'
3430 << convert_command_inset_arg(p.verbatim_item());
3431 os << "\"\ndescription \""
3432 << convert_command_inset_arg(p.verbatim_item())
3435 preamble.registerAutomaticallyLoadedPackage("nomencl");
3438 else if (t.cs() == "label") {
3439 context.check_layout(os);
3440 begin_command_inset(os, "label", "label");
3442 << convert_command_inset_arg(p.verbatim_item())
3447 else if (t.cs() == "printindex") {
3448 context.check_layout(os);
3449 begin_command_inset(os, "index_print", "printindex");
3450 os << "type \"idx\"\n";
3452 skip_spaces_braces(p);
3453 preamble.registerAutomaticallyLoadedPackage("makeidx");
3454 if (preamble.use_indices() == "true")
3455 preamble.registerAutomaticallyLoadedPackage("splitidx");
3458 else if (t.cs() == "printnomenclature") {
3460 string width_type = "";
3461 context.check_layout(os);
3462 begin_command_inset(os, "nomencl_print", "printnomenclature");
3463 // case of a custom width
3465 width = p.getArg('[', ']');
3466 width = translate_len(width);
3467 width_type = "custom";
3469 // case of no custom width
3470 // the case of no custom width but the width set
3471 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3472 // because the user could have set anything, not only the width
3473 // of the longest label (which would be width_type = "auto")
3474 string label = convert_command_inset_arg(p.getArg('{', '}'));
3475 if (label.empty() && width_type.empty())
3476 width_type = "none";
3477 os << "set_width \"" << width_type << "\"\n";
3478 if (width_type == "custom")
3479 os << "width \"" << width << '\"';
3481 skip_spaces_braces(p);
3482 preamble.registerAutomaticallyLoadedPackage("nomencl");
3485 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3486 context.check_layout(os);
3487 begin_inset(os, "script ");
3488 os << t.cs().substr(4) << '\n';
3489 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3491 if (t.cs() == "textsubscript")
3492 preamble.registerAutomaticallyLoadedPackage("subscript");
3495 else if ((where = is_known(t.cs(), known_quotes))) {
3496 context.check_layout(os);
3497 begin_inset(os, "Quotes ");
3498 os << known_coded_quotes[where - known_quotes];
3500 // LyX adds {} after the quote, so we have to eat
3501 // spaces here if there are any before a possible
3503 eat_whitespace(p, os, context, false);
3507 else if ((where = is_known(t.cs(), known_sizes)) &&
3508 context.new_layout_allowed) {
3509 context.check_layout(os);
3510 TeXFont const oldFont = context.font;
3511 context.font.size = known_coded_sizes[where - known_sizes];
3512 output_font_change(os, oldFont, context.font);
3513 eat_whitespace(p, os, context, false);
3516 else if ((where = is_known(t.cs(), known_font_families)) &&
3517 context.new_layout_allowed) {
3518 context.check_layout(os);
3519 TeXFont const oldFont = context.font;
3520 context.font.family =
3521 known_coded_font_families[where - known_font_families];
3522 output_font_change(os, oldFont, context.font);
3523 eat_whitespace(p, os, context, false);
3526 else if ((where = is_known(t.cs(), known_font_series)) &&
3527 context.new_layout_allowed) {
3528 context.check_layout(os);
3529 TeXFont const oldFont = context.font;
3530 context.font.series =
3531 known_coded_font_series[where - known_font_series];
3532 output_font_change(os, oldFont, context.font);
3533 eat_whitespace(p, os, context, false);
3536 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3537 context.new_layout_allowed) {
3538 context.check_layout(os);
3539 TeXFont const oldFont = context.font;
3540 context.font.shape =
3541 known_coded_font_shapes[where - known_font_shapes];
3542 output_font_change(os, oldFont, context.font);
3543 eat_whitespace(p, os, context, false);
3545 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3546 context.new_layout_allowed) {
3547 context.check_layout(os);
3548 TeXFont const oldFont = context.font;
3549 context.font.init();
3550 context.font.size = oldFont.size;
3551 context.font.family =
3552 known_coded_font_families[where - known_old_font_families];
3553 output_font_change(os, oldFont, context.font);
3554 eat_whitespace(p, os, context, false);
3557 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3558 context.new_layout_allowed) {
3559 context.check_layout(os);
3560 TeXFont const oldFont = context.font;
3561 context.font.init();
3562 context.font.size = oldFont.size;
3563 context.font.series =
3564 known_coded_font_series[where - known_old_font_series];
3565 output_font_change(os, oldFont, context.font);
3566 eat_whitespace(p, os, context, false);
3569 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3570 context.new_layout_allowed) {
3571 context.check_layout(os);
3572 TeXFont const oldFont = context.font;
3573 context.font.init();
3574 context.font.size = oldFont.size;
3575 context.font.shape =
3576 known_coded_font_shapes[where - known_old_font_shapes];
3577 output_font_change(os, oldFont, context.font);
3578 eat_whitespace(p, os, context, false);
3581 else if (t.cs() == "selectlanguage") {
3582 context.check_layout(os);
3583 // save the language for the case that a
3584 // \foreignlanguage is used
3585 context.font.language = babel2lyx(p.verbatim_item());
3586 os << "\n\\lang " << context.font.language << "\n";
3589 else if (t.cs() == "foreignlanguage") {
3590 string const lang = babel2lyx(p.verbatim_item());
3591 parse_text_attributes(p, os, FLAG_ITEM, outer,
3593 context.font.language, lang);
3596 else if (prefixIs(t.cs(), "text")
3597 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3598 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3600 // We have to output the whole command if it has an option
3601 // because LyX doesn't support this yet, see bug #8214,
3602 // only if there is a single option specifying a variant, we can handle it.
3604 string langopts = p.getOpt();
3605 // check if the option contains a variant, if yes, extract it
3606 string::size_type pos_var = langopts.find("variant");
3607 string::size_type i = langopts.find(',');
3608 string::size_type k = langopts.find('=', pos_var);
3609 if (pos_var != string::npos && i == string::npos) {
3611 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3612 lang = preamble.polyglossia2lyx(variant);
3613 parse_text_attributes(p, os, FLAG_ITEM, outer,
3615 context.font.language, lang);
3617 handle_ert(os, t.asInput() + langopts, context);
3619 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3620 parse_text_attributes(p, os, FLAG_ITEM, outer,
3622 context.font.language, lang);
3626 else if (t.cs() == "inputencoding") {
3627 // nothing to write here
3628 string const enc = subst(p.verbatim_item(), "\n", " ");
3632 else if ((where = is_known(t.cs(), known_special_chars))) {
3633 context.check_layout(os);
3634 os << "\\SpecialChar \\"
3635 << known_coded_special_chars[where - known_special_chars]
3637 skip_spaces_braces(p);
3640 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3641 context.check_layout(os);
3642 os << "\\SpecialChar \\nobreakdash-\n";
3646 else if (t.cs() == "textquotedbl") {
3647 context.check_layout(os);
3652 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3653 context.check_layout(os);
3654 os << "\\SpecialChar \\@.\n";
3658 else if (t.cs() == "-") {
3659 context.check_layout(os);
3660 os << "\\SpecialChar \\-\n";
3663 else if (t.cs() == "textasciitilde") {
3664 context.check_layout(os);
3666 skip_spaces_braces(p);
3669 else if (t.cs() == "textasciicircum") {
3670 context.check_layout(os);
3672 skip_spaces_braces(p);
3675 else if (t.cs() == "textbackslash") {
3676 context.check_layout(os);
3677 os << "\n\\backslash\n";
3678 skip_spaces_braces(p);
3681 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3682 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3684 context.check_layout(os);
3688 else if (t.cs() == "char") {
3689 context.check_layout(os);
3690 if (p.next_token().character() == '`') {
3692 if (p.next_token().cs() == "\"") {
3697 handle_ert(os, "\\char`", context);
3700 handle_ert(os, "\\char", context);
3704 else if (t.cs() == "verb") {
3705 context.check_layout(os);
3706 char const delimiter = p.next_token().character();
3707 // \verb is special: The usual escaping rules do not
3708 // apply, e.g. "\verb+\+" is valid and denotes a single
3709 // backslash (bug #4468). Therefore we do not allow
3710 // escaping in getArg().
3711 string const arg = p.getArg(delimiter, delimiter, false);
3713 oss << "\\verb" << delimiter << arg << delimiter;
3714 handle_ert(os, oss.str(), context);
3717 // Problem: \= creates a tabstop inside the tabbing environment
3718 // and else an accent. In the latter case we really would want
3719 // \={o} instead of \= o.
3720 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3721 handle_ert(os, t.asInput(), context);
3723 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3724 else if (t.cs().size() == 1
3725 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3726 context.check_layout(os);
3727 // try to see whether the string is in unicodesymbols
3730 string command = t.asInput() + "{"
3731 + trimSpaceAndEol(p.verbatim_item())
3734 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3735 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3736 termination, rem, &req);
3739 cerr << "When parsing " << command
3740 << ", result is " << to_utf8(s)
3741 << "+" << to_utf8(rem) << endl;
3743 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3744 preamble.registerAutomaticallyLoadedPackage(*it);
3746 // we did not find a non-ert version
3747 handle_ert(os, command, context);
3750 else if (t.cs() == "\\") {
3751 context.check_layout(os);
3753 handle_ert(os, "\\\\" + p.getOpt(), context);
3754 else if (p.next_token().asInput() == "*") {
3756 // getOpt() eats the following space if there
3757 // is no optional argument, but that is OK
3758 // here since it has no effect in the output.
3759 handle_ert(os, "\\\\*" + p.getOpt(), context);
3762 begin_inset(os, "Newline newline");
3767 else if (t.cs() == "newline" ||
3768 (t.cs() == "linebreak" && !p.hasOpt())) {
3769 context.check_layout(os);
3770 begin_inset(os, "Newline ");
3773 skip_spaces_braces(p);
3776 else if (t.cs() == "input" || t.cs() == "include"
3777 || t.cs() == "verbatiminput") {
3778 string name = t.cs();
3779 if (t.cs() == "verbatiminput"
3780 && p.next_token().asInput() == "*")
3781 name += p.get_token().asInput();
3782 context.check_layout(os);
3783 string filename(normalize_filename(p.getArg('{', '}')));
3784 string const path = getMasterFilePath(true);
3785 // We want to preserve relative / absolute filenames,
3786 // therefore path is only used for testing
3787 if ((t.cs() == "include" || t.cs() == "input") &&
3788 !makeAbsPath(filename, path).exists()) {
3789 // The file extension is probably missing.
3790 // Now try to find it out.
3791 string const tex_name =
3792 find_file(filename, path,
3793 known_tex_extensions);
3794 if (!tex_name.empty())
3795 filename = tex_name;
3797 bool external = false;
3799 if (makeAbsPath(filename, path).exists()) {
3800 string const abstexname =
3801 makeAbsPath(filename, path).absFileName();
3802 string const absfigname =
3803 changeExtension(abstexname, ".fig");
3804 fix_child_filename(filename);
3805 string const lyxname =
3806 changeExtension(filename, ".lyx");
3807 string const abslyxname = makeAbsPath(
3808 lyxname, getParentFilePath(false)).absFileName();
3810 external = FileName(absfigname).exists();
3811 if (t.cs() == "input") {
3812 string const ext = getExtension(abstexname);
3814 // Combined PS/LaTeX:
3815 // x.eps, x.pstex_t (old xfig)
3816 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3817 FileName const absepsname(
3818 changeExtension(abstexname, ".eps"));
3819 FileName const abspstexname(
3820 changeExtension(abstexname, ".pstex"));
3821 bool const xfigeps =
3822 (absepsname.exists() ||
3823 abspstexname.exists()) &&
3826 // Combined PDF/LaTeX:
3827 // x.pdf, x.pdftex_t (old xfig)
3828 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3829 FileName const abspdfname(
3830 changeExtension(abstexname, ".pdf"));
3831 bool const xfigpdf =
3832 abspdfname.exists() &&
3833 (ext == "pdftex_t" || ext == "pdf_t");
3837 // Combined PS/PDF/LaTeX:
3838 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3839 string const absbase2(
3840 removeExtension(abstexname) + "_pspdftex");
3841 FileName const abseps2name(
3842 addExtension(absbase2, ".eps"));
3843 FileName const abspdf2name(
3844 addExtension(absbase2, ".pdf"));
3845 bool const xfigboth =
3846 abspdf2name.exists() &&
3847 abseps2name.exists() && ext == "pspdftex";
3849 xfig = xfigpdf || xfigeps || xfigboth;
3850 external = external && xfig;
3853 outname = changeExtension(filename, ".fig");
3854 FileName abssrc(changeExtension(abstexname, ".fig"));
3855 copy_file(abssrc, outname);
3857 // Don't try to convert, the result
3858 // would be full of ERT.
3860 FileName abssrc(abstexname);
3861 copy_file(abssrc, outname);
3862 } else if (t.cs() != "verbatiminput" &&
3863 tex2lyx(abstexname, FileName(abslyxname),
3866 // no need to call copy_file
3867 // tex2lyx creates the file
3870 FileName abssrc(abstexname);
3871 copy_file(abssrc, outname);
3874 cerr << "Warning: Could not find included file '"
3875 << filename << "'." << endl;
3879 begin_inset(os, "External\n");
3880 os << "\ttemplate XFig\n"
3881 << "\tfilename " << outname << '\n';
3882 registerExternalTemplatePackages("XFig");
3884 begin_command_inset(os, "include", name);
3885 os << "preview false\n"
3886 "filename \"" << outname << "\"\n";
3887 if (t.cs() == "verbatiminput")
3888 preamble.registerAutomaticallyLoadedPackage("verbatim");
3893 else if (t.cs() == "bibliographystyle") {
3894 // store new bibliographystyle
3895 bibliographystyle = p.verbatim_item();
3896 // If any other command than \bibliography and
3897 // \nocite{*} follows, we need to output the style
3898 // (because it might be used by that command).
3899 // Otherwise, it will automatically be output by LyX.
3902 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3903 if (t2.cat() == catBegin)
3905 if (t2.cat() != catEscape)
3907 if (t2.cs() == "nocite") {
3908 if (p.getArg('{', '}') == "*")
3910 } else if (t2.cs() == "bibliography")
3917 "\\bibliographystyle{" + bibliographystyle + '}',
3922 else if (t.cs() == "bibliography") {
3923 context.check_layout(os);
3924 begin_command_inset(os, "bibtex", "bibtex");
3925 if (!btprint.empty()) {
3926 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3927 // clear the string because the next BibTeX inset can be without the
3928 // \nocite{*} option
3931 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3932 // Do we have a bibliographystyle set?
3933 if (!bibliographystyle.empty())
3934 os << "options " << '"' << bibliographystyle << '"' << "\n";
3938 else if (t.cs() == "parbox") {
3939 // Test whether this is an outer box of a shaded box
3941 // swallow arguments
3942 while (p.hasOpt()) {
3944 p.skip_spaces(true);
3947 p.skip_spaces(true);
3949 if (p.next_token().cat() == catBegin)
3951 p.skip_spaces(true);
3952 Token to = p.get_token();
3953 bool shaded = false;
3954 if (to.asInput() == "\\begin") {
3955 p.skip_spaces(true);
3956 if (p.getArg('{', '}') == "shaded")
3961 parse_outer_box(p, os, FLAG_ITEM, outer,
3962 context, "parbox", "shaded");
3964 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3968 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3969 t.cs() == "shadowbox" || t.cs() == "doublebox")
3970 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3972 else if (t.cs() == "framebox") {
3973 if (p.next_token().character() == '(') {
3974 //the syntax is: \framebox(x,y)[position]{content}
3975 string arg = t.asInput();
3976 arg += p.getFullParentheseArg();
3977 arg += p.getFullOpt();
3978 eat_whitespace(p, os, context, false);
3979 handle_ert(os, arg + '{', context);
3980 parse_text(p, os, FLAG_ITEM, outer, context);
3981 handle_ert(os, "}", context);
3983 string special = p.getFullOpt();
3984 special += p.getOpt();
3985 // LyX does not yet support \framebox without any option
3986 if (!special.empty())
3987 parse_outer_box(p, os, FLAG_ITEM, outer,
3988 context, t.cs(), special);
3990 eat_whitespace(p, os, context, false);
3991 handle_ert(os, "\\framebox{", context);
3992 parse_text(p, os, FLAG_ITEM, outer, context);
3993 handle_ert(os, "}", context);
3998 //\makebox() is part of the picture environment and different from \makebox{}
3999 //\makebox{} will be parsed by parse_box
4000 else if (t.cs() == "makebox") {
4001 if (p.next_token().character() == '(') {
4002 //the syntax is: \makebox(x,y)[position]{content}
4003 string arg = t.asInput();
4004 arg += p.getFullParentheseArg();
4005 arg += p.getFullOpt();
4006 eat_whitespace(p, os, context, false);
4007 handle_ert(os, arg + '{', context);
4008 parse_text(p, os, FLAG_ITEM, outer, context);
4009 handle_ert(os, "}", context);
4011 //the syntax is: \makebox[width][position]{content}
4012 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4016 else if (t.cs() == "smallskip" ||
4017 t.cs() == "medskip" ||
4018 t.cs() == "bigskip" ||
4019 t.cs() == "vfill") {
4020 context.check_layout(os);
4021 begin_inset(os, "VSpace ");
4024 skip_spaces_braces(p);
4027 else if ((where = is_known(t.cs(), known_spaces))) {
4028 context.check_layout(os);
4029 begin_inset(os, "space ");
4030 os << '\\' << known_coded_spaces[where - known_spaces]
4033 // LaTeX swallows whitespace after all spaces except
4034 // "\\,". We have to do that here, too, because LyX
4035 // adds "{}" which would make the spaces significant.
4037 eat_whitespace(p, os, context, false);
4038 // LyX adds "{}" after all spaces except "\\ " and
4039 // "\\,", so we have to remove "{}".
4040 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4041 // remove the braces after "\\,", too.
4046 else if (t.cs() == "newpage" ||
4047 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4048 t.cs() == "clearpage" ||
4049 t.cs() == "cleardoublepage") {
4050 context.check_layout(os);
4051 begin_inset(os, "Newpage ");
4054 skip_spaces_braces(p);
4057 else if (t.cs() == "DeclareRobustCommand" ||
4058 t.cs() == "DeclareRobustCommandx" ||
4059 t.cs() == "newcommand" ||
4060 t.cs() == "newcommandx" ||
4061 t.cs() == "providecommand" ||
4062 t.cs() == "providecommandx" ||
4063 t.cs() == "renewcommand" ||
4064 t.cs() == "renewcommandx") {
4065 // DeclareRobustCommand, DeclareRobustCommandx,
4066 // providecommand and providecommandx could be handled
4067 // by parse_command(), but we need to call
4068 // add_known_command() here.
4069 string name = t.asInput();
4070 if (p.next_token().asInput() == "*") {
4071 // Starred form. Eat '*'
4075 string const command = p.verbatim_item();
4076 string const opt1 = p.getFullOpt();
4077 string const opt2 = p.getFullOpt();
4078 add_known_command(command, opt1, !opt2.empty());
4079 string const ert = name + '{' + command + '}' +
4081 '{' + p.verbatim_item() + '}';
4083 if (t.cs() == "DeclareRobustCommand" ||
4084 t.cs() == "DeclareRobustCommandx" ||
4085 t.cs() == "providecommand" ||
4086 t.cs() == "providecommandx" ||
4087 name[name.length()-1] == '*')
4088 handle_ert(os, ert, context);
4090 context.check_layout(os);
4091 begin_inset(os, "FormulaMacro");
4097 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4098 // let could be handled by parse_command(),
4099 // but we need to call add_known_command() here.
4100 string ert = t.asInput();
4103 if (p.next_token().cat() == catBegin) {
4104 name = p.verbatim_item();
4105 ert += '{' + name + '}';
4107 name = p.verbatim_item();
4112 if (p.next_token().cat() == catBegin) {
4113 command = p.verbatim_item();
4114 ert += '{' + command + '}';
4116 command = p.verbatim_item();
4119 // If command is known, make name known too, to parse
4120 // its arguments correctly. For this reason we also
4121 // have commands in syntax.default that are hardcoded.
4122 CommandMap::iterator it = known_commands.find(command);
4123 if (it != known_commands.end())
4124 known_commands[t.asInput()] = it->second;
4125 handle_ert(os, ert, context);
4128 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4129 bool starred = false;
4130 if (p.next_token().asInput() == "*") {
4134 string name = t.asInput();
4135 string const length = p.verbatim_item();
4138 bool valid = splitLatexLength(length, valstring, unit);
4139 bool known_hspace = false;
4140 bool known_vspace = false;
4141 bool known_unit = false;
4144 istringstream iss(valstring);
4147 if (t.cs()[0] == 'h') {
4148 if (unit == "\\fill") {
4153 known_hspace = true;
4156 if (unit == "\\smallskipamount") {
4158 known_vspace = true;
4159 } else if (unit == "\\medskipamount") {
4161 known_vspace = true;
4162 } else if (unit == "\\bigskipamount") {
4164 known_vspace = true;
4165 } else if (unit == "\\fill") {
4167 known_vspace = true;
4171 if (!known_hspace && !known_vspace) {
4172 switch (unitFromString(unit)) {
4193 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4194 // Literal horizontal length or known variable
4195 context.check_layout(os);
4196 begin_inset(os, "space ");
4204 if (known_unit && !known_hspace)
4206 << translate_len(length);
4208 } else if (known_unit || known_vspace) {
4209 // Literal vertical length or known variable
4210 context.check_layout(os);
4211 begin_inset(os, "VSpace ");
4219 // LyX can't handle other length variables in Inset VSpace/space
4224 handle_ert(os, name + '{' + unit + '}', context);
4225 else if (value == -1.0)
4226 handle_ert(os, name + "{-" + unit + '}', context);
4228 handle_ert(os, name + '{' + valstring + unit + '}', context);
4230 handle_ert(os, name + '{' + length + '}', context);
4234 // The single '=' is meant here.
4235 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4237 context.check_layout(os);
4238 begin_inset(os, "Flex ");
4239 os << to_utf8(newinsetlayout->name()) << '\n'
4240 << "status collapsed\n";
4241 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4245 else if (t.cs() == "includepdf") {
4247 string const arg = p.getArg('[', ']');
4248 map<string, string> opts;
4249 vector<string> keys;
4250 split_map(arg, opts, keys);
4251 string name = normalize_filename(p.verbatim_item());
4252 string const path = getMasterFilePath(true);
4253 // We want to preserve relative / absolute filenames,
4254 // therefore path is only used for testing
4255 if (!makeAbsPath(name, path).exists()) {
4256 // The file extension is probably missing.
4257 // Now try to find it out.
4258 char const * const pdfpages_format[] = {"pdf", 0};
4259 string const pdftex_name =
4260 find_file(name, path, pdfpages_format);
4261 if (!pdftex_name.empty()) {
4266 FileName const absname = makeAbsPath(name, path);
4267 if (absname.exists())
4269 fix_child_filename(name);
4270 copy_file(absname, name);
4272 cerr << "Warning: Could not find file '"
4273 << name << "'." << endl;
4275 context.check_layout(os);
4276 begin_inset(os, "External\n\ttemplate ");
4277 os << "PDFPages\n\tfilename "
4279 // parse the options
4280 if (opts.find("pages") != opts.end())
4281 os << "\textra LaTeX \"pages="
4282 << opts["pages"] << "\"\n";
4283 if (opts.find("angle") != opts.end())
4284 os << "\trotateAngle "
4285 << opts["angle"] << '\n';
4286 if (opts.find("origin") != opts.end()) {
4288 string const opt = opts["origin"];
4289 if (opt == "tl") ss << "topleft";
4290 if (opt == "bl") ss << "bottomleft";
4291 if (opt == "Bl") ss << "baselineleft";
4292 if (opt == "c") ss << "center";
4293 if (opt == "tc") ss << "topcenter";
4294 if (opt == "bc") ss << "bottomcenter";
4295 if (opt == "Bc") ss << "baselinecenter";
4296 if (opt == "tr") ss << "topright";
4297 if (opt == "br") ss << "bottomright";
4298 if (opt == "Br") ss << "baselineright";
4299 if (!ss.str().empty())
4300 os << "\trotateOrigin " << ss.str() << '\n';
4302 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4304 if (opts.find("width") != opts.end())
4306 << translate_len(opts["width"]) << '\n';
4307 if (opts.find("height") != opts.end())
4309 << translate_len(opts["height"]) << '\n';
4310 if (opts.find("keepaspectratio") != opts.end())
4311 os << "\tkeepAspectRatio\n";
4313 context.check_layout(os);
4314 registerExternalTemplatePackages("PDFPages");
4317 else if (t.cs() == "loadgame") {
4319 string name = normalize_filename(p.verbatim_item());
4320 string const path = getMasterFilePath(true);
4321 // We want to preserve relative / absolute filenames,
4322 // therefore path is only used for testing
4323 if (!makeAbsPath(name, path).exists()) {
4324 // The file extension is probably missing.
4325 // Now try to find it out.
4326 char const * const lyxskak_format[] = {"fen", 0};
4327 string const lyxskak_name =
4328 find_file(name, path, lyxskak_format);
4329 if (!lyxskak_name.empty())
4330 name = lyxskak_name;
4332 FileName const absname = makeAbsPath(name, path);
4333 if (absname.exists())
4335 fix_child_filename(name);
4336 copy_file(absname, name);
4338 cerr << "Warning: Could not find file '"
4339 << name << "'." << endl;
4340 context.check_layout(os);
4341 begin_inset(os, "External\n\ttemplate ");
4342 os << "ChessDiagram\n\tfilename "
4345 context.check_layout(os);
4346 // after a \loadgame follows a \showboard
4347 if (p.get_token().asInput() == "showboard")
4349 registerExternalTemplatePackages("ChessDiagram");
4353 // try to see whether the string is in unicodesymbols
4354 // Only use text mode commands, since we are in text mode here,
4355 // and math commands may be invalid (bug 6797)
4359 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4360 Encodings::TEXT_CMD, termination, rem, &req);
4363 cerr << "When parsing " << t.cs()
4364 << ", result is " << to_utf8(s)
4365 << "+" << to_utf8(rem) << endl;
4366 context.check_layout(os);
4369 skip_spaces_braces(p);
4370 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4371 preamble.registerAutomaticallyLoadedPackage(*it);
4373 //cerr << "#: " << t << " mode: " << mode << endl;
4374 // heuristic: read up to next non-nested space
4376 string s = t.asInput();
4377 string z = p.verbatim_item();
4378 while (p.good() && z != " " && z.size()) {
4379 //cerr << "read: " << z << endl;
4381 z = p.verbatim_item();
4383 cerr << "found ERT: " << s << endl;
4384 handle_ert(os, s + ' ', context);
4387 string name = t.asInput();
4388 if (p.next_token().asInput() == "*") {
4389 // Starred commands like \vspace*{}
4390 p.get_token(); // Eat '*'
4393 if (!parse_command(name, p, os, outer, context))
4394 handle_ert(os, name, context);
4398 if (flags & FLAG_LEAVE) {
4399 flags &= ~FLAG_LEAVE;
4406 string guessLanguage(Parser & p, string const & lang)
4408 typedef std::map<std::string, size_t> LangMap;
4409 // map from language names to number of characters
4412 for (char const * const * i = supported_CJK_languages; *i; i++)
4413 used[string(*i)] = 0;
4416 Token const t = p.get_token();
4417 // comments are not counted for any language
4418 if (t.cat() == catComment)
4420 // commands are not counted as well, but we need to detect
4421 // \begin{CJK} and switch encoding if needed
4422 if (t.cat() == catEscape) {
4423 if (t.cs() == "inputencoding") {
4424 string const enc = subst(p.verbatim_item(), "\n", " ");
4428 if (t.cs() != "begin")
4431 // Non-CJK content is counted for lang.
4432 // We do not care about the real language here:
4433 // If we have more non-CJK contents than CJK contents,
4434 // we simply use the language that was specified as
4435 // babel main language.
4436 used[lang] += t.asInput().length();
4439 // Now we are starting an environment
4441 string const name = p.getArg('{', '}');
4442 if (name != "CJK") {
4446 // It is a CJK environment
4448 /* name = */ p.getArg('{', '}');
4449 string const encoding = p.getArg('{', '}');
4450 /* mapping = */ p.getArg('{', '}');
4451 string const encoding_old = p.getEncoding();
4452 char const * const * const where =
4453 is_known(encoding, supported_CJK_encodings);
4455 p.setEncoding(encoding);
4457 p.setEncoding("utf8");
4458 string const text = p.verbatimEnvironment("CJK");
4459 p.setEncoding(encoding_old);
4462 // ignore contents in unknown CJK encoding
4465 // the language of the text
4467 supported_CJK_languages[where - supported_CJK_encodings];
4468 used[cjk] += text.length();
4470 LangMap::const_iterator use = used.begin();
4471 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4472 if (it->second > use->second)