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 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
523 if (layout.forcePlainLayout())
524 newcontext.layout = &context.textclass.plainLayout();
525 begin_inset(os, "ERT");
526 os << "\nstatus collapsed\n";
527 newcontext.check_layout(os);
528 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
530 os << "\n\\backslash\n";
531 else if (*it == '\n') {
532 newcontext.new_paragraph(os);
533 newcontext.check_layout(os);
537 newcontext.check_end_layout(os);
542 void handle_comment(ostream & os, string const & s, Context & context)
544 // TODO: Handle this better
545 Context newcontext(true, context.textclass);
546 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
547 if (layout.forcePlainLayout())
548 newcontext.layout = &context.textclass.plainLayout();
549 begin_inset(os, "ERT");
550 os << "\nstatus collapsed\n";
551 newcontext.check_layout(os);
552 handle_backslash(os, s);
553 // make sure that our comment is the last thing on the line
554 newcontext.new_paragraph(os);
555 newcontext.check_layout(os);
556 newcontext.check_end_layout(os);
561 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
563 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
566 if (checkModule(name, command))
567 return findLayoutWithoutModule(textclass, name, command);
572 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
574 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
577 if (checkModule(name, command))
578 return findInsetLayoutWithoutModule(textclass, name, command);
583 void eat_whitespace(Parser &, ostream &, Context &, bool);
587 * Skips whitespace and braces.
588 * This should be called after a command has been parsed that is not put into
589 * ERT, and where LyX adds "{}" if needed.
591 void skip_spaces_braces(Parser & p, bool keepws = false)
593 /* The following four examples produce the same typeset output and
594 should be handled by this function:
602 // Unfortunately we need to skip comments, too.
603 // We can't use eat_whitespace since writing them after the {}
604 // results in different output in some cases.
605 bool const skipped_spaces = p.skip_spaces(true);
606 bool const skipped_braces = skip_braces(p);
607 if (keepws && skipped_spaces && !skipped_braces)
608 // put back the space (it is better handled by check_space)
609 p.unskip_spaces(true);
613 void output_command_layout(ostream & os, Parser & p, bool outer,
614 Context & parent_context,
615 Layout const * newlayout)
617 TeXFont const oldFont = parent_context.font;
618 // save the current font size
619 string const size = oldFont.size;
620 // reset the font size to default, because the font size switches
621 // don't affect section headings and the like
622 parent_context.font.size = Context::normalfont.size;
623 // we only need to write the font change if we have an open layout
624 if (!parent_context.atParagraphStart())
625 output_font_change(os, oldFont, parent_context.font);
626 parent_context.check_end_layout(os);
627 Context context(true, parent_context.textclass, newlayout,
628 parent_context.layout, parent_context.font);
629 if (parent_context.deeper_paragraph) {
630 // We are beginning a nested environment after a
631 // deeper paragraph inside the outer list environment.
632 // Therefore we don't need to output a "begin deeper".
633 context.need_end_deeper = true;
635 context.check_deeper(os);
636 context.check_layout(os);
637 // FIXME: Adjust to format 446!
638 // Since format 446, layouts do not require anymore all optional
639 // arguments before the required ones. Needs to be implemented!
641 while (optargs < context.layout->optArgs()) {
642 eat_whitespace(p, os, context, false);
643 if (p.next_token().cat() == catEscape ||
644 p.next_token().character() != '[')
646 p.get_token(); // eat '['
647 // FIXME: Just a workaround. InsetArgument::updateBuffer
648 // will compute a proper ID for all "999" Arguments
649 // (which is also what lyx2lyx produces).
650 // However, tex2lyx should be able to output proper IDs
652 begin_inset(os, "Argument 999\n");
653 os << "status collapsed\n\n";
654 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
656 eat_whitespace(p, os, context, false);
660 while (reqargs < context.layout->requiredArgs()) {
661 eat_whitespace(p, os, context, false);
662 if (p.next_token().cat() != catBegin)
664 p.get_token(); // eat '{'
665 // FIXME: Just a workaround. InsetArgument::updateBuffer
666 // will compute a proper ID for all "999" Arguments
667 // (which is also what lyx2lyx produces).
668 // However, tex2lyx should be able to output proper IDs
670 begin_inset(os, "Argument 999\n");
671 os << "status collapsed\n\n";
672 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
674 eat_whitespace(p, os, context, false);
677 parse_text(p, os, FLAG_ITEM, outer, context);
678 context.check_end_layout(os);
679 if (parent_context.deeper_paragraph) {
680 // We must suppress the "end deeper" because we
681 // suppressed the "begin deeper" above.
682 context.need_end_deeper = false;
684 context.check_end_deeper(os);
685 // We don't need really a new paragraph, but
686 // we must make sure that the next item gets a \begin_layout.
687 parent_context.new_paragraph(os);
688 // Set the font size to the original value. No need to output it here
689 // (Context::begin_layout() will do that if needed)
690 parent_context.font.size = size;
695 * Output a space if necessary.
696 * This function gets called for every whitespace token.
698 * We have three cases here:
699 * 1. A space must be suppressed. Example: The lyxcode case below
700 * 2. A space may be suppressed. Example: Spaces before "\par"
701 * 3. A space must not be suppressed. Example: A space between two words
703 * We currently handle only 1. and 3 and from 2. only the case of
704 * spaces before newlines as a side effect.
706 * 2. could be used to suppress as many spaces as possible. This has two effects:
707 * - Reimporting LyX generated LaTeX files changes almost no whitespace
708 * - Superflous whitespace from non LyX generated LaTeX files is removed.
709 * The drawback is that the logic inside the function becomes
710 * complicated, and that is the reason why it is not implemented.
712 void check_space(Parser & p, ostream & os, Context & context)
714 Token const next = p.next_token();
715 Token const curr = p.curr_token();
716 // A space before a single newline and vice versa must be ignored
717 // LyX emits a newline before \end{lyxcode}.
718 // This newline must be ignored,
719 // otherwise LyX will add an additional protected space.
720 if (next.cat() == catSpace ||
721 next.cat() == catNewline ||
722 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
725 context.check_layout(os);
731 * Parse all arguments of \p command
733 void parse_arguments(string const & command,
734 vector<ArgumentType> const & template_arguments,
735 Parser & p, ostream & os, bool outer, Context & context)
737 string ert = command;
738 size_t no_arguments = template_arguments.size();
739 for (size_t i = 0; i < no_arguments; ++i) {
740 switch (template_arguments[i]) {
743 // This argument contains regular LaTeX
744 handle_ert(os, ert + '{', context);
745 eat_whitespace(p, os, context, false);
746 if (template_arguments[i] == required)
747 parse_text(p, os, FLAG_ITEM, outer, context);
749 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
753 // This argument consists only of a single item.
754 // The presence of '{' or not must be preserved.
756 if (p.next_token().cat() == catBegin)
757 ert += '{' + p.verbatim_item() + '}';
759 ert += p.verbatim_item();
763 // This argument may contain special characters
764 ert += '{' + p.verbatim_item() + '}';
768 // true because we must not eat whitespace
769 // if an optional arg follows we must not strip the
770 // brackets from this one
771 if (i < no_arguments - 1 &&
772 template_arguments[i+1] == optional)
773 ert += p.getFullOpt(true);
775 ert += p.getOpt(true);
779 handle_ert(os, ert, context);
784 * Check whether \p command is a known command. If yes,
785 * handle the command with all arguments.
786 * \return true if the command was parsed, false otherwise.
788 bool parse_command(string const & command, Parser & p, ostream & os,
789 bool outer, Context & context)
791 if (known_commands.find(command) != known_commands.end()) {
792 parse_arguments(command, known_commands[command], p, os,
800 /// Parses a minipage or parbox
801 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
802 unsigned inner_flags, bool outer, Context & parent_context,
803 string const & outer_type, string const & special,
804 string const & inner_type)
808 string hor_pos = "c";
809 // We need to set the height to the LaTeX default of 1\\totalheight
810 // for the case when no height argument is given
811 string height_value = "1";
812 string height_unit = "in";
813 string height_special = "totalheight";
818 string width_special = "none";
819 if (!inner_type.empty() && p.hasOpt()) {
820 if (inner_type != "makebox")
821 position = p.getArg('[', ']');
823 latex_width = p.getArg('[', ']');
824 translate_box_len(latex_width, width_value, width_unit, width_special);
827 if (position != "t" && position != "c" && position != "b") {
828 cerr << "invalid position " << position << " for "
829 << inner_type << endl;
833 if (inner_type != "makebox") {
834 latex_height = p.getArg('[', ']');
835 translate_box_len(latex_height, height_value, height_unit, height_special);
837 string const opt = p.getArg('[', ']');
840 if (hor_pos != "l" && hor_pos != "c" &&
841 hor_pos != "r" && hor_pos != "s") {
842 cerr << "invalid hor_pos " << hor_pos
843 << " for " << inner_type << endl;
850 inner_pos = p.getArg('[', ']');
851 if (inner_pos != "c" && inner_pos != "t" &&
852 inner_pos != "b" && inner_pos != "s") {
853 cerr << "invalid inner_pos "
854 << inner_pos << " for "
855 << inner_type << endl;
856 inner_pos = position;
861 if (inner_type.empty()) {
862 if (special.empty() && outer_type != "framebox")
863 latex_width = "1\\columnwidth";
866 latex_width = p2.getArg('[', ']');
867 string const opt = p2.getArg('[', ']');
870 if (hor_pos != "l" && hor_pos != "c" &&
871 hor_pos != "r" && hor_pos != "s") {
872 cerr << "invalid hor_pos " << hor_pos
873 << " for " << outer_type << endl;
878 } else if (inner_type != "makebox")
879 latex_width = p.verbatim_item();
880 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
881 // as this is LyX's standard for such cases (except for makebox)
882 // \framebox is more special and handled below
883 if (latex_width.empty() && inner_type != "makebox"
884 && outer_type != "framebox")
885 latex_width = "1\\columnwidth";
887 translate_len(latex_width, width_value, width_unit);
889 bool shadedparbox = false;
890 if (inner_type == "shaded") {
891 eat_whitespace(p, os, parent_context, false);
892 if (outer_type == "parbox") {
894 if (p.next_token().cat() == catBegin)
896 eat_whitespace(p, os, parent_context, false);
902 // If we already read the inner box we have to push the inner env
903 if (!outer_type.empty() && !inner_type.empty() &&
904 (inner_flags & FLAG_END))
905 active_environments.push_back(inner_type);
906 // LyX can't handle length variables
907 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
908 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
909 // Look whether there is some content after the end of the
910 // inner box, but before the end of the outer box.
911 // If yes, we need to output ERT.
913 if (inner_flags & FLAG_END)
914 p.verbatimEnvironment(inner_type);
918 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
919 if ((outer_env && p.next_token().asInput() != "\\end") ||
920 (!outer_env && p.next_token().cat() != catEnd)) {
921 // something is between the end of the inner box and
922 // the end of the outer box, so we need to use ERT.
927 // if only \makebox{content} was used we can set its width to 1\width
928 // because this identic and also identic to \mbox
929 // this doesn't work for \framebox{content}, thus we have to use ERT for this
930 if (latex_width.empty() && inner_type == "makebox") {
933 width_special = "width";
934 } else if (latex_width.empty() && outer_type == "framebox") {
939 if (!outer_type.empty()) {
940 if (outer_flags & FLAG_END)
941 ss << "\\begin{" << outer_type << '}';
943 ss << '\\' << outer_type << '{';
944 if (!special.empty())
948 if (!inner_type.empty()) {
949 if (inner_type != "shaded") {
950 if (inner_flags & FLAG_END)
951 ss << "\\begin{" << inner_type << '}';
953 ss << '\\' << inner_type;
955 if (!position.empty())
956 ss << '[' << position << ']';
957 if (!latex_height.empty())
958 ss << '[' << latex_height << ']';
959 if (!inner_pos.empty())
960 ss << '[' << inner_pos << ']';
961 ss << '{' << latex_width << '}';
962 if (!(inner_flags & FLAG_END))
965 if (inner_type == "shaded")
966 ss << "\\begin{shaded}";
967 handle_ert(os, ss.str(), parent_context);
968 if (!inner_type.empty()) {
969 parse_text(p, os, inner_flags, outer, parent_context);
970 if (inner_flags & FLAG_END)
971 handle_ert(os, "\\end{" + inner_type + '}',
974 handle_ert(os, "}", parent_context);
976 if (!outer_type.empty()) {
977 // If we already read the inner box we have to pop
979 if (!inner_type.empty() && (inner_flags & FLAG_END))
980 active_environments.pop_back();
982 // Ensure that the end of the outer box is parsed correctly:
983 // The opening brace has been eaten by parse_outer_box()
984 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
985 outer_flags &= ~FLAG_ITEM;
986 outer_flags |= FLAG_BRACE_LAST;
988 parse_text(p, os, outer_flags, outer, parent_context);
989 if (outer_flags & FLAG_END)
990 handle_ert(os, "\\end{" + outer_type + '}',
992 else if (inner_type.empty() && outer_type == "framebox")
993 // in this case it is already closed later
996 handle_ert(os, "}", parent_context);
999 // LyX does not like empty positions, so we have
1000 // to set them to the LaTeX default values here.
1001 if (position.empty())
1003 if (inner_pos.empty())
1004 inner_pos = position;
1005 parent_context.check_layout(os);
1006 begin_inset(os, "Box ");
1007 if (outer_type == "framed")
1009 else if (outer_type == "framebox")
1011 else if (outer_type == "shadowbox")
1012 os << "Shadowbox\n";
1013 else if ((outer_type == "shaded" && inner_type.empty()) ||
1014 (outer_type == "minipage" && inner_type == "shaded") ||
1015 (outer_type == "parbox" && inner_type == "shaded")) {
1017 preamble.registerAutomaticallyLoadedPackage("color");
1018 } else if (outer_type == "doublebox")
1019 os << "Doublebox\n";
1020 else if (outer_type.empty())
1021 os << "Frameless\n";
1023 os << outer_type << '\n';
1024 os << "position \"" << position << "\"\n";
1025 os << "hor_pos \"" << hor_pos << "\"\n";
1026 os << "has_inner_box " << !inner_type.empty() << "\n";
1027 os << "inner_pos \"" << inner_pos << "\"\n";
1028 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1030 os << "use_makebox " << (inner_type == "makebox") << '\n';
1031 os << "width \"" << width_value << width_unit << "\"\n";
1032 os << "special \"" << width_special << "\"\n";
1033 os << "height \"" << height_value << height_unit << "\"\n";
1034 os << "height_special \"" << height_special << "\"\n";
1035 os << "status open\n\n";
1037 // Unfortunately we can't use parse_text_in_inset:
1038 // InsetBox::forcePlainLayout() is hard coded and does not
1039 // use the inset layout. Apart from that do we call parse_text
1040 // up to two times, but need only one check_end_layout.
1041 bool const forcePlainLayout =
1042 (!inner_type.empty() || inner_type == "makebox") &&
1043 outer_type != "shaded" && outer_type != "framed";
1044 Context context(true, parent_context.textclass);
1045 if (forcePlainLayout)
1046 context.layout = &context.textclass.plainLayout();
1048 context.font = parent_context.font;
1050 // If we have no inner box the contents will be read with the outer box
1051 if (!inner_type.empty())
1052 parse_text(p, os, inner_flags, outer, context);
1054 // Ensure that the end of the outer box is parsed correctly:
1055 // The opening brace has been eaten by parse_outer_box()
1056 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1057 outer_flags &= ~FLAG_ITEM;
1058 outer_flags |= FLAG_BRACE_LAST;
1061 // Find end of outer box, output contents if inner_type is
1062 // empty and output possible comments
1063 if (!outer_type.empty()) {
1064 // If we already read the inner box we have to pop
1066 if (!inner_type.empty() && (inner_flags & FLAG_END))
1067 active_environments.pop_back();
1068 // This does not output anything but comments if
1069 // inner_type is not empty (see use_ert)
1070 parse_text(p, os, outer_flags, outer, context);
1073 context.check_end_layout(os);
1075 #ifdef PRESERVE_LAYOUT
1076 // LyX puts a % after the end of the minipage
1077 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1079 //handle_comment(os, "%dummy", parent_context);
1082 parent_context.new_paragraph(os);
1084 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1085 //handle_comment(os, "%dummy", parent_context);
1088 // We add a protected space if something real follows
1089 if (p.good() && p.next_token().cat() != catComment) {
1090 begin_inset(os, "space ~\n");
1099 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1100 Context & parent_context, string const & outer_type,
1101 string const & special)
1103 eat_whitespace(p, os, parent_context, false);
1104 if (flags & FLAG_ITEM) {
1106 if (p.next_token().cat() == catBegin)
1109 cerr << "Warning: Ignoring missing '{' after \\"
1110 << outer_type << '.' << endl;
1111 eat_whitespace(p, os, parent_context, false);
1114 unsigned int inner_flags = 0;
1116 if (outer_type == "minipage" || outer_type == "parbox") {
1117 p.skip_spaces(true);
1118 while (p.hasOpt()) {
1120 p.skip_spaces(true);
1123 p.skip_spaces(true);
1124 if (outer_type == "parbox") {
1126 if (p.next_token().cat() == catBegin)
1128 p.skip_spaces(true);
1131 if (outer_type == "shaded") {
1132 // These boxes never have an inner box
1134 } else if (p.next_token().asInput() == "\\parbox") {
1135 inner = p.get_token().cs();
1136 inner_flags = FLAG_ITEM;
1137 } else if (p.next_token().asInput() == "\\begin") {
1138 // Is this a minipage or shaded box?
1141 inner = p.getArg('{', '}');
1143 if (inner == "minipage" || inner == "shaded")
1144 inner_flags = FLAG_END;
1149 if (inner_flags == FLAG_END) {
1150 if (inner != "shaded")
1154 eat_whitespace(p, os, parent_context, false);
1156 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1157 outer_type, special, inner);
1159 if (inner_flags == FLAG_ITEM) {
1161 eat_whitespace(p, os, parent_context, false);
1163 parse_box(p, os, flags, inner_flags, outer, parent_context,
1164 outer_type, special, inner);
1169 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1171 parent_context.check_layout(os);
1172 begin_inset(os, "listings\n");
1174 string arg = p.verbatimOption();
1175 os << "lstparams " << '"' << arg << '"' << '\n';
1176 if (arg.find("\\color") != string::npos)
1177 preamble.registerAutomaticallyLoadedPackage("color");
1180 os << "inline true\n";
1182 os << "inline false\n";
1183 os << "status collapsed\n";
1184 Context context(true, parent_context.textclass);
1185 context.layout = &parent_context.textclass.plainLayout();
1188 s = p.plainCommand('!', '!', "lstinline");
1189 context.new_paragraph(os);
1190 context.check_layout(os);
1192 s = p.plainEnvironment("lstlisting");
1193 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1195 os << "\n\\backslash\n";
1196 else if (*it == '\n') {
1197 // avoid adding an empty paragraph at the end
1199 context.new_paragraph(os);
1200 context.check_layout(os);
1205 context.check_end_layout(os);
1210 /// parse an unknown environment
1211 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1212 unsigned flags, bool outer,
1213 Context & parent_context)
1215 if (name == "tabbing")
1216 // We need to remember that we have to handle '\=' specially
1217 flags |= FLAG_TABBING;
1219 // We need to translate font changes and paragraphs inside the
1220 // environment to ERT if we have a non standard font.
1221 // Otherwise things like
1222 // \large\begin{foo}\huge bar\end{foo}
1224 bool const specialfont =
1225 (parent_context.font != parent_context.normalfont);
1226 bool const new_layout_allowed = parent_context.new_layout_allowed;
1228 parent_context.new_layout_allowed = false;
1229 handle_ert(os, "\\begin{" + name + "}", parent_context);
1230 parse_text_snippet(p, os, flags, outer, parent_context);
1231 handle_ert(os, "\\end{" + name + "}", parent_context);
1233 parent_context.new_layout_allowed = new_layout_allowed;
1237 void parse_environment(Parser & p, ostream & os, bool outer,
1238 string & last_env, Context & parent_context)
1240 Layout const * newlayout;
1241 InsetLayout const * newinsetlayout = 0;
1242 string const name = p.getArg('{', '}');
1243 const bool is_starred = suffixIs(name, '*');
1244 string const unstarred_name = rtrim(name, "*");
1245 active_environments.push_back(name);
1247 if (is_math_env(name)) {
1248 parent_context.check_layout(os);
1249 begin_inset(os, "Formula ");
1250 os << "\\begin{" << name << "}";
1251 parse_math(p, os, FLAG_END, MATH_MODE);
1252 os << "\\end{" << name << "}";
1254 if (is_display_math_env(name)) {
1255 // Prevent the conversion of a line break to a space
1256 // (bug 7668). This does not change the output, but
1257 // looks ugly in LyX.
1258 eat_whitespace(p, os, parent_context, false);
1262 else if (is_known(name, preamble.polyglossia_languages)) {
1263 // We must begin a new paragraph if not already done
1264 if (! parent_context.atParagraphStart()) {
1265 parent_context.check_end_layout(os);
1266 parent_context.new_paragraph(os);
1268 // save the language in the context so that it is
1269 // handled by parse_text
1270 parent_context.font.language = preamble.polyglossia2lyx(name);
1271 parse_text(p, os, FLAG_END, outer, parent_context);
1272 // Just in case the environment is empty
1273 parent_context.extra_stuff.erase();
1274 // We must begin a new paragraph to reset the language
1275 parent_context.new_paragraph(os);
1279 else if (unstarred_name == "tabular" || name == "longtable") {
1280 eat_whitespace(p, os, parent_context, false);
1281 string width = "0pt";
1282 if (name == "tabular*") {
1283 width = lyx::translate_len(p.getArg('{', '}'));
1284 eat_whitespace(p, os, parent_context, false);
1286 parent_context.check_layout(os);
1287 begin_inset(os, "Tabular ");
1288 handle_tabular(p, os, name, width, parent_context);
1293 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1294 eat_whitespace(p, os, parent_context, false);
1295 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1296 eat_whitespace(p, os, parent_context, false);
1297 parent_context.check_layout(os);
1298 begin_inset(os, "Float " + unstarred_name + "\n");
1299 // store the float type for subfloats
1300 // subfloats only work with figures and tables
1301 if (unstarred_name == "figure")
1302 float_type = unstarred_name;
1303 else if (unstarred_name == "table")
1304 float_type = unstarred_name;
1308 os << "placement " << opt << '\n';
1309 if (contains(opt, "H"))
1310 preamble.registerAutomaticallyLoadedPackage("float");
1312 Floating const & fl = parent_context.textclass.floats()
1313 .getType(unstarred_name);
1314 if (!fl.floattype().empty() && fl.usesFloatPkg())
1315 preamble.registerAutomaticallyLoadedPackage("float");
1318 os << "wide " << convert<string>(is_starred)
1319 << "\nsideways false"
1320 << "\nstatus open\n\n";
1321 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1323 // We don't need really a new paragraph, but
1324 // we must make sure that the next item gets a \begin_layout.
1325 parent_context.new_paragraph(os);
1327 // the float is parsed thus delete the type
1331 else if (unstarred_name == "sidewaysfigure"
1332 || unstarred_name == "sidewaystable") {
1333 eat_whitespace(p, os, parent_context, false);
1334 parent_context.check_layout(os);
1335 if (unstarred_name == "sidewaysfigure")
1336 begin_inset(os, "Float figure\n");
1338 begin_inset(os, "Float table\n");
1339 os << "wide " << convert<string>(is_starred)
1340 << "\nsideways true"
1341 << "\nstatus open\n\n";
1342 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1344 // We don't need really a new paragraph, but
1345 // we must make sure that the next item gets a \begin_layout.
1346 parent_context.new_paragraph(os);
1348 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1351 else if (name == "wrapfigure" || name == "wraptable") {
1352 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1353 eat_whitespace(p, os, parent_context, false);
1354 parent_context.check_layout(os);
1357 string overhang = "0col%";
1360 lines = p.getArg('[', ']');
1361 string const placement = p.getArg('{', '}');
1363 overhang = p.getArg('[', ']');
1364 string const width = p.getArg('{', '}');
1366 if (name == "wrapfigure")
1367 begin_inset(os, "Wrap figure\n");
1369 begin_inset(os, "Wrap table\n");
1370 os << "lines " << lines
1371 << "\nplacement " << placement
1372 << "\noverhang " << lyx::translate_len(overhang)
1373 << "\nwidth " << lyx::translate_len(width)
1374 << "\nstatus open\n\n";
1375 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1377 // We don't need really a new paragraph, but
1378 // we must make sure that the next item gets a \begin_layout.
1379 parent_context.new_paragraph(os);
1381 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1384 else if (name == "minipage") {
1385 eat_whitespace(p, os, parent_context, false);
1386 // Test whether this is an outer box of a shaded box
1388 // swallow arguments
1389 while (p.hasOpt()) {
1391 p.skip_spaces(true);
1394 p.skip_spaces(true);
1395 Token t = p.get_token();
1396 bool shaded = false;
1397 if (t.asInput() == "\\begin") {
1398 p.skip_spaces(true);
1399 if (p.getArg('{', '}') == "shaded")
1404 parse_outer_box(p, os, FLAG_END, outer,
1405 parent_context, name, "shaded");
1407 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1412 else if (name == "comment") {
1413 eat_whitespace(p, os, parent_context, false);
1414 parent_context.check_layout(os);
1415 begin_inset(os, "Note Comment\n");
1416 os << "status open\n";
1417 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1420 skip_braces(p); // eat {} that might by set by LyX behind comments
1421 preamble.registerAutomaticallyLoadedPackage("verbatim");
1424 else if (name == "verbatim") {
1425 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1426 string const s = p.plainEnvironment("verbatim");
1427 string::const_iterator it2 = s.begin();
1428 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1430 os << "\\backslash ";
1431 else if (*it == '\n') {
1433 // avoid adding an empty paragraph at the end
1434 // FIXME: if there are 2 consecutive spaces at the end ignore it
1435 // because LyX will re-add a \n
1436 // This hack must be removed once bug 8049 is fixed!
1437 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1438 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1442 os << "\n\\end_layout\n\n";
1444 // reset to Standard layout
1445 os << "\n\\begin_layout Standard\n";
1448 else if (name == "CJK") {
1449 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1450 // It is impossible to decide if a CJK environment was in its own paragraph or within
1451 // a line. We therefore always assume a paragraph since the latter is a rare case.
1452 eat_whitespace(p, os, parent_context, false);
1453 parent_context.check_end_layout(os);
1454 // store the encoding to be able to reset it
1455 string const encoding_old = p.getEncoding();
1456 string const encoding = p.getArg('{', '}');
1457 // SJIS and Bg5 cannot be handled by iconv
1458 // JIS does not work with LyX's encoding conversion
1459 if (encoding != "Bg5" && encoding != "JIS" && encoding != "SJIS")
1460 p.setEncoding(encoding);
1462 // FIXME: This will read garbage, since the data is not encoded in utf8.
1463 p.setEncoding("utf8");
1465 // LyX only supports the same mapping for all CJK
1466 // environments, so we might need to output everything as ERT
1467 string const mapping = trim(p.getArg('{', '}'));
1468 char const * const * const where =
1469 is_known(encoding, supported_CJK_encodings);
1470 if (!preamble.fontCJKSet())
1471 preamble.fontCJK(mapping);
1472 bool knownMapping = mapping == preamble.fontCJK();
1473 if (!knownMapping || !where) {
1474 parent_context.check_layout(os);
1475 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1477 // we must parse the content as verbatim because e.g. JIS can contain
1478 // normally invalid characters
1479 // FIXME: This works only for the most simple cases.
1480 // Since TeX control characters are not parsed,
1481 // things like comments are completely wrong.
1482 string const s = p.plainEnvironment("CJK");
1483 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1485 handle_ert(os, "\\", parent_context);
1486 else if (*it == '$')
1487 handle_ert(os, "$", parent_context);
1491 handle_ert(os, "\\end{" + name + "}",
1495 supported_CJK_languages[where - supported_CJK_encodings];
1496 // store the language because we must reset it at the end
1497 string const lang_old = parent_context.font.language;
1498 parent_context.font.language = lang;
1499 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1500 parent_context.font.language = lang_old;
1501 parent_context.new_paragraph(os);
1503 p.setEncoding(encoding_old);
1507 else if (name == "lyxgreyedout") {
1508 eat_whitespace(p, os, parent_context, false);
1509 parent_context.check_layout(os);
1510 begin_inset(os, "Note Greyedout\n");
1511 os << "status open\n";
1512 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1515 if (!preamble.notefontcolor().empty())
1516 preamble.registerAutomaticallyLoadedPackage("color");
1519 else if (name == "framed" || name == "shaded") {
1520 eat_whitespace(p, os, parent_context, false);
1521 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1525 else if (name == "lstlisting") {
1526 eat_whitespace(p, os, parent_context, false);
1527 parse_listings(p, os, parent_context, false);
1531 else if (!parent_context.new_layout_allowed)
1532 parse_unknown_environment(p, name, os, FLAG_END, outer,
1535 // Alignment and spacing settings
1536 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1537 // therefore are totally broken!
1538 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1539 // they are commands not environments. They are furthermore switches that
1540 // can be ended by another switches, but also by commands like \footnote or
1541 // \parbox. So the only safe way is to leave them untouched.
1542 else if (name == "center" || name == "centering" ||
1543 name == "flushleft" || name == "flushright" ||
1544 name == "singlespace" || name == "onehalfspace" ||
1545 name == "doublespace" || name == "spacing") {
1546 eat_whitespace(p, os, parent_context, false);
1547 // We must begin a new paragraph if not already done
1548 if (! parent_context.atParagraphStart()) {
1549 parent_context.check_end_layout(os);
1550 parent_context.new_paragraph(os);
1552 if (name == "flushleft")
1553 parent_context.add_extra_stuff("\\align left\n");
1554 else if (name == "flushright")
1555 parent_context.add_extra_stuff("\\align right\n");
1556 else if (name == "center" || name == "centering")
1557 parent_context.add_extra_stuff("\\align center\n");
1558 else if (name == "singlespace")
1559 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1560 else if (name == "onehalfspace") {
1561 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1562 preamble.registerAutomaticallyLoadedPackage("setspace");
1563 } else if (name == "doublespace") {
1564 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1565 preamble.registerAutomaticallyLoadedPackage("setspace");
1566 } else if (name == "spacing") {
1567 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1568 preamble.registerAutomaticallyLoadedPackage("setspace");
1570 parse_text(p, os, FLAG_END, outer, parent_context);
1571 // Just in case the environment is empty
1572 parent_context.extra_stuff.erase();
1573 // We must begin a new paragraph to reset the alignment
1574 parent_context.new_paragraph(os);
1578 // The single '=' is meant here.
1579 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1580 eat_whitespace(p, os, parent_context, false);
1581 Context context(true, parent_context.textclass, newlayout,
1582 parent_context.layout, parent_context.font);
1583 if (parent_context.deeper_paragraph) {
1584 // We are beginning a nested environment after a
1585 // deeper paragraph inside the outer list environment.
1586 // Therefore we don't need to output a "begin deeper".
1587 context.need_end_deeper = true;
1589 parent_context.check_end_layout(os);
1590 if (last_env == name) {
1591 // we need to output a separator since LyX would export
1592 // the two environments as one otherwise (bug 5716)
1593 docstring const sep = from_ascii("--Separator--");
1594 TeX2LyXDocClass const & textclass(parent_context.textclass);
1595 if (textclass.hasLayout(sep)) {
1596 Context newcontext(parent_context);
1597 newcontext.layout = &(textclass[sep]);
1598 newcontext.check_layout(os);
1599 newcontext.check_end_layout(os);
1601 parent_context.check_layout(os);
1602 begin_inset(os, "Note Note\n");
1603 os << "status closed\n";
1604 Context newcontext(true, textclass,
1605 &(textclass.defaultLayout()));
1606 newcontext.check_layout(os);
1607 newcontext.check_end_layout(os);
1609 parent_context.check_end_layout(os);
1612 switch (context.layout->latextype) {
1613 case LATEX_LIST_ENVIRONMENT:
1614 context.add_par_extra_stuff("\\labelwidthstring "
1615 + p.verbatim_item() + '\n');
1618 case LATEX_BIB_ENVIRONMENT:
1619 p.verbatim_item(); // swallow next arg
1625 context.check_deeper(os);
1626 // handle known optional and required arguments
1627 // FIXME: Since format 446, layouts do not require anymore all optional
1628 // arguments before the required ones. Needs to be implemented!
1629 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1630 // It is impossible to place anything after the environment name,
1631 // but before the first \\item.
1632 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1633 bool need_layout = true;
1635 while (optargs < context.layout->optArgs()) {
1636 eat_whitespace(p, os, context, false);
1637 if (p.next_token().cat() == catEscape ||
1638 p.next_token().character() != '[')
1640 p.get_token(); // eat '['
1642 context.check_layout(os);
1643 need_layout = false;
1645 // FIXME: Just a workaround. InsetArgument::updateBuffer
1646 // will compute a proper ID for all "999" Arguments
1647 // (which is also what lyx2lyx produces).
1648 // However, tex2lyx should be able to output proper IDs
1650 begin_inset(os, "Argument 999\n");
1651 os << "status collapsed\n\n";
1652 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1654 eat_whitespace(p, os, context, false);
1658 while (reqargs < context.layout->requiredArgs()) {
1659 eat_whitespace(p, os, context, false);
1660 if (p.next_token().cat() != catBegin)
1662 p.get_token(); // eat '{'
1664 context.check_layout(os);
1665 need_layout = false;
1667 // FIXME: Just a workaround. InsetArgument::updateBuffer
1668 // will compute a proper ID for all "999" Arguments
1669 // (which is also what lyx2lyx produces).
1670 // However, tex2lyx should be able to output proper IDs
1672 begin_inset(os, "Argument 999\n");
1673 os << "status collapsed\n\n";
1674 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1676 eat_whitespace(p, os, context, false);
1680 parse_text(p, os, FLAG_END, outer, context);
1681 context.check_end_layout(os);
1682 if (parent_context.deeper_paragraph) {
1683 // We must suppress the "end deeper" because we
1684 // suppressed the "begin deeper" above.
1685 context.need_end_deeper = false;
1687 context.check_end_deeper(os);
1688 parent_context.new_paragraph(os);
1690 if (!preamble.titleLayoutFound())
1691 preamble.titleLayoutFound(newlayout->intitle);
1692 set<string> const & req = newlayout->requires();
1693 set<string>::const_iterator it = req.begin();
1694 set<string>::const_iterator en = req.end();
1695 for (; it != en; ++it)
1696 preamble.registerAutomaticallyLoadedPackage(*it);
1699 // The single '=' is meant here.
1700 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1701 eat_whitespace(p, os, parent_context, false);
1702 parent_context.check_layout(os);
1703 begin_inset(os, "Flex ");
1704 os << to_utf8(newinsetlayout->name()) << '\n'
1705 << "status collapsed\n";
1706 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1710 else if (name == "appendix") {
1711 // This is no good latex style, but it works and is used in some documents...
1712 eat_whitespace(p, os, parent_context, false);
1713 parent_context.check_end_layout(os);
1714 Context context(true, parent_context.textclass, parent_context.layout,
1715 parent_context.layout, parent_context.font);
1716 context.check_layout(os);
1717 os << "\\start_of_appendix\n";
1718 parse_text(p, os, FLAG_END, outer, context);
1719 context.check_end_layout(os);
1723 else if (known_environments.find(name) != known_environments.end()) {
1724 vector<ArgumentType> arguments = known_environments[name];
1725 // The last "argument" denotes wether we may translate the
1726 // environment contents to LyX
1727 // The default required if no argument is given makes us
1728 // compatible with the reLyXre environment.
1729 ArgumentType contents = arguments.empty() ?
1732 if (!arguments.empty())
1733 arguments.pop_back();
1734 // See comment in parse_unknown_environment()
1735 bool const specialfont =
1736 (parent_context.font != parent_context.normalfont);
1737 bool const new_layout_allowed =
1738 parent_context.new_layout_allowed;
1740 parent_context.new_layout_allowed = false;
1741 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1742 outer, parent_context);
1743 if (contents == verbatim)
1744 handle_ert(os, p.verbatimEnvironment(name),
1747 parse_text_snippet(p, os, FLAG_END, outer,
1749 handle_ert(os, "\\end{" + name + "}", parent_context);
1751 parent_context.new_layout_allowed = new_layout_allowed;
1755 parse_unknown_environment(p, name, os, FLAG_END, outer,
1759 active_environments.pop_back();
1763 /// parses a comment and outputs it to \p os.
1764 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1766 LASSERT(t.cat() == catComment, return);
1767 if (!t.cs().empty()) {
1768 context.check_layout(os);
1769 handle_comment(os, '%' + t.cs(), context);
1770 if (p.next_token().cat() == catNewline) {
1771 // A newline after a comment line starts a new
1773 if (context.new_layout_allowed) {
1774 if(!context.atParagraphStart())
1775 // Only start a new paragraph if not already
1776 // done (we might get called recursively)
1777 context.new_paragraph(os);
1779 handle_ert(os, "\n", context);
1780 eat_whitespace(p, os, context, true);
1783 // "%\n" combination
1790 * Reads spaces and comments until the first non-space, non-comment token.
1791 * New paragraphs (double newlines or \\par) are handled like simple spaces
1792 * if \p eatParagraph is true.
1793 * Spaces are skipped, but comments are written to \p os.
1795 void eat_whitespace(Parser & p, ostream & os, Context & context,
1799 Token const & t = p.get_token();
1800 if (t.cat() == catComment)
1801 parse_comment(p, os, t, context);
1802 else if ((! eatParagraph && p.isParagraph()) ||
1803 (t.cat() != catSpace && t.cat() != catNewline)) {
1812 * Set a font attribute, parse text and reset the font attribute.
1813 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1814 * \param currentvalue Current value of the attribute. Is set to the new
1815 * value during parsing.
1816 * \param newvalue New value of the attribute
1818 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1819 Context & context, string const & attribute,
1820 string & currentvalue, string const & newvalue)
1822 context.check_layout(os);
1823 string const oldvalue = currentvalue;
1824 currentvalue = newvalue;
1825 os << '\n' << attribute << ' ' << newvalue << "\n";
1826 parse_text_snippet(p, os, flags, outer, context);
1827 context.check_layout(os);
1828 os << '\n' << attribute << ' ' << oldvalue << "\n";
1829 currentvalue = oldvalue;
1833 /// get the arguments of a natbib or jurabib citation command
1834 void get_cite_arguments(Parser & p, bool natbibOrder,
1835 string & before, string & after)
1837 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1839 // text before the citation
1841 // text after the citation
1842 after = p.getFullOpt();
1844 if (!after.empty()) {
1845 before = p.getFullOpt();
1846 if (natbibOrder && !before.empty())
1847 swap(before, after);
1852 /// Convert filenames with TeX macros and/or quotes to something LyX
1854 string const normalize_filename(string const & name)
1859 Token const & t = p.get_token();
1860 if (t.cat() != catEscape)
1862 else if (t.cs() == "lyxdot") {
1863 // This is used by LyX for simple dots in relative
1867 } else if (t.cs() == "space") {
1870 } else if (t.cs() == "string") {
1871 // Convert \string" to " and \string~ to ~
1872 Token const & n = p.next_token();
1873 if (n.asInput() != "\"" && n.asInput() != "~")
1878 // Strip quotes. This is a bit complicated (see latex_path()).
1879 string full = os.str();
1880 if (!full.empty() && full[0] == '"') {
1881 string base = removeExtension(full);
1882 string ext = getExtension(full);
1883 if (!base.empty() && base[base.length()-1] == '"')
1886 return addExtension(trim(base, "\""), ext);
1887 if (full[full.length()-1] == '"')
1890 return trim(full, "\"");
1896 /// Convert \p name from TeX convention (relative to master file) to LyX
1897 /// convention (relative to .lyx file) if it is relative
1898 void fix_child_filename(string & name)
1900 string const absMasterTeX = getMasterFilePath(true);
1901 bool const isabs = FileName::isAbsolute(name);
1902 // convert from "relative to .tex master" to absolute original path
1904 name = makeAbsPath(name, absMasterTeX).absFileName();
1905 bool copyfile = copyFiles();
1906 string const absParentLyX = getParentFilePath(false);
1909 // convert from absolute original path to "relative to master file"
1910 string const rel = to_utf8(makeRelPath(from_utf8(name),
1911 from_utf8(absMasterTeX)));
1912 // re-interpret "relative to .tex file" as "relative to .lyx file"
1913 // (is different if the master .lyx file resides in a
1914 // different path than the master .tex file)
1915 string const absMasterLyX = getMasterFilePath(false);
1916 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1917 // Do not copy if the new path is impossible to create. Example:
1918 // absMasterTeX = "/foo/bar/"
1919 // absMasterLyX = "/bar/"
1920 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1921 if (contains(name, "/../"))
1928 // convert from absolute original path to
1929 // "relative to .lyx file"
1930 name = to_utf8(makeRelPath(from_utf8(abs),
1931 from_utf8(absParentLyX)));
1935 // convert from absolute original path to "relative to .lyx file"
1936 name = to_utf8(makeRelPath(from_utf8(name),
1937 from_utf8(absParentLyX)));
1942 void copy_file(FileName const & src, string dstname)
1946 string const absParent = getParentFilePath(false);
1948 if (FileName::isAbsolute(dstname))
1949 dst = FileName(dstname);
1951 dst = makeAbsPath(dstname, absParent);
1952 string const absMaster = getMasterFilePath(false);
1953 FileName const srcpath = src.onlyPath();
1954 FileName const dstpath = dst.onlyPath();
1955 if (equivalent(srcpath, dstpath))
1957 if (!dstpath.isDirectory()) {
1958 if (!dstpath.createPath()) {
1959 cerr << "Warning: Could not create directory for file `"
1960 << dst.absFileName() << "´." << endl;
1964 if (dst.isReadableFile()) {
1965 if (overwriteFiles())
1966 cerr << "Warning: Overwriting existing file `"
1967 << dst.absFileName() << "´." << endl;
1969 cerr << "Warning: Not overwriting existing file `"
1970 << dst.absFileName() << "´." << endl;
1974 if (!src.copyTo(dst))
1975 cerr << "Warning: Could not copy file `" << src.absFileName()
1976 << "´ to `" << dst.absFileName() << "´." << endl;
1980 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1981 void parse_noweb(Parser & p, ostream & os, Context & context)
1983 // assemble the rest of the keyword
1987 Token const & t = p.get_token();
1988 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1991 chunk = (p.good() && p.next_token().asInput() == "=");
1993 name += p.get_token().asInput();
1996 name += t.asInput();
1999 if (!chunk || !context.new_layout_allowed ||
2000 !context.textclass.hasLayout(from_ascii("Chunk"))) {
2001 cerr << "Warning: Could not interpret '" << name
2002 << "'. Ignoring it." << endl;
2006 // We use new_paragraph instead of check_end_layout because the stuff
2007 // following the noweb chunk needs to start with a \begin_layout.
2008 // This may create a new paragraph even if there was none in the
2009 // noweb file, but the alternative is an invalid LyX file. Since
2010 // noweb code chunks are implemented with a layout style in LyX they
2011 // always must be in an own paragraph.
2012 context.new_paragraph(os);
2013 Context newcontext(true, context.textclass,
2014 &context.textclass[from_ascii("Chunk")]);
2015 newcontext.check_layout(os);
2018 Token const & t = p.get_token();
2019 // We abuse the parser a bit, because this is no TeX syntax
2021 if (t.cat() == catEscape)
2022 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2025 Context tmp(false, context.textclass,
2026 &context.textclass[from_ascii("Chunk")]);
2027 tmp.need_end_layout = true;
2028 tmp.check_layout(oss);
2029 os << subst(t.asInput(), "\n", oss.str());
2031 // The chunk is ended by an @ at the beginning of a line.
2032 // After the @ the line may contain a comment and/or
2033 // whitespace, but nothing else.
2034 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2035 (p.next_token().cat() == catSpace ||
2036 p.next_token().cat() == catNewline ||
2037 p.next_token().cat() == catComment)) {
2038 while (p.good() && p.next_token().cat() == catSpace)
2039 os << p.get_token().asInput();
2040 if (p.next_token().cat() == catComment)
2041 // The comment includes a final '\n'
2042 os << p.get_token().asInput();
2044 if (p.next_token().cat() == catNewline)
2051 newcontext.check_end_layout(os);
2055 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2056 bool is_macro(Parser & p)
2058 Token first = p.curr_token();
2059 if (first.cat() != catEscape || !p.good())
2061 if (first.cs() == "def")
2063 if (first.cs() != "global" && first.cs() != "long")
2065 Token second = p.get_token();
2067 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2068 second.cat() == catNewline || second.cat() == catComment)) {
2069 second = p.get_token();
2072 bool secondvalid = second.cat() == catEscape;
2074 bool thirdvalid = false;
2075 if (p.good() && first.cs() == "global" && secondvalid &&
2076 second.cs() == "long") {
2077 third = p.get_token();
2079 while (p.good() && !p.isParagraph() &&
2080 (third.cat() == catSpace ||
2081 third.cat() == catNewline ||
2082 third.cat() == catComment)) {
2083 third = p.get_token();
2086 thirdvalid = third.cat() == catEscape;
2088 for (int i = 0; i < pos; ++i)
2093 return (first.cs() == "global" || first.cs() == "long") &&
2094 second.cs() == "def";
2095 return first.cs() == "global" && second.cs() == "long" &&
2096 third.cs() == "def";
2100 /// Parse a macro definition (assumes that is_macro() returned true)
2101 void parse_macro(Parser & p, ostream & os, Context & context)
2103 context.check_layout(os);
2104 Token first = p.curr_token();
2107 string command = first.asInput();
2108 if (first.cs() != "def") {
2110 eat_whitespace(p, os, context, false);
2111 second = p.curr_token();
2112 command += second.asInput();
2113 if (second.cs() != "def") {
2115 eat_whitespace(p, os, context, false);
2116 third = p.curr_token();
2117 command += third.asInput();
2120 eat_whitespace(p, os, context, false);
2121 string const name = p.get_token().cs();
2122 eat_whitespace(p, os, context, false);
2128 while (p.next_token().cat() != catBegin) {
2129 if (p.next_token().cat() == catParameter) {
2134 // followed by number?
2135 if (p.next_token().cat() == catOther) {
2136 char c = p.getChar();
2138 // number = current arity + 1?
2139 if (c == arity + '0' + 1)
2144 paramtext += p.get_token().cs();
2146 paramtext += p.get_token().cs();
2151 // only output simple (i.e. compatible) macro as FormulaMacros
2152 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2154 context.check_layout(os);
2155 begin_inset(os, "FormulaMacro");
2156 os << "\n\\def" << ert;
2159 handle_ert(os, command + ert, context);
2163 void registerExternalTemplatePackages(string const & name)
2165 external::TemplateManager const & etm = external::TemplateManager::get();
2166 external::Template const * const et = etm.getTemplateByName(name);
2169 external::Template::Formats::const_iterator cit = et->formats.end();
2171 cit = et->formats.find("PDFLaTeX");
2172 if (cit == et->formats.end())
2173 // If the template has not specified a PDFLaTeX output,
2174 // we try the LaTeX format.
2175 cit = et->formats.find("LaTeX");
2176 if (cit == et->formats.end())
2178 vector<string>::const_iterator qit = cit->second.requirements.begin();
2179 vector<string>::const_iterator qend = cit->second.requirements.end();
2180 for (; qit != qend; ++qit)
2181 preamble.registerAutomaticallyLoadedPackage(*qit);
2184 } // anonymous namespace
2187 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2190 Layout const * newlayout = 0;
2191 InsetLayout const * newinsetlayout = 0;
2192 char const * const * where = 0;
2193 // Store the latest bibliographystyle and nocite{*} option
2194 // (needed for bibtex inset)
2196 string bibliographystyle = "default";
2197 bool const use_natbib = isProvided("natbib");
2198 bool const use_jurabib = isProvided("jurabib");
2201 Token const & t = p.get_token();
2203 // it is impossible to determine the correct encoding for non-CJK Japanese.
2204 // Therefore write a note at the beginning of the document
2205 if (is_nonCJKJapanese) {
2206 context.check_layout(os);
2207 begin_inset(os, "Note Note\n");
2208 os << "status open\n\\begin_layout Plain Layout\n"
2209 << "\\series bold\n"
2210 << "Important information:\n"
2211 << "\\end_layout\n\n"
2212 << "\\begin_layout Plain Layout\n"
2213 << "This document is in Japanese (non-CJK).\n"
2214 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2215 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2216 << " encoding in the document settings.\n"
2217 << "\\end_layout\n";
2219 is_nonCJKJapanese = false;
2223 debugToken(cerr, t, flags);
2226 if (flags & FLAG_ITEM) {
2227 if (t.cat() == catSpace)
2230 flags &= ~FLAG_ITEM;
2231 if (t.cat() == catBegin) {
2232 // skip the brace and collect everything to the next matching
2234 flags |= FLAG_BRACE_LAST;
2238 // handle only this single token, leave the loop if done
2239 flags |= FLAG_LEAVE;
2242 if (t.cat() != catEscape && t.character() == ']' &&
2243 (flags & FLAG_BRACK_LAST))
2245 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2248 // If there is anything between \end{env} and \begin{env} we
2249 // don't need to output a separator.
2250 if (t.cat() != catSpace && t.cat() != catNewline &&
2251 t.asInput() != "\\begin")
2257 if (t.cat() == catMath) {
2258 // we are inside some text mode thingy, so opening new math is allowed
2259 context.check_layout(os);
2260 begin_inset(os, "Formula ");
2261 Token const & n = p.get_token();
2262 bool const display(n.cat() == catMath && outer);
2264 // TeX's $$...$$ syntax for displayed math
2266 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2268 p.get_token(); // skip the second '$' token
2270 // simple $...$ stuff
2273 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2278 // Prevent the conversion of a line break to a
2279 // space (bug 7668). This does not change the
2280 // output, but looks ugly in LyX.
2281 eat_whitespace(p, os, context, false);
2285 else if (t.cat() == catSuper || t.cat() == catSub)
2286 cerr << "catcode " << t << " illegal in text mode\n";
2288 // Basic support for english quotes. This should be
2289 // extended to other quotes, but is not so easy (a
2290 // left english quote is the same as a right german
2292 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2293 context.check_layout(os);
2294 begin_inset(os, "Quotes ");
2300 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2301 context.check_layout(os);
2302 begin_inset(os, "Quotes ");
2309 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2310 context.check_layout(os);
2311 begin_inset(os, "Quotes ");
2318 else if (t.asInput() == "<"
2319 && p.next_token().asInput() == "<" && noweb_mode) {
2321 parse_noweb(p, os, context);
2324 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2325 context.check_layout(os);
2326 begin_inset(os, "Quotes ");
2333 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2334 check_space(p, os, context);
2336 else if (t.character() == '[' && noweb_mode &&
2337 p.next_token().character() == '[') {
2338 // These can contain underscores
2340 string const s = p.getFullOpt() + ']';
2341 if (p.next_token().character() == ']')
2344 cerr << "Warning: Inserting missing ']' in '"
2345 << s << "'." << endl;
2346 handle_ert(os, s, context);
2349 else if (t.cat() == catLetter) {
2350 context.check_layout(os);
2351 // Workaround for bug 4752.
2352 // FIXME: This whole code block needs to be removed
2353 // when the bug is fixed and tex2lyx produces
2354 // the updated file format.
2355 // The replacement algorithm in LyX is so stupid that
2356 // it even translates a phrase if it is part of a word.
2357 bool handled = false;
2358 for (int const * l = known_phrase_lengths; *l; ++l) {
2359 string phrase = t.cs();
2360 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2361 phrase += p.get_token().cs();
2362 if (is_known(phrase, known_coded_phrases)) {
2363 handle_ert(os, phrase, context);
2367 for (size_t i = 1; i < phrase.length(); ++i)
2375 else if (t.cat() == catOther ||
2376 t.cat() == catAlign ||
2377 t.cat() == catParameter) {
2378 // This translates "&" to "\\&" which may be wrong...
2379 context.check_layout(os);
2383 else if (p.isParagraph()) {
2384 if (context.new_layout_allowed)
2385 context.new_paragraph(os);
2387 handle_ert(os, "\\par ", context);
2388 eat_whitespace(p, os, context, true);
2391 else if (t.cat() == catActive) {
2392 context.check_layout(os);
2393 if (t.character() == '~') {
2394 if (context.layout->free_spacing)
2397 begin_inset(os, "space ~\n");
2404 else if (t.cat() == catBegin) {
2405 Token const next = p.next_token();
2406 Token const end = p.next_next_token();
2407 if (next.cat() == catEnd) {
2409 Token const prev = p.prev_token();
2411 if (p.next_token().character() == '`' ||
2412 (prev.character() == '-' &&
2413 p.next_token().character() == '-'))
2414 ; // ignore it in {}`` or -{}-
2416 handle_ert(os, "{}", context);
2417 } else if (next.cat() == catEscape &&
2418 is_known(next.cs(), known_quotes) &&
2419 end.cat() == catEnd) {
2420 // Something like {\textquoteright} (e.g.
2421 // from writer2latex). LyX writes
2422 // \textquoteright{}, so we may skip the
2423 // braces here for better readability.
2424 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2427 context.check_layout(os);
2428 // special handling of font attribute changes
2429 Token const prev = p.prev_token();
2430 TeXFont const oldFont = context.font;
2431 if (next.character() == '[' ||
2432 next.character() == ']' ||
2433 next.character() == '*') {
2435 if (p.next_token().cat() == catEnd) {
2440 handle_ert(os, "{", context);
2441 parse_text_snippet(p, os,
2444 handle_ert(os, "}", context);
2446 } else if (! context.new_layout_allowed) {
2447 handle_ert(os, "{", context);
2448 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2450 handle_ert(os, "}", context);
2451 } else if (is_known(next.cs(), known_sizes)) {
2452 // next will change the size, so we must
2454 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2456 if (!context.atParagraphStart())
2458 << context.font.size << "\n";
2459 } else if (is_known(next.cs(), known_font_families)) {
2460 // next will change the font family, so we
2461 // must reset it here
2462 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2464 if (!context.atParagraphStart())
2466 << context.font.family << "\n";
2467 } else if (is_known(next.cs(), known_font_series)) {
2468 // next will change the font series, so we
2469 // must reset it here
2470 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2472 if (!context.atParagraphStart())
2474 << context.font.series << "\n";
2475 } else if (is_known(next.cs(), known_font_shapes)) {
2476 // next will change the font shape, so we
2477 // must reset it here
2478 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2480 if (!context.atParagraphStart())
2482 << context.font.shape << "\n";
2483 } else if (is_known(next.cs(), known_old_font_families) ||
2484 is_known(next.cs(), known_old_font_series) ||
2485 is_known(next.cs(), known_old_font_shapes)) {
2486 // next will change the font family, series
2487 // and shape, so we must reset it here
2488 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2490 if (!context.atParagraphStart())
2492 << context.font.family
2494 << context.font.series
2496 << context.font.shape << "\n";
2498 handle_ert(os, "{", context);
2499 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2501 handle_ert(os, "}", context);
2506 else if (t.cat() == catEnd) {
2507 if (flags & FLAG_BRACE_LAST) {
2510 cerr << "stray '}' in text\n";
2511 handle_ert(os, "}", context);
2514 else if (t.cat() == catComment)
2515 parse_comment(p, os, t, context);
2518 // control sequences
2521 else if (t.cs() == "(") {
2522 context.check_layout(os);
2523 begin_inset(os, "Formula");
2525 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2530 else if (t.cs() == "[") {
2531 context.check_layout(os);
2532 begin_inset(os, "Formula");
2534 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2537 // Prevent the conversion of a line break to a space
2538 // (bug 7668). This does not change the output, but
2539 // looks ugly in LyX.
2540 eat_whitespace(p, os, context, false);
2543 else if (t.cs() == "begin")
2544 parse_environment(p, os, outer, last_env,
2547 else if (t.cs() == "end") {
2548 if (flags & FLAG_END) {
2549 // eat environment name
2550 string const name = p.getArg('{', '}');
2551 if (name != active_environment())
2552 cerr << "\\end{" + name + "} does not match \\begin{"
2553 + active_environment() + "}\n";
2556 p.error("found 'end' unexpectedly");
2559 else if (t.cs() == "item") {
2561 bool const optarg = p.hasOpt();
2563 // FIXME: This swallows comments, but we cannot use
2564 // eat_whitespace() since we must not output
2565 // anything before the item.
2566 p.skip_spaces(true);
2567 s = p.verbatimOption();
2569 p.skip_spaces(false);
2571 context.check_layout(os);
2572 if (context.has_item) {
2573 // An item in an unknown list-like environment
2574 // FIXME: Do this in check_layout()!
2575 context.has_item = false;
2577 handle_ert(os, "\\item", context);
2579 handle_ert(os, "\\item ", context);
2582 if (context.layout->labeltype != LABEL_MANUAL) {
2583 // LyX does not support \item[\mybullet]
2584 // in itemize environments
2586 os << parse_text_snippet(p2,
2587 FLAG_BRACK_LAST, outer, context);
2588 } else if (!s.empty()) {
2589 // LyX adds braces around the argument,
2590 // so we need to remove them here.
2591 if (s.size() > 2 && s[0] == '{' &&
2592 s[s.size()-1] == '}')
2593 s = s.substr(1, s.size()-2);
2594 // If the argument contains a space we
2595 // must put it into ERT: Otherwise LyX
2596 // would misinterpret the space as
2597 // item delimiter (bug 7663)
2598 if (contains(s, ' ')) {
2599 handle_ert(os, s, context);
2602 os << parse_text_snippet(p2,
2606 // The space is needed to separate the
2607 // item from the rest of the sentence.
2609 eat_whitespace(p, os, context, false);
2614 else if (t.cs() == "bibitem") {
2616 context.check_layout(os);
2617 eat_whitespace(p, os, context, false);
2618 string label = convert_command_inset_arg(p.verbatimOption());
2619 string key = convert_command_inset_arg(p.verbatim_item());
2620 if (contains(label, '\\') || contains(key, '\\')) {
2621 // LyX can't handle LaTeX commands in labels or keys
2622 handle_ert(os, t.asInput() + '[' + label +
2623 "]{" + p.verbatim_item() + '}',
2626 begin_command_inset(os, "bibitem", "bibitem");
2627 os << "label \"" << label << "\"\n"
2628 "key \"" << key << "\"\n";
2633 else if (is_macro(p)) {
2634 // catch the case of \def\inputGnumericTable
2636 if (t.cs() == "def") {
2637 Token second = p.next_token();
2638 if (second.cs() == "inputGnumericTable") {
2642 Token third = p.get_token();
2644 if (third.cs() == "input") {
2648 string name = normalize_filename(p.verbatim_item());
2649 string const path = getMasterFilePath(true);
2650 // We want to preserve relative / absolute filenames,
2651 // therefore path is only used for testing
2652 // The file extension is in every case ".tex".
2653 // So we need to remove this extension and check for
2654 // the original one.
2655 name = removeExtension(name);
2656 if (!makeAbsPath(name, path).exists()) {
2657 char const * const Gnumeric_formats[] = {"gnumeric",
2659 string const Gnumeric_name =
2660 find_file(name, path, Gnumeric_formats);
2661 if (!Gnumeric_name.empty())
2662 name = Gnumeric_name;
2664 FileName const absname = makeAbsPath(name, path);
2665 if (absname.exists()) {
2666 fix_child_filename(name);
2667 copy_file(absname, name);
2669 cerr << "Warning: Could not find file '"
2670 << name << "'." << endl;
2671 context.check_layout(os);
2672 begin_inset(os, "External\n\ttemplate ");
2673 os << "GnumericSpreadsheet\n\tfilename "
2676 context.check_layout(os);
2678 // register the packages that are automatically loaded
2679 // by the Gnumeric template
2680 registerExternalTemplatePackages("GnumericSpreadsheet");
2685 parse_macro(p, os, context);
2688 else if (t.cs() == "noindent") {
2690 context.add_par_extra_stuff("\\noindent\n");
2693 else if (t.cs() == "appendix") {
2694 context.add_par_extra_stuff("\\start_of_appendix\n");
2695 // We need to start a new paragraph. Otherwise the
2696 // appendix in 'bla\appendix\chapter{' would start
2698 context.new_paragraph(os);
2699 // We need to make sure that the paragraph is
2700 // generated even if it is empty. Otherwise the
2701 // appendix in '\par\appendix\par\chapter{' would
2703 context.check_layout(os);
2704 // FIXME: This is a hack to prevent paragraph
2705 // deletion if it is empty. Handle this better!
2707 "%dummy comment inserted by tex2lyx to "
2708 "ensure that this paragraph is not empty",
2710 // Both measures above may generate an additional
2711 // empty paragraph, but that does not hurt, because
2712 // whitespace does not matter here.
2713 eat_whitespace(p, os, context, true);
2716 // Must catch empty dates before findLayout is called below
2717 else if (t.cs() == "date") {
2718 eat_whitespace(p, os, context, false);
2720 string const date = p.verbatim_item();
2723 preamble.suppressDate(true);
2726 preamble.suppressDate(false);
2727 if (context.new_layout_allowed &&
2728 (newlayout = findLayout(context.textclass,
2731 output_command_layout(os, p, outer,
2732 context, newlayout);
2733 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2734 if (!preamble.titleLayoutFound())
2735 preamble.titleLayoutFound(newlayout->intitle);
2736 set<string> const & req = newlayout->requires();
2737 set<string>::const_iterator it = req.begin();
2738 set<string>::const_iterator en = req.end();
2739 for (; it != en; ++it)
2740 preamble.registerAutomaticallyLoadedPackage(*it);
2743 "\\date{" + p.verbatim_item() + '}',
2748 // Starred section headings
2749 // Must attempt to parse "Section*" before "Section".
2750 else if ((p.next_token().asInput() == "*") &&
2751 context.new_layout_allowed &&
2752 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2755 output_command_layout(os, p, outer, context, newlayout);
2757 if (!preamble.titleLayoutFound())
2758 preamble.titleLayoutFound(newlayout->intitle);
2759 set<string> const & req = newlayout->requires();
2760 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2761 preamble.registerAutomaticallyLoadedPackage(*it);
2764 // Section headings and the like
2765 else if (context.new_layout_allowed &&
2766 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2768 output_command_layout(os, p, outer, context, newlayout);
2770 if (!preamble.titleLayoutFound())
2771 preamble.titleLayoutFound(newlayout->intitle);
2772 set<string> const & req = newlayout->requires();
2773 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2774 preamble.registerAutomaticallyLoadedPackage(*it);
2777 else if (t.cs() == "caption") {
2779 context.check_layout(os);
2781 begin_inset(os, "Caption\n");
2782 Context newcontext(true, context.textclass, 0, 0, context.font);
2783 newcontext.check_layout(os);
2784 // FIXME InsetArgument is now properly implemented in InsetLayout
2785 // (for captions, but also for others)
2786 if (p.next_token().cat() != catEscape &&
2787 p.next_token().character() == '[') {
2788 p.get_token(); // eat '['
2789 begin_inset(os, "Argument 1\n");
2790 os << "status collapsed\n";
2791 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2793 eat_whitespace(p, os, context, false);
2795 parse_text(p, os, FLAG_ITEM, outer, context);
2796 context.check_end_layout(os);
2797 // We don't need really a new paragraph, but
2798 // we must make sure that the next item gets a \begin_layout.
2799 context.new_paragraph(os);
2802 newcontext.check_end_layout(os);
2805 else if (t.cs() == "subfloat") {
2806 // the syntax is \subfloat[caption]{content}
2807 // if it is a table of figure depends on the surrounding float
2808 bool has_caption = false;
2810 // do nothing if there is no outer float
2811 if (!float_type.empty()) {
2812 context.check_layout(os);
2814 begin_inset(os, "Float " + float_type + "\n");
2816 << "\nsideways false"
2817 << "\nstatus collapsed\n\n";
2820 if (p.next_token().cat() != catEscape &&
2821 p.next_token().character() == '[') {
2822 p.get_token(); // eat '['
2823 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2827 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2828 // the caption comes always as the last
2830 // we must make sure that the caption gets a \begin_layout
2831 os << "\n\\begin_layout Plain Layout";
2833 begin_inset(os, "Caption\n");
2834 Context newcontext(true, context.textclass,
2835 0, 0, context.font);
2836 newcontext.check_layout(os);
2837 os << caption << "\n";
2838 newcontext.check_end_layout(os);
2839 // We don't need really a new paragraph, but
2840 // we must make sure that the next item gets a \begin_layout.
2841 //newcontext.new_paragraph(os);
2845 // We don't need really a new paragraph, but
2846 // we must make sure that the next item gets a \begin_layout.
2848 context.new_paragraph(os);
2851 context.check_end_layout(os);
2852 // close the layout we opened
2854 os << "\n\\end_layout\n";
2856 // if the float type is not supported or there is no surrounding float
2859 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2860 handle_ert(os, t.asInput() + '[' + opt_arg +
2861 "]{" + p.verbatim_item() + '}', context);
2863 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2867 else if (t.cs() == "includegraphics") {
2868 bool const clip = p.next_token().asInput() == "*";
2871 string const arg = p.getArg('[', ']');
2872 map<string, string> opts;
2873 vector<string> keys;
2874 split_map(arg, opts, keys);
2876 opts["clip"] = string();
2877 string name = normalize_filename(p.verbatim_item());
2879 string const path = getMasterFilePath(true);
2880 // We want to preserve relative / absolute filenames,
2881 // therefore path is only used for testing
2882 if (!makeAbsPath(name, path).exists()) {
2883 // The file extension is probably missing.
2884 // Now try to find it out.
2885 string const dvips_name =
2886 find_file(name, path,
2887 known_dvips_graphics_formats);
2888 string const pdftex_name =
2889 find_file(name, path,
2890 known_pdftex_graphics_formats);
2891 if (!dvips_name.empty()) {
2892 if (!pdftex_name.empty()) {
2893 cerr << "This file contains the "
2895 "\"\\includegraphics{"
2897 "However, files\n\""
2898 << dvips_name << "\" and\n\""
2899 << pdftex_name << "\"\n"
2900 "both exist, so I had to make a "
2901 "choice and took the first one.\n"
2902 "Please move the unwanted one "
2903 "someplace else and try again\n"
2904 "if my choice was wrong."
2908 } else if (!pdftex_name.empty()) {
2914 FileName const absname = makeAbsPath(name, path);
2915 if (absname.exists()) {
2916 fix_child_filename(name);
2917 copy_file(absname, name);
2919 cerr << "Warning: Could not find graphics file '"
2920 << name << "'." << endl;
2922 context.check_layout(os);
2923 begin_inset(os, "Graphics ");
2924 os << "\n\tfilename " << name << '\n';
2925 if (opts.find("width") != opts.end())
2927 << translate_len(opts["width"]) << '\n';
2928 if (opts.find("height") != opts.end())
2930 << translate_len(opts["height"]) << '\n';
2931 if (opts.find("scale") != opts.end()) {
2932 istringstream iss(opts["scale"]);
2936 os << "\tscale " << val << '\n';
2938 if (opts.find("angle") != opts.end()) {
2939 os << "\trotateAngle "
2940 << opts["angle"] << '\n';
2941 vector<string>::const_iterator a =
2942 find(keys.begin(), keys.end(), "angle");
2943 vector<string>::const_iterator s =
2944 find(keys.begin(), keys.end(), "width");
2945 if (s == keys.end())
2946 s = find(keys.begin(), keys.end(), "height");
2947 if (s == keys.end())
2948 s = find(keys.begin(), keys.end(), "scale");
2949 if (s != keys.end() && distance(s, a) > 0)
2950 os << "\tscaleBeforeRotation\n";
2952 if (opts.find("origin") != opts.end()) {
2954 string const opt = opts["origin"];
2955 if (opt.find('l') != string::npos) ss << "left";
2956 if (opt.find('r') != string::npos) ss << "right";
2957 if (opt.find('c') != string::npos) ss << "center";
2958 if (opt.find('t') != string::npos) ss << "Top";
2959 if (opt.find('b') != string::npos) ss << "Bottom";
2960 if (opt.find('B') != string::npos) ss << "Baseline";
2961 if (!ss.str().empty())
2962 os << "\trotateOrigin " << ss.str() << '\n';
2964 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2966 if (opts.find("keepaspectratio") != opts.end())
2967 os << "\tkeepAspectRatio\n";
2968 if (opts.find("clip") != opts.end())
2970 if (opts.find("draft") != opts.end())
2972 if (opts.find("bb") != opts.end())
2973 os << "\tBoundingBox "
2974 << opts["bb"] << '\n';
2975 int numberOfbbOptions = 0;
2976 if (opts.find("bbllx") != opts.end())
2977 numberOfbbOptions++;
2978 if (opts.find("bblly") != opts.end())
2979 numberOfbbOptions++;
2980 if (opts.find("bburx") != opts.end())
2981 numberOfbbOptions++;
2982 if (opts.find("bbury") != opts.end())
2983 numberOfbbOptions++;
2984 if (numberOfbbOptions == 4)
2985 os << "\tBoundingBox "
2986 << opts["bbllx"] << " " << opts["bblly"] << " "
2987 << opts["bburx"] << " " << opts["bbury"] << '\n';
2988 else if (numberOfbbOptions > 0)
2989 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2990 numberOfbbOptions = 0;
2991 if (opts.find("natwidth") != opts.end())
2992 numberOfbbOptions++;
2993 if (opts.find("natheight") != opts.end())
2994 numberOfbbOptions++;
2995 if (numberOfbbOptions == 2)
2996 os << "\tBoundingBox 0bp 0bp "
2997 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2998 else if (numberOfbbOptions > 0)
2999 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3000 ostringstream special;
3001 if (opts.find("hiresbb") != opts.end())
3002 special << "hiresbb,";
3003 if (opts.find("trim") != opts.end())
3005 if (opts.find("viewport") != opts.end())
3006 special << "viewport=" << opts["viewport"] << ',';
3007 if (opts.find("totalheight") != opts.end())
3008 special << "totalheight=" << opts["totalheight"] << ',';
3009 if (opts.find("type") != opts.end())
3010 special << "type=" << opts["type"] << ',';
3011 if (opts.find("ext") != opts.end())
3012 special << "ext=" << opts["ext"] << ',';
3013 if (opts.find("read") != opts.end())
3014 special << "read=" << opts["read"] << ',';
3015 if (opts.find("command") != opts.end())
3016 special << "command=" << opts["command"] << ',';
3017 string s_special = special.str();
3018 if (!s_special.empty()) {
3019 // We had special arguments. Remove the trailing ','.
3020 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3022 // TODO: Handle the unknown settings better.
3023 // Warn about invalid options.
3024 // Check whether some option was given twice.
3026 preamble.registerAutomaticallyLoadedPackage("graphicx");
3029 else if (t.cs() == "footnote" ||
3030 (t.cs() == "thanks" && context.layout->intitle)) {
3032 context.check_layout(os);
3033 begin_inset(os, "Foot\n");
3034 os << "status collapsed\n\n";
3035 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3039 else if (t.cs() == "marginpar") {
3041 context.check_layout(os);
3042 begin_inset(os, "Marginal\n");
3043 os << "status collapsed\n\n";
3044 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3048 else if (t.cs() == "lstinline") {
3050 parse_listings(p, os, context, true);
3053 else if (t.cs() == "ensuremath") {
3055 context.check_layout(os);
3056 string const s = p.verbatim_item();
3057 //FIXME: this never triggers in UTF8
3058 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3061 handle_ert(os, "\\ensuremath{" + s + "}",
3065 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3066 if (preamble.titleLayoutFound()) {
3068 skip_spaces_braces(p);
3070 handle_ert(os, t.asInput(), context);
3073 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3074 context.check_layout(os);
3075 begin_command_inset(os, "toc", t.cs());
3077 skip_spaces_braces(p);
3078 if (t.cs() == "lstlistoflistings")
3079 preamble.registerAutomaticallyLoadedPackage("listings");
3082 else if (t.cs() == "listoffigures") {
3083 context.check_layout(os);
3084 begin_inset(os, "FloatList figure\n");
3086 skip_spaces_braces(p);
3089 else if (t.cs() == "listoftables") {
3090 context.check_layout(os);
3091 begin_inset(os, "FloatList table\n");
3093 skip_spaces_braces(p);
3096 else if (t.cs() == "listof") {
3097 p.skip_spaces(true);
3098 string const name = p.get_token().cs();
3099 if (context.textclass.floats().typeExist(name)) {
3100 context.check_layout(os);
3101 begin_inset(os, "FloatList ");
3104 p.get_token(); // swallow second arg
3106 handle_ert(os, "\\listof{" + name + "}", context);
3109 else if ((where = is_known(t.cs(), known_text_font_families)))
3110 parse_text_attributes(p, os, FLAG_ITEM, outer,
3111 context, "\\family", context.font.family,
3112 known_coded_font_families[where - known_text_font_families]);
3114 else if ((where = is_known(t.cs(), known_text_font_series)))
3115 parse_text_attributes(p, os, FLAG_ITEM, outer,
3116 context, "\\series", context.font.series,
3117 known_coded_font_series[where - known_text_font_series]);
3119 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3120 parse_text_attributes(p, os, FLAG_ITEM, outer,
3121 context, "\\shape", context.font.shape,
3122 known_coded_font_shapes[where - known_text_font_shapes]);
3124 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3125 context.check_layout(os);
3126 TeXFont oldFont = context.font;
3127 context.font.init();
3128 context.font.size = oldFont.size;
3129 os << "\n\\family " << context.font.family << "\n";
3130 os << "\n\\series " << context.font.series << "\n";
3131 os << "\n\\shape " << context.font.shape << "\n";
3132 if (t.cs() == "textnormal") {
3133 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3134 output_font_change(os, context.font, oldFont);
3135 context.font = oldFont;
3137 eat_whitespace(p, os, context, false);
3140 else if (t.cs() == "textcolor") {
3141 // scheme is \textcolor{color name}{text}
3142 string const color = p.verbatim_item();
3143 // we only support the predefined colors of the color package
3144 if (color == "black" || color == "blue" || color == "cyan"
3145 || color == "green" || color == "magenta" || color == "red"
3146 || color == "white" || color == "yellow") {
3147 context.check_layout(os);
3148 os << "\n\\color " << color << "\n";
3149 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3150 context.check_layout(os);
3151 os << "\n\\color inherit\n";
3152 preamble.registerAutomaticallyLoadedPackage("color");
3154 // for custom defined colors
3155 handle_ert(os, t.asInput() + "{" + color + "}", context);
3158 else if (t.cs() == "underbar" || t.cs() == "uline") {
3159 // \underbar is not 100% correct (LyX outputs \uline
3160 // of ulem.sty). The difference is that \ulem allows
3161 // line breaks, and \underbar does not.
3162 // Do NOT handle \underline.
3163 // \underbar cuts through y, g, q, p etc.,
3164 // \underline does not.
3165 context.check_layout(os);
3166 os << "\n\\bar under\n";
3167 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3168 context.check_layout(os);
3169 os << "\n\\bar default\n";
3170 preamble.registerAutomaticallyLoadedPackage("ulem");
3173 else if (t.cs() == "sout") {
3174 context.check_layout(os);
3175 os << "\n\\strikeout on\n";
3176 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3177 context.check_layout(os);
3178 os << "\n\\strikeout default\n";
3179 preamble.registerAutomaticallyLoadedPackage("ulem");
3182 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3183 t.cs() == "emph" || t.cs() == "noun") {
3184 context.check_layout(os);
3185 os << "\n\\" << t.cs() << " on\n";
3186 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3187 context.check_layout(os);
3188 os << "\n\\" << t.cs() << " default\n";
3189 if (t.cs() == "uuline" || t.cs() == "uwave")
3190 preamble.registerAutomaticallyLoadedPackage("ulem");
3193 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3194 context.check_layout(os);
3195 string name = p.getArg('{', '}');
3196 string localtime = p.getArg('{', '}');
3197 preamble.registerAuthor(name);
3198 Author const & author = preamble.getAuthor(name);
3199 // from_ctime() will fail if LyX decides to output the
3200 // time in the text language. It might also use a wrong
3201 // time zone (if the original LyX document was exported
3202 // with a different time zone).
3203 time_t ptime = from_ctime(localtime);
3204 if (ptime == static_cast<time_t>(-1)) {
3205 cerr << "Warning: Could not parse time `" << localtime
3206 << "´ for change tracking, using current time instead.\n";
3207 ptime = current_time();
3209 if (t.cs() == "lyxadded")
3210 os << "\n\\change_inserted ";
3212 os << "\n\\change_deleted ";
3213 os << author.bufferId() << ' ' << ptime << '\n';
3214 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3215 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3216 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3217 LaTeXPackages::isAvailable("xcolor");
3218 // No need to test for luatex, since luatex comes in
3219 // two flavours (dvi and pdf), like latex, and those
3220 // are detected by pdflatex.
3221 if (pdflatex || xetex) {
3223 preamble.registerAutomaticallyLoadedPackage("ulem");
3224 preamble.registerAutomaticallyLoadedPackage("xcolor");
3225 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3229 preamble.registerAutomaticallyLoadedPackage("dvipost");
3230 } else if (xcolorulem) {
3231 preamble.registerAutomaticallyLoadedPackage("ulem");
3232 preamble.registerAutomaticallyLoadedPackage("xcolor");
3237 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3238 t.cs() == "vphantom") {
3239 context.check_layout(os);
3240 if (t.cs() == "phantom")
3241 begin_inset(os, "Phantom Phantom\n");
3242 if (t.cs() == "hphantom")
3243 begin_inset(os, "Phantom HPhantom\n");
3244 if (t.cs() == "vphantom")
3245 begin_inset(os, "Phantom VPhantom\n");
3246 os << "status open\n";
3247 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3252 else if (t.cs() == "href") {
3253 context.check_layout(os);
3254 string target = convert_command_inset_arg(p.verbatim_item());
3255 string name = convert_command_inset_arg(p.verbatim_item());
3257 size_t i = target.find(':');
3258 if (i != string::npos) {
3259 type = target.substr(0, i + 1);
3260 if (type == "mailto:" || type == "file:")
3261 target = target.substr(i + 1);
3262 // handle the case that name is equal to target, except of "http://"
3263 else if (target.substr(i + 3) == name && type == "http:")
3266 begin_command_inset(os, "href", "href");
3268 os << "name \"" << name << "\"\n";
3269 os << "target \"" << target << "\"\n";
3270 if (type == "mailto:" || type == "file:")
3271 os << "type \"" << type << "\"\n";
3273 skip_spaces_braces(p);
3276 else if (t.cs() == "lyxline") {
3277 // swallow size argument (it is not used anyway)
3279 if (!context.atParagraphStart()) {
3280 // so our line is in the middle of a paragraph
3281 // we need to add a new line, lest this line
3282 // follow the other content on that line and
3283 // run off the side of the page
3284 // FIXME: This may create an empty paragraph,
3285 // but without that it would not be
3286 // possible to set noindent below.
3287 // Fortunately LaTeX does not care
3288 // about the empty paragraph.
3289 context.new_paragraph(os);
3291 if (preamble.indentParagraphs()) {
3292 // we need to unindent, lest the line be too long
3293 context.add_par_extra_stuff("\\noindent\n");
3295 context.check_layout(os);
3296 begin_command_inset(os, "line", "rule");
3297 os << "offset \"0.5ex\"\n"
3298 "width \"100line%\"\n"
3303 else if (t.cs() == "rule") {
3304 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3305 string const width = p.getArg('{', '}');
3306 string const thickness = p.getArg('{', '}');
3307 context.check_layout(os);
3308 begin_command_inset(os, "line", "rule");
3309 if (!offset.empty())
3310 os << "offset \"" << translate_len(offset) << "\"\n";
3311 os << "width \"" << translate_len(width) << "\"\n"
3312 "height \"" << translate_len(thickness) << "\"\n";
3316 else if (is_known(t.cs(), known_phrases) ||
3317 (t.cs() == "protect" &&
3318 p.next_token().cat() == catEscape &&
3319 is_known(p.next_token().cs(), known_phrases))) {
3320 // LyX sometimes puts a \protect in front, so we have to ignore it
3321 // FIXME: This needs to be changed when bug 4752 is fixed.
3323 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3325 context.check_layout(os);
3326 os << known_coded_phrases[where - known_phrases];
3327 skip_spaces_braces(p);
3330 else if ((where = is_known(t.cs(), known_ref_commands))) {
3331 string const opt = p.getOpt();
3333 context.check_layout(os);
3334 begin_command_inset(os, "ref",
3335 known_coded_ref_commands[where - known_ref_commands]);
3336 os << "reference \""
3337 << convert_command_inset_arg(p.verbatim_item())
3340 if (t.cs() == "vref" || t.cs() == "vpageref")
3341 preamble.registerAutomaticallyLoadedPackage("varioref");
3344 // LyX does not support optional arguments of ref commands
3345 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3346 p.verbatim_item() + "}", context);
3350 else if (use_natbib &&
3351 is_known(t.cs(), known_natbib_commands) &&
3352 ((t.cs() != "citefullauthor" &&
3353 t.cs() != "citeyear" &&
3354 t.cs() != "citeyearpar") ||
3355 p.next_token().asInput() != "*")) {
3356 context.check_layout(os);
3357 string command = t.cs();
3358 if (p.next_token().asInput() == "*") {
3362 if (command == "citefullauthor")
3363 // alternative name for "\\citeauthor*"
3364 command = "citeauthor*";
3366 // text before the citation
3368 // text after the citation
3370 get_cite_arguments(p, true, before, after);
3372 if (command == "cite") {
3373 // \cite without optional argument means
3374 // \citet, \cite with at least one optional
3375 // argument means \citep.
3376 if (before.empty() && after.empty())
3381 if (before.empty() && after == "[]")
3382 // avoid \citet[]{a}
3384 else if (before == "[]" && after == "[]") {
3385 // avoid \citet[][]{a}
3389 // remove the brackets around after and before
3390 if (!after.empty()) {
3392 after.erase(after.length() - 1, 1);
3393 after = convert_command_inset_arg(after);
3395 if (!before.empty()) {
3397 before.erase(before.length() - 1, 1);
3398 before = convert_command_inset_arg(before);
3400 begin_command_inset(os, "citation", command);
3401 os << "after " << '"' << after << '"' << "\n";
3402 os << "before " << '"' << before << '"' << "\n";
3404 << convert_command_inset_arg(p.verbatim_item())
3407 // Need to set the cite engine if natbib is loaded by
3408 // the document class directly
3409 if (preamble.citeEngine() == "basic")
3410 preamble.citeEngine("natbib");
3413 else if (use_jurabib &&
3414 is_known(t.cs(), known_jurabib_commands) &&
3415 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3416 context.check_layout(os);
3417 string command = t.cs();
3418 if (p.next_token().asInput() == "*") {
3422 char argumentOrder = '\0';
3423 vector<string> const options =
3424 preamble.getPackageOptions("jurabib");
3425 if (find(options.begin(), options.end(),
3426 "natbiborder") != options.end())
3427 argumentOrder = 'n';
3428 else if (find(options.begin(), options.end(),
3429 "jurabiborder") != options.end())
3430 argumentOrder = 'j';
3432 // text before the citation
3434 // text after the citation
3436 get_cite_arguments(p, argumentOrder != 'j', before, after);
3438 string const citation = p.verbatim_item();
3439 if (!before.empty() && argumentOrder == '\0') {
3440 cerr << "Warning: Assuming argument order "
3441 "of jurabib version 0.6 for\n'"
3442 << command << before << after << '{'
3443 << citation << "}'.\n"
3444 "Add 'jurabiborder' to the jurabib "
3445 "package options if you used an\n"
3446 "earlier jurabib version." << endl;
3448 if (!after.empty()) {
3450 after.erase(after.length() - 1, 1);
3452 if (!before.empty()) {
3454 before.erase(before.length() - 1, 1);
3456 begin_command_inset(os, "citation", command);
3457 os << "after " << '"' << after << '"' << "\n";
3458 os << "before " << '"' << before << '"' << "\n";
3459 os << "key " << '"' << citation << '"' << "\n";
3461 // Need to set the cite engine if jurabib is loaded by
3462 // the document class directly
3463 if (preamble.citeEngine() == "basic")
3464 preamble.citeEngine("jurabib");
3467 else if (t.cs() == "cite"
3468 || t.cs() == "nocite") {
3469 context.check_layout(os);
3470 string after = convert_command_inset_arg(p.getArg('[', ']'));
3471 string key = convert_command_inset_arg(p.verbatim_item());
3472 // store the case that it is "\nocite{*}" to use it later for
3475 begin_command_inset(os, "citation", t.cs());
3476 os << "after " << '"' << after << '"' << "\n";
3477 os << "key " << '"' << key << '"' << "\n";
3479 } else if (t.cs() == "nocite")
3483 else if (t.cs() == "index" ||
3484 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3485 context.check_layout(os);
3486 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3487 p.getArg('[', ']') : "";
3488 string const kind = arg.empty() ? "idx" : arg;
3489 begin_inset(os, "Index ");
3490 os << kind << "\nstatus collapsed\n";
3491 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3494 preamble.registerAutomaticallyLoadedPackage("splitidx");
3497 else if (t.cs() == "nomenclature") {
3498 context.check_layout(os);
3499 begin_command_inset(os, "nomenclature", "nomenclature");
3500 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3501 if (!prefix.empty())
3502 os << "prefix " << '"' << prefix << '"' << "\n";
3503 os << "symbol " << '"'
3504 << convert_command_inset_arg(p.verbatim_item());
3505 os << "\"\ndescription \""
3506 << convert_command_inset_arg(p.verbatim_item())
3509 preamble.registerAutomaticallyLoadedPackage("nomencl");
3512 else if (t.cs() == "label") {
3513 context.check_layout(os);
3514 begin_command_inset(os, "label", "label");
3516 << convert_command_inset_arg(p.verbatim_item())
3521 else if (t.cs() == "printindex") {
3522 context.check_layout(os);
3523 begin_command_inset(os, "index_print", "printindex");
3524 os << "type \"idx\"\n";
3526 skip_spaces_braces(p);
3527 preamble.registerAutomaticallyLoadedPackage("makeidx");
3528 if (preamble.use_indices() == "true")
3529 preamble.registerAutomaticallyLoadedPackage("splitidx");
3532 else if (t.cs() == "printnomenclature") {
3534 string width_type = "";
3535 context.check_layout(os);
3536 begin_command_inset(os, "nomencl_print", "printnomenclature");
3537 // case of a custom width
3539 width = p.getArg('[', ']');
3540 width = translate_len(width);
3541 width_type = "custom";
3543 // case of no custom width
3544 // the case of no custom width but the width set
3545 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3546 // because the user could have set anything, not only the width
3547 // of the longest label (which would be width_type = "auto")
3548 string label = convert_command_inset_arg(p.getArg('{', '}'));
3549 if (label.empty() && width_type.empty())
3550 width_type = "none";
3551 os << "set_width \"" << width_type << "\"\n";
3552 if (width_type == "custom")
3553 os << "width \"" << width << '\"';
3555 skip_spaces_braces(p);
3556 preamble.registerAutomaticallyLoadedPackage("nomencl");
3559 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3560 context.check_layout(os);
3561 begin_inset(os, "script ");
3562 os << t.cs().substr(4) << '\n';
3563 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3565 if (t.cs() == "textsubscript")
3566 preamble.registerAutomaticallyLoadedPackage("subscript");
3569 else if ((where = is_known(t.cs(), known_quotes))) {
3570 context.check_layout(os);
3571 begin_inset(os, "Quotes ");
3572 os << known_coded_quotes[where - known_quotes];
3574 // LyX adds {} after the quote, so we have to eat
3575 // spaces here if there are any before a possible
3577 eat_whitespace(p, os, context, false);
3581 else if ((where = is_known(t.cs(), known_sizes)) &&
3582 context.new_layout_allowed) {
3583 context.check_layout(os);
3584 TeXFont const oldFont = context.font;
3585 context.font.size = known_coded_sizes[where - known_sizes];
3586 output_font_change(os, oldFont, context.font);
3587 eat_whitespace(p, os, context, false);
3590 else if ((where = is_known(t.cs(), known_font_families)) &&
3591 context.new_layout_allowed) {
3592 context.check_layout(os);
3593 TeXFont const oldFont = context.font;
3594 context.font.family =
3595 known_coded_font_families[where - known_font_families];
3596 output_font_change(os, oldFont, context.font);
3597 eat_whitespace(p, os, context, false);
3600 else if ((where = is_known(t.cs(), known_font_series)) &&
3601 context.new_layout_allowed) {
3602 context.check_layout(os);
3603 TeXFont const oldFont = context.font;
3604 context.font.series =
3605 known_coded_font_series[where - known_font_series];
3606 output_font_change(os, oldFont, context.font);
3607 eat_whitespace(p, os, context, false);
3610 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3611 context.new_layout_allowed) {
3612 context.check_layout(os);
3613 TeXFont const oldFont = context.font;
3614 context.font.shape =
3615 known_coded_font_shapes[where - known_font_shapes];
3616 output_font_change(os, oldFont, context.font);
3617 eat_whitespace(p, os, context, false);
3619 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3620 context.new_layout_allowed) {
3621 context.check_layout(os);
3622 TeXFont const oldFont = context.font;
3623 context.font.init();
3624 context.font.size = oldFont.size;
3625 context.font.family =
3626 known_coded_font_families[where - known_old_font_families];
3627 output_font_change(os, oldFont, context.font);
3628 eat_whitespace(p, os, context, false);
3631 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3632 context.new_layout_allowed) {
3633 context.check_layout(os);
3634 TeXFont const oldFont = context.font;
3635 context.font.init();
3636 context.font.size = oldFont.size;
3637 context.font.series =
3638 known_coded_font_series[where - known_old_font_series];
3639 output_font_change(os, oldFont, context.font);
3640 eat_whitespace(p, os, context, false);
3643 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3644 context.new_layout_allowed) {
3645 context.check_layout(os);
3646 TeXFont const oldFont = context.font;
3647 context.font.init();
3648 context.font.size = oldFont.size;
3649 context.font.shape =
3650 known_coded_font_shapes[where - known_old_font_shapes];
3651 output_font_change(os, oldFont, context.font);
3652 eat_whitespace(p, os, context, false);
3655 else if (t.cs() == "selectlanguage") {
3656 context.check_layout(os);
3657 // save the language for the case that a
3658 // \foreignlanguage is used
3659 context.font.language = babel2lyx(p.verbatim_item());
3660 os << "\n\\lang " << context.font.language << "\n";
3663 else if (t.cs() == "foreignlanguage") {
3664 string const lang = babel2lyx(p.verbatim_item());
3665 parse_text_attributes(p, os, FLAG_ITEM, outer,
3667 context.font.language, lang);
3670 else if (prefixIs(t.cs(), "text")
3671 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3672 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3674 // We have to output the whole command if it has an option
3675 // because LyX doesn't support this yet, see bug #8214,
3676 // only if there is a single option specifying a variant, we can handle it.
3678 string langopts = p.getOpt();
3679 // check if the option contains a variant, if yes, extract it
3680 string::size_type pos_var = langopts.find("variant");
3681 string::size_type i = langopts.find(',');
3682 string::size_type k = langopts.find('=', pos_var);
3683 if (pos_var != string::npos && i == string::npos) {
3685 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3686 lang = preamble.polyglossia2lyx(variant);
3687 parse_text_attributes(p, os, FLAG_ITEM, outer,
3689 context.font.language, lang);
3691 handle_ert(os, t.asInput() + langopts, context);
3693 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3694 parse_text_attributes(p, os, FLAG_ITEM, outer,
3696 context.font.language, lang);
3700 else if (t.cs() == "inputencoding") {
3701 // nothing to write here
3702 string const enc = subst(p.verbatim_item(), "\n", " ");
3706 else if ((where = is_known(t.cs(), known_special_chars))) {
3707 context.check_layout(os);
3708 os << "\\SpecialChar \\"
3709 << known_coded_special_chars[where - known_special_chars]
3711 skip_spaces_braces(p);
3714 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3715 context.check_layout(os);
3716 os << "\\SpecialChar \\nobreakdash-\n";
3720 else if (t.cs() == "textquotedbl") {
3721 context.check_layout(os);
3726 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3727 context.check_layout(os);
3728 os << "\\SpecialChar \\@.\n";
3732 else if (t.cs() == "-") {
3733 context.check_layout(os);
3734 os << "\\SpecialChar \\-\n";
3737 else if (t.cs() == "textasciitilde") {
3738 context.check_layout(os);
3740 skip_spaces_braces(p);
3743 else if (t.cs() == "textasciicircum") {
3744 context.check_layout(os);
3746 skip_spaces_braces(p);
3749 else if (t.cs() == "textbackslash") {
3750 context.check_layout(os);
3751 os << "\n\\backslash\n";
3752 skip_spaces_braces(p);
3755 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3756 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3758 context.check_layout(os);
3762 else if (t.cs() == "char") {
3763 context.check_layout(os);
3764 if (p.next_token().character() == '`') {
3766 if (p.next_token().cs() == "\"") {
3771 handle_ert(os, "\\char`", context);
3774 handle_ert(os, "\\char", context);
3778 else if (t.cs() == "verb") {
3779 context.check_layout(os);
3780 char const delimiter = p.next_token().character();
3781 // \verb is special: The usual escaping rules do not
3782 // apply, e.g. "\verb+\+" is valid and denotes a single
3783 // backslash (bug #4468). Therefore we do not allow
3784 // escaping in getArg().
3785 string const arg = p.getArg(delimiter, delimiter, false);
3787 oss << "\\verb" << delimiter << arg << delimiter;
3788 handle_ert(os, oss.str(), context);
3791 // Problem: \= creates a tabstop inside the tabbing environment
3792 // and else an accent. In the latter case we really would want
3793 // \={o} instead of \= o.
3794 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3795 handle_ert(os, t.asInput(), context);
3797 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3798 else if (t.cs().size() == 1
3799 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3800 context.check_layout(os);
3801 // try to see whether the string is in unicodesymbols
3804 string command = t.asInput() + "{"
3805 + trimSpaceAndEol(p.verbatim_item())
3808 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3809 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3810 termination, rem, &req);
3813 cerr << "When parsing " << command
3814 << ", result is " << to_utf8(s)
3815 << "+" << to_utf8(rem) << endl;
3817 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3818 preamble.registerAutomaticallyLoadedPackage(*it);
3820 // we did not find a non-ert version
3821 handle_ert(os, command, context);
3824 else if (t.cs() == "\\") {
3825 context.check_layout(os);
3827 handle_ert(os, "\\\\" + p.getOpt(), context);
3828 else if (p.next_token().asInput() == "*") {
3830 // getOpt() eats the following space if there
3831 // is no optional argument, but that is OK
3832 // here since it has no effect in the output.
3833 handle_ert(os, "\\\\*" + p.getOpt(), context);
3836 begin_inset(os, "Newline newline");
3841 else if (t.cs() == "newline" ||
3842 (t.cs() == "linebreak" && !p.hasOpt())) {
3843 context.check_layout(os);
3844 begin_inset(os, "Newline ");
3847 skip_spaces_braces(p);
3850 else if (t.cs() == "input" || t.cs() == "include"
3851 || t.cs() == "verbatiminput") {
3852 string name = t.cs();
3853 if (t.cs() == "verbatiminput"
3854 && p.next_token().asInput() == "*")
3855 name += p.get_token().asInput();
3856 context.check_layout(os);
3857 string filename(normalize_filename(p.getArg('{', '}')));
3858 string const path = getMasterFilePath(true);
3859 // We want to preserve relative / absolute filenames,
3860 // therefore path is only used for testing
3861 if ((t.cs() == "include" || t.cs() == "input") &&
3862 !makeAbsPath(filename, path).exists()) {
3863 // The file extension is probably missing.
3864 // Now try to find it out.
3865 string const tex_name =
3866 find_file(filename, path,
3867 known_tex_extensions);
3868 if (!tex_name.empty())
3869 filename = tex_name;
3871 bool external = false;
3873 if (makeAbsPath(filename, path).exists()) {
3874 string const abstexname =
3875 makeAbsPath(filename, path).absFileName();
3876 string const absfigname =
3877 changeExtension(abstexname, ".fig");
3878 fix_child_filename(filename);
3879 string const lyxname =
3880 changeExtension(filename, ".lyx");
3881 string const abslyxname = makeAbsPath(
3882 lyxname, getParentFilePath(false)).absFileName();
3884 if (!skipChildren())
3885 external = FileName(absfigname).exists();
3886 if (t.cs() == "input" && !skipChildren()) {
3887 string const ext = getExtension(abstexname);
3889 // Combined PS/LaTeX:
3890 // x.eps, x.pstex_t (old xfig)
3891 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3892 FileName const absepsname(
3893 changeExtension(abstexname, ".eps"));
3894 FileName const abspstexname(
3895 changeExtension(abstexname, ".pstex"));
3896 bool const xfigeps =
3897 (absepsname.exists() ||
3898 abspstexname.exists()) &&
3901 // Combined PDF/LaTeX:
3902 // x.pdf, x.pdftex_t (old xfig)
3903 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3904 FileName const abspdfname(
3905 changeExtension(abstexname, ".pdf"));
3906 bool const xfigpdf =
3907 abspdfname.exists() &&
3908 (ext == "pdftex_t" || ext == "pdf_t");
3912 // Combined PS/PDF/LaTeX:
3913 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3914 string const absbase2(
3915 removeExtension(abstexname) + "_pspdftex");
3916 FileName const abseps2name(
3917 addExtension(absbase2, ".eps"));
3918 FileName const abspdf2name(
3919 addExtension(absbase2, ".pdf"));
3920 bool const xfigboth =
3921 abspdf2name.exists() &&
3922 abseps2name.exists() && ext == "pspdftex";
3924 xfig = xfigpdf || xfigeps || xfigboth;
3925 external = external && xfig;
3928 outname = changeExtension(filename, ".fig");
3929 FileName abssrc(changeExtension(abstexname, ".fig"));
3930 copy_file(abssrc, outname);
3932 // Don't try to convert, the result
3933 // would be full of ERT.
3935 FileName abssrc(abstexname);
3936 copy_file(abssrc, outname);
3937 } else if (t.cs() != "verbatiminput" &&
3939 tex2lyx(abstexname, FileName(abslyxname),
3942 // no need to call copy_file
3943 // tex2lyx creates the file
3946 FileName abssrc(abstexname);
3947 copy_file(abssrc, outname);
3950 cerr << "Warning: Could not find included file '"
3951 << filename << "'." << endl;
3955 begin_inset(os, "External\n");
3956 os << "\ttemplate XFig\n"
3957 << "\tfilename " << outname << '\n';
3958 registerExternalTemplatePackages("XFig");
3960 begin_command_inset(os, "include", name);
3961 outname = subst(outname, "\"", "\\\"");
3962 os << "preview false\n"
3963 "filename \"" << outname << "\"\n";
3964 if (t.cs() == "verbatiminput")
3965 preamble.registerAutomaticallyLoadedPackage("verbatim");
3970 else if (t.cs() == "bibliographystyle") {
3971 // store new bibliographystyle
3972 bibliographystyle = p.verbatim_item();
3973 // If any other command than \bibliography and
3974 // \nocite{*} follows, we need to output the style
3975 // (because it might be used by that command).
3976 // Otherwise, it will automatically be output by LyX.
3979 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3980 if (t2.cat() == catBegin)
3982 if (t2.cat() != catEscape)
3984 if (t2.cs() == "nocite") {
3985 if (p.getArg('{', '}') == "*")
3987 } else if (t2.cs() == "bibliography")
3994 "\\bibliographystyle{" + bibliographystyle + '}',
3999 else if (t.cs() == "bibliography") {
4000 context.check_layout(os);
4001 begin_command_inset(os, "bibtex", "bibtex");
4002 if (!btprint.empty()) {
4003 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4004 // clear the string because the next BibTeX inset can be without the
4005 // \nocite{*} option
4008 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4009 // Do we have a bibliographystyle set?
4010 if (!bibliographystyle.empty())
4011 os << "options " << '"' << bibliographystyle << '"' << "\n";
4015 else if (t.cs() == "parbox") {
4016 // Test whether this is an outer box of a shaded box
4018 // swallow arguments
4019 while (p.hasOpt()) {
4021 p.skip_spaces(true);
4024 p.skip_spaces(true);
4026 if (p.next_token().cat() == catBegin)
4028 p.skip_spaces(true);
4029 Token to = p.get_token();
4030 bool shaded = false;
4031 if (to.asInput() == "\\begin") {
4032 p.skip_spaces(true);
4033 if (p.getArg('{', '}') == "shaded")
4038 parse_outer_box(p, os, FLAG_ITEM, outer,
4039 context, "parbox", "shaded");
4041 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4045 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4046 t.cs() == "shadowbox" || t.cs() == "doublebox")
4047 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4049 else if (t.cs() == "framebox") {
4050 if (p.next_token().character() == '(') {
4051 //the syntax is: \framebox(x,y)[position]{content}
4052 string arg = t.asInput();
4053 arg += p.getFullParentheseArg();
4054 arg += p.getFullOpt();
4055 eat_whitespace(p, os, context, false);
4056 handle_ert(os, arg + '{', context);
4057 parse_text(p, os, FLAG_ITEM, outer, context);
4058 handle_ert(os, "}", context);
4060 string special = p.getFullOpt();
4061 special += p.getOpt();
4062 // LyX does not yet support \framebox without any option
4063 if (!special.empty())
4064 parse_outer_box(p, os, FLAG_ITEM, outer,
4065 context, t.cs(), special);
4067 eat_whitespace(p, os, context, false);
4068 handle_ert(os, "\\framebox{", context);
4069 parse_text(p, os, FLAG_ITEM, outer, context);
4070 handle_ert(os, "}", context);
4075 //\makebox() is part of the picture environment and different from \makebox{}
4076 //\makebox{} will be parsed by parse_box
4077 else if (t.cs() == "makebox") {
4078 if (p.next_token().character() == '(') {
4079 //the syntax is: \makebox(x,y)[position]{content}
4080 string arg = t.asInput();
4081 arg += p.getFullParentheseArg();
4082 arg += p.getFullOpt();
4083 eat_whitespace(p, os, context, false);
4084 handle_ert(os, arg + '{', context);
4085 parse_text(p, os, FLAG_ITEM, outer, context);
4086 handle_ert(os, "}", context);
4088 //the syntax is: \makebox[width][position]{content}
4089 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4093 else if (t.cs() == "smallskip" ||
4094 t.cs() == "medskip" ||
4095 t.cs() == "bigskip" ||
4096 t.cs() == "vfill") {
4097 context.check_layout(os);
4098 begin_inset(os, "VSpace ");
4101 skip_spaces_braces(p);
4104 else if ((where = is_known(t.cs(), known_spaces))) {
4105 context.check_layout(os);
4106 begin_inset(os, "space ");
4107 os << '\\' << known_coded_spaces[where - known_spaces]
4110 // LaTeX swallows whitespace after all spaces except
4111 // "\\,". We have to do that here, too, because LyX
4112 // adds "{}" which would make the spaces significant.
4114 eat_whitespace(p, os, context, false);
4115 // LyX adds "{}" after all spaces except "\\ " and
4116 // "\\,", so we have to remove "{}".
4117 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4118 // remove the braces after "\\,", too.
4123 else if (t.cs() == "newpage" ||
4124 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4125 t.cs() == "clearpage" ||
4126 t.cs() == "cleardoublepage") {
4127 context.check_layout(os);
4128 begin_inset(os, "Newpage ");
4131 skip_spaces_braces(p);
4134 else if (t.cs() == "DeclareRobustCommand" ||
4135 t.cs() == "DeclareRobustCommandx" ||
4136 t.cs() == "newcommand" ||
4137 t.cs() == "newcommandx" ||
4138 t.cs() == "providecommand" ||
4139 t.cs() == "providecommandx" ||
4140 t.cs() == "renewcommand" ||
4141 t.cs() == "renewcommandx") {
4142 // DeclareRobustCommand, DeclareRobustCommandx,
4143 // providecommand and providecommandx could be handled
4144 // by parse_command(), but we need to call
4145 // add_known_command() here.
4146 string name = t.asInput();
4147 if (p.next_token().asInput() == "*") {
4148 // Starred form. Eat '*'
4152 string const command = p.verbatim_item();
4153 string const opt1 = p.getFullOpt();
4154 string const opt2 = p.getFullOpt();
4155 add_known_command(command, opt1, !opt2.empty());
4156 string const ert = name + '{' + command + '}' +
4158 '{' + p.verbatim_item() + '}';
4160 if (t.cs() == "DeclareRobustCommand" ||
4161 t.cs() == "DeclareRobustCommandx" ||
4162 t.cs() == "providecommand" ||
4163 t.cs() == "providecommandx" ||
4164 name[name.length()-1] == '*')
4165 handle_ert(os, ert, context);
4167 context.check_layout(os);
4168 begin_inset(os, "FormulaMacro");
4174 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4175 // let could be handled by parse_command(),
4176 // but we need to call add_known_command() here.
4177 string ert = t.asInput();
4180 if (p.next_token().cat() == catBegin) {
4181 name = p.verbatim_item();
4182 ert += '{' + name + '}';
4184 name = p.verbatim_item();
4189 if (p.next_token().cat() == catBegin) {
4190 command = p.verbatim_item();
4191 ert += '{' + command + '}';
4193 command = p.verbatim_item();
4196 // If command is known, make name known too, to parse
4197 // its arguments correctly. For this reason we also
4198 // have commands in syntax.default that are hardcoded.
4199 CommandMap::iterator it = known_commands.find(command);
4200 if (it != known_commands.end())
4201 known_commands[t.asInput()] = it->second;
4202 handle_ert(os, ert, context);
4205 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4206 bool starred = false;
4207 if (p.next_token().asInput() == "*") {
4211 string name = t.asInput();
4212 string const length = p.verbatim_item();
4215 bool valid = splitLatexLength(length, valstring, unit);
4216 bool known_hspace = false;
4217 bool known_vspace = false;
4218 bool known_unit = false;
4221 istringstream iss(valstring);
4224 if (t.cs()[0] == 'h') {
4225 if (unit == "\\fill") {
4230 known_hspace = true;
4233 if (unit == "\\smallskipamount") {
4235 known_vspace = true;
4236 } else if (unit == "\\medskipamount") {
4238 known_vspace = true;
4239 } else if (unit == "\\bigskipamount") {
4241 known_vspace = true;
4242 } else if (unit == "\\fill") {
4244 known_vspace = true;
4248 if (!known_hspace && !known_vspace) {
4249 switch (unitFromString(unit)) {
4270 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4271 // Literal horizontal length or known variable
4272 context.check_layout(os);
4273 begin_inset(os, "space ");
4281 if (known_unit && !known_hspace)
4283 << translate_len(length);
4285 } else if (known_unit || known_vspace) {
4286 // Literal vertical length or known variable
4287 context.check_layout(os);
4288 begin_inset(os, "VSpace ");
4296 // LyX can't handle other length variables in Inset VSpace/space
4301 handle_ert(os, name + '{' + unit + '}', context);
4302 else if (value == -1.0)
4303 handle_ert(os, name + "{-" + unit + '}', context);
4305 handle_ert(os, name + '{' + valstring + unit + '}', context);
4307 handle_ert(os, name + '{' + length + '}', context);
4311 // The single '=' is meant here.
4312 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4314 context.check_layout(os);
4315 begin_inset(os, "Flex ");
4316 os << to_utf8(newinsetlayout->name()) << '\n'
4317 << "status collapsed\n";
4318 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4322 else if (t.cs() == "includepdf") {
4324 string const arg = p.getArg('[', ']');
4325 map<string, string> opts;
4326 vector<string> keys;
4327 split_map(arg, opts, keys);
4328 string name = normalize_filename(p.verbatim_item());
4329 string const path = getMasterFilePath(true);
4330 // We want to preserve relative / absolute filenames,
4331 // therefore path is only used for testing
4332 if (!makeAbsPath(name, path).exists()) {
4333 // The file extension is probably missing.
4334 // Now try to find it out.
4335 char const * const pdfpages_format[] = {"pdf", 0};
4336 string const pdftex_name =
4337 find_file(name, path, pdfpages_format);
4338 if (!pdftex_name.empty()) {
4343 FileName const absname = makeAbsPath(name, path);
4344 if (absname.exists())
4346 fix_child_filename(name);
4347 copy_file(absname, name);
4349 cerr << "Warning: Could not find file '"
4350 << name << "'." << endl;
4352 context.check_layout(os);
4353 begin_inset(os, "External\n\ttemplate ");
4354 os << "PDFPages\n\tfilename "
4356 // parse the options
4357 if (opts.find("pages") != opts.end())
4358 os << "\textra LaTeX \"pages="
4359 << opts["pages"] << "\"\n";
4360 if (opts.find("angle") != opts.end())
4361 os << "\trotateAngle "
4362 << opts["angle"] << '\n';
4363 if (opts.find("origin") != opts.end()) {
4365 string const opt = opts["origin"];
4366 if (opt == "tl") ss << "topleft";
4367 if (opt == "bl") ss << "bottomleft";
4368 if (opt == "Bl") ss << "baselineleft";
4369 if (opt == "c") ss << "center";
4370 if (opt == "tc") ss << "topcenter";
4371 if (opt == "bc") ss << "bottomcenter";
4372 if (opt == "Bc") ss << "baselinecenter";
4373 if (opt == "tr") ss << "topright";
4374 if (opt == "br") ss << "bottomright";
4375 if (opt == "Br") ss << "baselineright";
4376 if (!ss.str().empty())
4377 os << "\trotateOrigin " << ss.str() << '\n';
4379 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4381 if (opts.find("width") != opts.end())
4383 << translate_len(opts["width"]) << '\n';
4384 if (opts.find("height") != opts.end())
4386 << translate_len(opts["height"]) << '\n';
4387 if (opts.find("keepaspectratio") != opts.end())
4388 os << "\tkeepAspectRatio\n";
4390 context.check_layout(os);
4391 registerExternalTemplatePackages("PDFPages");
4394 else if (t.cs() == "loadgame") {
4396 string name = normalize_filename(p.verbatim_item());
4397 string const path = getMasterFilePath(true);
4398 // We want to preserve relative / absolute filenames,
4399 // therefore path is only used for testing
4400 if (!makeAbsPath(name, path).exists()) {
4401 // The file extension is probably missing.
4402 // Now try to find it out.
4403 char const * const lyxskak_format[] = {"fen", 0};
4404 string const lyxskak_name =
4405 find_file(name, path, lyxskak_format);
4406 if (!lyxskak_name.empty())
4407 name = lyxskak_name;
4409 FileName const absname = makeAbsPath(name, path);
4410 if (absname.exists())
4412 fix_child_filename(name);
4413 copy_file(absname, name);
4415 cerr << "Warning: Could not find file '"
4416 << name << "'." << endl;
4417 context.check_layout(os);
4418 begin_inset(os, "External\n\ttemplate ");
4419 os << "ChessDiagram\n\tfilename "
4422 context.check_layout(os);
4423 // after a \loadgame follows a \showboard
4424 if (p.get_token().asInput() == "showboard")
4426 registerExternalTemplatePackages("ChessDiagram");
4430 // try to see whether the string is in unicodesymbols
4431 // Only use text mode commands, since we are in text mode here,
4432 // and math commands may be invalid (bug 6797)
4436 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4437 Encodings::TEXT_CMD, termination, rem, &req);
4440 cerr << "When parsing " << t.cs()
4441 << ", result is " << to_utf8(s)
4442 << "+" << to_utf8(rem) << endl;
4443 context.check_layout(os);
4446 skip_spaces_braces(p);
4447 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4448 preamble.registerAutomaticallyLoadedPackage(*it);
4450 //cerr << "#: " << t << " mode: " << mode << endl;
4451 // heuristic: read up to next non-nested space
4453 string s = t.asInput();
4454 string z = p.verbatim_item();
4455 while (p.good() && z != " " && !z.empty()) {
4456 //cerr << "read: " << z << endl;
4458 z = p.verbatim_item();
4460 cerr << "found ERT: " << s << endl;
4461 handle_ert(os, s + ' ', context);
4464 string name = t.asInput();
4465 if (p.next_token().asInput() == "*") {
4466 // Starred commands like \vspace*{}
4467 p.get_token(); // Eat '*'
4470 if (!parse_command(name, p, os, outer, context))
4471 handle_ert(os, name, context);
4475 if (flags & FLAG_LEAVE) {
4476 flags &= ~FLAG_LEAVE;
4483 string guessLanguage(Parser & p, string const & lang)
4485 typedef std::map<std::string, size_t> LangMap;
4486 // map from language names to number of characters
4489 for (char const * const * i = supported_CJK_languages; *i; i++)
4490 used[string(*i)] = 0;
4493 Token const t = p.get_token();
4494 // comments are not counted for any language
4495 if (t.cat() == catComment)
4497 // commands are not counted as well, but we need to detect
4498 // \begin{CJK} and switch encoding if needed
4499 if (t.cat() == catEscape) {
4500 if (t.cs() == "inputencoding") {
4501 string const enc = subst(p.verbatim_item(), "\n", " ");
4505 if (t.cs() != "begin")
4508 // Non-CJK content is counted for lang.
4509 // We do not care about the real language here:
4510 // If we have more non-CJK contents than CJK contents,
4511 // we simply use the language that was specified as
4512 // babel main language.
4513 used[lang] += t.asInput().length();
4516 // Now we are starting an environment
4518 string const name = p.getArg('{', '}');
4519 if (name != "CJK") {
4523 // It is a CJK environment
4525 /* name = */ p.getArg('{', '}');
4526 string const encoding = p.getArg('{', '}');
4527 /* mapping = */ p.getArg('{', '}');
4528 string const encoding_old = p.getEncoding();
4529 char const * const * const where =
4530 is_known(encoding, supported_CJK_encodings);
4532 p.setEncoding(encoding);
4534 p.setEncoding("utf8");
4535 string const text = p.verbatimEnvironment("CJK");
4536 p.setEncoding(encoding_old);
4539 // ignore contents in unknown CJK encoding
4542 // the language of the text
4544 supported_CJK_languages[where - supported_CJK_encodings];
4545 used[cjk] += text.length();
4547 LangMap::const_iterator use = used.begin();
4548 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4549 if (it->second > use->second)