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 * JIS does not work with LyX's encoding conversion
124 const char * const supported_CJK_encodings[] = {
125 "EUC-JP", "KS", "GB", "UTF8",
126 "Bg5", /*"JIS",*/ "SJIS", 0};
129 * the same as supported_CJK_encodings with their corresponding LyX language name
130 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
132 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
133 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
134 * please keep this in sync with supported_CJK_encodings line by line!
136 const char * const supported_CJK_languages[] = {
137 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
138 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
142 * The starred forms are also known except for "citefullauthor",
143 * "citeyear" and "citeyearpar".
145 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
146 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
147 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
151 * No starred form other than "cite*" known.
153 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
154 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
155 // jurabib commands not (yet) supported by LyX:
157 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
158 // "footciteauthor", "footciteyear", "footciteyearpar",
159 "citefield", "citetitle", 0 };
161 /// LaTeX names for quotes
162 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
163 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
164 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
165 "guilsinglleft", "frq", "guilsinglright", 0};
167 /// the same as known_quotes with .lyx names
168 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
169 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
170 "gld", "grd", "gls", "ers", "fls",
171 "fls", "frs", "frs", 0};
173 /// LaTeX names for font sizes
174 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
175 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
177 /// the same as known_sizes with .lyx names
178 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
179 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
181 /// LaTeX 2.09 names for font families
182 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
184 /// LaTeX names for font families
185 char const * const known_font_families[] = { "rmfamily", "sffamily",
188 /// LaTeX names for font family changing commands
189 char const * const known_text_font_families[] = { "textrm", "textsf",
192 /// The same as known_old_font_families, known_font_families and
193 /// known_text_font_families with .lyx names
194 char const * const known_coded_font_families[] = { "roman", "sans",
197 /// LaTeX 2.09 names for font series
198 char const * const known_old_font_series[] = { "bf", 0};
200 /// LaTeX names for font series
201 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
203 /// LaTeX names for font series changing commands
204 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
206 /// The same as known_old_font_series, known_font_series and
207 /// known_text_font_series with .lyx names
208 char const * const known_coded_font_series[] = { "bold", "medium", 0};
210 /// LaTeX 2.09 names for font shapes
211 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
213 /// LaTeX names for font shapes
214 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
217 /// LaTeX names for font shape changing commands
218 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
221 /// The same as known_old_font_shapes, known_font_shapes and
222 /// known_text_font_shapes with .lyx names
223 char const * const known_coded_font_shapes[] = { "italic", "slanted",
224 "smallcaps", "up", 0};
226 /// Known special characters which need skip_spaces_braces() afterwards
227 char const * const known_special_chars[] = {"ldots", "lyxarrow",
228 "textcompwordmark", "slash", 0};
230 /// the same as known_special_chars with .lyx names
231 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
232 "textcompwordmark{}", "slash{}", 0};
235 * Graphics file extensions known by the dvips driver of the graphics package.
236 * These extensions are used to complete the filename of an included
237 * graphics file if it does not contain an extension.
238 * The order must be the same that latex uses to find a file, because we
239 * will use the first extension that matches.
240 * This is only an approximation for the common cases. If we would want to
241 * do it right in all cases, we would need to know which graphics driver is
242 * used and know the extensions of every driver of the graphics package.
244 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
245 "ps.gz", "eps.Z", "ps.Z", 0};
248 * Graphics file extensions known by the pdftex driver of the graphics package.
249 * \sa known_dvips_graphics_formats
251 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
255 * Known file extensions for TeX files as used by \\include.
257 char const * const known_tex_extensions[] = {"tex", 0};
259 /// spaces known by InsetSpace
260 char const * const known_spaces[] = { " ", "space", ",",
261 "thinspace", "quad", "qquad", "enspace", "enskip",
262 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
263 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
264 "upbracefill", "downbracefill", 0};
266 /// the same as known_spaces with .lyx names
267 char const * const known_coded_spaces[] = { "space{}", "space{}",
268 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
269 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
270 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
271 "upbracefill{}", "downbracefill{}", 0};
273 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
274 /// them in ERT. "LaTeXe" must come before "LaTeX"!
275 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
276 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
277 int const known_phrase_lengths[] = {3, 5, 7, 0};
279 // string to store the float type to be able to determine the type of subfloats
280 string float_type = "";
283 /// splits "x=z, y=b" into a map and an ordered keyword vector
284 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
289 keys.resize(v.size());
290 for (size_t i = 0; i < v.size(); ++i) {
291 size_t const pos = v[i].find('=');
292 string const index = trimSpaceAndEol(v[i].substr(0, pos));
293 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
301 * Split a LaTeX length into value and unit.
302 * The latter can be a real unit like "pt", or a latex length variable
303 * like "\textwidth". The unit may contain additional stuff like glue
304 * lengths, but we don't care, because such lengths are ERT anyway.
305 * \returns true if \p value and \p unit are valid.
307 bool splitLatexLength(string const & len, string & value, string & unit)
311 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
312 //'4,5' is a valid LaTeX length number. Change it to '4.5'
313 string const length = subst(len, ',', '.');
314 if (i == string::npos)
317 if (len[0] == '\\') {
318 // We had something like \textwidth without a factor
324 value = trimSpaceAndEol(string(length, 0, i));
328 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
329 if (contains(len, '\\'))
330 unit = trimSpaceAndEol(string(len, i));
332 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
337 /// A simple function to translate a latex length to something LyX can
338 /// understand. Not perfect, but rather best-effort.
339 bool translate_len(string const & length, string & valstring, string & unit)
341 if (!splitLatexLength(length, valstring, unit))
343 // LyX uses percent values
345 istringstream iss(valstring);
350 string const percentval = oss.str();
352 if (unit.empty() || unit[0] != '\\')
354 string::size_type const i = unit.find(' ');
355 string const endlen = (i == string::npos) ? string() : string(unit, i);
356 if (unit == "\\textwidth") {
357 valstring = percentval;
358 unit = "text%" + endlen;
359 } else if (unit == "\\columnwidth") {
360 valstring = percentval;
361 unit = "col%" + endlen;
362 } else if (unit == "\\paperwidth") {
363 valstring = percentval;
364 unit = "page%" + endlen;
365 } else if (unit == "\\linewidth") {
366 valstring = percentval;
367 unit = "line%" + endlen;
368 } else if (unit == "\\paperheight") {
369 valstring = percentval;
370 unit = "pheight%" + endlen;
371 } else if (unit == "\\textheight") {
372 valstring = percentval;
373 unit = "theight%" + endlen;
381 string translate_len(string const & length)
385 if (translate_len(length, value, unit))
387 // If the input is invalid, return what we have.
395 * Translates a LaTeX length into \p value, \p unit and
396 * \p special parts suitable for a box inset.
397 * The difference from translate_len() is that a box inset knows about
398 * some special "units" that are stored in \p special.
400 void translate_box_len(string const & length, string & value, string & unit, string & special)
402 if (translate_len(length, value, unit)) {
403 if (unit == "\\height" || unit == "\\depth" ||
404 unit == "\\totalheight" || unit == "\\width") {
405 special = unit.substr(1);
406 // The unit is not used, but LyX requires a dummy setting
419 * Find a file with basename \p name in path \p path and an extension
422 string find_file(string const & name, string const & path,
423 char const * const * extensions)
425 for (char const * const * what = extensions; *what; ++what) {
426 string const trial = addExtension(name, *what);
427 if (makeAbsPath(trial, path).exists())
434 void begin_inset(ostream & os, string const & name)
436 os << "\n\\begin_inset " << name;
440 void begin_command_inset(ostream & os, string const & name,
441 string const & latexname)
443 begin_inset(os, "CommandInset ");
444 os << name << "\nLatexCommand " << latexname << '\n';
448 void end_inset(ostream & os)
450 os << "\n\\end_inset\n\n";
454 bool skip_braces(Parser & p)
456 if (p.next_token().cat() != catBegin)
459 if (p.next_token().cat() == catEnd) {
468 /// replace LaTeX commands in \p s from the unicodesymbols file with their
470 docstring convert_unicodesymbols(docstring s)
473 for (size_t i = 0; i < s.size();) {
482 docstring parsed = encodings.fromLaTeXCommand(s,
483 Encodings::TEXT_CMD, termination, rem, &req);
484 set<string>::const_iterator it = req.begin();
485 set<string>::const_iterator en = req.end();
486 for (; it != en; ++it)
487 preamble.registerAutomaticallyLoadedPackage(*it);
490 if (s.empty() || s[0] != '\\')
499 /// try to convert \p s to a valid InsetCommand argument
500 string convert_command_inset_arg(string s)
503 // since we don't know the input encoding we can't use from_utf8
504 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
505 // LyX cannot handle newlines in a latex command
506 return subst(s, "\n", " ");
510 void handle_backslash(ostream & os, string const & s)
512 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
514 os << "\n\\backslash\n";
521 void handle_ert(ostream & os, string const & s, Context & context)
523 // We must have a valid layout before outputting the ERT inset.
524 context.check_layout(os);
525 Context newcontext(true, context.textclass);
526 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
527 if (layout.forcePlainLayout())
528 newcontext.layout = &context.textclass.plainLayout();
529 begin_inset(os, "ERT");
530 os << "\nstatus collapsed\n";
531 newcontext.check_layout(os);
532 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
534 os << "\n\\backslash\n";
535 else if (*it == '\n') {
536 newcontext.new_paragraph(os);
537 newcontext.check_layout(os);
541 newcontext.check_end_layout(os);
546 void handle_comment(ostream & os, string const & s, Context & context)
548 // TODO: Handle this better
549 Context newcontext(true, context.textclass);
550 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
551 if (layout.forcePlainLayout())
552 newcontext.layout = &context.textclass.plainLayout();
553 begin_inset(os, "ERT");
554 os << "\nstatus collapsed\n";
555 newcontext.check_layout(os);
556 handle_backslash(os, s);
557 // make sure that our comment is the last thing on the line
558 newcontext.new_paragraph(os);
559 newcontext.check_layout(os);
560 newcontext.check_end_layout(os);
565 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
567 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
570 if (checkModule(name, command))
571 return findLayoutWithoutModule(textclass, name, command);
576 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
578 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
581 if (checkModule(name, command))
582 return findInsetLayoutWithoutModule(textclass, name, command);
587 void eat_whitespace(Parser &, ostream &, Context &, bool);
591 * Skips whitespace and braces.
592 * This should be called after a command has been parsed that is not put into
593 * ERT, and where LyX adds "{}" if needed.
595 void skip_spaces_braces(Parser & p, bool keepws = false)
597 /* The following four examples produce the same typeset output and
598 should be handled by this function:
606 // Unfortunately we need to skip comments, too.
607 // We can't use eat_whitespace since writing them after the {}
608 // results in different output in some cases.
609 bool const skipped_spaces = p.skip_spaces(true);
610 bool const skipped_braces = skip_braces(p);
611 if (keepws && skipped_spaces && !skipped_braces)
612 // put back the space (it is better handled by check_space)
613 p.unskip_spaces(true);
617 void output_command_layout(ostream & os, Parser & p, bool outer,
618 Context & parent_context,
619 Layout const * newlayout)
621 TeXFont const oldFont = parent_context.font;
622 // save the current font size
623 string const size = oldFont.size;
624 // reset the font size to default, because the font size switches
625 // don't affect section headings and the like
626 parent_context.font.size = Context::normalfont.size;
627 // we only need to write the font change if we have an open layout
628 if (!parent_context.atParagraphStart())
629 output_font_change(os, oldFont, parent_context.font);
630 parent_context.check_end_layout(os);
631 Context context(true, parent_context.textclass, newlayout,
632 parent_context.layout, parent_context.font);
633 if (parent_context.deeper_paragraph) {
634 // We are beginning a nested environment after a
635 // deeper paragraph inside the outer list environment.
636 // Therefore we don't need to output a "begin deeper".
637 context.need_end_deeper = true;
639 context.check_deeper(os);
640 context.check_layout(os);
641 // FIXME: Adjust to format 446!
642 // Since format 446, layouts do not require anymore all optional
643 // arguments before the required ones. Needs to be implemented!
645 while (optargs < context.layout->optArgs()) {
646 eat_whitespace(p, os, context, false);
647 if (p.next_token().cat() == catEscape ||
648 p.next_token().character() != '[')
650 p.get_token(); // eat '['
651 // FIXME: Just a workaround. InsetArgument::updateBuffer
652 // will compute a proper ID for all "999" Arguments
653 // (which is also what lyx2lyx produces).
654 // However, tex2lyx should be able to output proper IDs
656 begin_inset(os, "Argument 999\n");
657 os << "status collapsed\n\n";
658 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
660 eat_whitespace(p, os, context, false);
664 while (reqargs < context.layout->requiredArgs()) {
665 eat_whitespace(p, os, context, false);
666 if (p.next_token().cat() != catBegin)
668 p.get_token(); // eat '{'
669 // FIXME: Just a workaround. InsetArgument::updateBuffer
670 // will compute a proper ID for all "999" Arguments
671 // (which is also what lyx2lyx produces).
672 // However, tex2lyx should be able to output proper IDs
674 begin_inset(os, "Argument 999\n");
675 os << "status collapsed\n\n";
676 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
678 eat_whitespace(p, os, context, false);
681 parse_text(p, os, FLAG_ITEM, outer, context);
682 context.check_end_layout(os);
683 if (parent_context.deeper_paragraph) {
684 // We must suppress the "end deeper" because we
685 // suppressed the "begin deeper" above.
686 context.need_end_deeper = false;
688 context.check_end_deeper(os);
689 // We don't need really a new paragraph, but
690 // we must make sure that the next item gets a \begin_layout.
691 parent_context.new_paragraph(os);
692 // Set the font size to the original value. No need to output it here
693 // (Context::begin_layout() will do that if needed)
694 parent_context.font.size = size;
699 * Output a space if necessary.
700 * This function gets called for every whitespace token.
702 * We have three cases here:
703 * 1. A space must be suppressed. Example: The lyxcode case below
704 * 2. A space may be suppressed. Example: Spaces before "\par"
705 * 3. A space must not be suppressed. Example: A space between two words
707 * We currently handle only 1. and 3 and from 2. only the case of
708 * spaces before newlines as a side effect.
710 * 2. could be used to suppress as many spaces as possible. This has two effects:
711 * - Reimporting LyX generated LaTeX files changes almost no whitespace
712 * - Superflous whitespace from non LyX generated LaTeX files is removed.
713 * The drawback is that the logic inside the function becomes
714 * complicated, and that is the reason why it is not implemented.
716 void check_space(Parser & p, ostream & os, Context & context)
718 Token const next = p.next_token();
719 Token const curr = p.curr_token();
720 // A space before a single newline and vice versa must be ignored
721 // LyX emits a newline before \end{lyxcode}.
722 // This newline must be ignored,
723 // otherwise LyX will add an additional protected space.
724 if (next.cat() == catSpace ||
725 next.cat() == catNewline ||
726 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
729 context.check_layout(os);
735 * Parse all arguments of \p command
737 void parse_arguments(string const & command,
738 vector<ArgumentType> const & template_arguments,
739 Parser & p, ostream & os, bool outer, Context & context)
741 string ert = command;
742 size_t no_arguments = template_arguments.size();
743 for (size_t i = 0; i < no_arguments; ++i) {
744 switch (template_arguments[i]) {
747 // This argument contains regular LaTeX
748 handle_ert(os, ert + '{', context);
749 eat_whitespace(p, os, context, false);
750 if (template_arguments[i] == required)
751 parse_text(p, os, FLAG_ITEM, outer, context);
753 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
757 // This argument consists only of a single item.
758 // The presence of '{' or not must be preserved.
760 if (p.next_token().cat() == catBegin)
761 ert += '{' + p.verbatim_item() + '}';
763 ert += p.verbatim_item();
767 // This argument may contain special characters
768 ert += '{' + p.verbatim_item() + '}';
772 // true because we must not eat whitespace
773 // if an optional arg follows we must not strip the
774 // brackets from this one
775 if (i < no_arguments - 1 &&
776 template_arguments[i+1] == optional)
777 ert += p.getFullOpt(true);
779 ert += p.getOpt(true);
783 handle_ert(os, ert, context);
788 * Check whether \p command is a known command. If yes,
789 * handle the command with all arguments.
790 * \return true if the command was parsed, false otherwise.
792 bool parse_command(string const & command, Parser & p, ostream & os,
793 bool outer, Context & context)
795 if (known_commands.find(command) != known_commands.end()) {
796 parse_arguments(command, known_commands[command], p, os,
804 /// Parses a minipage or parbox
805 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
806 unsigned inner_flags, bool outer, Context & parent_context,
807 string const & outer_type, string const & special,
808 string const & inner_type)
812 string hor_pos = "c";
813 // We need to set the height to the LaTeX default of 1\\totalheight
814 // for the case when no height argument is given
815 string height_value = "1";
816 string height_unit = "in";
817 string height_special = "totalheight";
822 string width_special = "none";
823 if (!inner_type.empty() && p.hasOpt()) {
824 if (inner_type != "makebox")
825 position = p.getArg('[', ']');
827 latex_width = p.getArg('[', ']');
828 translate_box_len(latex_width, width_value, width_unit, width_special);
831 if (position != "t" && position != "c" && position != "b") {
832 cerr << "invalid position " << position << " for "
833 << inner_type << endl;
837 if (inner_type != "makebox") {
838 latex_height = p.getArg('[', ']');
839 translate_box_len(latex_height, height_value, height_unit, height_special);
841 string const opt = p.getArg('[', ']');
844 if (hor_pos != "l" && hor_pos != "c" &&
845 hor_pos != "r" && hor_pos != "s") {
846 cerr << "invalid hor_pos " << hor_pos
847 << " for " << inner_type << endl;
854 inner_pos = p.getArg('[', ']');
855 if (inner_pos != "c" && inner_pos != "t" &&
856 inner_pos != "b" && inner_pos != "s") {
857 cerr << "invalid inner_pos "
858 << inner_pos << " for "
859 << inner_type << endl;
860 inner_pos = position;
865 if (inner_type.empty()) {
866 if (special.empty() && outer_type != "framebox")
867 latex_width = "1\\columnwidth";
870 latex_width = p2.getArg('[', ']');
871 string const opt = p2.getArg('[', ']');
874 if (hor_pos != "l" && hor_pos != "c" &&
875 hor_pos != "r" && hor_pos != "s") {
876 cerr << "invalid hor_pos " << hor_pos
877 << " for " << outer_type << endl;
882 } else if (inner_type != "makebox")
883 latex_width = p.verbatim_item();
884 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
885 // as this is LyX's standard for such cases (except for makebox)
886 // \framebox is more special and handled below
887 if (latex_width.empty() && inner_type != "makebox"
888 && outer_type != "framebox")
889 latex_width = "1\\columnwidth";
891 translate_len(latex_width, width_value, width_unit);
893 bool shadedparbox = false;
894 if (inner_type == "shaded") {
895 eat_whitespace(p, os, parent_context, false);
896 if (outer_type == "parbox") {
898 if (p.next_token().cat() == catBegin)
900 eat_whitespace(p, os, parent_context, false);
906 // If we already read the inner box we have to push the inner env
907 if (!outer_type.empty() && !inner_type.empty() &&
908 (inner_flags & FLAG_END))
909 active_environments.push_back(inner_type);
910 // LyX can't handle length variables
911 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
912 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
913 // Look whether there is some content after the end of the
914 // inner box, but before the end of the outer box.
915 // If yes, we need to output ERT.
917 if (inner_flags & FLAG_END)
918 p.verbatimEnvironment(inner_type);
922 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
923 if ((outer_env && p.next_token().asInput() != "\\end") ||
924 (!outer_env && p.next_token().cat() != catEnd)) {
925 // something is between the end of the inner box and
926 // the end of the outer box, so we need to use ERT.
931 // if only \makebox{content} was used we can set its width to 1\width
932 // because this identic and also identic to \mbox
933 // this doesn't work for \framebox{content}, thus we have to use ERT for this
934 if (latex_width.empty() && inner_type == "makebox") {
937 width_special = "width";
938 } else if (latex_width.empty() && outer_type == "framebox") {
943 if (!outer_type.empty()) {
944 if (outer_flags & FLAG_END)
945 ss << "\\begin{" << outer_type << '}';
947 ss << '\\' << outer_type << '{';
948 if (!special.empty())
952 if (!inner_type.empty()) {
953 if (inner_type != "shaded") {
954 if (inner_flags & FLAG_END)
955 ss << "\\begin{" << inner_type << '}';
957 ss << '\\' << inner_type;
959 if (!position.empty())
960 ss << '[' << position << ']';
961 if (!latex_height.empty())
962 ss << '[' << latex_height << ']';
963 if (!inner_pos.empty())
964 ss << '[' << inner_pos << ']';
965 ss << '{' << latex_width << '}';
966 if (!(inner_flags & FLAG_END))
969 if (inner_type == "shaded")
970 ss << "\\begin{shaded}";
971 handle_ert(os, ss.str(), parent_context);
972 if (!inner_type.empty()) {
973 parse_text(p, os, inner_flags, outer, parent_context);
974 if (inner_flags & FLAG_END)
975 handle_ert(os, "\\end{" + inner_type + '}',
978 handle_ert(os, "}", parent_context);
980 if (!outer_type.empty()) {
981 // If we already read the inner box we have to pop
983 if (!inner_type.empty() && (inner_flags & FLAG_END))
984 active_environments.pop_back();
986 // Ensure that the end of the outer box is parsed correctly:
987 // The opening brace has been eaten by parse_outer_box()
988 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
989 outer_flags &= ~FLAG_ITEM;
990 outer_flags |= FLAG_BRACE_LAST;
992 parse_text(p, os, outer_flags, outer, parent_context);
993 if (outer_flags & FLAG_END)
994 handle_ert(os, "\\end{" + outer_type + '}',
996 else if (inner_type.empty() && outer_type == "framebox")
997 // in this case it is already closed later
1000 handle_ert(os, "}", parent_context);
1003 // LyX does not like empty positions, so we have
1004 // to set them to the LaTeX default values here.
1005 if (position.empty())
1007 if (inner_pos.empty())
1008 inner_pos = position;
1009 parent_context.check_layout(os);
1010 begin_inset(os, "Box ");
1011 if (outer_type == "framed")
1013 else if (outer_type == "framebox")
1015 else if (outer_type == "shadowbox")
1016 os << "Shadowbox\n";
1017 else if ((outer_type == "shaded" && inner_type.empty()) ||
1018 (outer_type == "minipage" && inner_type == "shaded") ||
1019 (outer_type == "parbox" && inner_type == "shaded")) {
1021 preamble.registerAutomaticallyLoadedPackage("color");
1022 } else if (outer_type == "doublebox")
1023 os << "Doublebox\n";
1024 else if (outer_type.empty())
1025 os << "Frameless\n";
1027 os << outer_type << '\n';
1028 os << "position \"" << position << "\"\n";
1029 os << "hor_pos \"" << hor_pos << "\"\n";
1030 os << "has_inner_box " << !inner_type.empty() << "\n";
1031 os << "inner_pos \"" << inner_pos << "\"\n";
1032 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1034 os << "use_makebox " << (inner_type == "makebox") << '\n';
1035 os << "width \"" << width_value << width_unit << "\"\n";
1036 os << "special \"" << width_special << "\"\n";
1037 os << "height \"" << height_value << height_unit << "\"\n";
1038 os << "height_special \"" << height_special << "\"\n";
1039 os << "status open\n\n";
1041 // Unfortunately we can't use parse_text_in_inset:
1042 // InsetBox::forcePlainLayout() is hard coded and does not
1043 // use the inset layout. Apart from that do we call parse_text
1044 // up to two times, but need only one check_end_layout.
1045 bool const forcePlainLayout =
1046 (!inner_type.empty() || inner_type == "makebox") &&
1047 outer_type != "shaded" && outer_type != "framed";
1048 Context context(true, parent_context.textclass);
1049 if (forcePlainLayout)
1050 context.layout = &context.textclass.plainLayout();
1052 context.font = parent_context.font;
1054 // If we have no inner box the contents will be read with the outer box
1055 if (!inner_type.empty())
1056 parse_text(p, os, inner_flags, outer, context);
1058 // Ensure that the end of the outer box is parsed correctly:
1059 // The opening brace has been eaten by parse_outer_box()
1060 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1061 outer_flags &= ~FLAG_ITEM;
1062 outer_flags |= FLAG_BRACE_LAST;
1065 // Find end of outer box, output contents if inner_type is
1066 // empty and output possible comments
1067 if (!outer_type.empty()) {
1068 // If we already read the inner box we have to pop
1070 if (!inner_type.empty() && (inner_flags & FLAG_END))
1071 active_environments.pop_back();
1072 // This does not output anything but comments if
1073 // inner_type is not empty (see use_ert)
1074 parse_text(p, os, outer_flags, outer, context);
1077 context.check_end_layout(os);
1079 #ifdef PRESERVE_LAYOUT
1080 // LyX puts a % after the end of the minipage
1081 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1083 //handle_comment(os, "%dummy", parent_context);
1086 parent_context.new_paragraph(os);
1088 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1089 //handle_comment(os, "%dummy", parent_context);
1092 // We add a protected space if something real follows
1093 if (p.good() && p.next_token().cat() != catComment) {
1094 begin_inset(os, "space ~\n");
1103 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1104 Context & parent_context, string const & outer_type,
1105 string const & special)
1107 eat_whitespace(p, os, parent_context, false);
1108 if (flags & FLAG_ITEM) {
1110 if (p.next_token().cat() == catBegin)
1113 cerr << "Warning: Ignoring missing '{' after \\"
1114 << outer_type << '.' << endl;
1115 eat_whitespace(p, os, parent_context, false);
1118 unsigned int inner_flags = 0;
1120 if (outer_type == "minipage" || outer_type == "parbox") {
1121 p.skip_spaces(true);
1122 while (p.hasOpt()) {
1124 p.skip_spaces(true);
1127 p.skip_spaces(true);
1128 if (outer_type == "parbox") {
1130 if (p.next_token().cat() == catBegin)
1132 p.skip_spaces(true);
1135 if (outer_type == "shaded") {
1136 // These boxes never have an inner box
1138 } else if (p.next_token().asInput() == "\\parbox") {
1139 inner = p.get_token().cs();
1140 inner_flags = FLAG_ITEM;
1141 } else if (p.next_token().asInput() == "\\begin") {
1142 // Is this a minipage or shaded box?
1145 inner = p.getArg('{', '}');
1147 if (inner == "minipage" || inner == "shaded")
1148 inner_flags = FLAG_END;
1153 if (inner_flags == FLAG_END) {
1154 if (inner != "shaded")
1158 eat_whitespace(p, os, parent_context, false);
1160 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1161 outer_type, special, inner);
1163 if (inner_flags == FLAG_ITEM) {
1165 eat_whitespace(p, os, parent_context, false);
1167 parse_box(p, os, flags, inner_flags, outer, parent_context,
1168 outer_type, special, inner);
1173 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1175 parent_context.check_layout(os);
1176 begin_inset(os, "listings\n");
1178 string arg = p.verbatimOption();
1179 os << "lstparams " << '"' << arg << '"' << '\n';
1180 if (arg.find("\\color") != string::npos)
1181 preamble.registerAutomaticallyLoadedPackage("color");
1184 os << "inline true\n";
1186 os << "inline false\n";
1187 os << "status collapsed\n";
1188 Context context(true, parent_context.textclass);
1189 context.layout = &parent_context.textclass.plainLayout();
1192 s = p.plainCommand('!', '!', "lstinline");
1193 context.new_paragraph(os);
1194 context.check_layout(os);
1196 s = p.plainEnvironment("lstlisting");
1197 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1199 os << "\n\\backslash\n";
1200 else if (*it == '\n') {
1201 // avoid adding an empty paragraph at the end
1203 context.new_paragraph(os);
1204 context.check_layout(os);
1209 context.check_end_layout(os);
1214 /// parse an unknown environment
1215 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1216 unsigned flags, bool outer,
1217 Context & parent_context)
1219 if (name == "tabbing")
1220 // We need to remember that we have to handle '\=' specially
1221 flags |= FLAG_TABBING;
1223 // We need to translate font changes and paragraphs inside the
1224 // environment to ERT if we have a non standard font.
1225 // Otherwise things like
1226 // \large\begin{foo}\huge bar\end{foo}
1228 bool const specialfont =
1229 (parent_context.font != parent_context.normalfont);
1230 bool const new_layout_allowed = parent_context.new_layout_allowed;
1232 parent_context.new_layout_allowed = false;
1233 handle_ert(os, "\\begin{" + name + "}", parent_context);
1234 parse_text_snippet(p, os, flags, outer, parent_context);
1235 handle_ert(os, "\\end{" + name + "}", parent_context);
1237 parent_context.new_layout_allowed = new_layout_allowed;
1241 void parse_environment(Parser & p, ostream & os, bool outer,
1242 string & last_env, Context & parent_context)
1244 Layout const * newlayout;
1245 InsetLayout const * newinsetlayout = 0;
1246 string const name = p.getArg('{', '}');
1247 const bool is_starred = suffixIs(name, '*');
1248 string const unstarred_name = rtrim(name, "*");
1249 active_environments.push_back(name);
1251 if (is_math_env(name)) {
1252 parent_context.check_layout(os);
1253 begin_inset(os, "Formula ");
1254 os << "\\begin{" << name << "}";
1255 parse_math(p, os, FLAG_END, MATH_MODE);
1256 os << "\\end{" << name << "}";
1258 if (is_display_math_env(name)) {
1259 // Prevent the conversion of a line break to a space
1260 // (bug 7668). This does not change the output, but
1261 // looks ugly in LyX.
1262 eat_whitespace(p, os, parent_context, false);
1266 else if (is_known(name, preamble.polyglossia_languages)) {
1267 // We must begin a new paragraph if not already done
1268 if (! parent_context.atParagraphStart()) {
1269 parent_context.check_end_layout(os);
1270 parent_context.new_paragraph(os);
1272 // save the language in the context so that it is
1273 // handled by parse_text
1274 parent_context.font.language = preamble.polyglossia2lyx(name);
1275 parse_text(p, os, FLAG_END, outer, parent_context);
1276 // Just in case the environment is empty
1277 parent_context.extra_stuff.erase();
1278 // We must begin a new paragraph to reset the language
1279 parent_context.new_paragraph(os);
1283 else if (unstarred_name == "tabular" || name == "longtable") {
1284 eat_whitespace(p, os, parent_context, false);
1285 string width = "0pt";
1286 if (name == "tabular*") {
1287 width = lyx::translate_len(p.getArg('{', '}'));
1288 eat_whitespace(p, os, parent_context, false);
1290 parent_context.check_layout(os);
1291 begin_inset(os, "Tabular ");
1292 handle_tabular(p, os, name, width, parent_context);
1297 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1298 eat_whitespace(p, os, parent_context, false);
1299 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1300 eat_whitespace(p, os, parent_context, false);
1301 parent_context.check_layout(os);
1302 begin_inset(os, "Float " + unstarred_name + "\n");
1303 // store the float type for subfloats
1304 // subfloats only work with figures and tables
1305 if (unstarred_name == "figure")
1306 float_type = unstarred_name;
1307 else if (unstarred_name == "table")
1308 float_type = unstarred_name;
1312 os << "placement " << opt << '\n';
1313 if (contains(opt, "H"))
1314 preamble.registerAutomaticallyLoadedPackage("float");
1316 Floating const & fl = parent_context.textclass.floats()
1317 .getType(unstarred_name);
1318 if (!fl.floattype().empty() && fl.usesFloatPkg())
1319 preamble.registerAutomaticallyLoadedPackage("float");
1322 os << "wide " << convert<string>(is_starred)
1323 << "\nsideways false"
1324 << "\nstatus open\n\n";
1325 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1327 // We don't need really a new paragraph, but
1328 // we must make sure that the next item gets a \begin_layout.
1329 parent_context.new_paragraph(os);
1331 // the float is parsed thus delete the type
1335 else if (unstarred_name == "sidewaysfigure"
1336 || unstarred_name == "sidewaystable") {
1337 eat_whitespace(p, os, parent_context, false);
1338 parent_context.check_layout(os);
1339 if (unstarred_name == "sidewaysfigure")
1340 begin_inset(os, "Float figure\n");
1342 begin_inset(os, "Float table\n");
1343 os << "wide " << convert<string>(is_starred)
1344 << "\nsideways true"
1345 << "\nstatus open\n\n";
1346 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1348 // We don't need really a new paragraph, but
1349 // we must make sure that the next item gets a \begin_layout.
1350 parent_context.new_paragraph(os);
1352 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1355 else if (name == "wrapfigure" || name == "wraptable") {
1356 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1357 eat_whitespace(p, os, parent_context, false);
1358 parent_context.check_layout(os);
1361 string overhang = "0col%";
1364 lines = p.getArg('[', ']');
1365 string const placement = p.getArg('{', '}');
1367 overhang = p.getArg('[', ']');
1368 string const width = p.getArg('{', '}');
1370 if (name == "wrapfigure")
1371 begin_inset(os, "Wrap figure\n");
1373 begin_inset(os, "Wrap table\n");
1374 os << "lines " << lines
1375 << "\nplacement " << placement
1376 << "\noverhang " << lyx::translate_len(overhang)
1377 << "\nwidth " << lyx::translate_len(width)
1378 << "\nstatus open\n\n";
1379 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1381 // We don't need really a new paragraph, but
1382 // we must make sure that the next item gets a \begin_layout.
1383 parent_context.new_paragraph(os);
1385 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1388 else if (name == "minipage") {
1389 eat_whitespace(p, os, parent_context, false);
1390 // Test whether this is an outer box of a shaded box
1392 // swallow arguments
1393 while (p.hasOpt()) {
1395 p.skip_spaces(true);
1398 p.skip_spaces(true);
1399 Token t = p.get_token();
1400 bool shaded = false;
1401 if (t.asInput() == "\\begin") {
1402 p.skip_spaces(true);
1403 if (p.getArg('{', '}') == "shaded")
1408 parse_outer_box(p, os, FLAG_END, outer,
1409 parent_context, name, "shaded");
1411 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1416 else if (name == "comment") {
1417 eat_whitespace(p, os, parent_context, false);
1418 parent_context.check_layout(os);
1419 begin_inset(os, "Note Comment\n");
1420 os << "status open\n";
1421 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1424 skip_braces(p); // eat {} that might by set by LyX behind comments
1425 preamble.registerAutomaticallyLoadedPackage("verbatim");
1428 else if (name == "verbatim") {
1429 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1430 string const s = p.plainEnvironment("verbatim");
1431 string::const_iterator it2 = s.begin();
1432 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1434 os << "\\backslash ";
1435 else if (*it == '\n') {
1437 // avoid adding an empty paragraph at the end
1438 // FIXME: if there are 2 consecutive spaces at the end ignore it
1439 // because LyX will re-add a \n
1440 // This hack must be removed once bug 8049 is fixed!
1441 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1442 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1446 os << "\n\\end_layout\n\n";
1448 // reset to Standard layout
1449 os << "\n\\begin_layout Standard\n";
1452 else if (name == "CJK") {
1453 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1454 // It is impossible to decide if a CJK environment was in its own paragraph or within
1455 // a line. We therefore always assume a paragraph since the latter is a rare case.
1456 eat_whitespace(p, os, parent_context, false);
1457 parent_context.check_end_layout(os);
1458 // store the encoding to be able to reset it
1459 string const encoding_old = p.getEncoding();
1460 string const encoding = p.getArg('{', '}');
1461 // FIXME: For some reason JIS does not work. Although the text
1462 // in tests/CJK.tex is identical with the SJIS version if you
1463 // convert both snippets using the recode command line utility,
1464 // the resulting .lyx file contains some extra characters if
1465 // you set buggy_encoding to false for JIS.
1466 bool const buggy_encoding = encoding == "JIS";
1467 if (!buggy_encoding)
1468 p.setEncoding(encoding, Encoding::CJK);
1470 // FIXME: This will read garbage, since the data is not encoded in utf8.
1471 p.setEncoding("UTF-8");
1473 // LyX only supports the same mapping for all CJK
1474 // environments, so we might need to output everything as ERT
1475 string const mapping = trim(p.getArg('{', '}'));
1476 char const * const * const where =
1477 is_known(encoding, supported_CJK_encodings);
1478 if (!buggy_encoding && !preamble.fontCJKSet())
1479 preamble.fontCJK(mapping);
1480 bool knownMapping = mapping == preamble.fontCJK();
1481 if (buggy_encoding || !knownMapping || !where) {
1482 parent_context.check_layout(os);
1483 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1485 // we must parse the content as verbatim because e.g. JIS can contain
1486 // normally invalid characters
1487 // FIXME: This works only for the most simple cases.
1488 // Since TeX control characters are not parsed,
1489 // things like comments are completely wrong.
1490 string const s = p.plainEnvironment("CJK");
1491 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1493 handle_ert(os, "\\", parent_context);
1494 else if (*it == '$')
1495 handle_ert(os, "$", parent_context);
1499 handle_ert(os, "\\end{" + name + "}",
1503 supported_CJK_languages[where - supported_CJK_encodings];
1504 // store the language because we must reset it at the end
1505 string const lang_old = parent_context.font.language;
1506 parent_context.font.language = lang;
1507 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1508 parent_context.font.language = lang_old;
1509 parent_context.new_paragraph(os);
1511 p.setEncoding(encoding_old);
1515 else if (name == "lyxgreyedout") {
1516 eat_whitespace(p, os, parent_context, false);
1517 parent_context.check_layout(os);
1518 begin_inset(os, "Note Greyedout\n");
1519 os << "status open\n";
1520 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1523 if (!preamble.notefontcolor().empty())
1524 preamble.registerAutomaticallyLoadedPackage("color");
1527 else if (name == "framed" || name == "shaded") {
1528 eat_whitespace(p, os, parent_context, false);
1529 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1533 else if (name == "lstlisting") {
1534 eat_whitespace(p, os, parent_context, false);
1535 parse_listings(p, os, parent_context, false);
1539 else if (!parent_context.new_layout_allowed)
1540 parse_unknown_environment(p, name, os, FLAG_END, outer,
1543 // Alignment and spacing settings
1544 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1545 // therefore are totally broken!
1546 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1547 // they are commands not environments. They are furthermore switches that
1548 // can be ended by another switches, but also by commands like \footnote or
1549 // \parbox. So the only safe way is to leave them untouched.
1550 else if (name == "center" || name == "centering" ||
1551 name == "flushleft" || name == "flushright" ||
1552 name == "singlespace" || name == "onehalfspace" ||
1553 name == "doublespace" || name == "spacing") {
1554 eat_whitespace(p, os, parent_context, false);
1555 // We must begin a new paragraph if not already done
1556 if (! parent_context.atParagraphStart()) {
1557 parent_context.check_end_layout(os);
1558 parent_context.new_paragraph(os);
1560 if (name == "flushleft")
1561 parent_context.add_extra_stuff("\\align left\n");
1562 else if (name == "flushright")
1563 parent_context.add_extra_stuff("\\align right\n");
1564 else if (name == "center" || name == "centering")
1565 parent_context.add_extra_stuff("\\align center\n");
1566 else if (name == "singlespace")
1567 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1568 else if (name == "onehalfspace") {
1569 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1570 preamble.registerAutomaticallyLoadedPackage("setspace");
1571 } else if (name == "doublespace") {
1572 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1573 preamble.registerAutomaticallyLoadedPackage("setspace");
1574 } else if (name == "spacing") {
1575 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1576 preamble.registerAutomaticallyLoadedPackage("setspace");
1578 parse_text(p, os, FLAG_END, outer, parent_context);
1579 // Just in case the environment is empty
1580 parent_context.extra_stuff.erase();
1581 // We must begin a new paragraph to reset the alignment
1582 parent_context.new_paragraph(os);
1586 // The single '=' is meant here.
1587 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1588 eat_whitespace(p, os, parent_context, false);
1589 Context context(true, parent_context.textclass, newlayout,
1590 parent_context.layout, parent_context.font);
1591 if (parent_context.deeper_paragraph) {
1592 // We are beginning a nested environment after a
1593 // deeper paragraph inside the outer list environment.
1594 // Therefore we don't need to output a "begin deeper".
1595 context.need_end_deeper = true;
1597 parent_context.check_end_layout(os);
1598 if (last_env == name) {
1599 // we need to output a separator since LyX would export
1600 // the two environments as one otherwise (bug 5716)
1601 docstring const sep = from_ascii("--Separator--");
1602 TeX2LyXDocClass const & textclass(parent_context.textclass);
1603 if (textclass.hasLayout(sep)) {
1604 Context newcontext(parent_context);
1605 newcontext.layout = &(textclass[sep]);
1606 newcontext.check_layout(os);
1607 newcontext.check_end_layout(os);
1609 parent_context.check_layout(os);
1610 begin_inset(os, "Note Note\n");
1611 os << "status closed\n";
1612 Context newcontext(true, textclass,
1613 &(textclass.defaultLayout()));
1614 newcontext.check_layout(os);
1615 newcontext.check_end_layout(os);
1617 parent_context.check_end_layout(os);
1620 switch (context.layout->latextype) {
1621 case LATEX_LIST_ENVIRONMENT:
1622 context.add_par_extra_stuff("\\labelwidthstring "
1623 + p.verbatim_item() + '\n');
1626 case LATEX_BIB_ENVIRONMENT:
1627 p.verbatim_item(); // swallow next arg
1633 context.check_deeper(os);
1634 // handle known optional and required arguments
1635 // FIXME: Since format 446, layouts do not require anymore all optional
1636 // arguments before the required ones. Needs to be implemented!
1637 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1638 // It is impossible to place anything after the environment name,
1639 // but before the first \\item.
1640 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1641 bool need_layout = true;
1643 while (optargs < context.layout->optArgs()) {
1644 eat_whitespace(p, os, context, false);
1645 if (p.next_token().cat() == catEscape ||
1646 p.next_token().character() != '[')
1648 p.get_token(); // eat '['
1650 context.check_layout(os);
1651 need_layout = false;
1653 // FIXME: Just a workaround. InsetArgument::updateBuffer
1654 // will compute a proper ID for all "999" Arguments
1655 // (which is also what lyx2lyx produces).
1656 // However, tex2lyx should be able to output proper IDs
1658 begin_inset(os, "Argument 999\n");
1659 os << "status collapsed\n\n";
1660 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1662 eat_whitespace(p, os, context, false);
1666 while (reqargs < context.layout->requiredArgs()) {
1667 eat_whitespace(p, os, context, false);
1668 if (p.next_token().cat() != catBegin)
1670 p.get_token(); // eat '{'
1672 context.check_layout(os);
1673 need_layout = false;
1675 // FIXME: Just a workaround. InsetArgument::updateBuffer
1676 // will compute a proper ID for all "999" Arguments
1677 // (which is also what lyx2lyx produces).
1678 // However, tex2lyx should be able to output proper IDs
1680 begin_inset(os, "Argument 999\n");
1681 os << "status collapsed\n\n";
1682 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1684 eat_whitespace(p, os, context, false);
1688 parse_text(p, os, FLAG_END, outer, context);
1689 context.check_end_layout(os);
1690 if (parent_context.deeper_paragraph) {
1691 // We must suppress the "end deeper" because we
1692 // suppressed the "begin deeper" above.
1693 context.need_end_deeper = false;
1695 context.check_end_deeper(os);
1696 parent_context.new_paragraph(os);
1698 if (!preamble.titleLayoutFound())
1699 preamble.titleLayoutFound(newlayout->intitle);
1700 set<string> const & req = newlayout->requires();
1701 set<string>::const_iterator it = req.begin();
1702 set<string>::const_iterator en = req.end();
1703 for (; it != en; ++it)
1704 preamble.registerAutomaticallyLoadedPackage(*it);
1707 // The single '=' is meant here.
1708 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1709 eat_whitespace(p, os, parent_context, false);
1710 parent_context.check_layout(os);
1711 begin_inset(os, "Flex ");
1712 os << to_utf8(newinsetlayout->name()) << '\n'
1713 << "status collapsed\n";
1714 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1718 else if (name == "appendix") {
1719 // This is no good latex style, but it works and is used in some documents...
1720 eat_whitespace(p, os, parent_context, false);
1721 parent_context.check_end_layout(os);
1722 Context context(true, parent_context.textclass, parent_context.layout,
1723 parent_context.layout, parent_context.font);
1724 context.check_layout(os);
1725 os << "\\start_of_appendix\n";
1726 parse_text(p, os, FLAG_END, outer, context);
1727 context.check_end_layout(os);
1731 else if (known_environments.find(name) != known_environments.end()) {
1732 vector<ArgumentType> arguments = known_environments[name];
1733 // The last "argument" denotes wether we may translate the
1734 // environment contents to LyX
1735 // The default required if no argument is given makes us
1736 // compatible with the reLyXre environment.
1737 ArgumentType contents = arguments.empty() ?
1740 if (!arguments.empty())
1741 arguments.pop_back();
1742 // See comment in parse_unknown_environment()
1743 bool const specialfont =
1744 (parent_context.font != parent_context.normalfont);
1745 bool const new_layout_allowed =
1746 parent_context.new_layout_allowed;
1748 parent_context.new_layout_allowed = false;
1749 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1750 outer, parent_context);
1751 if (contents == verbatim)
1752 handle_ert(os, p.verbatimEnvironment(name),
1755 parse_text_snippet(p, os, FLAG_END, outer,
1757 handle_ert(os, "\\end{" + name + "}", parent_context);
1759 parent_context.new_layout_allowed = new_layout_allowed;
1763 parse_unknown_environment(p, name, os, FLAG_END, outer,
1767 active_environments.pop_back();
1771 /// parses a comment and outputs it to \p os.
1772 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1774 LASSERT(t.cat() == catComment, return);
1775 if (!t.cs().empty()) {
1776 context.check_layout(os);
1777 handle_comment(os, '%' + t.cs(), context);
1778 if (p.next_token().cat() == catNewline) {
1779 // A newline after a comment line starts a new
1781 if (context.new_layout_allowed) {
1782 if(!context.atParagraphStart())
1783 // Only start a new paragraph if not already
1784 // done (we might get called recursively)
1785 context.new_paragraph(os);
1787 handle_ert(os, "\n", context);
1788 eat_whitespace(p, os, context, true);
1791 // "%\n" combination
1798 * Reads spaces and comments until the first non-space, non-comment token.
1799 * New paragraphs (double newlines or \\par) are handled like simple spaces
1800 * if \p eatParagraph is true.
1801 * Spaces are skipped, but comments are written to \p os.
1803 void eat_whitespace(Parser & p, ostream & os, Context & context,
1807 Token const & t = p.get_token();
1808 if (t.cat() == catComment)
1809 parse_comment(p, os, t, context);
1810 else if ((! eatParagraph && p.isParagraph()) ||
1811 (t.cat() != catSpace && t.cat() != catNewline)) {
1820 * Set a font attribute, parse text and reset the font attribute.
1821 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1822 * \param currentvalue Current value of the attribute. Is set to the new
1823 * value during parsing.
1824 * \param newvalue New value of the attribute
1826 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1827 Context & context, string const & attribute,
1828 string & currentvalue, string const & newvalue)
1830 context.check_layout(os);
1831 string const oldvalue = currentvalue;
1832 currentvalue = newvalue;
1833 os << '\n' << attribute << ' ' << newvalue << "\n";
1834 parse_text_snippet(p, os, flags, outer, context);
1835 context.check_layout(os);
1836 os << '\n' << attribute << ' ' << oldvalue << "\n";
1837 currentvalue = oldvalue;
1841 /// get the arguments of a natbib or jurabib citation command
1842 void get_cite_arguments(Parser & p, bool natbibOrder,
1843 string & before, string & after)
1845 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1847 // text before the citation
1849 // text after the citation
1850 after = p.getFullOpt();
1852 if (!after.empty()) {
1853 before = p.getFullOpt();
1854 if (natbibOrder && !before.empty())
1855 swap(before, after);
1860 /// Convert filenames with TeX macros and/or quotes to something LyX
1862 string const normalize_filename(string const & name)
1867 Token const & t = p.get_token();
1868 if (t.cat() != catEscape)
1870 else if (t.cs() == "lyxdot") {
1871 // This is used by LyX for simple dots in relative
1875 } else if (t.cs() == "space") {
1878 } else if (t.cs() == "string") {
1879 // Convert \string" to " and \string~ to ~
1880 Token const & n = p.next_token();
1881 if (n.asInput() != "\"" && n.asInput() != "~")
1886 // Strip quotes. This is a bit complicated (see latex_path()).
1887 string full = os.str();
1888 if (!full.empty() && full[0] == '"') {
1889 string base = removeExtension(full);
1890 string ext = getExtension(full);
1891 if (!base.empty() && base[base.length()-1] == '"')
1894 return addExtension(trim(base, "\""), ext);
1895 if (full[full.length()-1] == '"')
1898 return trim(full, "\"");
1904 /// Convert \p name from TeX convention (relative to master file) to LyX
1905 /// convention (relative to .lyx file) if it is relative
1906 void fix_child_filename(string & name)
1908 string const absMasterTeX = getMasterFilePath(true);
1909 bool const isabs = FileName::isAbsolute(name);
1910 // convert from "relative to .tex master" to absolute original path
1912 name = makeAbsPath(name, absMasterTeX).absFileName();
1913 bool copyfile = copyFiles();
1914 string const absParentLyX = getParentFilePath(false);
1917 // convert from absolute original path to "relative to master file"
1918 string const rel = to_utf8(makeRelPath(from_utf8(name),
1919 from_utf8(absMasterTeX)));
1920 // re-interpret "relative to .tex file" as "relative to .lyx file"
1921 // (is different if the master .lyx file resides in a
1922 // different path than the master .tex file)
1923 string const absMasterLyX = getMasterFilePath(false);
1924 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1925 // Do not copy if the new path is impossible to create. Example:
1926 // absMasterTeX = "/foo/bar/"
1927 // absMasterLyX = "/bar/"
1928 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1929 if (contains(name, "/../"))
1936 // convert from absolute original path to
1937 // "relative to .lyx file"
1938 name = to_utf8(makeRelPath(from_utf8(abs),
1939 from_utf8(absParentLyX)));
1943 // convert from absolute original path to "relative to .lyx file"
1944 name = to_utf8(makeRelPath(from_utf8(name),
1945 from_utf8(absParentLyX)));
1950 void copy_file(FileName const & src, string dstname)
1954 string const absParent = getParentFilePath(false);
1956 if (FileName::isAbsolute(dstname))
1957 dst = FileName(dstname);
1959 dst = makeAbsPath(dstname, absParent);
1960 string const absMaster = getMasterFilePath(false);
1961 FileName const srcpath = src.onlyPath();
1962 FileName const dstpath = dst.onlyPath();
1963 if (equivalent(srcpath, dstpath))
1965 if (!dstpath.isDirectory()) {
1966 if (!dstpath.createPath()) {
1967 cerr << "Warning: Could not create directory for file `"
1968 << dst.absFileName() << "´." << endl;
1972 if (dst.isReadableFile()) {
1973 if (overwriteFiles())
1974 cerr << "Warning: Overwriting existing file `"
1975 << dst.absFileName() << "´." << endl;
1977 cerr << "Warning: Not overwriting existing file `"
1978 << dst.absFileName() << "´." << endl;
1982 if (!src.copyTo(dst))
1983 cerr << "Warning: Could not copy file `" << src.absFileName()
1984 << "´ to `" << dst.absFileName() << "´." << endl;
1988 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1989 void parse_noweb(Parser & p, ostream & os, Context & context)
1991 // assemble the rest of the keyword
1995 Token const & t = p.get_token();
1996 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1999 chunk = (p.good() && p.next_token().asInput() == "=");
2001 name += p.get_token().asInput();
2004 name += t.asInput();
2007 if (!chunk || !context.new_layout_allowed ||
2008 !context.textclass.hasLayout(from_ascii("Chunk"))) {
2009 cerr << "Warning: Could not interpret '" << name
2010 << "'. Ignoring it." << endl;
2014 // We use new_paragraph instead of check_end_layout because the stuff
2015 // following the noweb chunk needs to start with a \begin_layout.
2016 // This may create a new paragraph even if there was none in the
2017 // noweb file, but the alternative is an invalid LyX file. Since
2018 // noweb code chunks are implemented with a layout style in LyX they
2019 // always must be in an own paragraph.
2020 context.new_paragraph(os);
2021 Context newcontext(true, context.textclass,
2022 &context.textclass[from_ascii("Chunk")]);
2023 newcontext.check_layout(os);
2026 Token const & t = p.get_token();
2027 // We abuse the parser a bit, because this is no TeX syntax
2029 if (t.cat() == catEscape)
2030 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2033 Context tmp(false, context.textclass,
2034 &context.textclass[from_ascii("Chunk")]);
2035 tmp.need_end_layout = true;
2036 tmp.check_layout(oss);
2037 os << subst(t.asInput(), "\n", oss.str());
2039 // The chunk is ended by an @ at the beginning of a line.
2040 // After the @ the line may contain a comment and/or
2041 // whitespace, but nothing else.
2042 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2043 (p.next_token().cat() == catSpace ||
2044 p.next_token().cat() == catNewline ||
2045 p.next_token().cat() == catComment)) {
2046 while (p.good() && p.next_token().cat() == catSpace)
2047 os << p.get_token().asInput();
2048 if (p.next_token().cat() == catComment)
2049 // The comment includes a final '\n'
2050 os << p.get_token().asInput();
2052 if (p.next_token().cat() == catNewline)
2059 newcontext.check_end_layout(os);
2063 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2064 bool is_macro(Parser & p)
2066 Token first = p.curr_token();
2067 if (first.cat() != catEscape || !p.good())
2069 if (first.cs() == "def")
2071 if (first.cs() != "global" && first.cs() != "long")
2073 Token second = p.get_token();
2075 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2076 second.cat() == catNewline || second.cat() == catComment)) {
2077 second = p.get_token();
2080 bool secondvalid = second.cat() == catEscape;
2082 bool thirdvalid = false;
2083 if (p.good() && first.cs() == "global" && secondvalid &&
2084 second.cs() == "long") {
2085 third = p.get_token();
2087 while (p.good() && !p.isParagraph() &&
2088 (third.cat() == catSpace ||
2089 third.cat() == catNewline ||
2090 third.cat() == catComment)) {
2091 third = p.get_token();
2094 thirdvalid = third.cat() == catEscape;
2096 for (int i = 0; i < pos; ++i)
2101 return (first.cs() == "global" || first.cs() == "long") &&
2102 second.cs() == "def";
2103 return first.cs() == "global" && second.cs() == "long" &&
2104 third.cs() == "def";
2108 /// Parse a macro definition (assumes that is_macro() returned true)
2109 void parse_macro(Parser & p, ostream & os, Context & context)
2111 context.check_layout(os);
2112 Token first = p.curr_token();
2115 string command = first.asInput();
2116 if (first.cs() != "def") {
2118 eat_whitespace(p, os, context, false);
2119 second = p.curr_token();
2120 command += second.asInput();
2121 if (second.cs() != "def") {
2123 eat_whitespace(p, os, context, false);
2124 third = p.curr_token();
2125 command += third.asInput();
2128 eat_whitespace(p, os, context, false);
2129 string const name = p.get_token().cs();
2130 eat_whitespace(p, os, context, false);
2136 while (p.next_token().cat() != catBegin) {
2137 if (p.next_token().cat() == catParameter) {
2142 // followed by number?
2143 if (p.next_token().cat() == catOther) {
2144 char c = p.getChar();
2146 // number = current arity + 1?
2147 if (c == arity + '0' + 1)
2152 paramtext += p.get_token().cs();
2154 paramtext += p.get_token().cs();
2159 // only output simple (i.e. compatible) macro as FormulaMacros
2160 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2162 context.check_layout(os);
2163 begin_inset(os, "FormulaMacro");
2164 os << "\n\\def" << ert;
2167 handle_ert(os, command + ert, context);
2171 void registerExternalTemplatePackages(string const & name)
2173 external::TemplateManager const & etm = external::TemplateManager::get();
2174 external::Template const * const et = etm.getTemplateByName(name);
2177 external::Template::Formats::const_iterator cit = et->formats.end();
2179 cit = et->formats.find("PDFLaTeX");
2180 if (cit == et->formats.end())
2181 // If the template has not specified a PDFLaTeX output,
2182 // we try the LaTeX format.
2183 cit = et->formats.find("LaTeX");
2184 if (cit == et->formats.end())
2186 vector<string>::const_iterator qit = cit->second.requirements.begin();
2187 vector<string>::const_iterator qend = cit->second.requirements.end();
2188 for (; qit != qend; ++qit)
2189 preamble.registerAutomaticallyLoadedPackage(*qit);
2192 } // anonymous namespace
2195 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2198 Layout const * newlayout = 0;
2199 InsetLayout const * newinsetlayout = 0;
2200 char const * const * where = 0;
2201 // Store the latest bibliographystyle and nocite{*} option
2202 // (needed for bibtex inset)
2204 string bibliographystyle = "default";
2205 bool const use_natbib = isProvided("natbib");
2206 bool const use_jurabib = isProvided("jurabib");
2209 Token const & t = p.get_token();
2211 // it is impossible to determine the correct encoding for non-CJK Japanese.
2212 // Therefore write a note at the beginning of the document
2213 if (is_nonCJKJapanese) {
2214 context.check_layout(os);
2215 begin_inset(os, "Note Note\n");
2216 os << "status open\n\\begin_layout Plain Layout\n"
2217 << "\\series bold\n"
2218 << "Important information:\n"
2219 << "\\end_layout\n\n"
2220 << "\\begin_layout Plain Layout\n"
2221 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2222 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2223 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2224 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2225 << " and specify the encoding using the -e command-line switch.\n"
2226 << " In addition, you might want to double check that the desired output encoding\n"
2227 << " is correctly selected in Document > Settings > Language.\n"
2228 << "\\end_layout\n";
2230 is_nonCJKJapanese = false;
2234 debugToken(cerr, t, flags);
2237 if (flags & FLAG_ITEM) {
2238 if (t.cat() == catSpace)
2241 flags &= ~FLAG_ITEM;
2242 if (t.cat() == catBegin) {
2243 // skip the brace and collect everything to the next matching
2245 flags |= FLAG_BRACE_LAST;
2249 // handle only this single token, leave the loop if done
2250 flags |= FLAG_LEAVE;
2253 if (t.cat() != catEscape && t.character() == ']' &&
2254 (flags & FLAG_BRACK_LAST))
2256 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2259 // If there is anything between \end{env} and \begin{env} we
2260 // don't need to output a separator.
2261 if (t.cat() != catSpace && t.cat() != catNewline &&
2262 t.asInput() != "\\begin")
2268 if (t.cat() == catMath) {
2269 // we are inside some text mode thingy, so opening new math is allowed
2270 context.check_layout(os);
2271 begin_inset(os, "Formula ");
2272 Token const & n = p.get_token();
2273 bool const display(n.cat() == catMath && outer);
2275 // TeX's $$...$$ syntax for displayed math
2277 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2279 p.get_token(); // skip the second '$' token
2281 // simple $...$ stuff
2284 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2289 // Prevent the conversion of a line break to a
2290 // space (bug 7668). This does not change the
2291 // output, but looks ugly in LyX.
2292 eat_whitespace(p, os, context, false);
2296 else if (t.cat() == catSuper || t.cat() == catSub)
2297 cerr << "catcode " << t << " illegal in text mode\n";
2299 // Basic support for english quotes. This should be
2300 // extended to other quotes, but is not so easy (a
2301 // left english quote is the same as a right german
2303 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2304 context.check_layout(os);
2305 begin_inset(os, "Quotes ");
2311 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2312 context.check_layout(os);
2313 begin_inset(os, "Quotes ");
2320 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2321 context.check_layout(os);
2322 begin_inset(os, "Quotes ");
2329 else if (t.asInput() == "<"
2330 && p.next_token().asInput() == "<" && noweb_mode) {
2332 parse_noweb(p, os, context);
2335 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2336 context.check_layout(os);
2337 begin_inset(os, "Quotes ");
2344 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2345 check_space(p, os, context);
2347 else if (t.character() == '[' && noweb_mode &&
2348 p.next_token().character() == '[') {
2349 // These can contain underscores
2351 string const s = p.getFullOpt() + ']';
2352 if (p.next_token().character() == ']')
2355 cerr << "Warning: Inserting missing ']' in '"
2356 << s << "'." << endl;
2357 handle_ert(os, s, context);
2360 else if (t.cat() == catLetter) {
2361 context.check_layout(os);
2362 // Workaround for bug 4752.
2363 // FIXME: This whole code block needs to be removed
2364 // when the bug is fixed and tex2lyx produces
2365 // the updated file format.
2366 // The replacement algorithm in LyX is so stupid that
2367 // it even translates a phrase if it is part of a word.
2368 bool handled = false;
2369 for (int const * l = known_phrase_lengths; *l; ++l) {
2370 string phrase = t.cs();
2371 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2372 phrase += p.get_token().cs();
2373 if (is_known(phrase, known_coded_phrases)) {
2374 handle_ert(os, phrase, context);
2378 for (size_t i = 1; i < phrase.length(); ++i)
2386 else if (t.cat() == catOther ||
2387 t.cat() == catAlign ||
2388 t.cat() == catParameter) {
2389 // This translates "&" to "\\&" which may be wrong...
2390 context.check_layout(os);
2394 else if (p.isParagraph()) {
2395 if (context.new_layout_allowed)
2396 context.new_paragraph(os);
2398 handle_ert(os, "\\par ", context);
2399 eat_whitespace(p, os, context, true);
2402 else if (t.cat() == catActive) {
2403 context.check_layout(os);
2404 if (t.character() == '~') {
2405 if (context.layout->free_spacing)
2408 begin_inset(os, "space ~\n");
2415 else if (t.cat() == catBegin) {
2416 Token const next = p.next_token();
2417 Token const end = p.next_next_token();
2418 if (next.cat() == catEnd) {
2420 Token const prev = p.prev_token();
2422 if (p.next_token().character() == '`' ||
2423 (prev.character() == '-' &&
2424 p.next_token().character() == '-'))
2425 ; // ignore it in {}`` or -{}-
2427 handle_ert(os, "{}", context);
2428 } else if (next.cat() == catEscape &&
2429 is_known(next.cs(), known_quotes) &&
2430 end.cat() == catEnd) {
2431 // Something like {\textquoteright} (e.g.
2432 // from writer2latex). LyX writes
2433 // \textquoteright{}, so we may skip the
2434 // braces here for better readability.
2435 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2438 context.check_layout(os);
2439 // special handling of font attribute changes
2440 Token const prev = p.prev_token();
2441 TeXFont const oldFont = context.font;
2442 if (next.character() == '[' ||
2443 next.character() == ']' ||
2444 next.character() == '*') {
2446 if (p.next_token().cat() == catEnd) {
2451 handle_ert(os, "{", context);
2452 parse_text_snippet(p, os,
2455 handle_ert(os, "}", context);
2457 } else if (! context.new_layout_allowed) {
2458 handle_ert(os, "{", context);
2459 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2461 handle_ert(os, "}", context);
2462 } else if (is_known(next.cs(), known_sizes)) {
2463 // next will change the size, so we must
2465 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2467 if (!context.atParagraphStart())
2469 << context.font.size << "\n";
2470 } else if (is_known(next.cs(), known_font_families)) {
2471 // next will change the font family, so we
2472 // must reset it here
2473 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2475 if (!context.atParagraphStart())
2477 << context.font.family << "\n";
2478 } else if (is_known(next.cs(), known_font_series)) {
2479 // next will change the font series, so we
2480 // must reset it here
2481 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2483 if (!context.atParagraphStart())
2485 << context.font.series << "\n";
2486 } else if (is_known(next.cs(), known_font_shapes)) {
2487 // next will change the font shape, so we
2488 // must reset it here
2489 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2491 if (!context.atParagraphStart())
2493 << context.font.shape << "\n";
2494 } else if (is_known(next.cs(), known_old_font_families) ||
2495 is_known(next.cs(), known_old_font_series) ||
2496 is_known(next.cs(), known_old_font_shapes)) {
2497 // next will change the font family, series
2498 // and shape, so we must reset it here
2499 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2501 if (!context.atParagraphStart())
2503 << context.font.family
2505 << context.font.series
2507 << context.font.shape << "\n";
2509 handle_ert(os, "{", context);
2510 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2512 handle_ert(os, "}", context);
2517 else if (t.cat() == catEnd) {
2518 if (flags & FLAG_BRACE_LAST) {
2521 cerr << "stray '}' in text\n";
2522 handle_ert(os, "}", context);
2525 else if (t.cat() == catComment)
2526 parse_comment(p, os, t, context);
2529 // control sequences
2532 else if (t.cs() == "(") {
2533 context.check_layout(os);
2534 begin_inset(os, "Formula");
2536 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2541 else if (t.cs() == "[") {
2542 context.check_layout(os);
2543 begin_inset(os, "Formula");
2545 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2548 // Prevent the conversion of a line break to a space
2549 // (bug 7668). This does not change the output, but
2550 // looks ugly in LyX.
2551 eat_whitespace(p, os, context, false);
2554 else if (t.cs() == "begin")
2555 parse_environment(p, os, outer, last_env,
2558 else if (t.cs() == "end") {
2559 if (flags & FLAG_END) {
2560 // eat environment name
2561 string const name = p.getArg('{', '}');
2562 if (name != active_environment())
2563 cerr << "\\end{" + name + "} does not match \\begin{"
2564 + active_environment() + "}\n";
2567 p.error("found 'end' unexpectedly");
2570 else if (t.cs() == "item") {
2572 bool const optarg = p.hasOpt();
2574 // FIXME: This swallows comments, but we cannot use
2575 // eat_whitespace() since we must not output
2576 // anything before the item.
2577 p.skip_spaces(true);
2578 s = p.verbatimOption();
2580 p.skip_spaces(false);
2582 context.check_layout(os);
2583 if (context.has_item) {
2584 // An item in an unknown list-like environment
2585 // FIXME: Do this in check_layout()!
2586 context.has_item = false;
2588 handle_ert(os, "\\item", context);
2590 handle_ert(os, "\\item ", context);
2593 if (context.layout->labeltype != LABEL_MANUAL) {
2594 // LyX does not support \item[\mybullet]
2595 // in itemize environments
2597 os << parse_text_snippet(p2,
2598 FLAG_BRACK_LAST, outer, context);
2599 } else if (!s.empty()) {
2600 // LyX adds braces around the argument,
2601 // so we need to remove them here.
2602 if (s.size() > 2 && s[0] == '{' &&
2603 s[s.size()-1] == '}')
2604 s = s.substr(1, s.size()-2);
2605 // If the argument contains a space we
2606 // must put it into ERT: Otherwise LyX
2607 // would misinterpret the space as
2608 // item delimiter (bug 7663)
2609 if (contains(s, ' ')) {
2610 handle_ert(os, s, context);
2613 os << parse_text_snippet(p2,
2617 // The space is needed to separate the
2618 // item from the rest of the sentence.
2620 eat_whitespace(p, os, context, false);
2625 else if (t.cs() == "bibitem") {
2627 context.check_layout(os);
2628 eat_whitespace(p, os, context, false);
2629 string label = convert_command_inset_arg(p.verbatimOption());
2630 string key = convert_command_inset_arg(p.verbatim_item());
2631 if (contains(label, '\\') || contains(key, '\\')) {
2632 // LyX can't handle LaTeX commands in labels or keys
2633 handle_ert(os, t.asInput() + '[' + label +
2634 "]{" + p.verbatim_item() + '}',
2637 begin_command_inset(os, "bibitem", "bibitem");
2638 os << "label \"" << label << "\"\n"
2639 "key \"" << key << "\"\n";
2644 else if (is_macro(p)) {
2645 // catch the case of \def\inputGnumericTable
2647 if (t.cs() == "def") {
2648 Token second = p.next_token();
2649 if (second.cs() == "inputGnumericTable") {
2653 Token third = p.get_token();
2655 if (third.cs() == "input") {
2659 string name = normalize_filename(p.verbatim_item());
2660 string const path = getMasterFilePath(true);
2661 // We want to preserve relative / absolute filenames,
2662 // therefore path is only used for testing
2663 // The file extension is in every case ".tex".
2664 // So we need to remove this extension and check for
2665 // the original one.
2666 name = removeExtension(name);
2667 if (!makeAbsPath(name, path).exists()) {
2668 char const * const Gnumeric_formats[] = {"gnumeric",
2670 string const Gnumeric_name =
2671 find_file(name, path, Gnumeric_formats);
2672 if (!Gnumeric_name.empty())
2673 name = Gnumeric_name;
2675 FileName const absname = makeAbsPath(name, path);
2676 if (absname.exists()) {
2677 fix_child_filename(name);
2678 copy_file(absname, name);
2680 cerr << "Warning: Could not find file '"
2681 << name << "'." << endl;
2682 context.check_layout(os);
2683 begin_inset(os, "External\n\ttemplate ");
2684 os << "GnumericSpreadsheet\n\tfilename "
2687 context.check_layout(os);
2689 // register the packages that are automatically loaded
2690 // by the Gnumeric template
2691 registerExternalTemplatePackages("GnumericSpreadsheet");
2696 parse_macro(p, os, context);
2699 else if (t.cs() == "noindent") {
2701 context.add_par_extra_stuff("\\noindent\n");
2704 else if (t.cs() == "appendix") {
2705 context.add_par_extra_stuff("\\start_of_appendix\n");
2706 // We need to start a new paragraph. Otherwise the
2707 // appendix in 'bla\appendix\chapter{' would start
2709 context.new_paragraph(os);
2710 // We need to make sure that the paragraph is
2711 // generated even if it is empty. Otherwise the
2712 // appendix in '\par\appendix\par\chapter{' would
2714 context.check_layout(os);
2715 // FIXME: This is a hack to prevent paragraph
2716 // deletion if it is empty. Handle this better!
2718 "%dummy comment inserted by tex2lyx to "
2719 "ensure that this paragraph is not empty",
2721 // Both measures above may generate an additional
2722 // empty paragraph, but that does not hurt, because
2723 // whitespace does not matter here.
2724 eat_whitespace(p, os, context, true);
2727 // Must catch empty dates before findLayout is called below
2728 else if (t.cs() == "date") {
2729 eat_whitespace(p, os, context, false);
2731 string const date = p.verbatim_item();
2734 preamble.suppressDate(true);
2737 preamble.suppressDate(false);
2738 if (context.new_layout_allowed &&
2739 (newlayout = findLayout(context.textclass,
2742 output_command_layout(os, p, outer,
2743 context, newlayout);
2744 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2745 if (!preamble.titleLayoutFound())
2746 preamble.titleLayoutFound(newlayout->intitle);
2747 set<string> const & req = newlayout->requires();
2748 set<string>::const_iterator it = req.begin();
2749 set<string>::const_iterator en = req.end();
2750 for (; it != en; ++it)
2751 preamble.registerAutomaticallyLoadedPackage(*it);
2754 "\\date{" + p.verbatim_item() + '}',
2759 // Starred section headings
2760 // Must attempt to parse "Section*" before "Section".
2761 else if ((p.next_token().asInput() == "*") &&
2762 context.new_layout_allowed &&
2763 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2766 output_command_layout(os, p, outer, context, newlayout);
2768 if (!preamble.titleLayoutFound())
2769 preamble.titleLayoutFound(newlayout->intitle);
2770 set<string> const & req = newlayout->requires();
2771 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2772 preamble.registerAutomaticallyLoadedPackage(*it);
2775 // Section headings and the like
2776 else if (context.new_layout_allowed &&
2777 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2779 output_command_layout(os, p, outer, context, newlayout);
2781 if (!preamble.titleLayoutFound())
2782 preamble.titleLayoutFound(newlayout->intitle);
2783 set<string> const & req = newlayout->requires();
2784 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2785 preamble.registerAutomaticallyLoadedPackage(*it);
2788 else if (t.cs() == "caption") {
2790 context.check_layout(os);
2792 begin_inset(os, "Caption Standard\n");
2793 Context newcontext(true, context.textclass, 0, 0, context.font);
2794 newcontext.check_layout(os);
2795 // FIXME InsetArgument is now properly implemented in InsetLayout
2796 // (for captions, but also for others)
2797 if (p.next_token().cat() != catEscape &&
2798 p.next_token().character() == '[') {
2799 p.get_token(); // eat '['
2800 begin_inset(os, "Argument 1\n");
2801 os << "status collapsed\n";
2802 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2804 eat_whitespace(p, os, context, false);
2806 parse_text(p, os, FLAG_ITEM, outer, context);
2807 context.check_end_layout(os);
2808 // We don't need really a new paragraph, but
2809 // we must make sure that the next item gets a \begin_layout.
2810 context.new_paragraph(os);
2813 newcontext.check_end_layout(os);
2816 else if (t.cs() == "subfloat") {
2817 // the syntax is \subfloat[caption]{content}
2818 // if it is a table of figure depends on the surrounding float
2819 bool has_caption = false;
2821 // do nothing if there is no outer float
2822 if (!float_type.empty()) {
2823 context.check_layout(os);
2825 begin_inset(os, "Float " + float_type + "\n");
2827 << "\nsideways false"
2828 << "\nstatus collapsed\n\n";
2831 if (p.next_token().cat() != catEscape &&
2832 p.next_token().character() == '[') {
2833 p.get_token(); // eat '['
2834 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2838 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2839 // the caption comes always as the last
2841 // we must make sure that the caption gets a \begin_layout
2842 os << "\n\\begin_layout Plain Layout";
2844 begin_inset(os, "Caption Standard\n");
2845 Context newcontext(true, context.textclass,
2846 0, 0, context.font);
2847 newcontext.check_layout(os);
2848 os << caption << "\n";
2849 newcontext.check_end_layout(os);
2850 // We don't need really a new paragraph, but
2851 // we must make sure that the next item gets a \begin_layout.
2852 //newcontext.new_paragraph(os);
2856 // We don't need really a new paragraph, but
2857 // we must make sure that the next item gets a \begin_layout.
2859 context.new_paragraph(os);
2862 context.check_end_layout(os);
2863 // close the layout we opened
2865 os << "\n\\end_layout\n";
2867 // if the float type is not supported or there is no surrounding float
2870 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2871 handle_ert(os, t.asInput() + '[' + opt_arg +
2872 "]{" + p.verbatim_item() + '}', context);
2874 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2878 else if (t.cs() == "includegraphics") {
2879 bool const clip = p.next_token().asInput() == "*";
2882 string const arg = p.getArg('[', ']');
2883 map<string, string> opts;
2884 vector<string> keys;
2885 split_map(arg, opts, keys);
2887 opts["clip"] = string();
2888 string name = normalize_filename(p.verbatim_item());
2890 string const path = getMasterFilePath(true);
2891 // We want to preserve relative / absolute filenames,
2892 // therefore path is only used for testing
2893 if (!makeAbsPath(name, path).exists()) {
2894 // The file extension is probably missing.
2895 // Now try to find it out.
2896 string const dvips_name =
2897 find_file(name, path,
2898 known_dvips_graphics_formats);
2899 string const pdftex_name =
2900 find_file(name, path,
2901 known_pdftex_graphics_formats);
2902 if (!dvips_name.empty()) {
2903 if (!pdftex_name.empty()) {
2904 cerr << "This file contains the "
2906 "\"\\includegraphics{"
2908 "However, files\n\""
2909 << dvips_name << "\" and\n\""
2910 << pdftex_name << "\"\n"
2911 "both exist, so I had to make a "
2912 "choice and took the first one.\n"
2913 "Please move the unwanted one "
2914 "someplace else and try again\n"
2915 "if my choice was wrong."
2919 } else if (!pdftex_name.empty()) {
2925 FileName const absname = makeAbsPath(name, path);
2926 if (absname.exists()) {
2927 fix_child_filename(name);
2928 copy_file(absname, name);
2930 cerr << "Warning: Could not find graphics file '"
2931 << name << "'." << endl;
2933 context.check_layout(os);
2934 begin_inset(os, "Graphics ");
2935 os << "\n\tfilename " << name << '\n';
2936 if (opts.find("width") != opts.end())
2938 << translate_len(opts["width"]) << '\n';
2939 if (opts.find("height") != opts.end())
2941 << translate_len(opts["height"]) << '\n';
2942 if (opts.find("scale") != opts.end()) {
2943 istringstream iss(opts["scale"]);
2947 os << "\tscale " << val << '\n';
2949 if (opts.find("angle") != opts.end()) {
2950 os << "\trotateAngle "
2951 << opts["angle"] << '\n';
2952 vector<string>::const_iterator a =
2953 find(keys.begin(), keys.end(), "angle");
2954 vector<string>::const_iterator s =
2955 find(keys.begin(), keys.end(), "width");
2956 if (s == keys.end())
2957 s = find(keys.begin(), keys.end(), "height");
2958 if (s == keys.end())
2959 s = find(keys.begin(), keys.end(), "scale");
2960 if (s != keys.end() && distance(s, a) > 0)
2961 os << "\tscaleBeforeRotation\n";
2963 if (opts.find("origin") != opts.end()) {
2965 string const opt = opts["origin"];
2966 if (opt.find('l') != string::npos) ss << "left";
2967 if (opt.find('r') != string::npos) ss << "right";
2968 if (opt.find('c') != string::npos) ss << "center";
2969 if (opt.find('t') != string::npos) ss << "Top";
2970 if (opt.find('b') != string::npos) ss << "Bottom";
2971 if (opt.find('B') != string::npos) ss << "Baseline";
2972 if (!ss.str().empty())
2973 os << "\trotateOrigin " << ss.str() << '\n';
2975 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2977 if (opts.find("keepaspectratio") != opts.end())
2978 os << "\tkeepAspectRatio\n";
2979 if (opts.find("clip") != opts.end())
2981 if (opts.find("draft") != opts.end())
2983 if (opts.find("bb") != opts.end())
2984 os << "\tBoundingBox "
2985 << opts["bb"] << '\n';
2986 int numberOfbbOptions = 0;
2987 if (opts.find("bbllx") != opts.end())
2988 numberOfbbOptions++;
2989 if (opts.find("bblly") != opts.end())
2990 numberOfbbOptions++;
2991 if (opts.find("bburx") != opts.end())
2992 numberOfbbOptions++;
2993 if (opts.find("bbury") != opts.end())
2994 numberOfbbOptions++;
2995 if (numberOfbbOptions == 4)
2996 os << "\tBoundingBox "
2997 << opts["bbllx"] << " " << opts["bblly"] << " "
2998 << opts["bburx"] << " " << opts["bbury"] << '\n';
2999 else if (numberOfbbOptions > 0)
3000 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3001 numberOfbbOptions = 0;
3002 if (opts.find("natwidth") != opts.end())
3003 numberOfbbOptions++;
3004 if (opts.find("natheight") != opts.end())
3005 numberOfbbOptions++;
3006 if (numberOfbbOptions == 2)
3007 os << "\tBoundingBox 0bp 0bp "
3008 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3009 else if (numberOfbbOptions > 0)
3010 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3011 ostringstream special;
3012 if (opts.find("hiresbb") != opts.end())
3013 special << "hiresbb,";
3014 if (opts.find("trim") != opts.end())
3016 if (opts.find("viewport") != opts.end())
3017 special << "viewport=" << opts["viewport"] << ',';
3018 if (opts.find("totalheight") != opts.end())
3019 special << "totalheight=" << opts["totalheight"] << ',';
3020 if (opts.find("type") != opts.end())
3021 special << "type=" << opts["type"] << ',';
3022 if (opts.find("ext") != opts.end())
3023 special << "ext=" << opts["ext"] << ',';
3024 if (opts.find("read") != opts.end())
3025 special << "read=" << opts["read"] << ',';
3026 if (opts.find("command") != opts.end())
3027 special << "command=" << opts["command"] << ',';
3028 string s_special = special.str();
3029 if (!s_special.empty()) {
3030 // We had special arguments. Remove the trailing ','.
3031 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3033 // TODO: Handle the unknown settings better.
3034 // Warn about invalid options.
3035 // Check whether some option was given twice.
3037 preamble.registerAutomaticallyLoadedPackage("graphicx");
3040 else if (t.cs() == "footnote" ||
3041 (t.cs() == "thanks" && context.layout->intitle)) {
3043 context.check_layout(os);
3044 begin_inset(os, "Foot\n");
3045 os << "status collapsed\n\n";
3046 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3050 else if (t.cs() == "marginpar") {
3052 context.check_layout(os);
3053 begin_inset(os, "Marginal\n");
3054 os << "status collapsed\n\n";
3055 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3059 else if (t.cs() == "lstinline") {
3061 parse_listings(p, os, context, true);
3064 else if (t.cs() == "ensuremath") {
3066 context.check_layout(os);
3067 string const s = p.verbatim_item();
3068 //FIXME: this never triggers in UTF8
3069 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3072 handle_ert(os, "\\ensuremath{" + s + "}",
3076 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3077 if (preamble.titleLayoutFound()) {
3079 skip_spaces_braces(p);
3081 handle_ert(os, t.asInput(), context);
3084 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3085 context.check_layout(os);
3086 begin_command_inset(os, "toc", t.cs());
3088 skip_spaces_braces(p);
3089 if (t.cs() == "lstlistoflistings")
3090 preamble.registerAutomaticallyLoadedPackage("listings");
3093 else if (t.cs() == "listoffigures") {
3094 context.check_layout(os);
3095 begin_inset(os, "FloatList figure\n");
3097 skip_spaces_braces(p);
3100 else if (t.cs() == "listoftables") {
3101 context.check_layout(os);
3102 begin_inset(os, "FloatList table\n");
3104 skip_spaces_braces(p);
3107 else if (t.cs() == "listof") {
3108 p.skip_spaces(true);
3109 string const name = p.get_token().cs();
3110 if (context.textclass.floats().typeExist(name)) {
3111 context.check_layout(os);
3112 begin_inset(os, "FloatList ");
3115 p.get_token(); // swallow second arg
3117 handle_ert(os, "\\listof{" + name + "}", context);
3120 else if ((where = is_known(t.cs(), known_text_font_families)))
3121 parse_text_attributes(p, os, FLAG_ITEM, outer,
3122 context, "\\family", context.font.family,
3123 known_coded_font_families[where - known_text_font_families]);
3125 else if ((where = is_known(t.cs(), known_text_font_series)))
3126 parse_text_attributes(p, os, FLAG_ITEM, outer,
3127 context, "\\series", context.font.series,
3128 known_coded_font_series[where - known_text_font_series]);
3130 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3131 parse_text_attributes(p, os, FLAG_ITEM, outer,
3132 context, "\\shape", context.font.shape,
3133 known_coded_font_shapes[where - known_text_font_shapes]);
3135 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3136 context.check_layout(os);
3137 TeXFont oldFont = context.font;
3138 context.font.init();
3139 context.font.size = oldFont.size;
3140 os << "\n\\family " << context.font.family << "\n";
3141 os << "\n\\series " << context.font.series << "\n";
3142 os << "\n\\shape " << context.font.shape << "\n";
3143 if (t.cs() == "textnormal") {
3144 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3145 output_font_change(os, context.font, oldFont);
3146 context.font = oldFont;
3148 eat_whitespace(p, os, context, false);
3151 else if (t.cs() == "textcolor") {
3152 // scheme is \textcolor{color name}{text}
3153 string const color = p.verbatim_item();
3154 // we only support the predefined colors of the color package
3155 if (color == "black" || color == "blue" || color == "cyan"
3156 || color == "green" || color == "magenta" || color == "red"
3157 || color == "white" || color == "yellow") {
3158 context.check_layout(os);
3159 os << "\n\\color " << color << "\n";
3160 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3161 context.check_layout(os);
3162 os << "\n\\color inherit\n";
3163 preamble.registerAutomaticallyLoadedPackage("color");
3165 // for custom defined colors
3166 handle_ert(os, t.asInput() + "{" + color + "}", context);
3169 else if (t.cs() == "underbar" || t.cs() == "uline") {
3170 // \underbar is not 100% correct (LyX outputs \uline
3171 // of ulem.sty). The difference is that \ulem allows
3172 // line breaks, and \underbar does not.
3173 // Do NOT handle \underline.
3174 // \underbar cuts through y, g, q, p etc.,
3175 // \underline does not.
3176 context.check_layout(os);
3177 os << "\n\\bar under\n";
3178 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3179 context.check_layout(os);
3180 os << "\n\\bar default\n";
3181 preamble.registerAutomaticallyLoadedPackage("ulem");
3184 else if (t.cs() == "sout") {
3185 context.check_layout(os);
3186 os << "\n\\strikeout on\n";
3187 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3188 context.check_layout(os);
3189 os << "\n\\strikeout default\n";
3190 preamble.registerAutomaticallyLoadedPackage("ulem");
3193 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3194 t.cs() == "emph" || t.cs() == "noun") {
3195 context.check_layout(os);
3196 os << "\n\\" << t.cs() << " on\n";
3197 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3198 context.check_layout(os);
3199 os << "\n\\" << t.cs() << " default\n";
3200 if (t.cs() == "uuline" || t.cs() == "uwave")
3201 preamble.registerAutomaticallyLoadedPackage("ulem");
3204 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3205 context.check_layout(os);
3206 string name = p.getArg('{', '}');
3207 string localtime = p.getArg('{', '}');
3208 preamble.registerAuthor(name);
3209 Author const & author = preamble.getAuthor(name);
3210 // from_asctime_utc() will fail if LyX decides to output the
3211 // time in the text language.
3212 time_t ptime = from_asctime_utc(localtime);
3213 if (ptime == static_cast<time_t>(-1)) {
3214 cerr << "Warning: Could not parse time `" << localtime
3215 << "´ for change tracking, using current time instead.\n";
3216 ptime = current_time();
3218 if (t.cs() == "lyxadded")
3219 os << "\n\\change_inserted ";
3221 os << "\n\\change_deleted ";
3222 os << author.bufferId() << ' ' << ptime << '\n';
3223 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3224 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3225 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3226 LaTeXPackages::isAvailable("xcolor");
3227 // No need to test for luatex, since luatex comes in
3228 // two flavours (dvi and pdf), like latex, and those
3229 // are detected by pdflatex.
3230 if (pdflatex || xetex) {
3232 preamble.registerAutomaticallyLoadedPackage("ulem");
3233 preamble.registerAutomaticallyLoadedPackage("xcolor");
3234 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3238 preamble.registerAutomaticallyLoadedPackage("dvipost");
3239 } else if (xcolorulem) {
3240 preamble.registerAutomaticallyLoadedPackage("ulem");
3241 preamble.registerAutomaticallyLoadedPackage("xcolor");
3246 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3247 t.cs() == "vphantom") {
3248 context.check_layout(os);
3249 if (t.cs() == "phantom")
3250 begin_inset(os, "Phantom Phantom\n");
3251 if (t.cs() == "hphantom")
3252 begin_inset(os, "Phantom HPhantom\n");
3253 if (t.cs() == "vphantom")
3254 begin_inset(os, "Phantom VPhantom\n");
3255 os << "status open\n";
3256 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3261 else if (t.cs() == "href") {
3262 context.check_layout(os);
3263 string target = convert_command_inset_arg(p.verbatim_item());
3264 string name = convert_command_inset_arg(p.verbatim_item());
3266 size_t i = target.find(':');
3267 if (i != string::npos) {
3268 type = target.substr(0, i + 1);
3269 if (type == "mailto:" || type == "file:")
3270 target = target.substr(i + 1);
3271 // handle the case that name is equal to target, except of "http://"
3272 else if (target.substr(i + 3) == name && type == "http:")
3275 begin_command_inset(os, "href", "href");
3277 os << "name \"" << name << "\"\n";
3278 os << "target \"" << target << "\"\n";
3279 if (type == "mailto:" || type == "file:")
3280 os << "type \"" << type << "\"\n";
3282 skip_spaces_braces(p);
3285 else if (t.cs() == "lyxline") {
3286 // swallow size argument (it is not used anyway)
3288 if (!context.atParagraphStart()) {
3289 // so our line is in the middle of a paragraph
3290 // we need to add a new line, lest this line
3291 // follow the other content on that line and
3292 // run off the side of the page
3293 // FIXME: This may create an empty paragraph,
3294 // but without that it would not be
3295 // possible to set noindent below.
3296 // Fortunately LaTeX does not care
3297 // about the empty paragraph.
3298 context.new_paragraph(os);
3300 if (preamble.indentParagraphs()) {
3301 // we need to unindent, lest the line be too long
3302 context.add_par_extra_stuff("\\noindent\n");
3304 context.check_layout(os);
3305 begin_command_inset(os, "line", "rule");
3306 os << "offset \"0.5ex\"\n"
3307 "width \"100line%\"\n"
3312 else if (t.cs() == "rule") {
3313 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3314 string const width = p.getArg('{', '}');
3315 string const thickness = p.getArg('{', '}');
3316 context.check_layout(os);
3317 begin_command_inset(os, "line", "rule");
3318 if (!offset.empty())
3319 os << "offset \"" << translate_len(offset) << "\"\n";
3320 os << "width \"" << translate_len(width) << "\"\n"
3321 "height \"" << translate_len(thickness) << "\"\n";
3325 else if (is_known(t.cs(), known_phrases) ||
3326 (t.cs() == "protect" &&
3327 p.next_token().cat() == catEscape &&
3328 is_known(p.next_token().cs(), known_phrases))) {
3329 // LyX sometimes puts a \protect in front, so we have to ignore it
3330 // FIXME: This needs to be changed when bug 4752 is fixed.
3332 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3334 context.check_layout(os);
3335 os << known_coded_phrases[where - known_phrases];
3336 skip_spaces_braces(p);
3339 else if ((where = is_known(t.cs(), known_ref_commands))) {
3340 string const opt = p.getOpt();
3342 context.check_layout(os);
3343 begin_command_inset(os, "ref",
3344 known_coded_ref_commands[where - known_ref_commands]);
3345 os << "reference \""
3346 << convert_command_inset_arg(p.verbatim_item())
3349 if (t.cs() == "vref" || t.cs() == "vpageref")
3350 preamble.registerAutomaticallyLoadedPackage("varioref");
3353 // LyX does not support optional arguments of ref commands
3354 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3355 p.verbatim_item() + "}", context);
3359 else if (use_natbib &&
3360 is_known(t.cs(), known_natbib_commands) &&
3361 ((t.cs() != "citefullauthor" &&
3362 t.cs() != "citeyear" &&
3363 t.cs() != "citeyearpar") ||
3364 p.next_token().asInput() != "*")) {
3365 context.check_layout(os);
3366 string command = t.cs();
3367 if (p.next_token().asInput() == "*") {
3371 if (command == "citefullauthor")
3372 // alternative name for "\\citeauthor*"
3373 command = "citeauthor*";
3375 // text before the citation
3377 // text after the citation
3379 get_cite_arguments(p, true, before, after);
3381 if (command == "cite") {
3382 // \cite without optional argument means
3383 // \citet, \cite with at least one optional
3384 // argument means \citep.
3385 if (before.empty() && after.empty())
3390 if (before.empty() && after == "[]")
3391 // avoid \citet[]{a}
3393 else if (before == "[]" && after == "[]") {
3394 // avoid \citet[][]{a}
3398 // remove the brackets around after and before
3399 if (!after.empty()) {
3401 after.erase(after.length() - 1, 1);
3402 after = convert_command_inset_arg(after);
3404 if (!before.empty()) {
3406 before.erase(before.length() - 1, 1);
3407 before = convert_command_inset_arg(before);
3409 begin_command_inset(os, "citation", command);
3410 os << "after " << '"' << after << '"' << "\n";
3411 os << "before " << '"' << before << '"' << "\n";
3413 << convert_command_inset_arg(p.verbatim_item())
3416 // Need to set the cite engine if natbib is loaded by
3417 // the document class directly
3418 if (preamble.citeEngine() == "basic")
3419 preamble.citeEngine("natbib");
3422 else if (use_jurabib &&
3423 is_known(t.cs(), known_jurabib_commands) &&
3424 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3425 context.check_layout(os);
3426 string command = t.cs();
3427 if (p.next_token().asInput() == "*") {
3431 char argumentOrder = '\0';
3432 vector<string> const options =
3433 preamble.getPackageOptions("jurabib");
3434 if (find(options.begin(), options.end(),
3435 "natbiborder") != options.end())
3436 argumentOrder = 'n';
3437 else if (find(options.begin(), options.end(),
3438 "jurabiborder") != options.end())
3439 argumentOrder = 'j';
3441 // text before the citation
3443 // text after the citation
3445 get_cite_arguments(p, argumentOrder != 'j', before, after);
3447 string const citation = p.verbatim_item();
3448 if (!before.empty() && argumentOrder == '\0') {
3449 cerr << "Warning: Assuming argument order "
3450 "of jurabib version 0.6 for\n'"
3451 << command << before << after << '{'
3452 << citation << "}'.\n"
3453 "Add 'jurabiborder' to the jurabib "
3454 "package options if you used an\n"
3455 "earlier jurabib version." << endl;
3457 if (!after.empty()) {
3459 after.erase(after.length() - 1, 1);
3461 if (!before.empty()) {
3463 before.erase(before.length() - 1, 1);
3465 begin_command_inset(os, "citation", command);
3466 os << "after " << '"' << after << '"' << "\n";
3467 os << "before " << '"' << before << '"' << "\n";
3468 os << "key " << '"' << citation << '"' << "\n";
3470 // Need to set the cite engine if jurabib is loaded by
3471 // the document class directly
3472 if (preamble.citeEngine() == "basic")
3473 preamble.citeEngine("jurabib");
3476 else if (t.cs() == "cite"
3477 || t.cs() == "nocite") {
3478 context.check_layout(os);
3479 string after = convert_command_inset_arg(p.getArg('[', ']'));
3480 string key = convert_command_inset_arg(p.verbatim_item());
3481 // store the case that it is "\nocite{*}" to use it later for
3484 begin_command_inset(os, "citation", t.cs());
3485 os << "after " << '"' << after << '"' << "\n";
3486 os << "key " << '"' << key << '"' << "\n";
3488 } else if (t.cs() == "nocite")
3492 else if (t.cs() == "index" ||
3493 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3494 context.check_layout(os);
3495 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3496 p.getArg('[', ']') : "";
3497 string const kind = arg.empty() ? "idx" : arg;
3498 begin_inset(os, "Index ");
3499 os << kind << "\nstatus collapsed\n";
3500 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3503 preamble.registerAutomaticallyLoadedPackage("splitidx");
3506 else if (t.cs() == "nomenclature") {
3507 context.check_layout(os);
3508 begin_command_inset(os, "nomenclature", "nomenclature");
3509 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3510 if (!prefix.empty())
3511 os << "prefix " << '"' << prefix << '"' << "\n";
3512 os << "symbol " << '"'
3513 << convert_command_inset_arg(p.verbatim_item());
3514 os << "\"\ndescription \""
3515 << convert_command_inset_arg(p.verbatim_item())
3518 preamble.registerAutomaticallyLoadedPackage("nomencl");
3521 else if (t.cs() == "label") {
3522 context.check_layout(os);
3523 begin_command_inset(os, "label", "label");
3525 << convert_command_inset_arg(p.verbatim_item())
3530 else if (t.cs() == "printindex") {
3531 context.check_layout(os);
3532 begin_command_inset(os, "index_print", "printindex");
3533 os << "type \"idx\"\n";
3535 skip_spaces_braces(p);
3536 preamble.registerAutomaticallyLoadedPackage("makeidx");
3537 if (preamble.use_indices() == "true")
3538 preamble.registerAutomaticallyLoadedPackage("splitidx");
3541 else if (t.cs() == "printnomenclature") {
3543 string width_type = "";
3544 context.check_layout(os);
3545 begin_command_inset(os, "nomencl_print", "printnomenclature");
3546 // case of a custom width
3548 width = p.getArg('[', ']');
3549 width = translate_len(width);
3550 width_type = "custom";
3552 // case of no custom width
3553 // the case of no custom width but the width set
3554 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3555 // because the user could have set anything, not only the width
3556 // of the longest label (which would be width_type = "auto")
3557 string label = convert_command_inset_arg(p.getArg('{', '}'));
3558 if (label.empty() && width_type.empty())
3559 width_type = "none";
3560 os << "set_width \"" << width_type << "\"\n";
3561 if (width_type == "custom")
3562 os << "width \"" << width << '\"';
3564 skip_spaces_braces(p);
3565 preamble.registerAutomaticallyLoadedPackage("nomencl");
3568 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3569 context.check_layout(os);
3570 begin_inset(os, "script ");
3571 os << t.cs().substr(4) << '\n';
3572 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3574 if (t.cs() == "textsubscript")
3575 preamble.registerAutomaticallyLoadedPackage("subscript");
3578 else if ((where = is_known(t.cs(), known_quotes))) {
3579 context.check_layout(os);
3580 begin_inset(os, "Quotes ");
3581 os << known_coded_quotes[where - known_quotes];
3583 // LyX adds {} after the quote, so we have to eat
3584 // spaces here if there are any before a possible
3586 eat_whitespace(p, os, context, false);
3590 else if ((where = is_known(t.cs(), known_sizes)) &&
3591 context.new_layout_allowed) {
3592 context.check_layout(os);
3593 TeXFont const oldFont = context.font;
3594 context.font.size = known_coded_sizes[where - known_sizes];
3595 output_font_change(os, oldFont, context.font);
3596 eat_whitespace(p, os, context, false);
3599 else if ((where = is_known(t.cs(), known_font_families)) &&
3600 context.new_layout_allowed) {
3601 context.check_layout(os);
3602 TeXFont const oldFont = context.font;
3603 context.font.family =
3604 known_coded_font_families[where - known_font_families];
3605 output_font_change(os, oldFont, context.font);
3606 eat_whitespace(p, os, context, false);
3609 else if ((where = is_known(t.cs(), known_font_series)) &&
3610 context.new_layout_allowed) {
3611 context.check_layout(os);
3612 TeXFont const oldFont = context.font;
3613 context.font.series =
3614 known_coded_font_series[where - known_font_series];
3615 output_font_change(os, oldFont, context.font);
3616 eat_whitespace(p, os, context, false);
3619 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3620 context.new_layout_allowed) {
3621 context.check_layout(os);
3622 TeXFont const oldFont = context.font;
3623 context.font.shape =
3624 known_coded_font_shapes[where - known_font_shapes];
3625 output_font_change(os, oldFont, context.font);
3626 eat_whitespace(p, os, context, false);
3628 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3629 context.new_layout_allowed) {
3630 context.check_layout(os);
3631 TeXFont const oldFont = context.font;
3632 context.font.init();
3633 context.font.size = oldFont.size;
3634 context.font.family =
3635 known_coded_font_families[where - known_old_font_families];
3636 output_font_change(os, oldFont, context.font);
3637 eat_whitespace(p, os, context, false);
3640 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3641 context.new_layout_allowed) {
3642 context.check_layout(os);
3643 TeXFont const oldFont = context.font;
3644 context.font.init();
3645 context.font.size = oldFont.size;
3646 context.font.series =
3647 known_coded_font_series[where - known_old_font_series];
3648 output_font_change(os, oldFont, context.font);
3649 eat_whitespace(p, os, context, false);
3652 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3653 context.new_layout_allowed) {
3654 context.check_layout(os);
3655 TeXFont const oldFont = context.font;
3656 context.font.init();
3657 context.font.size = oldFont.size;
3658 context.font.shape =
3659 known_coded_font_shapes[where - known_old_font_shapes];
3660 output_font_change(os, oldFont, context.font);
3661 eat_whitespace(p, os, context, false);
3664 else if (t.cs() == "selectlanguage") {
3665 context.check_layout(os);
3666 // save the language for the case that a
3667 // \foreignlanguage is used
3668 context.font.language = babel2lyx(p.verbatim_item());
3669 os << "\n\\lang " << context.font.language << "\n";
3672 else if (t.cs() == "foreignlanguage") {
3673 string const lang = babel2lyx(p.verbatim_item());
3674 parse_text_attributes(p, os, FLAG_ITEM, outer,
3676 context.font.language, lang);
3679 else if (prefixIs(t.cs(), "text")
3680 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3681 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3683 // We have to output the whole command if it has an option
3684 // because LyX doesn't support this yet, see bug #8214,
3685 // only if there is a single option specifying a variant, we can handle it.
3687 string langopts = p.getOpt();
3688 // check if the option contains a variant, if yes, extract it
3689 string::size_type pos_var = langopts.find("variant");
3690 string::size_type i = langopts.find(',');
3691 string::size_type k = langopts.find('=', pos_var);
3692 if (pos_var != string::npos && i == string::npos) {
3694 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3695 lang = preamble.polyglossia2lyx(variant);
3696 parse_text_attributes(p, os, FLAG_ITEM, outer,
3698 context.font.language, lang);
3700 handle_ert(os, t.asInput() + langopts, context);
3702 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3703 parse_text_attributes(p, os, FLAG_ITEM, outer,
3705 context.font.language, lang);
3709 else if (t.cs() == "inputencoding") {
3710 // nothing to write here
3711 string const enc = subst(p.verbatim_item(), "\n", " ");
3712 p.setEncoding(enc, Encoding::inputenc);
3715 else if ((where = is_known(t.cs(), known_special_chars))) {
3716 context.check_layout(os);
3717 os << "\\SpecialChar \\"
3718 << known_coded_special_chars[where - known_special_chars]
3720 skip_spaces_braces(p);
3723 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3724 context.check_layout(os);
3725 os << "\\SpecialChar \\nobreakdash-\n";
3729 else if (t.cs() == "textquotedbl") {
3730 context.check_layout(os);
3735 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3736 context.check_layout(os);
3737 os << "\\SpecialChar \\@.\n";
3741 else if (t.cs() == "-") {
3742 context.check_layout(os);
3743 os << "\\SpecialChar \\-\n";
3746 else if (t.cs() == "textasciitilde") {
3747 context.check_layout(os);
3749 skip_spaces_braces(p);
3752 else if (t.cs() == "textasciicircum") {
3753 context.check_layout(os);
3755 skip_spaces_braces(p);
3758 else if (t.cs() == "textbackslash") {
3759 context.check_layout(os);
3760 os << "\n\\backslash\n";
3761 skip_spaces_braces(p);
3764 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3765 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3767 context.check_layout(os);
3771 else if (t.cs() == "char") {
3772 context.check_layout(os);
3773 if (p.next_token().character() == '`') {
3775 if (p.next_token().cs() == "\"") {
3780 handle_ert(os, "\\char`", context);
3783 handle_ert(os, "\\char", context);
3787 else if (t.cs() == "verb") {
3788 context.check_layout(os);
3789 char const delimiter = p.next_token().character();
3790 // \verb is special: The usual escaping rules do not
3791 // apply, e.g. "\verb+\+" is valid and denotes a single
3792 // backslash (bug #4468). Therefore we do not allow
3793 // escaping in getArg().
3794 string const arg = p.getArg(delimiter, delimiter, false);
3796 oss << "\\verb" << delimiter << arg << delimiter;
3797 handle_ert(os, oss.str(), context);
3800 // Problem: \= creates a tabstop inside the tabbing environment
3801 // and else an accent. In the latter case we really would want
3802 // \={o} instead of \= o.
3803 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3804 handle_ert(os, t.asInput(), context);
3806 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3807 else if (t.cs().size() == 1
3808 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3809 context.check_layout(os);
3810 // try to see whether the string is in unicodesymbols
3813 string command = t.asInput() + "{"
3814 + trimSpaceAndEol(p.verbatim_item())
3817 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3818 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3819 termination, rem, &req);
3822 cerr << "When parsing " << command
3823 << ", result is " << to_utf8(s)
3824 << "+" << to_utf8(rem) << endl;
3826 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3827 preamble.registerAutomaticallyLoadedPackage(*it);
3829 // we did not find a non-ert version
3830 handle_ert(os, command, context);
3833 else if (t.cs() == "\\") {
3834 context.check_layout(os);
3836 handle_ert(os, "\\\\" + p.getOpt(), context);
3837 else if (p.next_token().asInput() == "*") {
3839 // getOpt() eats the following space if there
3840 // is no optional argument, but that is OK
3841 // here since it has no effect in the output.
3842 handle_ert(os, "\\\\*" + p.getOpt(), context);
3845 begin_inset(os, "Newline newline");
3850 else if (t.cs() == "newline" ||
3851 (t.cs() == "linebreak" && !p.hasOpt())) {
3852 context.check_layout(os);
3853 begin_inset(os, "Newline ");
3856 skip_spaces_braces(p);
3859 else if (t.cs() == "input" || t.cs() == "include"
3860 || t.cs() == "verbatiminput") {
3861 string name = t.cs();
3862 if (t.cs() == "verbatiminput"
3863 && p.next_token().asInput() == "*")
3864 name += p.get_token().asInput();
3865 context.check_layout(os);
3866 string filename(normalize_filename(p.getArg('{', '}')));
3867 string const path = getMasterFilePath(true);
3868 // We want to preserve relative / absolute filenames,
3869 // therefore path is only used for testing
3870 if ((t.cs() == "include" || t.cs() == "input") &&
3871 !makeAbsPath(filename, path).exists()) {
3872 // The file extension is probably missing.
3873 // Now try to find it out.
3874 string const tex_name =
3875 find_file(filename, path,
3876 known_tex_extensions);
3877 if (!tex_name.empty())
3878 filename = tex_name;
3880 bool external = false;
3882 if (makeAbsPath(filename, path).exists()) {
3883 string const abstexname =
3884 makeAbsPath(filename, path).absFileName();
3885 string const absfigname =
3886 changeExtension(abstexname, ".fig");
3887 fix_child_filename(filename);
3888 string const lyxname =
3889 changeExtension(filename, ".lyx");
3890 string const abslyxname = makeAbsPath(
3891 lyxname, getParentFilePath(false)).absFileName();
3893 if (!skipChildren())
3894 external = FileName(absfigname).exists();
3895 if (t.cs() == "input" && !skipChildren()) {
3896 string const ext = getExtension(abstexname);
3898 // Combined PS/LaTeX:
3899 // x.eps, x.pstex_t (old xfig)
3900 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3901 FileName const absepsname(
3902 changeExtension(abstexname, ".eps"));
3903 FileName const abspstexname(
3904 changeExtension(abstexname, ".pstex"));
3905 bool const xfigeps =
3906 (absepsname.exists() ||
3907 abspstexname.exists()) &&
3910 // Combined PDF/LaTeX:
3911 // x.pdf, x.pdftex_t (old xfig)
3912 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3913 FileName const abspdfname(
3914 changeExtension(abstexname, ".pdf"));
3915 bool const xfigpdf =
3916 abspdfname.exists() &&
3917 (ext == "pdftex_t" || ext == "pdf_t");
3921 // Combined PS/PDF/LaTeX:
3922 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3923 string const absbase2(
3924 removeExtension(abstexname) + "_pspdftex");
3925 FileName const abseps2name(
3926 addExtension(absbase2, ".eps"));
3927 FileName const abspdf2name(
3928 addExtension(absbase2, ".pdf"));
3929 bool const xfigboth =
3930 abspdf2name.exists() &&
3931 abseps2name.exists() && ext == "pspdftex";
3933 xfig = xfigpdf || xfigeps || xfigboth;
3934 external = external && xfig;
3937 outname = changeExtension(filename, ".fig");
3938 FileName abssrc(changeExtension(abstexname, ".fig"));
3939 copy_file(abssrc, outname);
3941 // Don't try to convert, the result
3942 // would be full of ERT.
3944 FileName abssrc(abstexname);
3945 copy_file(abssrc, outname);
3946 } else if (t.cs() != "verbatiminput" &&
3948 tex2lyx(abstexname, FileName(abslyxname),
3951 // no need to call copy_file
3952 // tex2lyx creates the file
3955 FileName abssrc(abstexname);
3956 copy_file(abssrc, outname);
3959 cerr << "Warning: Could not find included file '"
3960 << filename << "'." << endl;
3964 begin_inset(os, "External\n");
3965 os << "\ttemplate XFig\n"
3966 << "\tfilename " << outname << '\n';
3967 registerExternalTemplatePackages("XFig");
3969 begin_command_inset(os, "include", name);
3970 outname = subst(outname, "\"", "\\\"");
3971 os << "preview false\n"
3972 "filename \"" << outname << "\"\n";
3973 if (t.cs() == "verbatiminput")
3974 preamble.registerAutomaticallyLoadedPackage("verbatim");
3979 else if (t.cs() == "bibliographystyle") {
3980 // store new bibliographystyle
3981 bibliographystyle = p.verbatim_item();
3982 // If any other command than \bibliography and
3983 // \nocite{*} follows, we need to output the style
3984 // (because it might be used by that command).
3985 // Otherwise, it will automatically be output by LyX.
3988 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3989 if (t2.cat() == catBegin)
3991 if (t2.cat() != catEscape)
3993 if (t2.cs() == "nocite") {
3994 if (p.getArg('{', '}') == "*")
3996 } else if (t2.cs() == "bibliography")
4003 "\\bibliographystyle{" + bibliographystyle + '}',
4008 else if (t.cs() == "bibliography") {
4009 context.check_layout(os);
4010 begin_command_inset(os, "bibtex", "bibtex");
4011 if (!btprint.empty()) {
4012 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4013 // clear the string because the next BibTeX inset can be without the
4014 // \nocite{*} option
4017 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4018 // Do we have a bibliographystyle set?
4019 if (!bibliographystyle.empty())
4020 os << "options " << '"' << bibliographystyle << '"' << "\n";
4024 else if (t.cs() == "parbox") {
4025 // Test whether this is an outer box of a shaded box
4027 // swallow arguments
4028 while (p.hasOpt()) {
4030 p.skip_spaces(true);
4033 p.skip_spaces(true);
4035 if (p.next_token().cat() == catBegin)
4037 p.skip_spaces(true);
4038 Token to = p.get_token();
4039 bool shaded = false;
4040 if (to.asInput() == "\\begin") {
4041 p.skip_spaces(true);
4042 if (p.getArg('{', '}') == "shaded")
4047 parse_outer_box(p, os, FLAG_ITEM, outer,
4048 context, "parbox", "shaded");
4050 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4054 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4055 t.cs() == "shadowbox" || t.cs() == "doublebox")
4056 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4058 else if (t.cs() == "framebox") {
4059 if (p.next_token().character() == '(') {
4060 //the syntax is: \framebox(x,y)[position]{content}
4061 string arg = t.asInput();
4062 arg += p.getFullParentheseArg();
4063 arg += p.getFullOpt();
4064 eat_whitespace(p, os, context, false);
4065 handle_ert(os, arg + '{', context);
4066 parse_text(p, os, FLAG_ITEM, outer, context);
4067 handle_ert(os, "}", context);
4069 string special = p.getFullOpt();
4070 special += p.getOpt();
4071 // LyX does not yet support \framebox without any option
4072 if (!special.empty())
4073 parse_outer_box(p, os, FLAG_ITEM, outer,
4074 context, t.cs(), special);
4076 eat_whitespace(p, os, context, false);
4077 handle_ert(os, "\\framebox{", context);
4078 parse_text(p, os, FLAG_ITEM, outer, context);
4079 handle_ert(os, "}", context);
4084 //\makebox() is part of the picture environment and different from \makebox{}
4085 //\makebox{} will be parsed by parse_box
4086 else if (t.cs() == "makebox") {
4087 if (p.next_token().character() == '(') {
4088 //the syntax is: \makebox(x,y)[position]{content}
4089 string arg = t.asInput();
4090 arg += p.getFullParentheseArg();
4091 arg += p.getFullOpt();
4092 eat_whitespace(p, os, context, false);
4093 handle_ert(os, arg + '{', context);
4094 parse_text(p, os, FLAG_ITEM, outer, context);
4095 handle_ert(os, "}", context);
4097 //the syntax is: \makebox[width][position]{content}
4098 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4102 else if (t.cs() == "smallskip" ||
4103 t.cs() == "medskip" ||
4104 t.cs() == "bigskip" ||
4105 t.cs() == "vfill") {
4106 context.check_layout(os);
4107 begin_inset(os, "VSpace ");
4110 skip_spaces_braces(p);
4113 else if ((where = is_known(t.cs(), known_spaces))) {
4114 context.check_layout(os);
4115 begin_inset(os, "space ");
4116 os << '\\' << known_coded_spaces[where - known_spaces]
4119 // LaTeX swallows whitespace after all spaces except
4120 // "\\,". We have to do that here, too, because LyX
4121 // adds "{}" which would make the spaces significant.
4123 eat_whitespace(p, os, context, false);
4124 // LyX adds "{}" after all spaces except "\\ " and
4125 // "\\,", so we have to remove "{}".
4126 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4127 // remove the braces after "\\,", too.
4132 else if (t.cs() == "newpage" ||
4133 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4134 t.cs() == "clearpage" ||
4135 t.cs() == "cleardoublepage") {
4136 context.check_layout(os);
4137 begin_inset(os, "Newpage ");
4140 skip_spaces_braces(p);
4143 else if (t.cs() == "DeclareRobustCommand" ||
4144 t.cs() == "DeclareRobustCommandx" ||
4145 t.cs() == "newcommand" ||
4146 t.cs() == "newcommandx" ||
4147 t.cs() == "providecommand" ||
4148 t.cs() == "providecommandx" ||
4149 t.cs() == "renewcommand" ||
4150 t.cs() == "renewcommandx") {
4151 // DeclareRobustCommand, DeclareRobustCommandx,
4152 // providecommand and providecommandx could be handled
4153 // by parse_command(), but we need to call
4154 // add_known_command() here.
4155 string name = t.asInput();
4156 if (p.next_token().asInput() == "*") {
4157 // Starred form. Eat '*'
4161 string const command = p.verbatim_item();
4162 string const opt1 = p.getFullOpt();
4163 string const opt2 = p.getFullOpt();
4164 add_known_command(command, opt1, !opt2.empty());
4165 string const ert = name + '{' + command + '}' +
4167 '{' + p.verbatim_item() + '}';
4169 if (t.cs() == "DeclareRobustCommand" ||
4170 t.cs() == "DeclareRobustCommandx" ||
4171 t.cs() == "providecommand" ||
4172 t.cs() == "providecommandx" ||
4173 name[name.length()-1] == '*')
4174 handle_ert(os, ert, context);
4176 context.check_layout(os);
4177 begin_inset(os, "FormulaMacro");
4183 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4184 // let could be handled by parse_command(),
4185 // but we need to call add_known_command() here.
4186 string ert = t.asInput();
4189 if (p.next_token().cat() == catBegin) {
4190 name = p.verbatim_item();
4191 ert += '{' + name + '}';
4193 name = p.verbatim_item();
4198 if (p.next_token().cat() == catBegin) {
4199 command = p.verbatim_item();
4200 ert += '{' + command + '}';
4202 command = p.verbatim_item();
4205 // If command is known, make name known too, to parse
4206 // its arguments correctly. For this reason we also
4207 // have commands in syntax.default that are hardcoded.
4208 CommandMap::iterator it = known_commands.find(command);
4209 if (it != known_commands.end())
4210 known_commands[t.asInput()] = it->second;
4211 handle_ert(os, ert, context);
4214 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4215 bool starred = false;
4216 if (p.next_token().asInput() == "*") {
4220 string name = t.asInput();
4221 string const length = p.verbatim_item();
4224 bool valid = splitLatexLength(length, valstring, unit);
4225 bool known_hspace = false;
4226 bool known_vspace = false;
4227 bool known_unit = false;
4230 istringstream iss(valstring);
4233 if (t.cs()[0] == 'h') {
4234 if (unit == "\\fill") {
4239 known_hspace = true;
4242 if (unit == "\\smallskipamount") {
4244 known_vspace = true;
4245 } else if (unit == "\\medskipamount") {
4247 known_vspace = true;
4248 } else if (unit == "\\bigskipamount") {
4250 known_vspace = true;
4251 } else if (unit == "\\fill") {
4253 known_vspace = true;
4257 if (!known_hspace && !known_vspace) {
4258 switch (unitFromString(unit)) {
4279 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4280 // Literal horizontal length or known variable
4281 context.check_layout(os);
4282 begin_inset(os, "space ");
4290 if (known_unit && !known_hspace)
4292 << translate_len(length);
4294 } else if (known_unit || known_vspace) {
4295 // Literal vertical length or known variable
4296 context.check_layout(os);
4297 begin_inset(os, "VSpace ");
4305 // LyX can't handle other length variables in Inset VSpace/space
4310 handle_ert(os, name + '{' + unit + '}', context);
4311 else if (value == -1.0)
4312 handle_ert(os, name + "{-" + unit + '}', context);
4314 handle_ert(os, name + '{' + valstring + unit + '}', context);
4316 handle_ert(os, name + '{' + length + '}', context);
4320 // The single '=' is meant here.
4321 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4323 context.check_layout(os);
4324 begin_inset(os, "Flex ");
4325 os << to_utf8(newinsetlayout->name()) << '\n'
4326 << "status collapsed\n";
4327 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4331 else if (t.cs() == "includepdf") {
4333 string const arg = p.getArg('[', ']');
4334 map<string, string> opts;
4335 vector<string> keys;
4336 split_map(arg, opts, keys);
4337 string name = normalize_filename(p.verbatim_item());
4338 string const path = getMasterFilePath(true);
4339 // We want to preserve relative / absolute filenames,
4340 // therefore path is only used for testing
4341 if (!makeAbsPath(name, path).exists()) {
4342 // The file extension is probably missing.
4343 // Now try to find it out.
4344 char const * const pdfpages_format[] = {"pdf", 0};
4345 string const pdftex_name =
4346 find_file(name, path, pdfpages_format);
4347 if (!pdftex_name.empty()) {
4352 FileName const absname = makeAbsPath(name, path);
4353 if (absname.exists())
4355 fix_child_filename(name);
4356 copy_file(absname, name);
4358 cerr << "Warning: Could not find file '"
4359 << name << "'." << endl;
4361 context.check_layout(os);
4362 begin_inset(os, "External\n\ttemplate ");
4363 os << "PDFPages\n\tfilename "
4365 // parse the options
4366 if (opts.find("pages") != opts.end())
4367 os << "\textra LaTeX \"pages="
4368 << opts["pages"] << "\"\n";
4369 if (opts.find("angle") != opts.end())
4370 os << "\trotateAngle "
4371 << opts["angle"] << '\n';
4372 if (opts.find("origin") != opts.end()) {
4374 string const opt = opts["origin"];
4375 if (opt == "tl") ss << "topleft";
4376 if (opt == "bl") ss << "bottomleft";
4377 if (opt == "Bl") ss << "baselineleft";
4378 if (opt == "c") ss << "center";
4379 if (opt == "tc") ss << "topcenter";
4380 if (opt == "bc") ss << "bottomcenter";
4381 if (opt == "Bc") ss << "baselinecenter";
4382 if (opt == "tr") ss << "topright";
4383 if (opt == "br") ss << "bottomright";
4384 if (opt == "Br") ss << "baselineright";
4385 if (!ss.str().empty())
4386 os << "\trotateOrigin " << ss.str() << '\n';
4388 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4390 if (opts.find("width") != opts.end())
4392 << translate_len(opts["width"]) << '\n';
4393 if (opts.find("height") != opts.end())
4395 << translate_len(opts["height"]) << '\n';
4396 if (opts.find("keepaspectratio") != opts.end())
4397 os << "\tkeepAspectRatio\n";
4399 context.check_layout(os);
4400 registerExternalTemplatePackages("PDFPages");
4403 else if (t.cs() == "loadgame") {
4405 string name = normalize_filename(p.verbatim_item());
4406 string const path = getMasterFilePath(true);
4407 // We want to preserve relative / absolute filenames,
4408 // therefore path is only used for testing
4409 if (!makeAbsPath(name, path).exists()) {
4410 // The file extension is probably missing.
4411 // Now try to find it out.
4412 char const * const lyxskak_format[] = {"fen", 0};
4413 string const lyxskak_name =
4414 find_file(name, path, lyxskak_format);
4415 if (!lyxskak_name.empty())
4416 name = lyxskak_name;
4418 FileName const absname = makeAbsPath(name, path);
4419 if (absname.exists())
4421 fix_child_filename(name);
4422 copy_file(absname, name);
4424 cerr << "Warning: Could not find file '"
4425 << name << "'." << endl;
4426 context.check_layout(os);
4427 begin_inset(os, "External\n\ttemplate ");
4428 os << "ChessDiagram\n\tfilename "
4431 context.check_layout(os);
4432 // after a \loadgame follows a \showboard
4433 if (p.get_token().asInput() == "showboard")
4435 registerExternalTemplatePackages("ChessDiagram");
4439 // try to see whether the string is in unicodesymbols
4440 // Only use text mode commands, since we are in text mode here,
4441 // and math commands may be invalid (bug 6797)
4445 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4446 Encodings::TEXT_CMD, termination, rem, &req);
4449 cerr << "When parsing " << t.cs()
4450 << ", result is " << to_utf8(s)
4451 << "+" << to_utf8(rem) << endl;
4452 context.check_layout(os);
4455 skip_spaces_braces(p);
4456 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4457 preamble.registerAutomaticallyLoadedPackage(*it);
4459 //cerr << "#: " << t << " mode: " << mode << endl;
4460 // heuristic: read up to next non-nested space
4462 string s = t.asInput();
4463 string z = p.verbatim_item();
4464 while (p.good() && z != " " && !z.empty()) {
4465 //cerr << "read: " << z << endl;
4467 z = p.verbatim_item();
4469 cerr << "found ERT: " << s << endl;
4470 handle_ert(os, s + ' ', context);
4473 string name = t.asInput();
4474 if (p.next_token().asInput() == "*") {
4475 // Starred commands like \vspace*{}
4476 p.get_token(); // Eat '*'
4479 if (!parse_command(name, p, os, outer, context))
4480 handle_ert(os, name, context);
4484 if (flags & FLAG_LEAVE) {
4485 flags &= ~FLAG_LEAVE;
4492 string guessLanguage(Parser & p, string const & lang)
4494 typedef std::map<std::string, size_t> LangMap;
4495 // map from language names to number of characters
4498 for (char const * const * i = supported_CJK_languages; *i; i++)
4499 used[string(*i)] = 0;
4502 Token const t = p.get_token();
4503 // comments are not counted for any language
4504 if (t.cat() == catComment)
4506 // commands are not counted as well, but we need to detect
4507 // \begin{CJK} and switch encoding if needed
4508 if (t.cat() == catEscape) {
4509 if (t.cs() == "inputencoding") {
4510 string const enc = subst(p.verbatim_item(), "\n", " ");
4511 p.setEncoding(enc, Encoding::inputenc);
4514 if (t.cs() != "begin")
4517 // Non-CJK content is counted for lang.
4518 // We do not care about the real language here:
4519 // If we have more non-CJK contents than CJK contents,
4520 // we simply use the language that was specified as
4521 // babel main language.
4522 used[lang] += t.asInput().length();
4525 // Now we are starting an environment
4527 string const name = p.getArg('{', '}');
4528 if (name != "CJK") {
4532 // It is a CJK environment
4534 /* name = */ p.getArg('{', '}');
4535 string const encoding = p.getArg('{', '}');
4536 /* mapping = */ p.getArg('{', '}');
4537 string const encoding_old = p.getEncoding();
4538 char const * const * const where =
4539 is_known(encoding, supported_CJK_encodings);
4541 p.setEncoding(encoding, Encoding::CJK);
4543 p.setEncoding("UTF-8");
4544 string const text = p.verbatimEnvironment("CJK");
4545 p.setEncoding(encoding_old);
4548 // ignore contents in unknown CJK encoding
4551 // the language of the text
4553 supported_CJK_languages[where - supported_CJK_encodings];
4554 used[cjk] += text.length();
4556 LangMap::const_iterator use = used.begin();
4557 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4558 if (it->second > use->second)