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 };
120 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
121 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
122 "secref", "subref", "tabref", "thmref", 0 };
124 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
125 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
126 "sec", "sub", "tab", "thm", 0 };
130 * supported CJK encodings
131 * JIS does not work with LyX's encoding conversion
133 const char * const supported_CJK_encodings[] = {
134 "EUC-JP", "KS", "GB", "UTF8",
135 "Bg5", /*"JIS",*/ "SJIS", 0};
138 * the same as supported_CJK_encodings with their corresponding LyX language name
139 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
141 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
142 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
143 * please keep this in sync with supported_CJK_encodings line by line!
145 const char * const supported_CJK_languages[] = {
146 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
147 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
151 * The starred forms are also known except for "citefullauthor",
152 * "citeyear" and "citeyearpar".
154 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
155 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
156 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
160 * No starred form other than "cite*" known.
162 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
163 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
164 // jurabib commands not (yet) supported by LyX:
166 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
167 // "footciteauthor", "footciteyear", "footciteyearpar",
168 "citefield", "citetitle", 0 };
170 /// LaTeX names for quotes
171 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
172 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
173 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
174 "guilsinglleft", "frq", "guilsinglright", 0};
176 /// the same as known_quotes with .lyx names
177 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
178 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
179 "gld", "grd", "gls", "ers", "fls",
180 "fls", "frs", "frs", 0};
182 /// LaTeX names for font sizes
183 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
184 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
186 /// the same as known_sizes with .lyx names
187 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
188 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
190 /// LaTeX 2.09 names for font families
191 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
193 /// LaTeX names for font families
194 char const * const known_font_families[] = { "rmfamily", "sffamily",
197 /// LaTeX names for font family changing commands
198 char const * const known_text_font_families[] = { "textrm", "textsf",
201 /// The same as known_old_font_families, known_font_families and
202 /// known_text_font_families with .lyx names
203 char const * const known_coded_font_families[] = { "roman", "sans",
206 /// LaTeX 2.09 names for font series
207 char const * const known_old_font_series[] = { "bf", 0};
209 /// LaTeX names for font series
210 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
212 /// LaTeX names for font series changing commands
213 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
215 /// The same as known_old_font_series, known_font_series and
216 /// known_text_font_series with .lyx names
217 char const * const known_coded_font_series[] = { "bold", "medium", 0};
219 /// LaTeX 2.09 names for font shapes
220 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
222 /// LaTeX names for font shapes
223 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
226 /// LaTeX names for font shape changing commands
227 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
230 /// The same as known_old_font_shapes, known_font_shapes and
231 /// known_text_font_shapes with .lyx names
232 char const * const known_coded_font_shapes[] = { "italic", "slanted",
233 "smallcaps", "up", 0};
235 /// Known special characters which need skip_spaces_braces() afterwards
236 char const * const known_special_chars[] = {"ldots", "lyxarrow",
237 "textcompwordmark", "slash", 0};
239 /// the same as known_special_chars with .lyx names
240 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
241 "textcompwordmark{}", "slash{}", 0};
244 * Graphics file extensions known by the dvips driver of the graphics package.
245 * These extensions are used to complete the filename of an included
246 * graphics file if it does not contain an extension.
247 * The order must be the same that latex uses to find a file, because we
248 * will use the first extension that matches.
249 * This is only an approximation for the common cases. If we would want to
250 * do it right in all cases, we would need to know which graphics driver is
251 * used and know the extensions of every driver of the graphics package.
253 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
254 "ps.gz", "eps.Z", "ps.Z", 0};
257 * Graphics file extensions known by the pdftex driver of the graphics package.
258 * \sa known_dvips_graphics_formats
260 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
264 * Known file extensions for TeX files as used by \\include.
266 char const * const known_tex_extensions[] = {"tex", 0};
268 /// spaces known by InsetSpace
269 char const * const known_spaces[] = { " ", "space", ",",
270 "thinspace", "quad", "qquad", "enspace", "enskip",
271 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
272 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
273 "upbracefill", "downbracefill", 0};
275 /// the same as known_spaces with .lyx names
276 char const * const known_coded_spaces[] = { "space{}", "space{}",
277 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
278 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
279 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
280 "upbracefill{}", "downbracefill{}", 0};
282 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
283 /// them in ERT. "LaTeXe" must come before "LaTeX"!
284 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
285 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
286 int const known_phrase_lengths[] = {3, 5, 7, 0};
288 // string to store the float type to be able to determine the type of subfloats
289 string float_type = "";
292 /// splits "x=z, y=b" into a map and an ordered keyword vector
293 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
298 keys.resize(v.size());
299 for (size_t i = 0; i < v.size(); ++i) {
300 size_t const pos = v[i].find('=');
301 string const index = trimSpaceAndEol(v[i].substr(0, pos));
302 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
310 * Split a LaTeX length into value and unit.
311 * The latter can be a real unit like "pt", or a latex length variable
312 * like "\textwidth". The unit may contain additional stuff like glue
313 * lengths, but we don't care, because such lengths are ERT anyway.
314 * \returns true if \p value and \p unit are valid.
316 bool splitLatexLength(string const & len, string & value, string & unit)
320 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
321 //'4,5' is a valid LaTeX length number. Change it to '4.5'
322 string const length = subst(len, ',', '.');
323 if (i == string::npos)
326 if (len[0] == '\\') {
327 // We had something like \textwidth without a factor
333 value = trimSpaceAndEol(string(length, 0, i));
337 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
338 if (contains(len, '\\'))
339 unit = trimSpaceAndEol(string(len, i));
341 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
346 /// A simple function to translate a latex length to something LyX can
347 /// understand. Not perfect, but rather best-effort.
348 bool translate_len(string const & length, string & valstring, string & unit)
350 if (!splitLatexLength(length, valstring, unit))
352 // LyX uses percent values
354 istringstream iss(valstring);
359 string const percentval = oss.str();
361 if (unit.empty() || unit[0] != '\\')
363 string::size_type const i = unit.find(' ');
364 string const endlen = (i == string::npos) ? string() : string(unit, i);
365 if (unit == "\\textwidth") {
366 valstring = percentval;
367 unit = "text%" + endlen;
368 } else if (unit == "\\columnwidth") {
369 valstring = percentval;
370 unit = "col%" + endlen;
371 } else if (unit == "\\paperwidth") {
372 valstring = percentval;
373 unit = "page%" + endlen;
374 } else if (unit == "\\linewidth") {
375 valstring = percentval;
376 unit = "line%" + endlen;
377 } else if (unit == "\\paperheight") {
378 valstring = percentval;
379 unit = "pheight%" + endlen;
380 } else if (unit == "\\textheight") {
381 valstring = percentval;
382 unit = "theight%" + endlen;
390 string translate_len(string const & length)
394 if (translate_len(length, value, unit))
396 // If the input is invalid, return what we have.
404 * Translates a LaTeX length into \p value, \p unit and
405 * \p special parts suitable for a box inset.
406 * The difference from translate_len() is that a box inset knows about
407 * some special "units" that are stored in \p special.
409 void translate_box_len(string const & length, string & value, string & unit, string & special)
411 if (translate_len(length, value, unit)) {
412 if (unit == "\\height" || unit == "\\depth" ||
413 unit == "\\totalheight" || unit == "\\width") {
414 special = unit.substr(1);
415 // The unit is not used, but LyX requires a dummy setting
428 * Find a file with basename \p name in path \p path and an extension
431 string find_file(string const & name, string const & path,
432 char const * const * extensions)
434 for (char const * const * what = extensions; *what; ++what) {
435 string const trial = addExtension(name, *what);
436 if (makeAbsPath(trial, path).exists())
443 void begin_inset(ostream & os, string const & name)
445 os << "\n\\begin_inset " << name;
449 void begin_command_inset(ostream & os, string const & name,
450 string const & latexname)
452 begin_inset(os, "CommandInset ");
453 os << name << "\nLatexCommand " << latexname << '\n';
457 void end_inset(ostream & os)
459 os << "\n\\end_inset\n\n";
463 bool skip_braces(Parser & p)
465 if (p.next_token().cat() != catBegin)
468 if (p.next_token().cat() == catEnd) {
477 /// replace LaTeX commands in \p s from the unicodesymbols file with their
479 docstring convert_unicodesymbols(docstring s)
482 for (size_t i = 0; i < s.size();) {
491 docstring parsed = encodings.fromLaTeXCommand(s,
492 Encodings::TEXT_CMD, termination, rem, &req);
493 set<string>::const_iterator it = req.begin();
494 set<string>::const_iterator en = req.end();
495 for (; it != en; ++it)
496 preamble.registerAutomaticallyLoadedPackage(*it);
499 if (s.empty() || s[0] != '\\')
508 /// try to convert \p s to a valid InsetCommand argument
509 string convert_command_inset_arg(string s)
512 // since we don't know the input encoding we can't use from_utf8
513 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
514 // LyX cannot handle newlines in a latex command
515 return subst(s, "\n", " ");
519 void output_ert(ostream & os, string const & s, Context & context)
521 context.check_layout(os);
522 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
524 os << "\n\\backslash\n";
525 else if (*it == '\n') {
526 context.new_paragraph(os);
527 context.check_layout(os);
531 context.check_end_layout(os);
535 void output_ert_inset(ostream & os, string const & s, Context & context)
537 // We must have a valid layout before outputting the ERT inset.
538 context.check_layout(os);
539 Context newcontext(true, context.textclass);
540 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
541 if (layout.forcePlainLayout())
542 newcontext.layout = &context.textclass.plainLayout();
543 begin_inset(os, "ERT");
544 os << "\nstatus collapsed\n";
545 output_ert(os, s, newcontext);
550 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
552 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
555 if (checkModule(name, command))
556 return findLayoutWithoutModule(textclass, name, command);
561 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
563 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
566 if (checkModule(name, command))
567 return findInsetLayoutWithoutModule(textclass, name, command);
572 void eat_whitespace(Parser &, ostream &, Context &, bool);
576 * Skips whitespace and braces.
577 * This should be called after a command has been parsed that is not put into
578 * ERT, and where LyX adds "{}" if needed.
580 void skip_spaces_braces(Parser & p, bool keepws = false)
582 /* The following four examples produce the same typeset output and
583 should be handled by this function:
591 // Unfortunately we need to skip comments, too.
592 // We can't use eat_whitespace since writing them after the {}
593 // results in different output in some cases.
594 bool const skipped_spaces = p.skip_spaces(true);
595 bool const skipped_braces = skip_braces(p);
596 if (keepws && skipped_spaces && !skipped_braces)
597 // put back the space (it is better handled by check_space)
598 p.unskip_spaces(true);
602 void output_command_layout(ostream & os, Parser & p, bool outer,
603 Context & parent_context,
604 Layout const * newlayout)
606 TeXFont const oldFont = parent_context.font;
607 // save the current font size
608 string const size = oldFont.size;
609 // reset the font size to default, because the font size switches
610 // don't affect section headings and the like
611 parent_context.font.size = Context::normalfont.size;
612 // we only need to write the font change if we have an open layout
613 if (!parent_context.atParagraphStart())
614 output_font_change(os, oldFont, parent_context.font);
615 parent_context.check_end_layout(os);
616 Context context(true, parent_context.textclass, newlayout,
617 parent_context.layout, parent_context.font);
618 if (parent_context.deeper_paragraph) {
619 // We are beginning a nested environment after a
620 // deeper paragraph inside the outer list environment.
621 // Therefore we don't need to output a "begin deeper".
622 context.need_end_deeper = true;
624 context.check_deeper(os);
625 context.check_layout(os);
626 // FIXME: Adjust to format 446!
627 // Since format 446, layouts do not require anymore all optional
628 // arguments before the required ones. Needs to be implemented!
630 while (optargs < context.layout->optArgs()) {
631 eat_whitespace(p, os, context, false);
632 if (p.next_token().cat() == catEscape ||
633 p.next_token().character() != '[')
635 p.get_token(); // eat '['
636 // FIXME: Just a workaround. InsetArgument::updateBuffer
637 // will compute a proper ID for all "999" Arguments
638 // (which is also what lyx2lyx produces).
639 // However, tex2lyx should be able to output proper IDs
641 begin_inset(os, "Argument 999\n");
642 os << "status collapsed\n\n";
643 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
645 eat_whitespace(p, os, context, false);
649 while (reqargs < context.layout->requiredArgs()) {
650 eat_whitespace(p, os, context, false);
651 if (p.next_token().cat() != catBegin)
653 p.get_token(); // eat '{'
654 // FIXME: Just a workaround. InsetArgument::updateBuffer
655 // will compute a proper ID for all "999" Arguments
656 // (which is also what lyx2lyx produces).
657 // However, tex2lyx should be able to output proper IDs
659 begin_inset(os, "Argument 999\n");
660 os << "status collapsed\n\n";
661 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
663 eat_whitespace(p, os, context, false);
666 parse_text(p, os, FLAG_ITEM, outer, context);
667 context.check_end_layout(os);
668 if (parent_context.deeper_paragraph) {
669 // We must suppress the "end deeper" because we
670 // suppressed the "begin deeper" above.
671 context.need_end_deeper = false;
673 context.check_end_deeper(os);
674 // We don't need really a new paragraph, but
675 // we must make sure that the next item gets a \begin_layout.
676 parent_context.new_paragraph(os);
677 // Set the font size to the original value. No need to output it here
678 // (Context::begin_layout() will do that if needed)
679 parent_context.font.size = size;
684 * Output a space if necessary.
685 * This function gets called for every whitespace token.
687 * We have three cases here:
688 * 1. A space must be suppressed. Example: The lyxcode case below
689 * 2. A space may be suppressed. Example: Spaces before "\par"
690 * 3. A space must not be suppressed. Example: A space between two words
692 * We currently handle only 1. and 3 and from 2. only the case of
693 * spaces before newlines as a side effect.
695 * 2. could be used to suppress as many spaces as possible. This has two effects:
696 * - Reimporting LyX generated LaTeX files changes almost no whitespace
697 * - Superflous whitespace from non LyX generated LaTeX files is removed.
698 * The drawback is that the logic inside the function becomes
699 * complicated, and that is the reason why it is not implemented.
701 void check_space(Parser & p, ostream & os, Context & context)
703 Token const next = p.next_token();
704 Token const curr = p.curr_token();
705 // A space before a single newline and vice versa must be ignored
706 // LyX emits a newline before \end{lyxcode}.
707 // This newline must be ignored,
708 // otherwise LyX will add an additional protected space.
709 if (next.cat() == catSpace ||
710 next.cat() == catNewline ||
711 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
714 context.check_layout(os);
720 * Parse all arguments of \p command
722 void parse_arguments(string const & command,
723 vector<ArgumentType> const & template_arguments,
724 Parser & p, ostream & os, bool outer, Context & context)
726 string ert = command;
727 size_t no_arguments = template_arguments.size();
728 for (size_t i = 0; i < no_arguments; ++i) {
729 switch (template_arguments[i]) {
732 // This argument contains regular LaTeX
733 output_ert_inset(os, ert + '{', context);
734 eat_whitespace(p, os, context, false);
735 if (template_arguments[i] == required)
736 parse_text(p, os, FLAG_ITEM, outer, context);
738 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
742 // This argument consists only of a single item.
743 // The presence of '{' or not must be preserved.
745 if (p.next_token().cat() == catBegin)
746 ert += '{' + p.verbatim_item() + '}';
748 ert += p.verbatim_item();
752 // This argument may contain special characters
753 ert += '{' + p.verbatim_item() + '}';
757 // true because we must not eat whitespace
758 // if an optional arg follows we must not strip the
759 // brackets from this one
760 if (i < no_arguments - 1 &&
761 template_arguments[i+1] == optional)
762 ert += p.getFullOpt(true);
764 ert += p.getOpt(true);
768 output_ert_inset(os, ert, context);
773 * Check whether \p command is a known command. If yes,
774 * handle the command with all arguments.
775 * \return true if the command was parsed, false otherwise.
777 bool parse_command(string const & command, Parser & p, ostream & os,
778 bool outer, Context & context)
780 if (known_commands.find(command) != known_commands.end()) {
781 parse_arguments(command, known_commands[command], p, os,
789 /// Parses a minipage or parbox
790 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
791 unsigned inner_flags, bool outer, Context & parent_context,
792 string const & outer_type, string const & special,
793 string const & inner_type)
797 string hor_pos = "c";
798 // We need to set the height to the LaTeX default of 1\\totalheight
799 // for the case when no height argument is given
800 string height_value = "1";
801 string height_unit = "in";
802 string height_special = "totalheight";
807 string width_special = "none";
808 if (!inner_type.empty() && p.hasOpt()) {
809 if (inner_type != "makebox")
810 position = p.getArg('[', ']');
812 latex_width = p.getArg('[', ']');
813 translate_box_len(latex_width, width_value, width_unit, width_special);
816 if (position != "t" && position != "c" && position != "b") {
817 cerr << "invalid position " << position << " for "
818 << inner_type << endl;
822 if (inner_type != "makebox") {
823 latex_height = p.getArg('[', ']');
824 translate_box_len(latex_height, height_value, height_unit, height_special);
826 string const opt = p.getArg('[', ']');
829 if (hor_pos != "l" && hor_pos != "c" &&
830 hor_pos != "r" && hor_pos != "s") {
831 cerr << "invalid hor_pos " << hor_pos
832 << " for " << inner_type << endl;
839 inner_pos = p.getArg('[', ']');
840 if (inner_pos != "c" && inner_pos != "t" &&
841 inner_pos != "b" && inner_pos != "s") {
842 cerr << "invalid inner_pos "
843 << inner_pos << " for "
844 << inner_type << endl;
845 inner_pos = position;
850 if (inner_type.empty()) {
851 if (special.empty() && outer_type != "framebox")
852 latex_width = "1\\columnwidth";
855 latex_width = p2.getArg('[', ']');
856 string const opt = p2.getArg('[', ']');
859 if (hor_pos != "l" && hor_pos != "c" &&
860 hor_pos != "r" && hor_pos != "s") {
861 cerr << "invalid hor_pos " << hor_pos
862 << " for " << outer_type << endl;
867 } else if (inner_type != "makebox")
868 latex_width = p.verbatim_item();
869 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
870 // as this is LyX's standard for such cases (except for makebox)
871 // \framebox is more special and handled below
872 if (latex_width.empty() && inner_type != "makebox"
873 && outer_type != "framebox")
874 latex_width = "1\\columnwidth";
876 translate_len(latex_width, width_value, width_unit);
878 bool shadedparbox = false;
879 if (inner_type == "shaded") {
880 eat_whitespace(p, os, parent_context, false);
881 if (outer_type == "parbox") {
883 if (p.next_token().cat() == catBegin)
885 eat_whitespace(p, os, parent_context, false);
891 // If we already read the inner box we have to push the inner env
892 if (!outer_type.empty() && !inner_type.empty() &&
893 (inner_flags & FLAG_END))
894 active_environments.push_back(inner_type);
895 // LyX can't handle length variables
896 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
897 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
898 // Look whether there is some content after the end of the
899 // inner box, but before the end of the outer box.
900 // If yes, we need to output ERT.
902 if (inner_flags & FLAG_END)
903 p.ertEnvironment(inner_type);
907 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
908 if ((outer_env && p.next_token().asInput() != "\\end") ||
909 (!outer_env && p.next_token().cat() != catEnd)) {
910 // something is between the end of the inner box and
911 // the end of the outer box, so we need to use ERT.
916 // if only \makebox{content} was used we can set its width to 1\width
917 // because this identic and also identic to \mbox
918 // this doesn't work for \framebox{content}, thus we have to use ERT for this
919 if (latex_width.empty() && inner_type == "makebox") {
922 width_special = "width";
923 } else if (latex_width.empty() && outer_type == "framebox") {
928 if (!outer_type.empty()) {
929 if (outer_flags & FLAG_END)
930 ss << "\\begin{" << outer_type << '}';
932 ss << '\\' << outer_type << '{';
933 if (!special.empty())
937 if (!inner_type.empty()) {
938 if (inner_type != "shaded") {
939 if (inner_flags & FLAG_END)
940 ss << "\\begin{" << inner_type << '}';
942 ss << '\\' << inner_type;
944 if (!position.empty())
945 ss << '[' << position << ']';
946 if (!latex_height.empty())
947 ss << '[' << latex_height << ']';
948 if (!inner_pos.empty())
949 ss << '[' << inner_pos << ']';
950 ss << '{' << latex_width << '}';
951 if (!(inner_flags & FLAG_END))
954 if (inner_type == "shaded")
955 ss << "\\begin{shaded}";
956 output_ert_inset(os, ss.str(), parent_context);
957 if (!inner_type.empty()) {
958 parse_text(p, os, inner_flags, outer, parent_context);
959 if (inner_flags & FLAG_END)
960 output_ert_inset(os, "\\end{" + inner_type + '}',
963 output_ert_inset(os, "}", parent_context);
965 if (!outer_type.empty()) {
966 // If we already read the inner box we have to pop
968 if (!inner_type.empty() && (inner_flags & FLAG_END))
969 active_environments.pop_back();
971 // Ensure that the end of the outer box is parsed correctly:
972 // The opening brace has been eaten by parse_outer_box()
973 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
974 outer_flags &= ~FLAG_ITEM;
975 outer_flags |= FLAG_BRACE_LAST;
977 parse_text(p, os, outer_flags, outer, parent_context);
978 if (outer_flags & FLAG_END)
979 output_ert_inset(os, "\\end{" + outer_type + '}',
981 else if (inner_type.empty() && outer_type == "framebox")
982 // in this case it is already closed later
985 output_ert_inset(os, "}", parent_context);
988 // LyX does not like empty positions, so we have
989 // to set them to the LaTeX default values here.
990 if (position.empty())
992 if (inner_pos.empty())
993 inner_pos = position;
994 parent_context.check_layout(os);
995 begin_inset(os, "Box ");
996 if (outer_type == "framed")
998 else if (outer_type == "framebox")
1000 else if (outer_type == "shadowbox")
1001 os << "Shadowbox\n";
1002 else if ((outer_type == "shaded" && inner_type.empty()) ||
1003 (outer_type == "minipage" && inner_type == "shaded") ||
1004 (outer_type == "parbox" && inner_type == "shaded")) {
1006 preamble.registerAutomaticallyLoadedPackage("color");
1007 } else if (outer_type == "doublebox")
1008 os << "Doublebox\n";
1009 else if (outer_type.empty())
1010 os << "Frameless\n";
1012 os << outer_type << '\n';
1013 os << "position \"" << position << "\"\n";
1014 os << "hor_pos \"" << hor_pos << "\"\n";
1015 os << "has_inner_box " << !inner_type.empty() << "\n";
1016 os << "inner_pos \"" << inner_pos << "\"\n";
1017 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1019 os << "use_makebox " << (inner_type == "makebox") << '\n';
1020 os << "width \"" << width_value << width_unit << "\"\n";
1021 os << "special \"" << width_special << "\"\n";
1022 os << "height \"" << height_value << height_unit << "\"\n";
1023 os << "height_special \"" << height_special << "\"\n";
1024 os << "status open\n\n";
1026 // Unfortunately we can't use parse_text_in_inset:
1027 // InsetBox::forcePlainLayout() is hard coded and does not
1028 // use the inset layout. Apart from that do we call parse_text
1029 // up to two times, but need only one check_end_layout.
1030 bool const forcePlainLayout =
1031 (!inner_type.empty() || inner_type == "makebox") &&
1032 outer_type != "shaded" && outer_type != "framed";
1033 Context context(true, parent_context.textclass);
1034 if (forcePlainLayout)
1035 context.layout = &context.textclass.plainLayout();
1037 context.font = parent_context.font;
1039 // If we have no inner box the contents will be read with the outer box
1040 if (!inner_type.empty())
1041 parse_text(p, os, inner_flags, outer, context);
1043 // Ensure that the end of the outer box is parsed correctly:
1044 // The opening brace has been eaten by parse_outer_box()
1045 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1046 outer_flags &= ~FLAG_ITEM;
1047 outer_flags |= FLAG_BRACE_LAST;
1050 // Find end of outer box, output contents if inner_type is
1051 // empty and output possible comments
1052 if (!outer_type.empty()) {
1053 // If we already read the inner box we have to pop
1055 if (!inner_type.empty() && (inner_flags & FLAG_END))
1056 active_environments.pop_back();
1057 // This does not output anything but comments if
1058 // inner_type is not empty (see use_ert)
1059 parse_text(p, os, outer_flags, outer, context);
1062 context.check_end_layout(os);
1064 #ifdef PRESERVE_LAYOUT
1065 // LyX puts a % after the end of the minipage
1066 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1068 //output_ert_inset(os, "%dummy", parent_context);
1071 parent_context.new_paragraph(os);
1073 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1074 //output_ert_inset(os, "%dummy", parent_context);
1077 // We add a protected space if something real follows
1078 if (p.good() && p.next_token().cat() != catComment) {
1079 begin_inset(os, "space ~\n");
1088 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1089 Context & parent_context, string const & outer_type,
1090 string const & special)
1092 eat_whitespace(p, os, parent_context, false);
1093 if (flags & FLAG_ITEM) {
1095 if (p.next_token().cat() == catBegin)
1098 cerr << "Warning: Ignoring missing '{' after \\"
1099 << outer_type << '.' << endl;
1100 eat_whitespace(p, os, parent_context, false);
1103 unsigned int inner_flags = 0;
1105 if (outer_type == "minipage" || outer_type == "parbox") {
1106 p.skip_spaces(true);
1107 while (p.hasOpt()) {
1109 p.skip_spaces(true);
1112 p.skip_spaces(true);
1113 if (outer_type == "parbox") {
1115 if (p.next_token().cat() == catBegin)
1117 p.skip_spaces(true);
1120 if (outer_type == "shaded") {
1121 // These boxes never have an inner box
1123 } else if (p.next_token().asInput() == "\\parbox") {
1124 inner = p.get_token().cs();
1125 inner_flags = FLAG_ITEM;
1126 } else if (p.next_token().asInput() == "\\begin") {
1127 // Is this a minipage or shaded box?
1130 inner = p.getArg('{', '}');
1132 if (inner == "minipage" || inner == "shaded")
1133 inner_flags = FLAG_END;
1138 if (inner_flags == FLAG_END) {
1139 if (inner != "shaded")
1143 eat_whitespace(p, os, parent_context, false);
1145 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1146 outer_type, special, inner);
1148 if (inner_flags == FLAG_ITEM) {
1150 eat_whitespace(p, os, parent_context, false);
1152 parse_box(p, os, flags, inner_flags, outer, parent_context,
1153 outer_type, special, inner);
1158 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1160 parent_context.check_layout(os);
1161 begin_inset(os, "listings\n");
1163 string arg = p.verbatimOption();
1164 os << "lstparams " << '"' << arg << '"' << '\n';
1165 if (arg.find("\\color") != string::npos)
1166 preamble.registerAutomaticallyLoadedPackage("color");
1169 os << "inline true\n";
1171 os << "inline false\n";
1172 os << "status collapsed\n";
1173 Context context(true, parent_context.textclass);
1174 context.layout = &parent_context.textclass.plainLayout();
1177 // set catcodes to verbatim early, just in case.
1178 p.setCatcodes(VERBATIM_CATCODES);
1179 string delim = p.get_token().asInput();
1180 s = p.verbatimStuff(delim);
1181 // context.new_paragraph(os);
1183 s = p.verbatimEnvironment("lstlisting");
1184 output_ert(os, s, context);
1189 /// parse an unknown environment
1190 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1191 unsigned flags, bool outer,
1192 Context & parent_context)
1194 if (name == "tabbing")
1195 // We need to remember that we have to handle '\=' specially
1196 flags |= FLAG_TABBING;
1198 // We need to translate font changes and paragraphs inside the
1199 // environment to ERT if we have a non standard font.
1200 // Otherwise things like
1201 // \large\begin{foo}\huge bar\end{foo}
1203 bool const specialfont =
1204 (parent_context.font != parent_context.normalfont);
1205 bool const new_layout_allowed = parent_context.new_layout_allowed;
1207 parent_context.new_layout_allowed = false;
1208 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1209 parse_text_snippet(p, os, flags, outer, parent_context);
1210 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1212 parent_context.new_layout_allowed = new_layout_allowed;
1216 void parse_environment(Parser & p, ostream & os, bool outer,
1217 string & last_env, Context & parent_context)
1219 Layout const * newlayout;
1220 InsetLayout const * newinsetlayout = 0;
1221 string const name = p.getArg('{', '}');
1222 const bool is_starred = suffixIs(name, '*');
1223 string const unstarred_name = rtrim(name, "*");
1224 active_environments.push_back(name);
1226 if (is_math_env(name)) {
1227 parent_context.check_layout(os);
1228 begin_inset(os, "Formula ");
1229 os << "\\begin{" << name << "}";
1230 parse_math(p, os, FLAG_END, MATH_MODE);
1231 os << "\\end{" << name << "}";
1233 if (is_display_math_env(name)) {
1234 // Prevent the conversion of a line break to a space
1235 // (bug 7668). This does not change the output, but
1236 // looks ugly in LyX.
1237 eat_whitespace(p, os, parent_context, false);
1241 else if (is_known(name, preamble.polyglossia_languages)) {
1242 // We must begin a new paragraph if not already done
1243 if (! parent_context.atParagraphStart()) {
1244 parent_context.check_end_layout(os);
1245 parent_context.new_paragraph(os);
1247 // save the language in the context so that it is
1248 // handled by parse_text
1249 parent_context.font.language = preamble.polyglossia2lyx(name);
1250 parse_text(p, os, FLAG_END, outer, parent_context);
1251 // Just in case the environment is empty
1252 parent_context.extra_stuff.erase();
1253 // We must begin a new paragraph to reset the language
1254 parent_context.new_paragraph(os);
1258 else if (unstarred_name == "tabular" || name == "longtable") {
1259 eat_whitespace(p, os, parent_context, false);
1260 string width = "0pt";
1261 if (name == "tabular*") {
1262 width = lyx::translate_len(p.getArg('{', '}'));
1263 eat_whitespace(p, os, parent_context, false);
1265 parent_context.check_layout(os);
1266 begin_inset(os, "Tabular ");
1267 handle_tabular(p, os, name, width, parent_context);
1272 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1273 eat_whitespace(p, os, parent_context, false);
1274 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1275 eat_whitespace(p, os, parent_context, false);
1276 parent_context.check_layout(os);
1277 begin_inset(os, "Float " + unstarred_name + "\n");
1278 // store the float type for subfloats
1279 // subfloats only work with figures and tables
1280 if (unstarred_name == "figure")
1281 float_type = unstarred_name;
1282 else if (unstarred_name == "table")
1283 float_type = unstarred_name;
1287 os << "placement " << opt << '\n';
1288 if (contains(opt, "H"))
1289 preamble.registerAutomaticallyLoadedPackage("float");
1291 Floating const & fl = parent_context.textclass.floats()
1292 .getType(unstarred_name);
1293 if (!fl.floattype().empty() && fl.usesFloatPkg())
1294 preamble.registerAutomaticallyLoadedPackage("float");
1297 os << "wide " << convert<string>(is_starred)
1298 << "\nsideways false"
1299 << "\nstatus open\n\n";
1300 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1302 // We don't need really a new paragraph, but
1303 // we must make sure that the next item gets a \begin_layout.
1304 parent_context.new_paragraph(os);
1306 // the float is parsed thus delete the type
1310 else if (unstarred_name == "sidewaysfigure"
1311 || unstarred_name == "sidewaystable") {
1312 eat_whitespace(p, os, parent_context, false);
1313 parent_context.check_layout(os);
1314 if (unstarred_name == "sidewaysfigure")
1315 begin_inset(os, "Float figure\n");
1317 begin_inset(os, "Float table\n");
1318 os << "wide " << convert<string>(is_starred)
1319 << "\nsideways true"
1320 << "\nstatus open\n\n";
1321 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1323 // We don't need really a new paragraph, but
1324 // we must make sure that the next item gets a \begin_layout.
1325 parent_context.new_paragraph(os);
1327 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1330 else if (name == "wrapfigure" || name == "wraptable") {
1331 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1332 eat_whitespace(p, os, parent_context, false);
1333 parent_context.check_layout(os);
1336 string overhang = "0col%";
1339 lines = p.getArg('[', ']');
1340 string const placement = p.getArg('{', '}');
1342 overhang = p.getArg('[', ']');
1343 string const width = p.getArg('{', '}');
1345 if (name == "wrapfigure")
1346 begin_inset(os, "Wrap figure\n");
1348 begin_inset(os, "Wrap table\n");
1349 os << "lines " << lines
1350 << "\nplacement " << placement
1351 << "\noverhang " << lyx::translate_len(overhang)
1352 << "\nwidth " << lyx::translate_len(width)
1353 << "\nstatus open\n\n";
1354 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1356 // We don't need really a new paragraph, but
1357 // we must make sure that the next item gets a \begin_layout.
1358 parent_context.new_paragraph(os);
1360 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1363 else if (name == "minipage") {
1364 eat_whitespace(p, os, parent_context, false);
1365 // Test whether this is an outer box of a shaded box
1367 // swallow arguments
1368 while (p.hasOpt()) {
1370 p.skip_spaces(true);
1373 p.skip_spaces(true);
1374 Token t = p.get_token();
1375 bool shaded = false;
1376 if (t.asInput() == "\\begin") {
1377 p.skip_spaces(true);
1378 if (p.getArg('{', '}') == "shaded")
1383 parse_outer_box(p, os, FLAG_END, outer,
1384 parent_context, name, "shaded");
1386 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1391 else if (name == "comment") {
1392 eat_whitespace(p, os, parent_context, false);
1393 parent_context.check_layout(os);
1394 begin_inset(os, "Note Comment\n");
1395 os << "status open\n";
1396 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1399 skip_braces(p); // eat {} that might by set by LyX behind comments
1400 preamble.registerAutomaticallyLoadedPackage("verbatim");
1403 else if (name == "verbatim") {
1404 // FIXME: this should go in the generic code that
1405 // handles environments defined in layout file that
1406 // have "PassThru 1". However, the code over there is
1407 // already too complicated for my taste.
1408 parent_context.new_paragraph(os);
1409 Context context(true, parent_context.textclass,
1410 &parent_context.textclass[from_ascii("Verbatim")]);
1411 string s = p.verbatimEnvironment("verbatim");
1412 output_ert(os, s, context);
1416 else if (name == "CJK") {
1417 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1418 // It is impossible to decide if a CJK environment was in its own paragraph or within
1419 // a line. We therefore always assume a paragraph since the latter is a rare case.
1420 eat_whitespace(p, os, parent_context, false);
1421 parent_context.check_end_layout(os);
1422 // store the encoding to be able to reset it
1423 string const encoding_old = p.getEncoding();
1424 string const encoding = p.getArg('{', '}');
1425 // FIXME: For some reason JIS does not work. Although the text
1426 // in tests/CJK.tex is identical with the SJIS version if you
1427 // convert both snippets using the recode command line utility,
1428 // the resulting .lyx file contains some extra characters if
1429 // you set buggy_encoding to false for JIS.
1430 bool const buggy_encoding = encoding == "JIS";
1431 if (!buggy_encoding)
1432 p.setEncoding(encoding, Encoding::CJK);
1434 // FIXME: This will read garbage, since the data is not encoded in utf8.
1435 p.setEncoding("UTF-8");
1437 // LyX only supports the same mapping for all CJK
1438 // environments, so we might need to output everything as ERT
1439 string const mapping = trim(p.getArg('{', '}'));
1440 char const * const * const where =
1441 is_known(encoding, supported_CJK_encodings);
1442 if (!buggy_encoding && !preamble.fontCJKSet())
1443 preamble.fontCJK(mapping);
1444 bool knownMapping = mapping == preamble.fontCJK();
1445 if (buggy_encoding || !knownMapping || !where) {
1446 parent_context.check_layout(os);
1447 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1449 // we must parse the content as verbatim because e.g. JIS can contain
1450 // normally invalid characters
1451 // FIXME: This works only for the most simple cases.
1452 // Since TeX control characters are not parsed,
1453 // things like comments are completely wrong.
1454 string const s = p.plainEnvironment("CJK");
1455 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1457 output_ert_inset(os, "\\", parent_context);
1458 else if (*it == '$')
1459 output_ert_inset(os, "$", parent_context);
1463 output_ert_inset(os, "\\end{" + name + "}",
1467 supported_CJK_languages[where - supported_CJK_encodings];
1468 // store the language because we must reset it at the end
1469 string const lang_old = parent_context.font.language;
1470 parent_context.font.language = lang;
1471 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1472 parent_context.font.language = lang_old;
1473 parent_context.new_paragraph(os);
1475 p.setEncoding(encoding_old);
1479 else if (name == "lyxgreyedout") {
1480 eat_whitespace(p, os, parent_context, false);
1481 parent_context.check_layout(os);
1482 begin_inset(os, "Note Greyedout\n");
1483 os << "status open\n";
1484 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1487 if (!preamble.notefontcolor().empty())
1488 preamble.registerAutomaticallyLoadedPackage("color");
1491 else if (name == "framed" || name == "shaded") {
1492 eat_whitespace(p, os, parent_context, false);
1493 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1497 else if (name == "lstlisting") {
1498 eat_whitespace(p, os, parent_context, false);
1499 parse_listings(p, os, parent_context, false);
1503 else if (!parent_context.new_layout_allowed)
1504 parse_unknown_environment(p, name, os, FLAG_END, outer,
1507 // Alignment and spacing settings
1508 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1509 // therefore are totally broken!
1510 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1511 // they are commands not environments. They are furthermore switches that
1512 // can be ended by another switches, but also by commands like \footnote or
1513 // \parbox. So the only safe way is to leave them untouched.
1514 else if (name == "center" || name == "centering" ||
1515 name == "flushleft" || name == "flushright" ||
1516 name == "singlespace" || name == "onehalfspace" ||
1517 name == "doublespace" || name == "spacing") {
1518 eat_whitespace(p, os, parent_context, false);
1519 // We must begin a new paragraph if not already done
1520 if (! parent_context.atParagraphStart()) {
1521 parent_context.check_end_layout(os);
1522 parent_context.new_paragraph(os);
1524 if (name == "flushleft")
1525 parent_context.add_extra_stuff("\\align left\n");
1526 else if (name == "flushright")
1527 parent_context.add_extra_stuff("\\align right\n");
1528 else if (name == "center" || name == "centering")
1529 parent_context.add_extra_stuff("\\align center\n");
1530 else if (name == "singlespace")
1531 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1532 else if (name == "onehalfspace") {
1533 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1534 preamble.registerAutomaticallyLoadedPackage("setspace");
1535 } else if (name == "doublespace") {
1536 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1537 preamble.registerAutomaticallyLoadedPackage("setspace");
1538 } else if (name == "spacing") {
1539 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1540 preamble.registerAutomaticallyLoadedPackage("setspace");
1542 parse_text(p, os, FLAG_END, outer, parent_context);
1543 // Just in case the environment is empty
1544 parent_context.extra_stuff.erase();
1545 // We must begin a new paragraph to reset the alignment
1546 parent_context.new_paragraph(os);
1550 // The single '=' is meant here.
1551 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1552 eat_whitespace(p, os, parent_context, false);
1553 Context context(true, parent_context.textclass, newlayout,
1554 parent_context.layout, parent_context.font);
1555 if (parent_context.deeper_paragraph) {
1556 // We are beginning a nested environment after a
1557 // deeper paragraph inside the outer list environment.
1558 // Therefore we don't need to output a "begin deeper".
1559 context.need_end_deeper = true;
1561 parent_context.check_end_layout(os);
1562 if (last_env == name) {
1563 // we need to output a separator since LyX would export
1564 // the two environments as one otherwise (bug 5716)
1565 docstring const sep = from_ascii("--Separator--");
1566 TeX2LyXDocClass const & textclass(parent_context.textclass);
1567 if (textclass.hasLayout(sep)) {
1568 Context newcontext(parent_context);
1569 newcontext.layout = &(textclass[sep]);
1570 newcontext.check_layout(os);
1571 newcontext.check_end_layout(os);
1573 parent_context.check_layout(os);
1574 begin_inset(os, "Note Note\n");
1575 os << "status closed\n";
1576 Context newcontext(true, textclass,
1577 &(textclass.defaultLayout()));
1578 newcontext.check_layout(os);
1579 newcontext.check_end_layout(os);
1581 parent_context.check_end_layout(os);
1584 switch (context.layout->latextype) {
1585 case LATEX_LIST_ENVIRONMENT:
1586 context.add_par_extra_stuff("\\labelwidthstring "
1587 + p.verbatim_item() + '\n');
1590 case LATEX_BIB_ENVIRONMENT:
1591 p.verbatim_item(); // swallow next arg
1597 context.check_deeper(os);
1598 // handle known optional and required arguments
1599 // FIXME: Since format 446, layouts do not require anymore all optional
1600 // arguments before the required ones. Needs to be implemented!
1601 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1602 // It is impossible to place anything after the environment name,
1603 // but before the first \\item.
1604 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1605 bool need_layout = true;
1607 while (optargs < context.layout->optArgs()) {
1608 eat_whitespace(p, os, context, false);
1609 if (p.next_token().cat() == catEscape ||
1610 p.next_token().character() != '[')
1612 p.get_token(); // eat '['
1614 context.check_layout(os);
1615 need_layout = false;
1617 // FIXME: Just a workaround. InsetArgument::updateBuffer
1618 // will compute a proper ID for all "999" Arguments
1619 // (which is also what lyx2lyx produces).
1620 // However, tex2lyx should be able to output proper IDs
1622 begin_inset(os, "Argument 999\n");
1623 os << "status collapsed\n\n";
1624 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1626 eat_whitespace(p, os, context, false);
1630 while (reqargs < context.layout->requiredArgs()) {
1631 eat_whitespace(p, os, context, false);
1632 if (p.next_token().cat() != catBegin)
1634 p.get_token(); // eat '{'
1636 context.check_layout(os);
1637 need_layout = false;
1639 // FIXME: Just a workaround. InsetArgument::updateBuffer
1640 // will compute a proper ID for all "999" Arguments
1641 // (which is also what lyx2lyx produces).
1642 // However, tex2lyx should be able to output proper IDs
1644 begin_inset(os, "Argument 999\n");
1645 os << "status collapsed\n\n";
1646 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1648 eat_whitespace(p, os, context, false);
1652 parse_text(p, os, FLAG_END, outer, context);
1653 context.check_end_layout(os);
1654 if (parent_context.deeper_paragraph) {
1655 // We must suppress the "end deeper" because we
1656 // suppressed the "begin deeper" above.
1657 context.need_end_deeper = false;
1659 context.check_end_deeper(os);
1660 parent_context.new_paragraph(os);
1662 if (!preamble.titleLayoutFound())
1663 preamble.titleLayoutFound(newlayout->intitle);
1664 set<string> const & req = newlayout->requires();
1665 set<string>::const_iterator it = req.begin();
1666 set<string>::const_iterator en = req.end();
1667 for (; it != en; ++it)
1668 preamble.registerAutomaticallyLoadedPackage(*it);
1671 // The single '=' is meant here.
1672 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1673 eat_whitespace(p, os, parent_context, false);
1674 parent_context.check_layout(os);
1675 begin_inset(os, "Flex ");
1676 os << to_utf8(newinsetlayout->name()) << '\n'
1677 << "status collapsed\n";
1678 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1682 else if (name == "appendix") {
1683 // This is no good latex style, but it works and is used in some documents...
1684 eat_whitespace(p, os, parent_context, false);
1685 parent_context.check_end_layout(os);
1686 Context context(true, parent_context.textclass, parent_context.layout,
1687 parent_context.layout, parent_context.font);
1688 context.check_layout(os);
1689 os << "\\start_of_appendix\n";
1690 parse_text(p, os, FLAG_END, outer, context);
1691 context.check_end_layout(os);
1695 else if (known_environments.find(name) != known_environments.end()) {
1696 vector<ArgumentType> arguments = known_environments[name];
1697 // The last "argument" denotes wether we may translate the
1698 // environment contents to LyX
1699 // The default required if no argument is given makes us
1700 // compatible with the reLyXre environment.
1701 ArgumentType contents = arguments.empty() ?
1704 if (!arguments.empty())
1705 arguments.pop_back();
1706 // See comment in parse_unknown_environment()
1707 bool const specialfont =
1708 (parent_context.font != parent_context.normalfont);
1709 bool const new_layout_allowed =
1710 parent_context.new_layout_allowed;
1712 parent_context.new_layout_allowed = false;
1713 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1714 outer, parent_context);
1715 if (contents == verbatim)
1716 output_ert_inset(os, p.ertEnvironment(name),
1719 parse_text_snippet(p, os, FLAG_END, outer,
1721 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1723 parent_context.new_layout_allowed = new_layout_allowed;
1727 parse_unknown_environment(p, name, os, FLAG_END, outer,
1731 active_environments.pop_back();
1735 /// parses a comment and outputs it to \p os.
1736 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1738 LASSERT(t.cat() == catComment, return);
1739 if (!t.cs().empty()) {
1740 context.check_layout(os);
1741 output_ert_inset(os, '%' + t.cs(), context);
1742 if (p.next_token().cat() == catNewline) {
1743 // A newline after a comment line starts a new
1745 if (context.new_layout_allowed) {
1746 if(!context.atParagraphStart())
1747 // Only start a new paragraph if not already
1748 // done (we might get called recursively)
1749 context.new_paragraph(os);
1751 output_ert_inset(os, "\n", context);
1752 eat_whitespace(p, os, context, true);
1755 // "%\n" combination
1762 * Reads spaces and comments until the first non-space, non-comment token.
1763 * New paragraphs (double newlines or \\par) are handled like simple spaces
1764 * if \p eatParagraph is true.
1765 * Spaces are skipped, but comments are written to \p os.
1767 void eat_whitespace(Parser & p, ostream & os, Context & context,
1771 Token const & t = p.get_token();
1772 if (t.cat() == catComment)
1773 parse_comment(p, os, t, context);
1774 else if ((! eatParagraph && p.isParagraph()) ||
1775 (t.cat() != catSpace && t.cat() != catNewline)) {
1784 * Set a font attribute, parse text and reset the font attribute.
1785 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1786 * \param currentvalue Current value of the attribute. Is set to the new
1787 * value during parsing.
1788 * \param newvalue New value of the attribute
1790 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1791 Context & context, string const & attribute,
1792 string & currentvalue, string const & newvalue)
1794 context.check_layout(os);
1795 string const oldvalue = currentvalue;
1796 currentvalue = newvalue;
1797 os << '\n' << attribute << ' ' << newvalue << "\n";
1798 parse_text_snippet(p, os, flags, outer, context);
1799 context.check_layout(os);
1800 os << '\n' << attribute << ' ' << oldvalue << "\n";
1801 currentvalue = oldvalue;
1805 /// get the arguments of a natbib or jurabib citation command
1806 void get_cite_arguments(Parser & p, bool natbibOrder,
1807 string & before, string & after)
1809 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1811 // text before the citation
1813 // text after the citation
1814 after = p.getFullOpt();
1816 if (!after.empty()) {
1817 before = p.getFullOpt();
1818 if (natbibOrder && !before.empty())
1819 swap(before, after);
1824 /// Convert filenames with TeX macros and/or quotes to something LyX
1826 string const normalize_filename(string const & name)
1831 Token const & t = p.get_token();
1832 if (t.cat() != catEscape)
1834 else if (t.cs() == "lyxdot") {
1835 // This is used by LyX for simple dots in relative
1839 } else if (t.cs() == "space") {
1842 } else if (t.cs() == "string") {
1843 // Convert \string" to " and \string~ to ~
1844 Token const & n = p.next_token();
1845 if (n.asInput() != "\"" && n.asInput() != "~")
1850 // Strip quotes. This is a bit complicated (see latex_path()).
1851 string full = os.str();
1852 if (!full.empty() && full[0] == '"') {
1853 string base = removeExtension(full);
1854 string ext = getExtension(full);
1855 if (!base.empty() && base[base.length()-1] == '"')
1858 return addExtension(trim(base, "\""), ext);
1859 if (full[full.length()-1] == '"')
1862 return trim(full, "\"");
1868 /// Convert \p name from TeX convention (relative to master file) to LyX
1869 /// convention (relative to .lyx file) if it is relative
1870 void fix_child_filename(string & name)
1872 string const absMasterTeX = getMasterFilePath(true);
1873 bool const isabs = FileName::isAbsolute(name);
1874 // convert from "relative to .tex master" to absolute original path
1876 name = makeAbsPath(name, absMasterTeX).absFileName();
1877 bool copyfile = copyFiles();
1878 string const absParentLyX = getParentFilePath(false);
1881 // convert from absolute original path to "relative to master file"
1882 string const rel = to_utf8(makeRelPath(from_utf8(name),
1883 from_utf8(absMasterTeX)));
1884 // re-interpret "relative to .tex file" as "relative to .lyx file"
1885 // (is different if the master .lyx file resides in a
1886 // different path than the master .tex file)
1887 string const absMasterLyX = getMasterFilePath(false);
1888 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1889 // Do not copy if the new path is impossible to create. Example:
1890 // absMasterTeX = "/foo/bar/"
1891 // absMasterLyX = "/bar/"
1892 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1893 if (contains(name, "/../"))
1900 // convert from absolute original path to
1901 // "relative to .lyx file"
1902 name = to_utf8(makeRelPath(from_utf8(abs),
1903 from_utf8(absParentLyX)));
1907 // convert from absolute original path to "relative to .lyx file"
1908 name = to_utf8(makeRelPath(from_utf8(name),
1909 from_utf8(absParentLyX)));
1914 void copy_file(FileName const & src, string dstname)
1918 string const absParent = getParentFilePath(false);
1920 if (FileName::isAbsolute(dstname))
1921 dst = FileName(dstname);
1923 dst = makeAbsPath(dstname, absParent);
1924 string const absMaster = getMasterFilePath(false);
1925 FileName const srcpath = src.onlyPath();
1926 FileName const dstpath = dst.onlyPath();
1927 if (equivalent(srcpath, dstpath))
1929 if (!dstpath.isDirectory()) {
1930 if (!dstpath.createPath()) {
1931 cerr << "Warning: Could not create directory for file `"
1932 << dst.absFileName() << "´." << endl;
1936 if (dst.isReadableFile()) {
1937 if (overwriteFiles())
1938 cerr << "Warning: Overwriting existing file `"
1939 << dst.absFileName() << "´." << endl;
1941 cerr << "Warning: Not overwriting existing file `"
1942 << dst.absFileName() << "´." << endl;
1946 if (!src.copyTo(dst))
1947 cerr << "Warning: Could not copy file `" << src.absFileName()
1948 << "´ to `" << dst.absFileName() << "´." << endl;
1952 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1953 void parse_noweb(Parser & p, ostream & os, Context & context)
1955 // assemble the rest of the keyword
1959 Token const & t = p.get_token();
1960 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1963 chunk = (p.good() && p.next_token().asInput() == "=");
1965 name += p.get_token().asInput();
1968 name += t.asInput();
1971 if (!chunk || !context.new_layout_allowed ||
1972 !context.textclass.hasLayout(from_ascii("Chunk"))) {
1973 cerr << "Warning: Could not interpret '" << name
1974 << "'. Ignoring it." << endl;
1978 // We use new_paragraph instead of check_end_layout because the stuff
1979 // following the noweb chunk needs to start with a \begin_layout.
1980 // This may create a new paragraph even if there was none in the
1981 // noweb file, but the alternative is an invalid LyX file. Since
1982 // noweb code chunks are implemented with a layout style in LyX they
1983 // always must be in an own paragraph.
1984 context.new_paragraph(os);
1985 Context newcontext(true, context.textclass,
1986 &context.textclass[from_ascii("Chunk")]);
1987 newcontext.check_layout(os);
1990 Token const & t = p.get_token();
1991 // We abuse the parser a bit, because this is no TeX syntax
1993 if (t.cat() == catEscape)
1994 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1997 Context tmp(false, context.textclass,
1998 &context.textclass[from_ascii("Chunk")]);
1999 tmp.need_end_layout = true;
2000 tmp.check_layout(oss);
2001 os << subst(t.asInput(), "\n", oss.str());
2003 // The chunk is ended by an @ at the beginning of a line.
2004 // After the @ the line may contain a comment and/or
2005 // whitespace, but nothing else.
2006 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2007 (p.next_token().cat() == catSpace ||
2008 p.next_token().cat() == catNewline ||
2009 p.next_token().cat() == catComment)) {
2010 while (p.good() && p.next_token().cat() == catSpace)
2011 os << p.get_token().asInput();
2012 if (p.next_token().cat() == catComment)
2013 // The comment includes a final '\n'
2014 os << p.get_token().asInput();
2016 if (p.next_token().cat() == catNewline)
2023 newcontext.check_end_layout(os);
2027 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2028 bool is_macro(Parser & p)
2030 Token first = p.curr_token();
2031 if (first.cat() != catEscape || !p.good())
2033 if (first.cs() == "def")
2035 if (first.cs() != "global" && first.cs() != "long")
2037 Token second = p.get_token();
2039 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2040 second.cat() == catNewline || second.cat() == catComment)) {
2041 second = p.get_token();
2044 bool secondvalid = second.cat() == catEscape;
2046 bool thirdvalid = false;
2047 if (p.good() && first.cs() == "global" && secondvalid &&
2048 second.cs() == "long") {
2049 third = p.get_token();
2051 while (p.good() && !p.isParagraph() &&
2052 (third.cat() == catSpace ||
2053 third.cat() == catNewline ||
2054 third.cat() == catComment)) {
2055 third = p.get_token();
2058 thirdvalid = third.cat() == catEscape;
2060 for (int i = 0; i < pos; ++i)
2065 return (first.cs() == "global" || first.cs() == "long") &&
2066 second.cs() == "def";
2067 return first.cs() == "global" && second.cs() == "long" &&
2068 third.cs() == "def";
2072 /// Parse a macro definition (assumes that is_macro() returned true)
2073 void parse_macro(Parser & p, ostream & os, Context & context)
2075 context.check_layout(os);
2076 Token first = p.curr_token();
2079 string command = first.asInput();
2080 if (first.cs() != "def") {
2082 eat_whitespace(p, os, context, false);
2083 second = p.curr_token();
2084 command += second.asInput();
2085 if (second.cs() != "def") {
2087 eat_whitespace(p, os, context, false);
2088 third = p.curr_token();
2089 command += third.asInput();
2092 eat_whitespace(p, os, context, false);
2093 string const name = p.get_token().cs();
2094 eat_whitespace(p, os, context, false);
2100 while (p.next_token().cat() != catBegin) {
2101 if (p.next_token().cat() == catParameter) {
2106 // followed by number?
2107 if (p.next_token().cat() == catOther) {
2108 char c = p.getChar();
2110 // number = current arity + 1?
2111 if (c == arity + '0' + 1)
2116 paramtext += p.get_token().cs();
2118 paramtext += p.get_token().cs();
2123 // only output simple (i.e. compatible) macro as FormulaMacros
2124 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2126 context.check_layout(os);
2127 begin_inset(os, "FormulaMacro");
2128 os << "\n\\def" << ert;
2131 output_ert_inset(os, command + ert, context);
2135 void registerExternalTemplatePackages(string const & name)
2137 external::TemplateManager const & etm = external::TemplateManager::get();
2138 external::Template const * const et = etm.getTemplateByName(name);
2141 external::Template::Formats::const_iterator cit = et->formats.end();
2143 cit = et->formats.find("PDFLaTeX");
2144 if (cit == et->formats.end())
2145 // If the template has not specified a PDFLaTeX output,
2146 // we try the LaTeX format.
2147 cit = et->formats.find("LaTeX");
2148 if (cit == et->formats.end())
2150 vector<string>::const_iterator qit = cit->second.requirements.begin();
2151 vector<string>::const_iterator qend = cit->second.requirements.end();
2152 for (; qit != qend; ++qit)
2153 preamble.registerAutomaticallyLoadedPackage(*qit);
2156 } // anonymous namespace
2159 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2162 Layout const * newlayout = 0;
2163 InsetLayout const * newinsetlayout = 0;
2164 char const * const * where = 0;
2165 // Store the latest bibliographystyle and nocite{*} option
2166 // (needed for bibtex inset)
2168 string bibliographystyle = "default";
2169 bool const use_natbib = isProvided("natbib");
2170 bool const use_jurabib = isProvided("jurabib");
2173 Token const & t = p.get_token();
2175 // it is impossible to determine the correct encoding for non-CJK Japanese.
2176 // Therefore write a note at the beginning of the document
2177 if (is_nonCJKJapanese) {
2178 context.check_layout(os);
2179 begin_inset(os, "Note Note\n");
2180 os << "status open\n\\begin_layout Plain Layout\n"
2181 << "\\series bold\n"
2182 << "Important information:\n"
2183 << "\\end_layout\n\n"
2184 << "\\begin_layout Plain Layout\n"
2185 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2186 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2187 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2188 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2189 << " and specify the encoding using the -e command-line switch.\n"
2190 << " In addition, you might want to double check that the desired output encoding\n"
2191 << " is correctly selected in Document > Settings > Language.\n"
2192 << "\\end_layout\n";
2194 is_nonCJKJapanese = false;
2198 debugToken(cerr, t, flags);
2201 if (flags & FLAG_ITEM) {
2202 if (t.cat() == catSpace)
2205 flags &= ~FLAG_ITEM;
2206 if (t.cat() == catBegin) {
2207 // skip the brace and collect everything to the next matching
2209 flags |= FLAG_BRACE_LAST;
2213 // handle only this single token, leave the loop if done
2214 flags |= FLAG_LEAVE;
2217 if (t.cat() != catEscape && t.character() == ']' &&
2218 (flags & FLAG_BRACK_LAST))
2220 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2223 // If there is anything between \end{env} and \begin{env} we
2224 // don't need to output a separator.
2225 if (t.cat() != catSpace && t.cat() != catNewline &&
2226 t.asInput() != "\\begin")
2232 if (t.cat() == catMath) {
2233 // we are inside some text mode thingy, so opening new math is allowed
2234 context.check_layout(os);
2235 begin_inset(os, "Formula ");
2236 Token const & n = p.get_token();
2237 bool const display(n.cat() == catMath && outer);
2239 // TeX's $$...$$ syntax for displayed math
2241 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2243 p.get_token(); // skip the second '$' token
2245 // simple $...$ stuff
2248 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2253 // Prevent the conversion of a line break to a
2254 // space (bug 7668). This does not change the
2255 // output, but looks ugly in LyX.
2256 eat_whitespace(p, os, context, false);
2260 else if (t.cat() == catSuper || t.cat() == catSub)
2261 cerr << "catcode " << t << " illegal in text mode\n";
2263 // Basic support for english quotes. This should be
2264 // extended to other quotes, but is not so easy (a
2265 // left english quote is the same as a right german
2267 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2268 context.check_layout(os);
2269 begin_inset(os, "Quotes ");
2275 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2276 context.check_layout(os);
2277 begin_inset(os, "Quotes ");
2284 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2285 context.check_layout(os);
2286 begin_inset(os, "Quotes ");
2293 else if (t.asInput() == "<"
2294 && p.next_token().asInput() == "<" && noweb_mode) {
2296 parse_noweb(p, os, context);
2299 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2300 context.check_layout(os);
2301 begin_inset(os, "Quotes ");
2308 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2309 check_space(p, os, context);
2311 else if (t.character() == '[' && noweb_mode &&
2312 p.next_token().character() == '[') {
2313 // These can contain underscores
2315 string const s = p.getFullOpt() + ']';
2316 if (p.next_token().character() == ']')
2319 cerr << "Warning: Inserting missing ']' in '"
2320 << s << "'." << endl;
2321 output_ert_inset(os, s, context);
2324 else if (t.cat() == catLetter) {
2325 context.check_layout(os);
2326 // Workaround for bug 4752.
2327 // FIXME: This whole code block needs to be removed
2328 // when the bug is fixed and tex2lyx produces
2329 // the updated file format.
2330 // The replacement algorithm in LyX is so stupid that
2331 // it even translates a phrase if it is part of a word.
2332 bool handled = false;
2333 for (int const * l = known_phrase_lengths; *l; ++l) {
2334 string phrase = t.cs();
2335 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2336 phrase += p.get_token().cs();
2337 if (is_known(phrase, known_coded_phrases)) {
2338 output_ert_inset(os, phrase, context);
2342 for (size_t i = 1; i < phrase.length(); ++i)
2350 else if (t.cat() == catOther ||
2351 t.cat() == catAlign ||
2352 t.cat() == catParameter) {
2353 // This translates "&" to "\\&" which may be wrong...
2354 context.check_layout(os);
2358 else if (p.isParagraph()) {
2359 if (context.new_layout_allowed)
2360 context.new_paragraph(os);
2362 output_ert_inset(os, "\\par ", context);
2363 eat_whitespace(p, os, context, true);
2366 else if (t.cat() == catActive) {
2367 context.check_layout(os);
2368 if (t.character() == '~') {
2369 if (context.layout->free_spacing)
2372 begin_inset(os, "space ~\n");
2379 else if (t.cat() == catBegin) {
2380 Token const next = p.next_token();
2381 Token const end = p.next_next_token();
2382 if (next.cat() == catEnd) {
2384 Token const prev = p.prev_token();
2386 if (p.next_token().character() == '`' ||
2387 (prev.character() == '-' &&
2388 p.next_token().character() == '-'))
2389 ; // ignore it in {}`` or -{}-
2391 output_ert_inset(os, "{}", context);
2392 } else if (next.cat() == catEscape &&
2393 is_known(next.cs(), known_quotes) &&
2394 end.cat() == catEnd) {
2395 // Something like {\textquoteright} (e.g.
2396 // from writer2latex). LyX writes
2397 // \textquoteright{}, so we may skip the
2398 // braces here for better readability.
2399 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2402 context.check_layout(os);
2403 // special handling of font attribute changes
2404 Token const prev = p.prev_token();
2405 TeXFont const oldFont = context.font;
2406 if (next.character() == '[' ||
2407 next.character() == ']' ||
2408 next.character() == '*') {
2410 if (p.next_token().cat() == catEnd) {
2415 output_ert_inset(os, "{", context);
2416 parse_text_snippet(p, os,
2419 output_ert_inset(os, "}", context);
2421 } else if (! context.new_layout_allowed) {
2422 output_ert_inset(os, "{", context);
2423 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2425 output_ert_inset(os, "}", context);
2426 } else if (is_known(next.cs(), known_sizes)) {
2427 // next will change the size, so we must
2429 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2431 if (!context.atParagraphStart())
2433 << context.font.size << "\n";
2434 } else if (is_known(next.cs(), known_font_families)) {
2435 // next will change the font family, so we
2436 // must reset it here
2437 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2439 if (!context.atParagraphStart())
2441 << context.font.family << "\n";
2442 } else if (is_known(next.cs(), known_font_series)) {
2443 // next will change the font series, so we
2444 // must reset it here
2445 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2447 if (!context.atParagraphStart())
2449 << context.font.series << "\n";
2450 } else if (is_known(next.cs(), known_font_shapes)) {
2451 // next will change the font shape, so we
2452 // must reset it here
2453 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2455 if (!context.atParagraphStart())
2457 << context.font.shape << "\n";
2458 } else if (is_known(next.cs(), known_old_font_families) ||
2459 is_known(next.cs(), known_old_font_series) ||
2460 is_known(next.cs(), known_old_font_shapes)) {
2461 // next will change the font family, series
2462 // and shape, so we must reset it here
2463 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2465 if (!context.atParagraphStart())
2467 << context.font.family
2469 << context.font.series
2471 << context.font.shape << "\n";
2473 output_ert_inset(os, "{", context);
2474 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2476 output_ert_inset(os, "}", context);
2481 else if (t.cat() == catEnd) {
2482 if (flags & FLAG_BRACE_LAST) {
2485 cerr << "stray '}' in text\n";
2486 output_ert_inset(os, "}", context);
2489 else if (t.cat() == catComment)
2490 parse_comment(p, os, t, context);
2493 // control sequences
2496 else if (t.cs() == "(") {
2497 context.check_layout(os);
2498 begin_inset(os, "Formula");
2500 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2505 else if (t.cs() == "[") {
2506 context.check_layout(os);
2507 begin_inset(os, "Formula");
2509 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2512 // Prevent the conversion of a line break to a space
2513 // (bug 7668). This does not change the output, but
2514 // looks ugly in LyX.
2515 eat_whitespace(p, os, context, false);
2518 else if (t.cs() == "begin")
2519 parse_environment(p, os, outer, last_env,
2522 else if (t.cs() == "end") {
2523 if (flags & FLAG_END) {
2524 // eat environment name
2525 string const name = p.getArg('{', '}');
2526 if (name != active_environment())
2527 cerr << "\\end{" + name + "} does not match \\begin{"
2528 + active_environment() + "}\n";
2531 p.error("found 'end' unexpectedly");
2534 else if (t.cs() == "item") {
2536 bool const optarg = p.hasOpt();
2538 // FIXME: This swallows comments, but we cannot use
2539 // eat_whitespace() since we must not output
2540 // anything before the item.
2541 p.skip_spaces(true);
2542 s = p.verbatimOption();
2544 p.skip_spaces(false);
2546 context.check_layout(os);
2547 if (context.has_item) {
2548 // An item in an unknown list-like environment
2549 // FIXME: Do this in check_layout()!
2550 context.has_item = false;
2552 output_ert_inset(os, "\\item", context);
2554 output_ert_inset(os, "\\item ", context);
2557 if (context.layout->labeltype != LABEL_MANUAL) {
2558 // LyX does not support \item[\mybullet]
2559 // in itemize environments
2561 os << parse_text_snippet(p2,
2562 FLAG_BRACK_LAST, outer, context);
2563 } else if (!s.empty()) {
2564 // LyX adds braces around the argument,
2565 // so we need to remove them here.
2566 if (s.size() > 2 && s[0] == '{' &&
2567 s[s.size()-1] == '}')
2568 s = s.substr(1, s.size()-2);
2569 // If the argument contains a space we
2570 // must put it into ERT: Otherwise LyX
2571 // would misinterpret the space as
2572 // item delimiter (bug 7663)
2573 if (contains(s, ' ')) {
2574 output_ert_inset(os, s, context);
2577 os << parse_text_snippet(p2,
2581 // The space is needed to separate the
2582 // item from the rest of the sentence.
2584 eat_whitespace(p, os, context, false);
2589 else if (t.cs() == "bibitem") {
2591 context.check_layout(os);
2592 eat_whitespace(p, os, context, false);
2593 string label = convert_command_inset_arg(p.verbatimOption());
2594 string key = convert_command_inset_arg(p.verbatim_item());
2595 if (contains(label, '\\') || contains(key, '\\')) {
2596 // LyX can't handle LaTeX commands in labels or keys
2597 output_ert_inset(os, t.asInput() + '[' + label +
2598 "]{" + p.verbatim_item() + '}',
2601 begin_command_inset(os, "bibitem", "bibitem");
2602 os << "label \"" << label << "\"\n"
2603 "key \"" << key << "\"\n";
2608 else if (is_macro(p)) {
2609 // catch the case of \def\inputGnumericTable
2611 if (t.cs() == "def") {
2612 Token second = p.next_token();
2613 if (second.cs() == "inputGnumericTable") {
2617 Token third = p.get_token();
2619 if (third.cs() == "input") {
2623 string name = normalize_filename(p.verbatim_item());
2624 string const path = getMasterFilePath(true);
2625 // We want to preserve relative / absolute filenames,
2626 // therefore path is only used for testing
2627 // The file extension is in every case ".tex".
2628 // So we need to remove this extension and check for
2629 // the original one.
2630 name = removeExtension(name);
2631 if (!makeAbsPath(name, path).exists()) {
2632 char const * const Gnumeric_formats[] = {"gnumeric",
2634 string const Gnumeric_name =
2635 find_file(name, path, Gnumeric_formats);
2636 if (!Gnumeric_name.empty())
2637 name = Gnumeric_name;
2639 FileName const absname = makeAbsPath(name, path);
2640 if (absname.exists()) {
2641 fix_child_filename(name);
2642 copy_file(absname, name);
2644 cerr << "Warning: Could not find file '"
2645 << name << "'." << endl;
2646 context.check_layout(os);
2647 begin_inset(os, "External\n\ttemplate ");
2648 os << "GnumericSpreadsheet\n\tfilename "
2651 context.check_layout(os);
2653 // register the packages that are automatically loaded
2654 // by the Gnumeric template
2655 registerExternalTemplatePackages("GnumericSpreadsheet");
2660 parse_macro(p, os, context);
2663 else if (t.cs() == "noindent") {
2665 context.add_par_extra_stuff("\\noindent\n");
2668 else if (t.cs() == "appendix") {
2669 context.add_par_extra_stuff("\\start_of_appendix\n");
2670 // We need to start a new paragraph. Otherwise the
2671 // appendix in 'bla\appendix\chapter{' would start
2673 context.new_paragraph(os);
2674 // We need to make sure that the paragraph is
2675 // generated even if it is empty. Otherwise the
2676 // appendix in '\par\appendix\par\chapter{' would
2678 context.check_layout(os);
2679 // FIXME: This is a hack to prevent paragraph
2680 // deletion if it is empty. Handle this better!
2681 output_ert_inset(os,
2682 "%dummy comment inserted by tex2lyx to "
2683 "ensure that this paragraph is not empty",
2685 // Both measures above may generate an additional
2686 // empty paragraph, but that does not hurt, because
2687 // whitespace does not matter here.
2688 eat_whitespace(p, os, context, true);
2691 // Must catch empty dates before findLayout is called below
2692 else if (t.cs() == "date") {
2693 eat_whitespace(p, os, context, false);
2695 string const date = p.verbatim_item();
2698 preamble.suppressDate(true);
2701 preamble.suppressDate(false);
2702 if (context.new_layout_allowed &&
2703 (newlayout = findLayout(context.textclass,
2706 output_command_layout(os, p, outer,
2707 context, newlayout);
2708 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2709 if (!preamble.titleLayoutFound())
2710 preamble.titleLayoutFound(newlayout->intitle);
2711 set<string> const & req = newlayout->requires();
2712 set<string>::const_iterator it = req.begin();
2713 set<string>::const_iterator en = req.end();
2714 for (; it != en; ++it)
2715 preamble.registerAutomaticallyLoadedPackage(*it);
2717 output_ert_inset(os,
2718 "\\date{" + p.verbatim_item() + '}',
2723 // Starred section headings
2724 // Must attempt to parse "Section*" before "Section".
2725 else if ((p.next_token().asInput() == "*") &&
2726 context.new_layout_allowed &&
2727 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2730 output_command_layout(os, p, outer, context, newlayout);
2732 if (!preamble.titleLayoutFound())
2733 preamble.titleLayoutFound(newlayout->intitle);
2734 set<string> const & req = newlayout->requires();
2735 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2736 preamble.registerAutomaticallyLoadedPackage(*it);
2739 // Section headings and the like
2740 else if (context.new_layout_allowed &&
2741 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2743 output_command_layout(os, p, outer, context, newlayout);
2745 if (!preamble.titleLayoutFound())
2746 preamble.titleLayoutFound(newlayout->intitle);
2747 set<string> const & req = newlayout->requires();
2748 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2749 preamble.registerAutomaticallyLoadedPackage(*it);
2752 else if (t.cs() == "caption") {
2754 context.check_layout(os);
2756 begin_inset(os, "Caption Standard\n");
2757 Context newcontext(true, context.textclass, 0, 0, context.font);
2758 newcontext.check_layout(os);
2759 // FIXME InsetArgument is now properly implemented in InsetLayout
2760 // (for captions, but also for others)
2761 if (p.next_token().cat() != catEscape &&
2762 p.next_token().character() == '[') {
2763 p.get_token(); // eat '['
2764 begin_inset(os, "Argument 1\n");
2765 os << "status collapsed\n";
2766 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2768 eat_whitespace(p, os, context, false);
2770 parse_text(p, os, FLAG_ITEM, outer, context);
2771 context.check_end_layout(os);
2772 // We don't need really a new paragraph, but
2773 // we must make sure that the next item gets a \begin_layout.
2774 context.new_paragraph(os);
2777 newcontext.check_end_layout(os);
2780 else if (t.cs() == "subfloat") {
2781 // the syntax is \subfloat[caption]{content}
2782 // if it is a table of figure depends on the surrounding float
2783 bool has_caption = false;
2785 // do nothing if there is no outer float
2786 if (!float_type.empty()) {
2787 context.check_layout(os);
2789 begin_inset(os, "Float " + float_type + "\n");
2791 << "\nsideways false"
2792 << "\nstatus collapsed\n\n";
2795 if (p.next_token().cat() != catEscape &&
2796 p.next_token().character() == '[') {
2797 p.get_token(); // eat '['
2798 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2802 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2803 // the caption comes always as the last
2805 // we must make sure that the caption gets a \begin_layout
2806 os << "\n\\begin_layout Plain Layout";
2808 begin_inset(os, "Caption Standard\n");
2809 Context newcontext(true, context.textclass,
2810 0, 0, context.font);
2811 newcontext.check_layout(os);
2812 os << caption << "\n";
2813 newcontext.check_end_layout(os);
2814 // We don't need really a new paragraph, but
2815 // we must make sure that the next item gets a \begin_layout.
2816 //newcontext.new_paragraph(os);
2820 // We don't need really a new paragraph, but
2821 // we must make sure that the next item gets a \begin_layout.
2823 context.new_paragraph(os);
2826 context.check_end_layout(os);
2827 // close the layout we opened
2829 os << "\n\\end_layout\n";
2831 // if the float type is not supported or there is no surrounding float
2834 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2835 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2836 "]{" + p.verbatim_item() + '}', context);
2838 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2842 else if (t.cs() == "includegraphics") {
2843 bool const clip = p.next_token().asInput() == "*";
2846 string const arg = p.getArg('[', ']');
2847 map<string, string> opts;
2848 vector<string> keys;
2849 split_map(arg, opts, keys);
2851 opts["clip"] = string();
2852 string name = normalize_filename(p.verbatim_item());
2854 string const path = getMasterFilePath(true);
2855 // We want to preserve relative / absolute filenames,
2856 // therefore path is only used for testing
2857 if (!makeAbsPath(name, path).exists()) {
2858 // The file extension is probably missing.
2859 // Now try to find it out.
2860 string const dvips_name =
2861 find_file(name, path,
2862 known_dvips_graphics_formats);
2863 string const pdftex_name =
2864 find_file(name, path,
2865 known_pdftex_graphics_formats);
2866 if (!dvips_name.empty()) {
2867 if (!pdftex_name.empty()) {
2868 cerr << "This file contains the "
2870 "\"\\includegraphics{"
2872 "However, files\n\""
2873 << dvips_name << "\" and\n\""
2874 << pdftex_name << "\"\n"
2875 "both exist, so I had to make a "
2876 "choice and took the first one.\n"
2877 "Please move the unwanted one "
2878 "someplace else and try again\n"
2879 "if my choice was wrong."
2883 } else if (!pdftex_name.empty()) {
2889 FileName const absname = makeAbsPath(name, path);
2890 if (absname.exists()) {
2891 fix_child_filename(name);
2892 copy_file(absname, name);
2894 cerr << "Warning: Could not find graphics file '"
2895 << name << "'." << endl;
2897 context.check_layout(os);
2898 begin_inset(os, "Graphics ");
2899 os << "\n\tfilename " << name << '\n';
2900 if (opts.find("width") != opts.end())
2902 << translate_len(opts["width"]) << '\n';
2903 if (opts.find("height") != opts.end())
2905 << translate_len(opts["height"]) << '\n';
2906 if (opts.find("scale") != opts.end()) {
2907 istringstream iss(opts["scale"]);
2911 os << "\tscale " << val << '\n';
2913 if (opts.find("angle") != opts.end()) {
2914 os << "\trotateAngle "
2915 << opts["angle"] << '\n';
2916 vector<string>::const_iterator a =
2917 find(keys.begin(), keys.end(), "angle");
2918 vector<string>::const_iterator s =
2919 find(keys.begin(), keys.end(), "width");
2920 if (s == keys.end())
2921 s = find(keys.begin(), keys.end(), "height");
2922 if (s == keys.end())
2923 s = find(keys.begin(), keys.end(), "scale");
2924 if (s != keys.end() && distance(s, a) > 0)
2925 os << "\tscaleBeforeRotation\n";
2927 if (opts.find("origin") != opts.end()) {
2929 string const opt = opts["origin"];
2930 if (opt.find('l') != string::npos) ss << "left";
2931 if (opt.find('r') != string::npos) ss << "right";
2932 if (opt.find('c') != string::npos) ss << "center";
2933 if (opt.find('t') != string::npos) ss << "Top";
2934 if (opt.find('b') != string::npos) ss << "Bottom";
2935 if (opt.find('B') != string::npos) ss << "Baseline";
2936 if (!ss.str().empty())
2937 os << "\trotateOrigin " << ss.str() << '\n';
2939 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2941 if (opts.find("keepaspectratio") != opts.end())
2942 os << "\tkeepAspectRatio\n";
2943 if (opts.find("clip") != opts.end())
2945 if (opts.find("draft") != opts.end())
2947 if (opts.find("bb") != opts.end())
2948 os << "\tBoundingBox "
2949 << opts["bb"] << '\n';
2950 int numberOfbbOptions = 0;
2951 if (opts.find("bbllx") != opts.end())
2952 numberOfbbOptions++;
2953 if (opts.find("bblly") != opts.end())
2954 numberOfbbOptions++;
2955 if (opts.find("bburx") != opts.end())
2956 numberOfbbOptions++;
2957 if (opts.find("bbury") != opts.end())
2958 numberOfbbOptions++;
2959 if (numberOfbbOptions == 4)
2960 os << "\tBoundingBox "
2961 << opts["bbllx"] << " " << opts["bblly"] << " "
2962 << opts["bburx"] << " " << opts["bbury"] << '\n';
2963 else if (numberOfbbOptions > 0)
2964 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2965 numberOfbbOptions = 0;
2966 if (opts.find("natwidth") != opts.end())
2967 numberOfbbOptions++;
2968 if (opts.find("natheight") != opts.end())
2969 numberOfbbOptions++;
2970 if (numberOfbbOptions == 2)
2971 os << "\tBoundingBox 0bp 0bp "
2972 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2973 else if (numberOfbbOptions > 0)
2974 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2975 ostringstream special;
2976 if (opts.find("hiresbb") != opts.end())
2977 special << "hiresbb,";
2978 if (opts.find("trim") != opts.end())
2980 if (opts.find("viewport") != opts.end())
2981 special << "viewport=" << opts["viewport"] << ',';
2982 if (opts.find("totalheight") != opts.end())
2983 special << "totalheight=" << opts["totalheight"] << ',';
2984 if (opts.find("type") != opts.end())
2985 special << "type=" << opts["type"] << ',';
2986 if (opts.find("ext") != opts.end())
2987 special << "ext=" << opts["ext"] << ',';
2988 if (opts.find("read") != opts.end())
2989 special << "read=" << opts["read"] << ',';
2990 if (opts.find("command") != opts.end())
2991 special << "command=" << opts["command"] << ',';
2992 string s_special = special.str();
2993 if (!s_special.empty()) {
2994 // We had special arguments. Remove the trailing ','.
2995 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2997 // TODO: Handle the unknown settings better.
2998 // Warn about invalid options.
2999 // Check whether some option was given twice.
3001 preamble.registerAutomaticallyLoadedPackage("graphicx");
3004 else if (t.cs() == "footnote" ||
3005 (t.cs() == "thanks" && context.layout->intitle)) {
3007 context.check_layout(os);
3008 begin_inset(os, "Foot\n");
3009 os << "status collapsed\n\n";
3010 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3014 else if (t.cs() == "marginpar") {
3016 context.check_layout(os);
3017 begin_inset(os, "Marginal\n");
3018 os << "status collapsed\n\n";
3019 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3023 else if (t.cs() == "lstinline") {
3025 parse_listings(p, os, context, true);
3028 else if (t.cs() == "ensuremath") {
3030 context.check_layout(os);
3031 string const s = p.verbatim_item();
3032 //FIXME: this never triggers in UTF8
3033 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3036 output_ert_inset(os, "\\ensuremath{" + s + "}",
3040 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3041 if (preamble.titleLayoutFound()) {
3043 skip_spaces_braces(p);
3045 output_ert_inset(os, t.asInput(), context);
3048 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3049 context.check_layout(os);
3050 begin_command_inset(os, "toc", t.cs());
3052 skip_spaces_braces(p);
3053 if (t.cs() == "lstlistoflistings")
3054 preamble.registerAutomaticallyLoadedPackage("listings");
3057 else if (t.cs() == "listoffigures") {
3058 context.check_layout(os);
3059 begin_inset(os, "FloatList figure\n");
3061 skip_spaces_braces(p);
3064 else if (t.cs() == "listoftables") {
3065 context.check_layout(os);
3066 begin_inset(os, "FloatList table\n");
3068 skip_spaces_braces(p);
3071 else if (t.cs() == "listof") {
3072 p.skip_spaces(true);
3073 string const name = p.get_token().cs();
3074 if (context.textclass.floats().typeExist(name)) {
3075 context.check_layout(os);
3076 begin_inset(os, "FloatList ");
3079 p.get_token(); // swallow second arg
3081 output_ert_inset(os, "\\listof{" + name + "}", context);
3084 else if ((where = is_known(t.cs(), known_text_font_families)))
3085 parse_text_attributes(p, os, FLAG_ITEM, outer,
3086 context, "\\family", context.font.family,
3087 known_coded_font_families[where - known_text_font_families]);
3089 else if ((where = is_known(t.cs(), known_text_font_series)))
3090 parse_text_attributes(p, os, FLAG_ITEM, outer,
3091 context, "\\series", context.font.series,
3092 known_coded_font_series[where - known_text_font_series]);
3094 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3095 parse_text_attributes(p, os, FLAG_ITEM, outer,
3096 context, "\\shape", context.font.shape,
3097 known_coded_font_shapes[where - known_text_font_shapes]);
3099 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3100 context.check_layout(os);
3101 TeXFont oldFont = context.font;
3102 context.font.init();
3103 context.font.size = oldFont.size;
3104 os << "\n\\family " << context.font.family << "\n";
3105 os << "\n\\series " << context.font.series << "\n";
3106 os << "\n\\shape " << context.font.shape << "\n";
3107 if (t.cs() == "textnormal") {
3108 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3109 output_font_change(os, context.font, oldFont);
3110 context.font = oldFont;
3112 eat_whitespace(p, os, context, false);
3115 else if (t.cs() == "textcolor") {
3116 // scheme is \textcolor{color name}{text}
3117 string const color = p.verbatim_item();
3118 // we only support the predefined colors of the color package
3119 if (color == "black" || color == "blue" || color == "cyan"
3120 || color == "green" || color == "magenta" || color == "red"
3121 || color == "white" || color == "yellow") {
3122 context.check_layout(os);
3123 os << "\n\\color " << color << "\n";
3124 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3125 context.check_layout(os);
3126 os << "\n\\color inherit\n";
3127 preamble.registerAutomaticallyLoadedPackage("color");
3129 // for custom defined colors
3130 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3133 else if (t.cs() == "underbar" || t.cs() == "uline") {
3134 // \underbar is not 100% correct (LyX outputs \uline
3135 // of ulem.sty). The difference is that \ulem allows
3136 // line breaks, and \underbar does not.
3137 // Do NOT handle \underline.
3138 // \underbar cuts through y, g, q, p etc.,
3139 // \underline does not.
3140 context.check_layout(os);
3141 os << "\n\\bar under\n";
3142 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3143 context.check_layout(os);
3144 os << "\n\\bar default\n";
3145 preamble.registerAutomaticallyLoadedPackage("ulem");
3148 else if (t.cs() == "sout") {
3149 context.check_layout(os);
3150 os << "\n\\strikeout on\n";
3151 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3152 context.check_layout(os);
3153 os << "\n\\strikeout default\n";
3154 preamble.registerAutomaticallyLoadedPackage("ulem");
3157 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3158 t.cs() == "emph" || t.cs() == "noun") {
3159 context.check_layout(os);
3160 os << "\n\\" << t.cs() << " on\n";
3161 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3162 context.check_layout(os);
3163 os << "\n\\" << t.cs() << " default\n";
3164 if (t.cs() == "uuline" || t.cs() == "uwave")
3165 preamble.registerAutomaticallyLoadedPackage("ulem");
3168 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3169 context.check_layout(os);
3170 string name = p.getArg('{', '}');
3171 string localtime = p.getArg('{', '}');
3172 preamble.registerAuthor(name);
3173 Author const & author = preamble.getAuthor(name);
3174 // from_asctime_utc() will fail if LyX decides to output the
3175 // time in the text language.
3176 time_t ptime = from_asctime_utc(localtime);
3177 if (ptime == static_cast<time_t>(-1)) {
3178 cerr << "Warning: Could not parse time `" << localtime
3179 << "´ for change tracking, using current time instead.\n";
3180 ptime = current_time();
3182 if (t.cs() == "lyxadded")
3183 os << "\n\\change_inserted ";
3185 os << "\n\\change_deleted ";
3186 os << author.bufferId() << ' ' << ptime << '\n';
3187 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3188 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3189 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3190 LaTeXPackages::isAvailable("xcolor");
3191 // No need to test for luatex, since luatex comes in
3192 // two flavours (dvi and pdf), like latex, and those
3193 // are detected by pdflatex.
3194 if (pdflatex || xetex) {
3196 preamble.registerAutomaticallyLoadedPackage("ulem");
3197 preamble.registerAutomaticallyLoadedPackage("xcolor");
3198 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3202 preamble.registerAutomaticallyLoadedPackage("dvipost");
3203 } else if (xcolorulem) {
3204 preamble.registerAutomaticallyLoadedPackage("ulem");
3205 preamble.registerAutomaticallyLoadedPackage("xcolor");
3210 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3211 t.cs() == "vphantom") {
3212 context.check_layout(os);
3213 if (t.cs() == "phantom")
3214 begin_inset(os, "Phantom Phantom\n");
3215 if (t.cs() == "hphantom")
3216 begin_inset(os, "Phantom HPhantom\n");
3217 if (t.cs() == "vphantom")
3218 begin_inset(os, "Phantom VPhantom\n");
3219 os << "status open\n";
3220 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3225 else if (t.cs() == "href") {
3226 context.check_layout(os);
3227 string target = convert_command_inset_arg(p.verbatim_item());
3228 string name = convert_command_inset_arg(p.verbatim_item());
3230 size_t i = target.find(':');
3231 if (i != string::npos) {
3232 type = target.substr(0, i + 1);
3233 if (type == "mailto:" || type == "file:")
3234 target = target.substr(i + 1);
3235 // handle the case that name is equal to target, except of "http://"
3236 else if (target.substr(i + 3) == name && type == "http:")
3239 begin_command_inset(os, "href", "href");
3241 os << "name \"" << name << "\"\n";
3242 os << "target \"" << target << "\"\n";
3243 if (type == "mailto:" || type == "file:")
3244 os << "type \"" << type << "\"\n";
3246 skip_spaces_braces(p);
3249 else if (t.cs() == "lyxline") {
3250 // swallow size argument (it is not used anyway)
3252 if (!context.atParagraphStart()) {
3253 // so our line is in the middle of a paragraph
3254 // we need to add a new line, lest this line
3255 // follow the other content on that line and
3256 // run off the side of the page
3257 // FIXME: This may create an empty paragraph,
3258 // but without that it would not be
3259 // possible to set noindent below.
3260 // Fortunately LaTeX does not care
3261 // about the empty paragraph.
3262 context.new_paragraph(os);
3264 if (preamble.indentParagraphs()) {
3265 // we need to unindent, lest the line be too long
3266 context.add_par_extra_stuff("\\noindent\n");
3268 context.check_layout(os);
3269 begin_command_inset(os, "line", "rule");
3270 os << "offset \"0.5ex\"\n"
3271 "width \"100line%\"\n"
3276 else if (t.cs() == "rule") {
3277 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3278 string const width = p.getArg('{', '}');
3279 string const thickness = p.getArg('{', '}');
3280 context.check_layout(os);
3281 begin_command_inset(os, "line", "rule");
3282 if (!offset.empty())
3283 os << "offset \"" << translate_len(offset) << "\"\n";
3284 os << "width \"" << translate_len(width) << "\"\n"
3285 "height \"" << translate_len(thickness) << "\"\n";
3289 else if (is_known(t.cs(), known_phrases) ||
3290 (t.cs() == "protect" &&
3291 p.next_token().cat() == catEscape &&
3292 is_known(p.next_token().cs(), known_phrases))) {
3293 // LyX sometimes puts a \protect in front, so we have to ignore it
3294 // FIXME: This needs to be changed when bug 4752 is fixed.
3296 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3298 context.check_layout(os);
3299 os << known_coded_phrases[where - known_phrases];
3300 skip_spaces_braces(p);
3303 else if ((where = is_known(t.cs(), known_ref_commands))) {
3304 // \eqref can also occur if refstyle is used
3305 if (t.cs() == "eqref" && preamble.refstyle() == "1") {
3306 context.check_layout(os);
3307 begin_command_inset(os, "ref", "formatted");
3308 os << "reference \"eq:"
3309 << convert_command_inset_arg(p.verbatim_item())
3312 preamble.registerAutomaticallyLoadedPackage("refstyle");
3314 string const opt = p.getOpt();
3316 context.check_layout(os);
3317 begin_command_inset(os, "ref",
3318 known_coded_ref_commands[where - known_ref_commands]);
3319 os << "reference \""
3320 << convert_command_inset_arg(p.verbatim_item())
3323 if (t.cs() == "vref" || t.cs() == "vpageref")
3324 preamble.registerAutomaticallyLoadedPackage("varioref");
3326 // LyX does not yet support optional arguments of ref commands
3327 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3328 p.verbatim_item() + "}", context);
3333 else if ((where = is_known(t.cs(), known_refstyle_commands))) {
3334 context.check_layout(os);
3335 // \eqref can also occur if refstyle is not used
3336 // this case is already handled in the previous else if
3337 begin_command_inset(os, "ref", "formatted");
3338 os << "reference \"";
3339 os << known_refstyle_prefixes[where - known_refstyle_commands]
3341 os << convert_command_inset_arg(p.verbatim_item())
3344 preamble.registerAutomaticallyLoadedPackage("refstyle");
3347 else if (use_natbib &&
3348 is_known(t.cs(), known_natbib_commands) &&
3349 ((t.cs() != "citefullauthor" &&
3350 t.cs() != "citeyear" &&
3351 t.cs() != "citeyearpar") ||
3352 p.next_token().asInput() != "*")) {
3353 context.check_layout(os);
3354 string command = t.cs();
3355 if (p.next_token().asInput() == "*") {
3359 if (command == "citefullauthor")
3360 // alternative name for "\\citeauthor*"
3361 command = "citeauthor*";
3363 // text before the citation
3365 // text after the citation
3367 get_cite_arguments(p, true, before, after);
3369 if (command == "cite") {
3370 // \cite without optional argument means
3371 // \citet, \cite with at least one optional
3372 // argument means \citep.
3373 if (before.empty() && after.empty())
3378 if (before.empty() && after == "[]")
3379 // avoid \citet[]{a}
3381 else if (before == "[]" && after == "[]") {
3382 // avoid \citet[][]{a}
3386 // remove the brackets around after and before
3387 if (!after.empty()) {
3389 after.erase(after.length() - 1, 1);
3390 after = convert_command_inset_arg(after);
3392 if (!before.empty()) {
3394 before.erase(before.length() - 1, 1);
3395 before = convert_command_inset_arg(before);
3397 begin_command_inset(os, "citation", command);
3398 os << "after " << '"' << after << '"' << "\n";
3399 os << "before " << '"' << before << '"' << "\n";
3401 << convert_command_inset_arg(p.verbatim_item())
3404 // Need to set the cite engine if natbib is loaded by
3405 // the document class directly
3406 if (preamble.citeEngine() == "basic")
3407 preamble.citeEngine("natbib");
3410 else if (use_jurabib &&
3411 is_known(t.cs(), known_jurabib_commands) &&
3412 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3413 context.check_layout(os);
3414 string command = t.cs();
3415 if (p.next_token().asInput() == "*") {
3419 char argumentOrder = '\0';
3420 vector<string> const options =
3421 preamble.getPackageOptions("jurabib");
3422 if (find(options.begin(), options.end(),
3423 "natbiborder") != options.end())
3424 argumentOrder = 'n';
3425 else if (find(options.begin(), options.end(),
3426 "jurabiborder") != options.end())
3427 argumentOrder = 'j';
3429 // text before the citation
3431 // text after the citation
3433 get_cite_arguments(p, argumentOrder != 'j', before, after);
3435 string const citation = p.verbatim_item();
3436 if (!before.empty() && argumentOrder == '\0') {
3437 cerr << "Warning: Assuming argument order "
3438 "of jurabib version 0.6 for\n'"
3439 << command << before << after << '{'
3440 << citation << "}'.\n"
3441 "Add 'jurabiborder' to the jurabib "
3442 "package options if you used an\n"
3443 "earlier jurabib version." << endl;
3445 if (!after.empty()) {
3447 after.erase(after.length() - 1, 1);
3449 if (!before.empty()) {
3451 before.erase(before.length() - 1, 1);
3453 begin_command_inset(os, "citation", command);
3454 os << "after " << '"' << after << '"' << "\n";
3455 os << "before " << '"' << before << '"' << "\n";
3456 os << "key " << '"' << citation << '"' << "\n";
3458 // Need to set the cite engine if jurabib is loaded by
3459 // the document class directly
3460 if (preamble.citeEngine() == "basic")
3461 preamble.citeEngine("jurabib");
3464 else if (t.cs() == "cite"
3465 || t.cs() == "nocite") {
3466 context.check_layout(os);
3467 string after = convert_command_inset_arg(p.getArg('[', ']'));
3468 string key = convert_command_inset_arg(p.verbatim_item());
3469 // store the case that it is "\nocite{*}" to use it later for
3472 begin_command_inset(os, "citation", t.cs());
3473 os << "after " << '"' << after << '"' << "\n";
3474 os << "key " << '"' << key << '"' << "\n";
3476 } else if (t.cs() == "nocite")
3480 else if (t.cs() == "index" ||
3481 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3482 context.check_layout(os);
3483 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3484 p.getArg('[', ']') : "";
3485 string const kind = arg.empty() ? "idx" : arg;
3486 begin_inset(os, "Index ");
3487 os << kind << "\nstatus collapsed\n";
3488 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3491 preamble.registerAutomaticallyLoadedPackage("splitidx");
3494 else if (t.cs() == "nomenclature") {
3495 context.check_layout(os);
3496 begin_command_inset(os, "nomenclature", "nomenclature");
3497 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3498 if (!prefix.empty())
3499 os << "prefix " << '"' << prefix << '"' << "\n";
3500 os << "symbol " << '"'
3501 << convert_command_inset_arg(p.verbatim_item());
3502 os << "\"\ndescription \""
3503 << convert_command_inset_arg(p.verbatim_item())
3506 preamble.registerAutomaticallyLoadedPackage("nomencl");
3509 else if (t.cs() == "label") {
3510 context.check_layout(os);
3511 begin_command_inset(os, "label", "label");
3513 << convert_command_inset_arg(p.verbatim_item())
3518 else if (t.cs() == "printindex") {
3519 context.check_layout(os);
3520 begin_command_inset(os, "index_print", "printindex");
3521 os << "type \"idx\"\n";
3523 skip_spaces_braces(p);
3524 preamble.registerAutomaticallyLoadedPackage("makeidx");
3525 if (preamble.use_indices() == "true")
3526 preamble.registerAutomaticallyLoadedPackage("splitidx");
3529 else if (t.cs() == "printnomenclature") {
3531 string width_type = "";
3532 context.check_layout(os);
3533 begin_command_inset(os, "nomencl_print", "printnomenclature");
3534 // case of a custom width
3536 width = p.getArg('[', ']');
3537 width = translate_len(width);
3538 width_type = "custom";
3540 // case of no custom width
3541 // the case of no custom width but the width set
3542 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3543 // because the user could have set anything, not only the width
3544 // of the longest label (which would be width_type = "auto")
3545 string label = convert_command_inset_arg(p.getArg('{', '}'));
3546 if (label.empty() && width_type.empty())
3547 width_type = "none";
3548 os << "set_width \"" << width_type << "\"\n";
3549 if (width_type == "custom")
3550 os << "width \"" << width << '\"';
3552 skip_spaces_braces(p);
3553 preamble.registerAutomaticallyLoadedPackage("nomencl");
3556 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3557 context.check_layout(os);
3558 begin_inset(os, "script ");
3559 os << t.cs().substr(4) << '\n';
3560 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3562 if (t.cs() == "textsubscript")
3563 preamble.registerAutomaticallyLoadedPackage("subscript");
3566 else if ((where = is_known(t.cs(), known_quotes))) {
3567 context.check_layout(os);
3568 begin_inset(os, "Quotes ");
3569 os << known_coded_quotes[where - known_quotes];
3571 // LyX adds {} after the quote, so we have to eat
3572 // spaces here if there are any before a possible
3574 eat_whitespace(p, os, context, false);
3578 else if ((where = is_known(t.cs(), known_sizes)) &&
3579 context.new_layout_allowed) {
3580 context.check_layout(os);
3581 TeXFont const oldFont = context.font;
3582 context.font.size = known_coded_sizes[where - known_sizes];
3583 output_font_change(os, oldFont, context.font);
3584 eat_whitespace(p, os, context, false);
3587 else if ((where = is_known(t.cs(), known_font_families)) &&
3588 context.new_layout_allowed) {
3589 context.check_layout(os);
3590 TeXFont const oldFont = context.font;
3591 context.font.family =
3592 known_coded_font_families[where - known_font_families];
3593 output_font_change(os, oldFont, context.font);
3594 eat_whitespace(p, os, context, false);
3597 else if ((where = is_known(t.cs(), known_font_series)) &&
3598 context.new_layout_allowed) {
3599 context.check_layout(os);
3600 TeXFont const oldFont = context.font;
3601 context.font.series =
3602 known_coded_font_series[where - known_font_series];
3603 output_font_change(os, oldFont, context.font);
3604 eat_whitespace(p, os, context, false);
3607 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3608 context.new_layout_allowed) {
3609 context.check_layout(os);
3610 TeXFont const oldFont = context.font;
3611 context.font.shape =
3612 known_coded_font_shapes[where - known_font_shapes];
3613 output_font_change(os, oldFont, context.font);
3614 eat_whitespace(p, os, context, false);
3616 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3617 context.new_layout_allowed) {
3618 context.check_layout(os);
3619 TeXFont const oldFont = context.font;
3620 context.font.init();
3621 context.font.size = oldFont.size;
3622 context.font.family =
3623 known_coded_font_families[where - known_old_font_families];
3624 output_font_change(os, oldFont, context.font);
3625 eat_whitespace(p, os, context, false);
3628 else if ((where = is_known(t.cs(), known_old_font_series)) &&
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.series =
3635 known_coded_font_series[where - known_old_font_series];
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_shapes)) &&
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.shape =
3647 known_coded_font_shapes[where - known_old_font_shapes];
3648 output_font_change(os, oldFont, context.font);
3649 eat_whitespace(p, os, context, false);
3652 else if (t.cs() == "selectlanguage") {
3653 context.check_layout(os);
3654 // save the language for the case that a
3655 // \foreignlanguage is used
3656 context.font.language = babel2lyx(p.verbatim_item());
3657 os << "\n\\lang " << context.font.language << "\n";
3660 else if (t.cs() == "foreignlanguage") {
3661 string const lang = babel2lyx(p.verbatim_item());
3662 parse_text_attributes(p, os, FLAG_ITEM, outer,
3664 context.font.language, lang);
3667 else if (prefixIs(t.cs(), "text")
3668 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3669 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3671 // We have to output the whole command if it has an option
3672 // because LyX doesn't support this yet, see bug #8214,
3673 // only if there is a single option specifying a variant, we can handle it.
3675 string langopts = p.getOpt();
3676 // check if the option contains a variant, if yes, extract it
3677 string::size_type pos_var = langopts.find("variant");
3678 string::size_type i = langopts.find(',');
3679 string::size_type k = langopts.find('=', pos_var);
3680 if (pos_var != string::npos && i == string::npos) {
3682 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3683 lang = preamble.polyglossia2lyx(variant);
3684 parse_text_attributes(p, os, FLAG_ITEM, outer,
3686 context.font.language, lang);
3688 output_ert_inset(os, t.asInput() + langopts, context);
3690 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3691 parse_text_attributes(p, os, FLAG_ITEM, outer,
3693 context.font.language, lang);
3697 else if (t.cs() == "inputencoding") {
3698 // nothing to write here
3699 string const enc = subst(p.verbatim_item(), "\n", " ");
3700 p.setEncoding(enc, Encoding::inputenc);
3703 else if ((where = is_known(t.cs(), known_special_chars))) {
3704 context.check_layout(os);
3705 os << "\\SpecialChar \\"
3706 << known_coded_special_chars[where - known_special_chars]
3708 skip_spaces_braces(p);
3711 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3712 context.check_layout(os);
3713 os << "\\SpecialChar \\nobreakdash-\n";
3717 else if (t.cs() == "textquotedbl") {
3718 context.check_layout(os);
3723 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3724 context.check_layout(os);
3725 os << "\\SpecialChar \\@.\n";
3729 else if (t.cs() == "-") {
3730 context.check_layout(os);
3731 os << "\\SpecialChar \\-\n";
3734 else if (t.cs() == "textasciitilde") {
3735 context.check_layout(os);
3737 skip_spaces_braces(p);
3740 else if (t.cs() == "textasciicircum") {
3741 context.check_layout(os);
3743 skip_spaces_braces(p);
3746 else if (t.cs() == "textbackslash") {
3747 context.check_layout(os);
3748 os << "\n\\backslash\n";
3749 skip_spaces_braces(p);
3752 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3753 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3755 context.check_layout(os);
3759 else if (t.cs() == "char") {
3760 context.check_layout(os);
3761 if (p.next_token().character() == '`') {
3763 if (p.next_token().cs() == "\"") {
3768 output_ert_inset(os, "\\char`", context);
3771 output_ert_inset(os, "\\char", context);
3775 else if (t.cs() == "verb") {
3776 context.check_layout(os);
3777 // set catcodes to verbatim early, just in case.
3778 p.setCatcodes(VERBATIM_CATCODES);
3779 string delim = p.get_token().asInput();
3780 string const arg = p.verbatimStuff(delim);
3781 output_ert_inset(os, "\\verb" + delim + arg + delim, context);
3784 // Problem: \= creates a tabstop inside the tabbing environment
3785 // and else an accent. In the latter case we really would want
3786 // \={o} instead of \= o.
3787 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3788 output_ert_inset(os, t.asInput(), context);
3790 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3791 else if (t.cs().size() == 1
3792 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3793 context.check_layout(os);
3794 // try to see whether the string is in unicodesymbols
3797 string command = t.asInput() + "{"
3798 + trimSpaceAndEol(p.verbatim_item())
3801 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3802 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3803 termination, rem, &req);
3806 cerr << "When parsing " << command
3807 << ", result is " << to_utf8(s)
3808 << "+" << to_utf8(rem) << endl;
3810 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3811 preamble.registerAutomaticallyLoadedPackage(*it);
3813 // we did not find a non-ert version
3814 output_ert_inset(os, command, context);
3817 else if (t.cs() == "\\") {
3818 context.check_layout(os);
3820 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3821 else if (p.next_token().asInput() == "*") {
3823 // getOpt() eats the following space if there
3824 // is no optional argument, but that is OK
3825 // here since it has no effect in the output.
3826 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3829 begin_inset(os, "Newline newline");
3834 else if (t.cs() == "newline" ||
3835 (t.cs() == "linebreak" && !p.hasOpt())) {
3836 context.check_layout(os);
3837 begin_inset(os, "Newline ");
3840 skip_spaces_braces(p);
3843 else if (t.cs() == "input" || t.cs() == "include"
3844 || t.cs() == "verbatiminput") {
3845 string name = t.cs();
3846 if (t.cs() == "verbatiminput"
3847 && p.next_token().asInput() == "*")
3848 name += p.get_token().asInput();
3849 context.check_layout(os);
3850 string filename(normalize_filename(p.getArg('{', '}')));
3851 string const path = getMasterFilePath(true);
3852 // We want to preserve relative / absolute filenames,
3853 // therefore path is only used for testing
3854 if ((t.cs() == "include" || t.cs() == "input") &&
3855 !makeAbsPath(filename, path).exists()) {
3856 // The file extension is probably missing.
3857 // Now try to find it out.
3858 string const tex_name =
3859 find_file(filename, path,
3860 known_tex_extensions);
3861 if (!tex_name.empty())
3862 filename = tex_name;
3864 bool external = false;
3866 if (makeAbsPath(filename, path).exists()) {
3867 string const abstexname =
3868 makeAbsPath(filename, path).absFileName();
3869 string const absfigname =
3870 changeExtension(abstexname, ".fig");
3871 fix_child_filename(filename);
3872 string const lyxname =
3873 changeExtension(filename, ".lyx");
3874 string const abslyxname = makeAbsPath(
3875 lyxname, getParentFilePath(false)).absFileName();
3877 if (!skipChildren())
3878 external = FileName(absfigname).exists();
3879 if (t.cs() == "input" && !skipChildren()) {
3880 string const ext = getExtension(abstexname);
3882 // Combined PS/LaTeX:
3883 // x.eps, x.pstex_t (old xfig)
3884 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3885 FileName const absepsname(
3886 changeExtension(abstexname, ".eps"));
3887 FileName const abspstexname(
3888 changeExtension(abstexname, ".pstex"));
3889 bool const xfigeps =
3890 (absepsname.exists() ||
3891 abspstexname.exists()) &&
3894 // Combined PDF/LaTeX:
3895 // x.pdf, x.pdftex_t (old xfig)
3896 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3897 FileName const abspdfname(
3898 changeExtension(abstexname, ".pdf"));
3899 bool const xfigpdf =
3900 abspdfname.exists() &&
3901 (ext == "pdftex_t" || ext == "pdf_t");
3905 // Combined PS/PDF/LaTeX:
3906 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3907 string const absbase2(
3908 removeExtension(abstexname) + "_pspdftex");
3909 FileName const abseps2name(
3910 addExtension(absbase2, ".eps"));
3911 FileName const abspdf2name(
3912 addExtension(absbase2, ".pdf"));
3913 bool const xfigboth =
3914 abspdf2name.exists() &&
3915 abseps2name.exists() && ext == "pspdftex";
3917 xfig = xfigpdf || xfigeps || xfigboth;
3918 external = external && xfig;
3921 outname = changeExtension(filename, ".fig");
3922 FileName abssrc(changeExtension(abstexname, ".fig"));
3923 copy_file(abssrc, outname);
3925 // Don't try to convert, the result
3926 // would be full of ERT.
3928 FileName abssrc(abstexname);
3929 copy_file(abssrc, outname);
3930 } else if (t.cs() != "verbatiminput" &&
3932 tex2lyx(abstexname, FileName(abslyxname),
3935 // no need to call copy_file
3936 // tex2lyx creates the file
3939 FileName abssrc(abstexname);
3940 copy_file(abssrc, outname);
3943 cerr << "Warning: Could not find included file '"
3944 << filename << "'." << endl;
3948 begin_inset(os, "External\n");
3949 os << "\ttemplate XFig\n"
3950 << "\tfilename " << outname << '\n';
3951 registerExternalTemplatePackages("XFig");
3953 begin_command_inset(os, "include", name);
3954 outname = subst(outname, "\"", "\\\"");
3955 os << "preview false\n"
3956 "filename \"" << outname << "\"\n";
3957 if (t.cs() == "verbatiminput")
3958 preamble.registerAutomaticallyLoadedPackage("verbatim");
3963 else if (t.cs() == "bibliographystyle") {
3964 // store new bibliographystyle
3965 bibliographystyle = p.verbatim_item();
3966 // If any other command than \bibliography and
3967 // \nocite{*} follows, we need to output the style
3968 // (because it might be used by that command).
3969 // Otherwise, it will automatically be output by LyX.
3972 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3973 if (t2.cat() == catBegin)
3975 if (t2.cat() != catEscape)
3977 if (t2.cs() == "nocite") {
3978 if (p.getArg('{', '}') == "*")
3980 } else if (t2.cs() == "bibliography")
3986 output_ert_inset(os,
3987 "\\bibliographystyle{" + bibliographystyle + '}',
3992 else if (t.cs() == "bibliography") {
3993 context.check_layout(os);
3994 begin_command_inset(os, "bibtex", "bibtex");
3995 if (!btprint.empty()) {
3996 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3997 // clear the string because the next BibTeX inset can be without the
3998 // \nocite{*} option
4001 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4002 // Do we have a bibliographystyle set?
4003 if (!bibliographystyle.empty())
4004 os << "options " << '"' << bibliographystyle << '"' << "\n";
4008 else if (t.cs() == "parbox") {
4009 // Test whether this is an outer box of a shaded box
4011 // swallow arguments
4012 while (p.hasOpt()) {
4014 p.skip_spaces(true);
4017 p.skip_spaces(true);
4019 if (p.next_token().cat() == catBegin)
4021 p.skip_spaces(true);
4022 Token to = p.get_token();
4023 bool shaded = false;
4024 if (to.asInput() == "\\begin") {
4025 p.skip_spaces(true);
4026 if (p.getArg('{', '}') == "shaded")
4031 parse_outer_box(p, os, FLAG_ITEM, outer,
4032 context, "parbox", "shaded");
4034 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4038 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4039 t.cs() == "shadowbox" || t.cs() == "doublebox")
4040 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4042 else if (t.cs() == "framebox") {
4043 if (p.next_token().character() == '(') {
4044 //the syntax is: \framebox(x,y)[position]{content}
4045 string arg = t.asInput();
4046 arg += p.getFullParentheseArg();
4047 arg += p.getFullOpt();
4048 eat_whitespace(p, os, context, false);
4049 output_ert_inset(os, arg + '{', context);
4050 parse_text(p, os, FLAG_ITEM, outer, context);
4051 output_ert_inset(os, "}", context);
4053 string special = p.getFullOpt();
4054 special += p.getOpt();
4055 // LyX does not yet support \framebox without any option
4056 if (!special.empty())
4057 parse_outer_box(p, os, FLAG_ITEM, outer,
4058 context, t.cs(), special);
4060 eat_whitespace(p, os, context, false);
4061 output_ert_inset(os, "\\framebox{", context);
4062 parse_text(p, os, FLAG_ITEM, outer, context);
4063 output_ert_inset(os, "}", context);
4068 //\makebox() is part of the picture environment and different from \makebox{}
4069 //\makebox{} will be parsed by parse_box
4070 else if (t.cs() == "makebox") {
4071 if (p.next_token().character() == '(') {
4072 //the syntax is: \makebox(x,y)[position]{content}
4073 string arg = t.asInput();
4074 arg += p.getFullParentheseArg();
4075 arg += p.getFullOpt();
4076 eat_whitespace(p, os, context, false);
4077 output_ert_inset(os, arg + '{', context);
4078 parse_text(p, os, FLAG_ITEM, outer, context);
4079 output_ert_inset(os, "}", context);
4081 //the syntax is: \makebox[width][position]{content}
4082 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4086 else if (t.cs() == "smallskip" ||
4087 t.cs() == "medskip" ||
4088 t.cs() == "bigskip" ||
4089 t.cs() == "vfill") {
4090 context.check_layout(os);
4091 begin_inset(os, "VSpace ");
4094 skip_spaces_braces(p);
4097 else if ((where = is_known(t.cs(), known_spaces))) {
4098 context.check_layout(os);
4099 begin_inset(os, "space ");
4100 os << '\\' << known_coded_spaces[where - known_spaces]
4103 // LaTeX swallows whitespace after all spaces except
4104 // "\\,". We have to do that here, too, because LyX
4105 // adds "{}" which would make the spaces significant.
4107 eat_whitespace(p, os, context, false);
4108 // LyX adds "{}" after all spaces except "\\ " and
4109 // "\\,", so we have to remove "{}".
4110 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4111 // remove the braces after "\\,", too.
4116 else if (t.cs() == "newpage" ||
4117 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4118 t.cs() == "clearpage" ||
4119 t.cs() == "cleardoublepage") {
4120 context.check_layout(os);
4121 begin_inset(os, "Newpage ");
4124 skip_spaces_braces(p);
4127 else if (t.cs() == "DeclareRobustCommand" ||
4128 t.cs() == "DeclareRobustCommandx" ||
4129 t.cs() == "newcommand" ||
4130 t.cs() == "newcommandx" ||
4131 t.cs() == "providecommand" ||
4132 t.cs() == "providecommandx" ||
4133 t.cs() == "renewcommand" ||
4134 t.cs() == "renewcommandx") {
4135 // DeclareRobustCommand, DeclareRobustCommandx,
4136 // providecommand and providecommandx could be handled
4137 // by parse_command(), but we need to call
4138 // add_known_command() here.
4139 string name = t.asInput();
4140 if (p.next_token().asInput() == "*") {
4141 // Starred form. Eat '*'
4145 string const command = p.verbatim_item();
4146 string const opt1 = p.getFullOpt();
4147 string const opt2 = p.getFullOpt();
4148 add_known_command(command, opt1, !opt2.empty());
4149 string const ert = name + '{' + command + '}' +
4151 '{' + p.verbatim_item() + '}';
4153 if (t.cs() == "DeclareRobustCommand" ||
4154 t.cs() == "DeclareRobustCommandx" ||
4155 t.cs() == "providecommand" ||
4156 t.cs() == "providecommandx" ||
4157 name[name.length()-1] == '*')
4158 output_ert_inset(os, ert, context);
4160 context.check_layout(os);
4161 begin_inset(os, "FormulaMacro");
4167 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4168 // let could be handled by parse_command(),
4169 // but we need to call add_known_command() here.
4170 string ert = t.asInput();
4173 if (p.next_token().cat() == catBegin) {
4174 name = p.verbatim_item();
4175 ert += '{' + name + '}';
4177 name = p.verbatim_item();
4182 if (p.next_token().cat() == catBegin) {
4183 command = p.verbatim_item();
4184 ert += '{' + command + '}';
4186 command = p.verbatim_item();
4189 // If command is known, make name known too, to parse
4190 // its arguments correctly. For this reason we also
4191 // have commands in syntax.default that are hardcoded.
4192 CommandMap::iterator it = known_commands.find(command);
4193 if (it != known_commands.end())
4194 known_commands[t.asInput()] = it->second;
4195 output_ert_inset(os, ert, context);
4198 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4199 bool starred = false;
4200 if (p.next_token().asInput() == "*") {
4204 string name = t.asInput();
4205 string const length = p.verbatim_item();
4208 bool valid = splitLatexLength(length, valstring, unit);
4209 bool known_hspace = false;
4210 bool known_vspace = false;
4211 bool known_unit = false;
4214 istringstream iss(valstring);
4217 if (t.cs()[0] == 'h') {
4218 if (unit == "\\fill") {
4223 known_hspace = true;
4226 if (unit == "\\smallskipamount") {
4228 known_vspace = true;
4229 } else if (unit == "\\medskipamount") {
4231 known_vspace = true;
4232 } else if (unit == "\\bigskipamount") {
4234 known_vspace = true;
4235 } else if (unit == "\\fill") {
4237 known_vspace = true;
4241 if (!known_hspace && !known_vspace) {
4242 switch (unitFromString(unit)) {
4263 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4264 // Literal horizontal length or known variable
4265 context.check_layout(os);
4266 begin_inset(os, "space ");
4274 if (known_unit && !known_hspace)
4276 << translate_len(length);
4278 } else if (known_unit || known_vspace) {
4279 // Literal vertical length or known variable
4280 context.check_layout(os);
4281 begin_inset(os, "VSpace ");
4289 // LyX can't handle other length variables in Inset VSpace/space
4294 output_ert_inset(os, name + '{' + unit + '}', context);
4295 else if (value == -1.0)
4296 output_ert_inset(os, name + "{-" + unit + '}', context);
4298 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4300 output_ert_inset(os, name + '{' + length + '}', context);
4304 // The single '=' is meant here.
4305 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4307 context.check_layout(os);
4308 begin_inset(os, "Flex ");
4309 os << to_utf8(newinsetlayout->name()) << '\n'
4310 << "status collapsed\n";
4311 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4315 else if (t.cs() == "includepdf") {
4317 string const arg = p.getArg('[', ']');
4318 map<string, string> opts;
4319 vector<string> keys;
4320 split_map(arg, opts, keys);
4321 string name = normalize_filename(p.verbatim_item());
4322 string const path = getMasterFilePath(true);
4323 // We want to preserve relative / absolute filenames,
4324 // therefore path is only used for testing
4325 if (!makeAbsPath(name, path).exists()) {
4326 // The file extension is probably missing.
4327 // Now try to find it out.
4328 char const * const pdfpages_format[] = {"pdf", 0};
4329 string const pdftex_name =
4330 find_file(name, path, pdfpages_format);
4331 if (!pdftex_name.empty()) {
4336 FileName const absname = makeAbsPath(name, path);
4337 if (absname.exists())
4339 fix_child_filename(name);
4340 copy_file(absname, name);
4342 cerr << "Warning: Could not find file '"
4343 << name << "'." << endl;
4345 context.check_layout(os);
4346 begin_inset(os, "External\n\ttemplate ");
4347 os << "PDFPages\n\tfilename "
4349 // parse the options
4350 if (opts.find("pages") != opts.end())
4351 os << "\textra LaTeX \"pages="
4352 << opts["pages"] << "\"\n";
4353 if (opts.find("angle") != opts.end())
4354 os << "\trotateAngle "
4355 << opts["angle"] << '\n';
4356 if (opts.find("origin") != opts.end()) {
4358 string const opt = opts["origin"];
4359 if (opt == "tl") ss << "topleft";
4360 if (opt == "bl") ss << "bottomleft";
4361 if (opt == "Bl") ss << "baselineleft";
4362 if (opt == "c") ss << "center";
4363 if (opt == "tc") ss << "topcenter";
4364 if (opt == "bc") ss << "bottomcenter";
4365 if (opt == "Bc") ss << "baselinecenter";
4366 if (opt == "tr") ss << "topright";
4367 if (opt == "br") ss << "bottomright";
4368 if (opt == "Br") ss << "baselineright";
4369 if (!ss.str().empty())
4370 os << "\trotateOrigin " << ss.str() << '\n';
4372 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4374 if (opts.find("width") != opts.end())
4376 << translate_len(opts["width"]) << '\n';
4377 if (opts.find("height") != opts.end())
4379 << translate_len(opts["height"]) << '\n';
4380 if (opts.find("keepaspectratio") != opts.end())
4381 os << "\tkeepAspectRatio\n";
4383 context.check_layout(os);
4384 registerExternalTemplatePackages("PDFPages");
4387 else if (t.cs() == "loadgame") {
4389 string name = normalize_filename(p.verbatim_item());
4390 string const path = getMasterFilePath(true);
4391 // We want to preserve relative / absolute filenames,
4392 // therefore path is only used for testing
4393 if (!makeAbsPath(name, path).exists()) {
4394 // The file extension is probably missing.
4395 // Now try to find it out.
4396 char const * const lyxskak_format[] = {"fen", 0};
4397 string const lyxskak_name =
4398 find_file(name, path, lyxskak_format);
4399 if (!lyxskak_name.empty())
4400 name = lyxskak_name;
4402 FileName const absname = makeAbsPath(name, path);
4403 if (absname.exists())
4405 fix_child_filename(name);
4406 copy_file(absname, name);
4408 cerr << "Warning: Could not find file '"
4409 << name << "'." << endl;
4410 context.check_layout(os);
4411 begin_inset(os, "External\n\ttemplate ");
4412 os << "ChessDiagram\n\tfilename "
4415 context.check_layout(os);
4416 // after a \loadgame follows a \showboard
4417 if (p.get_token().asInput() == "showboard")
4419 registerExternalTemplatePackages("ChessDiagram");
4423 // try to see whether the string is in unicodesymbols
4424 // Only use text mode commands, since we are in text mode here,
4425 // and math commands may be invalid (bug 6797)
4429 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4430 Encodings::TEXT_CMD, termination, rem, &req);
4433 cerr << "When parsing " << t.cs()
4434 << ", result is " << to_utf8(s)
4435 << "+" << to_utf8(rem) << endl;
4436 context.check_layout(os);
4439 skip_spaces_braces(p);
4440 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4441 preamble.registerAutomaticallyLoadedPackage(*it);
4443 //cerr << "#: " << t << " mode: " << mode << endl;
4444 // heuristic: read up to next non-nested space
4446 string s = t.asInput();
4447 string z = p.verbatim_item();
4448 while (p.good() && z != " " && !z.empty()) {
4449 //cerr << "read: " << z << endl;
4451 z = p.verbatim_item();
4453 cerr << "found ERT: " << s << endl;
4454 output_ert_inset(os, s + ' ', context);
4457 string name = t.asInput();
4458 if (p.next_token().asInput() == "*") {
4459 // Starred commands like \vspace*{}
4460 p.get_token(); // Eat '*'
4463 if (!parse_command(name, p, os, outer, context))
4464 output_ert_inset(os, name, context);
4468 if (flags & FLAG_LEAVE) {
4469 flags &= ~FLAG_LEAVE;
4476 string guessLanguage(Parser & p, string const & lang)
4478 typedef std::map<std::string, size_t> LangMap;
4479 // map from language names to number of characters
4482 for (char const * const * i = supported_CJK_languages; *i; i++)
4483 used[string(*i)] = 0;
4486 Token const t = p.get_token();
4487 // comments are not counted for any language
4488 if (t.cat() == catComment)
4490 // commands are not counted as well, but we need to detect
4491 // \begin{CJK} and switch encoding if needed
4492 if (t.cat() == catEscape) {
4493 if (t.cs() == "inputencoding") {
4494 string const enc = subst(p.verbatim_item(), "\n", " ");
4495 p.setEncoding(enc, Encoding::inputenc);
4498 if (t.cs() != "begin")
4501 // Non-CJK content is counted for lang.
4502 // We do not care about the real language here:
4503 // If we have more non-CJK contents than CJK contents,
4504 // we simply use the language that was specified as
4505 // babel main language.
4506 used[lang] += t.asInput().length();
4509 // Now we are starting an environment
4511 string const name = p.getArg('{', '}');
4512 if (name != "CJK") {
4516 // It is a CJK environment
4518 /* name = */ p.getArg('{', '}');
4519 string const encoding = p.getArg('{', '}');
4520 /* mapping = */ p.getArg('{', '}');
4521 string const encoding_old = p.getEncoding();
4522 char const * const * const where =
4523 is_known(encoding, supported_CJK_encodings);
4525 p.setEncoding(encoding, Encoding::CJK);
4527 p.setEncoding("UTF-8");
4528 string const text = p.ertEnvironment("CJK");
4529 p.setEncoding(encoding_old);
4532 // ignore contents in unknown CJK encoding
4535 // the language of the text
4537 supported_CJK_languages[where - supported_CJK_encodings];
4538 used[cjk] += text.length();
4540 LangMap::const_iterator use = used.begin();
4541 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4542 if (it->second > use->second)