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 string s = p.get_token().asInput();
2110 // number = current arity + 1?
2111 if (s.size() == 1 && s[0] == 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, addcontentslineContent and
2166 // nocite{*} option (needed for bibtex inset)
2168 string contentslineContent;
2169 string bibliographystyle = "default";
2170 bool const use_natbib = isProvided("natbib");
2171 bool const use_jurabib = isProvided("jurabib");
2174 Token const & t = p.get_token();
2176 // it is impossible to determine the correct encoding for non-CJK Japanese.
2177 // Therefore write a note at the beginning of the document
2178 if (is_nonCJKJapanese) {
2179 context.check_layout(os);
2180 begin_inset(os, "Note Note\n");
2181 os << "status open\n\\begin_layout Plain Layout\n"
2182 << "\\series bold\n"
2183 << "Important information:\n"
2184 << "\\end_layout\n\n"
2185 << "\\begin_layout Plain Layout\n"
2186 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2187 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2188 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2189 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2190 << " and specify the encoding using the -e command-line switch.\n"
2191 << " In addition, you might want to double check that the desired output encoding\n"
2192 << " is correctly selected in Document > Settings > Language.\n"
2193 << "\\end_layout\n";
2195 is_nonCJKJapanese = false;
2199 debugToken(cerr, t, flags);
2202 if (flags & FLAG_ITEM) {
2203 if (t.cat() == catSpace)
2206 flags &= ~FLAG_ITEM;
2207 if (t.cat() == catBegin) {
2208 // skip the brace and collect everything to the next matching
2210 flags |= FLAG_BRACE_LAST;
2214 // handle only this single token, leave the loop if done
2215 flags |= FLAG_LEAVE;
2218 if (t.cat() != catEscape && t.character() == ']' &&
2219 (flags & FLAG_BRACK_LAST))
2221 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2224 // If there is anything between \end{env} and \begin{env} we
2225 // don't need to output a separator.
2226 if (t.cat() != catSpace && t.cat() != catNewline &&
2227 t.asInput() != "\\begin")
2233 if (t.cat() == catMath) {
2234 // we are inside some text mode thingy, so opening new math is allowed
2235 context.check_layout(os);
2236 begin_inset(os, "Formula ");
2237 Token const & n = p.get_token();
2238 bool const display(n.cat() == catMath && outer);
2240 // TeX's $$...$$ syntax for displayed math
2242 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2244 p.get_token(); // skip the second '$' token
2246 // simple $...$ stuff
2249 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2254 // Prevent the conversion of a line break to a
2255 // space (bug 7668). This does not change the
2256 // output, but looks ugly in LyX.
2257 eat_whitespace(p, os, context, false);
2261 else if (t.cat() == catSuper || t.cat() == catSub)
2262 cerr << "catcode " << t << " illegal in text mode\n";
2264 // Basic support for english quotes. This should be
2265 // extended to other quotes, but is not so easy (a
2266 // left english quote is the same as a right german
2268 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2269 context.check_layout(os);
2270 begin_inset(os, "Quotes ");
2276 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2277 context.check_layout(os);
2278 begin_inset(os, "Quotes ");
2285 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2286 context.check_layout(os);
2287 begin_inset(os, "Quotes ");
2294 else if (t.asInput() == "<"
2295 && p.next_token().asInput() == "<" && noweb_mode) {
2297 parse_noweb(p, os, context);
2300 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2301 context.check_layout(os);
2302 begin_inset(os, "Quotes ");
2309 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2310 check_space(p, os, context);
2312 else if (t.character() == '[' && noweb_mode &&
2313 p.next_token().character() == '[') {
2314 // These can contain underscores
2316 string const s = p.getFullOpt() + ']';
2317 if (p.next_token().character() == ']')
2320 cerr << "Warning: Inserting missing ']' in '"
2321 << s << "'." << endl;
2322 output_ert_inset(os, s, context);
2325 else if (t.cat() == catLetter) {
2326 context.check_layout(os);
2327 // Workaround for bug 4752.
2328 // FIXME: This whole code block needs to be removed
2329 // when the bug is fixed and tex2lyx produces
2330 // the updated file format.
2331 // The replacement algorithm in LyX is so stupid that
2332 // it even translates a phrase if it is part of a word.
2333 bool handled = false;
2334 for (int const * l = known_phrase_lengths; *l; ++l) {
2335 string phrase = t.cs();
2336 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2337 phrase += p.get_token().cs();
2338 if (is_known(phrase, known_coded_phrases)) {
2339 output_ert_inset(os, phrase, context);
2343 for (size_t i = 1; i < phrase.length(); ++i)
2351 else if (t.cat() == catOther ||
2352 t.cat() == catAlign ||
2353 t.cat() == catParameter) {
2354 // This translates "&" to "\\&" which may be wrong...
2355 context.check_layout(os);
2359 else if (p.isParagraph()) {
2360 if (context.new_layout_allowed)
2361 context.new_paragraph(os);
2363 output_ert_inset(os, "\\par ", context);
2364 eat_whitespace(p, os, context, true);
2367 else if (t.cat() == catActive) {
2368 context.check_layout(os);
2369 if (t.character() == '~') {
2370 if (context.layout->free_spacing)
2373 begin_inset(os, "space ~\n");
2380 else if (t.cat() == catBegin) {
2381 Token const next = p.next_token();
2382 Token const end = p.next_next_token();
2383 if (next.cat() == catEnd) {
2385 Token const prev = p.prev_token();
2387 if (p.next_token().character() == '`' ||
2388 (prev.character() == '-' &&
2389 p.next_token().character() == '-'))
2390 ; // ignore it in {}`` or -{}-
2392 output_ert_inset(os, "{}", context);
2393 } else if (next.cat() == catEscape &&
2394 is_known(next.cs(), known_quotes) &&
2395 end.cat() == catEnd) {
2396 // Something like {\textquoteright} (e.g.
2397 // from writer2latex). LyX writes
2398 // \textquoteright{}, so we may skip the
2399 // braces here for better readability.
2400 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2403 context.check_layout(os);
2404 // special handling of font attribute changes
2405 Token const prev = p.prev_token();
2406 TeXFont const oldFont = context.font;
2407 if (next.character() == '[' ||
2408 next.character() == ']' ||
2409 next.character() == '*') {
2411 if (p.next_token().cat() == catEnd) {
2416 output_ert_inset(os, "{", context);
2417 parse_text_snippet(p, os,
2420 output_ert_inset(os, "}", context);
2422 } else if (! context.new_layout_allowed) {
2423 output_ert_inset(os, "{", context);
2424 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2426 output_ert_inset(os, "}", context);
2427 } else if (is_known(next.cs(), known_sizes)) {
2428 // next will change the size, so we must
2430 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2432 if (!context.atParagraphStart())
2434 << context.font.size << "\n";
2435 } else if (is_known(next.cs(), known_font_families)) {
2436 // next will change the font family, so we
2437 // must reset it here
2438 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2440 if (!context.atParagraphStart())
2442 << context.font.family << "\n";
2443 } else if (is_known(next.cs(), known_font_series)) {
2444 // next will change the font series, so we
2445 // must reset it here
2446 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2448 if (!context.atParagraphStart())
2450 << context.font.series << "\n";
2451 } else if (is_known(next.cs(), known_font_shapes)) {
2452 // next will change the font shape, so we
2453 // must reset it here
2454 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2456 if (!context.atParagraphStart())
2458 << context.font.shape << "\n";
2459 } else if (is_known(next.cs(), known_old_font_families) ||
2460 is_known(next.cs(), known_old_font_series) ||
2461 is_known(next.cs(), known_old_font_shapes)) {
2462 // next will change the font family, series
2463 // and shape, so we must reset it here
2464 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2466 if (!context.atParagraphStart())
2468 << context.font.family
2470 << context.font.series
2472 << context.font.shape << "\n";
2474 output_ert_inset(os, "{", context);
2475 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2477 output_ert_inset(os, "}", context);
2482 else if (t.cat() == catEnd) {
2483 if (flags & FLAG_BRACE_LAST) {
2486 cerr << "stray '}' in text\n";
2487 output_ert_inset(os, "}", context);
2490 else if (t.cat() == catComment)
2491 parse_comment(p, os, t, context);
2494 // control sequences
2497 else if (t.cs() == "(") {
2498 context.check_layout(os);
2499 begin_inset(os, "Formula");
2501 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2506 else if (t.cs() == "[") {
2507 context.check_layout(os);
2508 begin_inset(os, "Formula");
2510 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2513 // Prevent the conversion of a line break to a space
2514 // (bug 7668). This does not change the output, but
2515 // looks ugly in LyX.
2516 eat_whitespace(p, os, context, false);
2519 else if (t.cs() == "begin")
2520 parse_environment(p, os, outer, last_env,
2523 else if (t.cs() == "end") {
2524 if (flags & FLAG_END) {
2525 // eat environment name
2526 string const name = p.getArg('{', '}');
2527 if (name != active_environment())
2528 cerr << "\\end{" + name + "} does not match \\begin{"
2529 + active_environment() + "}\n";
2532 p.error("found 'end' unexpectedly");
2535 else if (t.cs() == "item") {
2537 bool const optarg = p.hasOpt();
2539 // FIXME: This swallows comments, but we cannot use
2540 // eat_whitespace() since we must not output
2541 // anything before the item.
2542 p.skip_spaces(true);
2543 s = p.verbatimOption();
2545 p.skip_spaces(false);
2547 context.check_layout(os);
2548 if (context.has_item) {
2549 // An item in an unknown list-like environment
2550 // FIXME: Do this in check_layout()!
2551 context.has_item = false;
2553 output_ert_inset(os, "\\item", context);
2555 output_ert_inset(os, "\\item ", context);
2558 if (context.layout->labeltype != LABEL_MANUAL) {
2559 // LyX does not support \item[\mybullet]
2560 // in itemize environments
2562 os << parse_text_snippet(p2,
2563 FLAG_BRACK_LAST, outer, context);
2564 } else if (!s.empty()) {
2565 // LyX adds braces around the argument,
2566 // so we need to remove them here.
2567 if (s.size() > 2 && s[0] == '{' &&
2568 s[s.size()-1] == '}')
2569 s = s.substr(1, s.size()-2);
2570 // If the argument contains a space we
2571 // must put it into ERT: Otherwise LyX
2572 // would misinterpret the space as
2573 // item delimiter (bug 7663)
2574 if (contains(s, ' ')) {
2575 output_ert_inset(os, s, context);
2578 os << parse_text_snippet(p2,
2582 // The space is needed to separate the
2583 // item from the rest of the sentence.
2585 eat_whitespace(p, os, context, false);
2590 else if (t.cs() == "bibitem") {
2592 context.check_layout(os);
2593 eat_whitespace(p, os, context, false);
2594 string label = convert_command_inset_arg(p.verbatimOption());
2595 string key = convert_command_inset_arg(p.verbatim_item());
2596 if (contains(label, '\\') || contains(key, '\\')) {
2597 // LyX can't handle LaTeX commands in labels or keys
2598 output_ert_inset(os, t.asInput() + '[' + label +
2599 "]{" + p.verbatim_item() + '}',
2602 begin_command_inset(os, "bibitem", "bibitem");
2603 os << "label \"" << label << "\"\n"
2604 "key \"" << key << "\"\n";
2609 else if (is_macro(p)) {
2610 // catch the case of \def\inputGnumericTable
2612 if (t.cs() == "def") {
2613 Token second = p.next_token();
2614 if (second.cs() == "inputGnumericTable") {
2618 Token third = p.get_token();
2620 if (third.cs() == "input") {
2624 string name = normalize_filename(p.verbatim_item());
2625 string const path = getMasterFilePath(true);
2626 // We want to preserve relative / absolute filenames,
2627 // therefore path is only used for testing
2628 // The file extension is in every case ".tex".
2629 // So we need to remove this extension and check for
2630 // the original one.
2631 name = removeExtension(name);
2632 if (!makeAbsPath(name, path).exists()) {
2633 char const * const Gnumeric_formats[] = {"gnumeric",
2635 string const Gnumeric_name =
2636 find_file(name, path, Gnumeric_formats);
2637 if (!Gnumeric_name.empty())
2638 name = Gnumeric_name;
2640 FileName const absname = makeAbsPath(name, path);
2641 if (absname.exists()) {
2642 fix_child_filename(name);
2643 copy_file(absname, name);
2645 cerr << "Warning: Could not find file '"
2646 << name << "'." << endl;
2647 context.check_layout(os);
2648 begin_inset(os, "External\n\ttemplate ");
2649 os << "GnumericSpreadsheet\n\tfilename "
2652 context.check_layout(os);
2654 // register the packages that are automatically loaded
2655 // by the Gnumeric template
2656 registerExternalTemplatePackages("GnumericSpreadsheet");
2661 parse_macro(p, os, context);
2664 else if (t.cs() == "noindent") {
2666 context.add_par_extra_stuff("\\noindent\n");
2669 else if (t.cs() == "appendix") {
2670 context.add_par_extra_stuff("\\start_of_appendix\n");
2671 // We need to start a new paragraph. Otherwise the
2672 // appendix in 'bla\appendix\chapter{' would start
2674 context.new_paragraph(os);
2675 // We need to make sure that the paragraph is
2676 // generated even if it is empty. Otherwise the
2677 // appendix in '\par\appendix\par\chapter{' would
2679 context.check_layout(os);
2680 // FIXME: This is a hack to prevent paragraph
2681 // deletion if it is empty. Handle this better!
2682 output_ert_inset(os,
2683 "%dummy comment inserted by tex2lyx to "
2684 "ensure that this paragraph is not empty",
2686 // Both measures above may generate an additional
2687 // empty paragraph, but that does not hurt, because
2688 // whitespace does not matter here.
2689 eat_whitespace(p, os, context, true);
2692 // Must catch empty dates before findLayout is called below
2693 else if (t.cs() == "date") {
2694 eat_whitespace(p, os, context, false);
2696 string const date = p.verbatim_item();
2699 preamble.suppressDate(true);
2702 preamble.suppressDate(false);
2703 if (context.new_layout_allowed &&
2704 (newlayout = findLayout(context.textclass,
2707 output_command_layout(os, p, outer,
2708 context, newlayout);
2709 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2710 if (!preamble.titleLayoutFound())
2711 preamble.titleLayoutFound(newlayout->intitle);
2712 set<string> const & req = newlayout->requires();
2713 set<string>::const_iterator it = req.begin();
2714 set<string>::const_iterator en = req.end();
2715 for (; it != en; ++it)
2716 preamble.registerAutomaticallyLoadedPackage(*it);
2718 output_ert_inset(os,
2719 "\\date{" + p.verbatim_item() + '}',
2724 // Starred section headings
2725 // Must attempt to parse "Section*" before "Section".
2726 else if ((p.next_token().asInput() == "*") &&
2727 context.new_layout_allowed &&
2728 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2731 output_command_layout(os, p, outer, context, newlayout);
2733 if (!preamble.titleLayoutFound())
2734 preamble.titleLayoutFound(newlayout->intitle);
2735 set<string> const & req = newlayout->requires();
2736 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2737 preamble.registerAutomaticallyLoadedPackage(*it);
2740 // Section headings and the like
2741 else if (context.new_layout_allowed &&
2742 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2744 output_command_layout(os, p, outer, context, newlayout);
2746 if (!preamble.titleLayoutFound())
2747 preamble.titleLayoutFound(newlayout->intitle);
2748 set<string> const & req = newlayout->requires();
2749 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2750 preamble.registerAutomaticallyLoadedPackage(*it);
2753 else if (t.cs() == "caption") {
2755 context.check_layout(os);
2757 begin_inset(os, "Caption Standard\n");
2758 Context newcontext(true, context.textclass, 0, 0, context.font);
2759 newcontext.check_layout(os);
2760 // FIXME InsetArgument is now properly implemented in InsetLayout
2761 // (for captions, but also for others)
2762 if (p.next_token().cat() != catEscape &&
2763 p.next_token().character() == '[') {
2764 p.get_token(); // eat '['
2765 begin_inset(os, "Argument 1\n");
2766 os << "status collapsed\n";
2767 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2769 eat_whitespace(p, os, context, false);
2771 parse_text(p, os, FLAG_ITEM, outer, context);
2772 context.check_end_layout(os);
2773 // We don't need really a new paragraph, but
2774 // we must make sure that the next item gets a \begin_layout.
2775 context.new_paragraph(os);
2778 newcontext.check_end_layout(os);
2781 else if (t.cs() == "subfloat") {
2782 // the syntax is \subfloat[caption]{content}
2783 // if it is a table of figure depends on the surrounding float
2784 bool has_caption = false;
2786 // do nothing if there is no outer float
2787 if (!float_type.empty()) {
2788 context.check_layout(os);
2790 begin_inset(os, "Float " + float_type + "\n");
2792 << "\nsideways false"
2793 << "\nstatus collapsed\n\n";
2796 if (p.next_token().cat() != catEscape &&
2797 p.next_token().character() == '[') {
2798 p.get_token(); // eat '['
2799 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2803 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2804 // the caption comes always as the last
2806 // we must make sure that the caption gets a \begin_layout
2807 os << "\n\\begin_layout Plain Layout";
2809 begin_inset(os, "Caption Standard\n");
2810 Context newcontext(true, context.textclass,
2811 0, 0, context.font);
2812 newcontext.check_layout(os);
2813 os << caption << "\n";
2814 newcontext.check_end_layout(os);
2815 // We don't need really a new paragraph, but
2816 // we must make sure that the next item gets a \begin_layout.
2817 //newcontext.new_paragraph(os);
2821 // We don't need really a new paragraph, but
2822 // we must make sure that the next item gets a \begin_layout.
2824 context.new_paragraph(os);
2827 context.check_end_layout(os);
2828 // close the layout we opened
2830 os << "\n\\end_layout\n";
2832 // if the float type is not supported or there is no surrounding float
2835 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2836 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2837 "]{" + p.verbatim_item() + '}', context);
2839 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2843 else if (t.cs() == "includegraphics") {
2844 bool const clip = p.next_token().asInput() == "*";
2847 string const arg = p.getArg('[', ']');
2848 map<string, string> opts;
2849 vector<string> keys;
2850 split_map(arg, opts, keys);
2852 opts["clip"] = string();
2853 string name = normalize_filename(p.verbatim_item());
2855 string const path = getMasterFilePath(true);
2856 // We want to preserve relative / absolute filenames,
2857 // therefore path is only used for testing
2858 if (!makeAbsPath(name, path).exists()) {
2859 // The file extension is probably missing.
2860 // Now try to find it out.
2861 string const dvips_name =
2862 find_file(name, path,
2863 known_dvips_graphics_formats);
2864 string const pdftex_name =
2865 find_file(name, path,
2866 known_pdftex_graphics_formats);
2867 if (!dvips_name.empty()) {
2868 if (!pdftex_name.empty()) {
2869 cerr << "This file contains the "
2871 "\"\\includegraphics{"
2873 "However, files\n\""
2874 << dvips_name << "\" and\n\""
2875 << pdftex_name << "\"\n"
2876 "both exist, so I had to make a "
2877 "choice and took the first one.\n"
2878 "Please move the unwanted one "
2879 "someplace else and try again\n"
2880 "if my choice was wrong."
2884 } else if (!pdftex_name.empty()) {
2890 FileName const absname = makeAbsPath(name, path);
2891 if (absname.exists()) {
2892 fix_child_filename(name);
2893 copy_file(absname, name);
2895 cerr << "Warning: Could not find graphics file '"
2896 << name << "'." << endl;
2898 context.check_layout(os);
2899 begin_inset(os, "Graphics ");
2900 os << "\n\tfilename " << name << '\n';
2901 if (opts.find("width") != opts.end())
2903 << translate_len(opts["width"]) << '\n';
2904 if (opts.find("height") != opts.end())
2906 << translate_len(opts["height"]) << '\n';
2907 if (opts.find("scale") != opts.end()) {
2908 istringstream iss(opts["scale"]);
2912 os << "\tscale " << val << '\n';
2914 if (opts.find("angle") != opts.end()) {
2915 os << "\trotateAngle "
2916 << opts["angle"] << '\n';
2917 vector<string>::const_iterator a =
2918 find(keys.begin(), keys.end(), "angle");
2919 vector<string>::const_iterator s =
2920 find(keys.begin(), keys.end(), "width");
2921 if (s == keys.end())
2922 s = find(keys.begin(), keys.end(), "height");
2923 if (s == keys.end())
2924 s = find(keys.begin(), keys.end(), "scale");
2925 if (s != keys.end() && distance(s, a) > 0)
2926 os << "\tscaleBeforeRotation\n";
2928 if (opts.find("origin") != opts.end()) {
2930 string const opt = opts["origin"];
2931 if (opt.find('l') != string::npos) ss << "left";
2932 if (opt.find('r') != string::npos) ss << "right";
2933 if (opt.find('c') != string::npos) ss << "center";
2934 if (opt.find('t') != string::npos) ss << "Top";
2935 if (opt.find('b') != string::npos) ss << "Bottom";
2936 if (opt.find('B') != string::npos) ss << "Baseline";
2937 if (!ss.str().empty())
2938 os << "\trotateOrigin " << ss.str() << '\n';
2940 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2942 if (opts.find("keepaspectratio") != opts.end())
2943 os << "\tkeepAspectRatio\n";
2944 if (opts.find("clip") != opts.end())
2946 if (opts.find("draft") != opts.end())
2948 if (opts.find("bb") != opts.end())
2949 os << "\tBoundingBox "
2950 << opts["bb"] << '\n';
2951 int numberOfbbOptions = 0;
2952 if (opts.find("bbllx") != opts.end())
2953 numberOfbbOptions++;
2954 if (opts.find("bblly") != opts.end())
2955 numberOfbbOptions++;
2956 if (opts.find("bburx") != opts.end())
2957 numberOfbbOptions++;
2958 if (opts.find("bbury") != opts.end())
2959 numberOfbbOptions++;
2960 if (numberOfbbOptions == 4)
2961 os << "\tBoundingBox "
2962 << opts["bbllx"] << " " << opts["bblly"] << " "
2963 << opts["bburx"] << " " << opts["bbury"] << '\n';
2964 else if (numberOfbbOptions > 0)
2965 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2966 numberOfbbOptions = 0;
2967 if (opts.find("natwidth") != opts.end())
2968 numberOfbbOptions++;
2969 if (opts.find("natheight") != opts.end())
2970 numberOfbbOptions++;
2971 if (numberOfbbOptions == 2)
2972 os << "\tBoundingBox 0bp 0bp "
2973 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2974 else if (numberOfbbOptions > 0)
2975 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2976 ostringstream special;
2977 if (opts.find("hiresbb") != opts.end())
2978 special << "hiresbb,";
2979 if (opts.find("trim") != opts.end())
2981 if (opts.find("viewport") != opts.end())
2982 special << "viewport=" << opts["viewport"] << ',';
2983 if (opts.find("totalheight") != opts.end())
2984 special << "totalheight=" << opts["totalheight"] << ',';
2985 if (opts.find("type") != opts.end())
2986 special << "type=" << opts["type"] << ',';
2987 if (opts.find("ext") != opts.end())
2988 special << "ext=" << opts["ext"] << ',';
2989 if (opts.find("read") != opts.end())
2990 special << "read=" << opts["read"] << ',';
2991 if (opts.find("command") != opts.end())
2992 special << "command=" << opts["command"] << ',';
2993 string s_special = special.str();
2994 if (!s_special.empty()) {
2995 // We had special arguments. Remove the trailing ','.
2996 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2998 // TODO: Handle the unknown settings better.
2999 // Warn about invalid options.
3000 // Check whether some option was given twice.
3002 preamble.registerAutomaticallyLoadedPackage("graphicx");
3005 else if (t.cs() == "footnote" ||
3006 (t.cs() == "thanks" && context.layout->intitle)) {
3008 context.check_layout(os);
3009 begin_inset(os, "Foot\n");
3010 os << "status collapsed\n\n";
3011 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3015 else if (t.cs() == "marginpar") {
3017 context.check_layout(os);
3018 begin_inset(os, "Marginal\n");
3019 os << "status collapsed\n\n";
3020 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3024 else if (t.cs() == "lstinline") {
3026 parse_listings(p, os, context, true);
3029 else if (t.cs() == "ensuremath") {
3031 context.check_layout(os);
3032 string const s = p.verbatim_item();
3033 //FIXME: this never triggers in UTF8
3034 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3037 output_ert_inset(os, "\\ensuremath{" + s + "}",
3041 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3042 if (preamble.titleLayoutFound()) {
3044 skip_spaces_braces(p);
3046 output_ert_inset(os, t.asInput(), context);
3049 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3050 context.check_layout(os);
3051 begin_command_inset(os, "toc", t.cs());
3053 skip_spaces_braces(p);
3054 if (t.cs() == "lstlistoflistings")
3055 preamble.registerAutomaticallyLoadedPackage("listings");
3058 else if (t.cs() == "listoffigures") {
3059 context.check_layout(os);
3060 begin_inset(os, "FloatList figure\n");
3062 skip_spaces_braces(p);
3065 else if (t.cs() == "listoftables") {
3066 context.check_layout(os);
3067 begin_inset(os, "FloatList table\n");
3069 skip_spaces_braces(p);
3072 else if (t.cs() == "listof") {
3073 p.skip_spaces(true);
3074 string const name = p.get_token().cs();
3075 if (context.textclass.floats().typeExist(name)) {
3076 context.check_layout(os);
3077 begin_inset(os, "FloatList ");
3080 p.get_token(); // swallow second arg
3082 output_ert_inset(os, "\\listof{" + name + "}", context);
3085 else if ((where = is_known(t.cs(), known_text_font_families)))
3086 parse_text_attributes(p, os, FLAG_ITEM, outer,
3087 context, "\\family", context.font.family,
3088 known_coded_font_families[where - known_text_font_families]);
3090 else if ((where = is_known(t.cs(), known_text_font_series)))
3091 parse_text_attributes(p, os, FLAG_ITEM, outer,
3092 context, "\\series", context.font.series,
3093 known_coded_font_series[where - known_text_font_series]);
3095 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3096 parse_text_attributes(p, os, FLAG_ITEM, outer,
3097 context, "\\shape", context.font.shape,
3098 known_coded_font_shapes[where - known_text_font_shapes]);
3100 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3101 context.check_layout(os);
3102 TeXFont oldFont = context.font;
3103 context.font.init();
3104 context.font.size = oldFont.size;
3105 os << "\n\\family " << context.font.family << "\n";
3106 os << "\n\\series " << context.font.series << "\n";
3107 os << "\n\\shape " << context.font.shape << "\n";
3108 if (t.cs() == "textnormal") {
3109 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3110 output_font_change(os, context.font, oldFont);
3111 context.font = oldFont;
3113 eat_whitespace(p, os, context, false);
3116 else if (t.cs() == "textcolor") {
3117 // scheme is \textcolor{color name}{text}
3118 string const color = p.verbatim_item();
3119 // we only support the predefined colors of the color package
3120 if (color == "black" || color == "blue" || color == "cyan"
3121 || color == "green" || color == "magenta" || color == "red"
3122 || color == "white" || color == "yellow") {
3123 context.check_layout(os);
3124 os << "\n\\color " << color << "\n";
3125 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3126 context.check_layout(os);
3127 os << "\n\\color inherit\n";
3128 preamble.registerAutomaticallyLoadedPackage("color");
3130 // for custom defined colors
3131 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3134 else if (t.cs() == "underbar" || t.cs() == "uline") {
3135 // \underbar is not 100% correct (LyX outputs \uline
3136 // of ulem.sty). The difference is that \ulem allows
3137 // line breaks, and \underbar does not.
3138 // Do NOT handle \underline.
3139 // \underbar cuts through y, g, q, p etc.,
3140 // \underline does not.
3141 context.check_layout(os);
3142 os << "\n\\bar under\n";
3143 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3144 context.check_layout(os);
3145 os << "\n\\bar default\n";
3146 preamble.registerAutomaticallyLoadedPackage("ulem");
3149 else if (t.cs() == "sout") {
3150 context.check_layout(os);
3151 os << "\n\\strikeout on\n";
3152 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3153 context.check_layout(os);
3154 os << "\n\\strikeout default\n";
3155 preamble.registerAutomaticallyLoadedPackage("ulem");
3158 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3159 t.cs() == "emph" || t.cs() == "noun") {
3160 context.check_layout(os);
3161 os << "\n\\" << t.cs() << " on\n";
3162 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3163 context.check_layout(os);
3164 os << "\n\\" << t.cs() << " default\n";
3165 if (t.cs() == "uuline" || t.cs() == "uwave")
3166 preamble.registerAutomaticallyLoadedPackage("ulem");
3169 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3170 context.check_layout(os);
3171 string name = p.getArg('{', '}');
3172 string localtime = p.getArg('{', '}');
3173 preamble.registerAuthor(name);
3174 Author const & author = preamble.getAuthor(name);
3175 // from_asctime_utc() will fail if LyX decides to output the
3176 // time in the text language.
3177 time_t ptime = from_asctime_utc(localtime);
3178 if (ptime == static_cast<time_t>(-1)) {
3179 cerr << "Warning: Could not parse time `" << localtime
3180 << "´ for change tracking, using current time instead.\n";
3181 ptime = current_time();
3183 if (t.cs() == "lyxadded")
3184 os << "\n\\change_inserted ";
3186 os << "\n\\change_deleted ";
3187 os << author.bufferId() << ' ' << ptime << '\n';
3188 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3189 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3190 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3191 LaTeXPackages::isAvailable("xcolor");
3192 // No need to test for luatex, since luatex comes in
3193 // two flavours (dvi and pdf), like latex, and those
3194 // are detected by pdflatex.
3195 if (pdflatex || xetex) {
3197 preamble.registerAutomaticallyLoadedPackage("ulem");
3198 preamble.registerAutomaticallyLoadedPackage("xcolor");
3199 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3203 preamble.registerAutomaticallyLoadedPackage("dvipost");
3204 } else if (xcolorulem) {
3205 preamble.registerAutomaticallyLoadedPackage("ulem");
3206 preamble.registerAutomaticallyLoadedPackage("xcolor");
3211 else if (t.cs() == "textipa") {
3212 context.check_layout(os);
3213 begin_inset(os, "IPA\n");
3214 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3217 preamble.registerAutomaticallyLoadedPackage("tipa");
3218 preamble.registerAutomaticallyLoadedPackage("tipx");
3221 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3222 t.cs() == "vphantom") {
3223 context.check_layout(os);
3224 if (t.cs() == "phantom")
3225 begin_inset(os, "Phantom Phantom\n");
3226 if (t.cs() == "hphantom")
3227 begin_inset(os, "Phantom HPhantom\n");
3228 if (t.cs() == "vphantom")
3229 begin_inset(os, "Phantom VPhantom\n");
3230 os << "status open\n";
3231 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3236 else if (t.cs() == "href") {
3237 context.check_layout(os);
3238 string target = convert_command_inset_arg(p.verbatim_item());
3239 string name = convert_command_inset_arg(p.verbatim_item());
3241 size_t i = target.find(':');
3242 if (i != string::npos) {
3243 type = target.substr(0, i + 1);
3244 if (type == "mailto:" || type == "file:")
3245 target = target.substr(i + 1);
3246 // handle the case that name is equal to target, except of "http://"
3247 else if (target.substr(i + 3) == name && type == "http:")
3250 begin_command_inset(os, "href", "href");
3252 os << "name \"" << name << "\"\n";
3253 os << "target \"" << target << "\"\n";
3254 if (type == "mailto:" || type == "file:")
3255 os << "type \"" << type << "\"\n";
3257 skip_spaces_braces(p);
3260 else if (t.cs() == "lyxline") {
3261 // swallow size argument (it is not used anyway)
3263 if (!context.atParagraphStart()) {
3264 // so our line is in the middle of a paragraph
3265 // we need to add a new line, lest this line
3266 // follow the other content on that line and
3267 // run off the side of the page
3268 // FIXME: This may create an empty paragraph,
3269 // but without that it would not be
3270 // possible to set noindent below.
3271 // Fortunately LaTeX does not care
3272 // about the empty paragraph.
3273 context.new_paragraph(os);
3275 if (preamble.indentParagraphs()) {
3276 // we need to unindent, lest the line be too long
3277 context.add_par_extra_stuff("\\noindent\n");
3279 context.check_layout(os);
3280 begin_command_inset(os, "line", "rule");
3281 os << "offset \"0.5ex\"\n"
3282 "width \"100line%\"\n"
3287 else if (t.cs() == "rule") {
3288 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3289 string const width = p.getArg('{', '}');
3290 string const thickness = p.getArg('{', '}');
3291 context.check_layout(os);
3292 begin_command_inset(os, "line", "rule");
3293 if (!offset.empty())
3294 os << "offset \"" << translate_len(offset) << "\"\n";
3295 os << "width \"" << translate_len(width) << "\"\n"
3296 "height \"" << translate_len(thickness) << "\"\n";
3300 else if (is_known(t.cs(), known_phrases) ||
3301 (t.cs() == "protect" &&
3302 p.next_token().cat() == catEscape &&
3303 is_known(p.next_token().cs(), known_phrases))) {
3304 // LyX sometimes puts a \protect in front, so we have to ignore it
3305 // FIXME: This needs to be changed when bug 4752 is fixed.
3307 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3309 context.check_layout(os);
3310 os << known_coded_phrases[where - known_phrases];
3311 skip_spaces_braces(p);
3314 else if ((where = is_known(t.cs(), known_ref_commands))) {
3315 // \eqref can also occur if refstyle is used
3316 if (t.cs() == "eqref" && preamble.refstyle() == "1") {
3317 context.check_layout(os);
3318 begin_command_inset(os, "ref", "formatted");
3319 os << "reference \"eq:"
3320 << convert_command_inset_arg(p.verbatim_item())
3323 preamble.registerAutomaticallyLoadedPackage("refstyle");
3325 string const opt = p.getOpt();
3327 context.check_layout(os);
3328 begin_command_inset(os, "ref",
3329 known_coded_ref_commands[where - known_ref_commands]);
3330 os << "reference \""
3331 << convert_command_inset_arg(p.verbatim_item())
3334 if (t.cs() == "vref" || t.cs() == "vpageref")
3335 preamble.registerAutomaticallyLoadedPackage("varioref");
3337 // LyX does not yet support optional arguments of ref commands
3338 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3339 p.verbatim_item() + "}", context);
3344 else if ((where = is_known(t.cs(), known_refstyle_commands))) {
3345 context.check_layout(os);
3346 // \eqref can also occur if refstyle is not used
3347 // this case is already handled in the previous else if
3348 begin_command_inset(os, "ref", "formatted");
3349 os << "reference \"";
3350 os << known_refstyle_prefixes[where - known_refstyle_commands]
3352 os << convert_command_inset_arg(p.verbatim_item())
3355 preamble.registerAutomaticallyLoadedPackage("refstyle");
3358 else if (use_natbib &&
3359 is_known(t.cs(), known_natbib_commands) &&
3360 ((t.cs() != "citefullauthor" &&
3361 t.cs() != "citeyear" &&
3362 t.cs() != "citeyearpar") ||
3363 p.next_token().asInput() != "*")) {
3364 context.check_layout(os);
3365 string command = t.cs();
3366 if (p.next_token().asInput() == "*") {
3370 if (command == "citefullauthor")
3371 // alternative name for "\\citeauthor*"
3372 command = "citeauthor*";
3374 // text before the citation
3376 // text after the citation
3378 get_cite_arguments(p, true, before, after);
3380 if (command == "cite") {
3381 // \cite without optional argument means
3382 // \citet, \cite with at least one optional
3383 // argument means \citep.
3384 if (before.empty() && after.empty())
3389 if (before.empty() && after == "[]")
3390 // avoid \citet[]{a}
3392 else if (before == "[]" && after == "[]") {
3393 // avoid \citet[][]{a}
3397 // remove the brackets around after and before
3398 if (!after.empty()) {
3400 after.erase(after.length() - 1, 1);
3401 after = convert_command_inset_arg(after);
3403 if (!before.empty()) {
3405 before.erase(before.length() - 1, 1);
3406 before = convert_command_inset_arg(before);
3408 begin_command_inset(os, "citation", command);
3409 os << "after " << '"' << after << '"' << "\n";
3410 os << "before " << '"' << before << '"' << "\n";
3412 << convert_command_inset_arg(p.verbatim_item())
3415 // Need to set the cite engine if natbib is loaded by
3416 // the document class directly
3417 if (preamble.citeEngine() == "basic")
3418 preamble.citeEngine("natbib");
3421 else if (use_jurabib &&
3422 is_known(t.cs(), known_jurabib_commands) &&
3423 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3424 context.check_layout(os);
3425 string command = t.cs();
3426 if (p.next_token().asInput() == "*") {
3430 char argumentOrder = '\0';
3431 vector<string> const options =
3432 preamble.getPackageOptions("jurabib");
3433 if (find(options.begin(), options.end(),
3434 "natbiborder") != options.end())
3435 argumentOrder = 'n';
3436 else if (find(options.begin(), options.end(),
3437 "jurabiborder") != options.end())
3438 argumentOrder = 'j';
3440 // text before the citation
3442 // text after the citation
3444 get_cite_arguments(p, argumentOrder != 'j', before, after);
3446 string const citation = p.verbatim_item();
3447 if (!before.empty() && argumentOrder == '\0') {
3448 cerr << "Warning: Assuming argument order "
3449 "of jurabib version 0.6 for\n'"
3450 << command << before << after << '{'
3451 << citation << "}'.\n"
3452 "Add 'jurabiborder' to the jurabib "
3453 "package options if you used an\n"
3454 "earlier jurabib version." << endl;
3456 if (!after.empty()) {
3458 after.erase(after.length() - 1, 1);
3460 if (!before.empty()) {
3462 before.erase(before.length() - 1, 1);
3464 begin_command_inset(os, "citation", command);
3465 os << "after " << '"' << after << '"' << "\n";
3466 os << "before " << '"' << before << '"' << "\n";
3467 os << "key " << '"' << citation << '"' << "\n";
3469 // Need to set the cite engine if jurabib is loaded by
3470 // the document class directly
3471 if (preamble.citeEngine() == "basic")
3472 preamble.citeEngine("jurabib");
3475 else if (t.cs() == "cite"
3476 || t.cs() == "nocite") {
3477 context.check_layout(os);
3478 string after = convert_command_inset_arg(p.getArg('[', ']'));
3479 string key = convert_command_inset_arg(p.verbatim_item());
3480 // store the case that it is "\nocite{*}" to use it later for
3483 begin_command_inset(os, "citation", t.cs());
3484 os << "after " << '"' << after << '"' << "\n";
3485 os << "key " << '"' << key << '"' << "\n";
3487 } else if (t.cs() == "nocite")
3491 else if (t.cs() == "index" ||
3492 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3493 context.check_layout(os);
3494 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3495 p.getArg('[', ']') : "";
3496 string const kind = arg.empty() ? "idx" : arg;
3497 begin_inset(os, "Index ");
3498 os << kind << "\nstatus collapsed\n";
3499 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3502 preamble.registerAutomaticallyLoadedPackage("splitidx");
3505 else if (t.cs() == "nomenclature") {
3506 context.check_layout(os);
3507 begin_command_inset(os, "nomenclature", "nomenclature");
3508 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3509 if (!prefix.empty())
3510 os << "prefix " << '"' << prefix << '"' << "\n";
3511 os << "symbol " << '"'
3512 << convert_command_inset_arg(p.verbatim_item());
3513 os << "\"\ndescription \""
3514 << convert_command_inset_arg(p.verbatim_item())
3517 preamble.registerAutomaticallyLoadedPackage("nomencl");
3520 else if (t.cs() == "label") {
3521 context.check_layout(os);
3522 begin_command_inset(os, "label", "label");
3524 << convert_command_inset_arg(p.verbatim_item())
3529 else if (t.cs() == "printindex") {
3530 context.check_layout(os);
3531 begin_command_inset(os, "index_print", "printindex");
3532 os << "type \"idx\"\n";
3534 skip_spaces_braces(p);
3535 preamble.registerAutomaticallyLoadedPackage("makeidx");
3536 if (preamble.use_indices() == "true")
3537 preamble.registerAutomaticallyLoadedPackage("splitidx");
3540 else if (t.cs() == "printnomenclature") {
3542 string width_type = "";
3543 context.check_layout(os);
3544 begin_command_inset(os, "nomencl_print", "printnomenclature");
3545 // case of a custom width
3547 width = p.getArg('[', ']');
3548 width = translate_len(width);
3549 width_type = "custom";
3551 // case of no custom width
3552 // the case of no custom width but the width set
3553 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3554 // because the user could have set anything, not only the width
3555 // of the longest label (which would be width_type = "auto")
3556 string label = convert_command_inset_arg(p.getArg('{', '}'));
3557 if (label.empty() && width_type.empty())
3558 width_type = "none";
3559 os << "set_width \"" << width_type << "\"\n";
3560 if (width_type == "custom")
3561 os << "width \"" << width << '\"';
3563 skip_spaces_braces(p);
3564 preamble.registerAutomaticallyLoadedPackage("nomencl");
3567 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3568 context.check_layout(os);
3569 begin_inset(os, "script ");
3570 os << t.cs().substr(4) << '\n';
3571 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3573 if (t.cs() == "textsubscript")
3574 preamble.registerAutomaticallyLoadedPackage("subscript");
3577 else if ((where = is_known(t.cs(), known_quotes))) {
3578 context.check_layout(os);
3579 begin_inset(os, "Quotes ");
3580 os << known_coded_quotes[where - known_quotes];
3582 // LyX adds {} after the quote, so we have to eat
3583 // spaces here if there are any before a possible
3585 eat_whitespace(p, os, context, false);
3589 else if ((where = is_known(t.cs(), known_sizes)) &&
3590 context.new_layout_allowed) {
3591 context.check_layout(os);
3592 TeXFont const oldFont = context.font;
3593 context.font.size = known_coded_sizes[where - known_sizes];
3594 output_font_change(os, oldFont, context.font);
3595 eat_whitespace(p, os, context, false);
3598 else if ((where = is_known(t.cs(), known_font_families)) &&
3599 context.new_layout_allowed) {
3600 context.check_layout(os);
3601 TeXFont const oldFont = context.font;
3602 context.font.family =
3603 known_coded_font_families[where - known_font_families];
3604 output_font_change(os, oldFont, context.font);
3605 eat_whitespace(p, os, context, false);
3608 else if ((where = is_known(t.cs(), known_font_series)) &&
3609 context.new_layout_allowed) {
3610 context.check_layout(os);
3611 TeXFont const oldFont = context.font;
3612 context.font.series =
3613 known_coded_font_series[where - known_font_series];
3614 output_font_change(os, oldFont, context.font);
3615 eat_whitespace(p, os, context, false);
3618 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3619 context.new_layout_allowed) {
3620 context.check_layout(os);
3621 TeXFont const oldFont = context.font;
3622 context.font.shape =
3623 known_coded_font_shapes[where - known_font_shapes];
3624 output_font_change(os, oldFont, context.font);
3625 eat_whitespace(p, os, context, false);
3627 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3628 context.new_layout_allowed) {
3629 context.check_layout(os);
3630 TeXFont const oldFont = context.font;
3631 context.font.init();
3632 context.font.size = oldFont.size;
3633 context.font.family =
3634 known_coded_font_families[where - known_old_font_families];
3635 output_font_change(os, oldFont, context.font);
3636 eat_whitespace(p, os, context, false);
3639 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3640 context.new_layout_allowed) {
3641 context.check_layout(os);
3642 TeXFont const oldFont = context.font;
3643 context.font.init();
3644 context.font.size = oldFont.size;
3645 context.font.series =
3646 known_coded_font_series[where - known_old_font_series];
3647 output_font_change(os, oldFont, context.font);
3648 eat_whitespace(p, os, context, false);
3651 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3652 context.new_layout_allowed) {
3653 context.check_layout(os);
3654 TeXFont const oldFont = context.font;
3655 context.font.init();
3656 context.font.size = oldFont.size;
3657 context.font.shape =
3658 known_coded_font_shapes[where - known_old_font_shapes];
3659 output_font_change(os, oldFont, context.font);
3660 eat_whitespace(p, os, context, false);
3663 else if (t.cs() == "selectlanguage") {
3664 context.check_layout(os);
3665 // save the language for the case that a
3666 // \foreignlanguage is used
3667 context.font.language = babel2lyx(p.verbatim_item());
3668 os << "\n\\lang " << context.font.language << "\n";
3671 else if (t.cs() == "foreignlanguage") {
3672 string const lang = babel2lyx(p.verbatim_item());
3673 parse_text_attributes(p, os, FLAG_ITEM, outer,
3675 context.font.language, lang);
3678 else if (prefixIs(t.cs(), "text")
3679 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3680 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3682 // We have to output the whole command if it has an option
3683 // because LyX doesn't support this yet, see bug #8214,
3684 // only if there is a single option specifying a variant, we can handle it.
3686 string langopts = p.getOpt();
3687 // check if the option contains a variant, if yes, extract it
3688 string::size_type pos_var = langopts.find("variant");
3689 string::size_type i = langopts.find(',');
3690 string::size_type k = langopts.find('=', pos_var);
3691 if (pos_var != string::npos && i == string::npos) {
3693 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3694 lang = preamble.polyglossia2lyx(variant);
3695 parse_text_attributes(p, os, FLAG_ITEM, outer,
3697 context.font.language, lang);
3699 output_ert_inset(os, t.asInput() + langopts, context);
3701 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3702 parse_text_attributes(p, os, FLAG_ITEM, outer,
3704 context.font.language, lang);
3708 else if (t.cs() == "inputencoding") {
3709 // nothing to write here
3710 string const enc = subst(p.verbatim_item(), "\n", " ");
3711 p.setEncoding(enc, Encoding::inputenc);
3714 else if ((where = is_known(t.cs(), known_special_chars))) {
3715 context.check_layout(os);
3716 os << "\\SpecialChar \\"
3717 << known_coded_special_chars[where - known_special_chars]
3719 skip_spaces_braces(p);
3722 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3723 context.check_layout(os);
3724 os << "\\SpecialChar \\nobreakdash-\n";
3728 else if (t.cs() == "textquotedbl") {
3729 context.check_layout(os);
3734 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3735 context.check_layout(os);
3736 os << "\\SpecialChar \\@.\n";
3740 else if (t.cs() == "-") {
3741 context.check_layout(os);
3742 os << "\\SpecialChar \\-\n";
3745 else if (t.cs() == "textasciitilde") {
3746 context.check_layout(os);
3748 skip_spaces_braces(p);
3751 else if (t.cs() == "textasciicircum") {
3752 context.check_layout(os);
3754 skip_spaces_braces(p);
3757 else if (t.cs() == "textbackslash") {
3758 context.check_layout(os);
3759 os << "\n\\backslash\n";
3760 skip_spaces_braces(p);
3763 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3764 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3766 context.check_layout(os);
3770 else if (t.cs() == "char") {
3771 context.check_layout(os);
3772 if (p.next_token().character() == '`') {
3774 if (p.next_token().cs() == "\"") {
3779 output_ert_inset(os, "\\char`", context);
3782 output_ert_inset(os, "\\char", context);
3786 else if (t.cs() == "verb") {
3787 context.check_layout(os);
3788 // set catcodes to verbatim early, just in case.
3789 p.setCatcodes(VERBATIM_CATCODES);
3790 string delim = p.get_token().asInput();
3791 string const arg = p.verbatimStuff(delim);
3792 output_ert_inset(os, "\\verb" + delim + arg + delim, context);
3795 // Problem: \= creates a tabstop inside the tabbing environment
3796 // and else an accent. In the latter case we really would want
3797 // \={o} instead of \= o.
3798 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3799 output_ert_inset(os, t.asInput(), context);
3801 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3802 else if (t.cs().size() == 1
3803 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3804 context.check_layout(os);
3805 // try to see whether the string is in unicodesymbols
3808 string command = t.asInput() + "{"
3809 + trimSpaceAndEol(p.verbatim_item())
3812 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3813 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3814 termination, rem, &req);
3817 cerr << "When parsing " << command
3818 << ", result is " << to_utf8(s)
3819 << "+" << to_utf8(rem) << endl;
3821 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3822 preamble.registerAutomaticallyLoadedPackage(*it);
3824 // we did not find a non-ert version
3825 output_ert_inset(os, command, context);
3828 else if (t.cs() == "\\") {
3829 context.check_layout(os);
3831 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3832 else if (p.next_token().asInput() == "*") {
3834 // getOpt() eats the following space if there
3835 // is no optional argument, but that is OK
3836 // here since it has no effect in the output.
3837 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3840 begin_inset(os, "Newline newline");
3845 else if (t.cs() == "newline" ||
3846 (t.cs() == "linebreak" && !p.hasOpt())) {
3847 context.check_layout(os);
3848 begin_inset(os, "Newline ");
3851 skip_spaces_braces(p);
3854 else if (t.cs() == "input" || t.cs() == "include"
3855 || t.cs() == "verbatiminput") {
3856 string name = t.cs();
3857 if (t.cs() == "verbatiminput"
3858 && p.next_token().asInput() == "*")
3859 name += p.get_token().asInput();
3860 context.check_layout(os);
3861 string filename(normalize_filename(p.getArg('{', '}')));
3862 string const path = getMasterFilePath(true);
3863 // We want to preserve relative / absolute filenames,
3864 // therefore path is only used for testing
3865 if ((t.cs() == "include" || t.cs() == "input") &&
3866 !makeAbsPath(filename, path).exists()) {
3867 // The file extension is probably missing.
3868 // Now try to find it out.
3869 string const tex_name =
3870 find_file(filename, path,
3871 known_tex_extensions);
3872 if (!tex_name.empty())
3873 filename = tex_name;
3875 bool external = false;
3877 if (makeAbsPath(filename, path).exists()) {
3878 string const abstexname =
3879 makeAbsPath(filename, path).absFileName();
3880 string const absfigname =
3881 changeExtension(abstexname, ".fig");
3882 fix_child_filename(filename);
3883 string const lyxname =
3884 changeExtension(filename, ".lyx");
3885 string const abslyxname = makeAbsPath(
3886 lyxname, getParentFilePath(false)).absFileName();
3888 if (!skipChildren())
3889 external = FileName(absfigname).exists();
3890 if (t.cs() == "input" && !skipChildren()) {
3891 string const ext = getExtension(abstexname);
3893 // Combined PS/LaTeX:
3894 // x.eps, x.pstex_t (old xfig)
3895 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3896 FileName const absepsname(
3897 changeExtension(abstexname, ".eps"));
3898 FileName const abspstexname(
3899 changeExtension(abstexname, ".pstex"));
3900 bool const xfigeps =
3901 (absepsname.exists() ||
3902 abspstexname.exists()) &&
3905 // Combined PDF/LaTeX:
3906 // x.pdf, x.pdftex_t (old xfig)
3907 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3908 FileName const abspdfname(
3909 changeExtension(abstexname, ".pdf"));
3910 bool const xfigpdf =
3911 abspdfname.exists() &&
3912 (ext == "pdftex_t" || ext == "pdf_t");
3916 // Combined PS/PDF/LaTeX:
3917 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3918 string const absbase2(
3919 removeExtension(abstexname) + "_pspdftex");
3920 FileName const abseps2name(
3921 addExtension(absbase2, ".eps"));
3922 FileName const abspdf2name(
3923 addExtension(absbase2, ".pdf"));
3924 bool const xfigboth =
3925 abspdf2name.exists() &&
3926 abseps2name.exists() && ext == "pspdftex";
3928 xfig = xfigpdf || xfigeps || xfigboth;
3929 external = external && xfig;
3932 outname = changeExtension(filename, ".fig");
3933 FileName abssrc(changeExtension(abstexname, ".fig"));
3934 copy_file(abssrc, outname);
3936 // Don't try to convert, the result
3937 // would be full of ERT.
3939 FileName abssrc(abstexname);
3940 copy_file(abssrc, outname);
3941 } else if (t.cs() != "verbatiminput" &&
3943 tex2lyx(abstexname, FileName(abslyxname),
3946 // no need to call copy_file
3947 // tex2lyx creates the file
3950 FileName abssrc(abstexname);
3951 copy_file(abssrc, outname);
3954 cerr << "Warning: Could not find included file '"
3955 << filename << "'." << endl;
3959 begin_inset(os, "External\n");
3960 os << "\ttemplate XFig\n"
3961 << "\tfilename " << outname << '\n';
3962 registerExternalTemplatePackages("XFig");
3964 begin_command_inset(os, "include", name);
3965 outname = subst(outname, "\"", "\\\"");
3966 os << "preview false\n"
3967 "filename \"" << outname << "\"\n";
3968 if (t.cs() == "verbatiminput")
3969 preamble.registerAutomaticallyLoadedPackage("verbatim");
3974 else if (t.cs() == "bibliographystyle") {
3975 // store new bibliographystyle
3976 bibliographystyle = p.verbatim_item();
3977 // If any other command than \bibliography, \addcontentsline
3978 // and \nocite{*} follows, we need to output the style
3979 // (because it might be used by that command).
3980 // Otherwise, it will automatically be output by LyX.
3983 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3984 if (t2.cat() == catBegin)
3986 if (t2.cat() != catEscape)
3988 if (t2.cs() == "nocite") {
3989 if (p.getArg('{', '}') == "*")
3991 } else if (t2.cs() == "bibliography")
3993 else if (t2.cs() == "addcontentsline") {
3994 // get the 3 arguments of \addcontentsline
3997 contentslineContent = p.getArg('{', '}');
3998 // if the last argument is not \refname we must output
3999 if (contentslineContent == "\\refname")
4006 output_ert_inset(os,
4007 "\\bibliographystyle{" + bibliographystyle + '}',
4012 else if (t.cs() == "addcontentsline") {
4013 context.check_layout(os);
4014 // get the 3 arguments of \addcontentsline
4015 string const one = p.getArg('{', '}');
4016 string const two = p.getArg('{', '}');
4017 string const three = p.getArg('{', '}');
4018 // only if it is a \refname, we support if for the bibtex inset
4019 if (contentslineContent != "\\refname") {
4020 output_ert_inset(os,
4021 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4026 else if (t.cs() == "bibliography") {
4027 context.check_layout(os);
4029 begin_command_inset(os, "bibtex", "bibtex");
4030 if (!btprint.empty()) {
4031 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4032 // clear the string because the next BibTeX inset can be without the
4033 // \nocite{*} option
4036 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4037 // Do we have addcontentsline?
4038 if (contentslineContent == "\\refname") {
4039 BibOpts = "bibtotoc";
4040 // clear string because next BibTeX inset can be without addcontentsline
4041 contentslineContent.clear();
4043 // Do we have a bibliographystyle set?
4044 if (!bibliographystyle.empty()) {
4045 if (BibOpts.empty())
4046 BibOpts = bibliographystyle;
4048 BibOpts = BibOpts + ',' + bibliographystyle;
4050 os << "options " << '"' << BibOpts << '"' << "\n";
4054 else if (t.cs() == "parbox") {
4055 // Test whether this is an outer box of a shaded box
4057 // swallow arguments
4058 while (p.hasOpt()) {
4060 p.skip_spaces(true);
4063 p.skip_spaces(true);
4065 if (p.next_token().cat() == catBegin)
4067 p.skip_spaces(true);
4068 Token to = p.get_token();
4069 bool shaded = false;
4070 if (to.asInput() == "\\begin") {
4071 p.skip_spaces(true);
4072 if (p.getArg('{', '}') == "shaded")
4077 parse_outer_box(p, os, FLAG_ITEM, outer,
4078 context, "parbox", "shaded");
4080 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4084 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4085 t.cs() == "shadowbox" || t.cs() == "doublebox")
4086 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4088 else if (t.cs() == "framebox") {
4089 if (p.next_token().character() == '(') {
4090 //the syntax is: \framebox(x,y)[position]{content}
4091 string arg = t.asInput();
4092 arg += p.getFullParentheseArg();
4093 arg += p.getFullOpt();
4094 eat_whitespace(p, os, context, false);
4095 output_ert_inset(os, arg + '{', context);
4096 parse_text(p, os, FLAG_ITEM, outer, context);
4097 output_ert_inset(os, "}", context);
4099 string special = p.getFullOpt();
4100 special += p.getOpt();
4101 // LyX does not yet support \framebox without any option
4102 if (!special.empty())
4103 parse_outer_box(p, os, FLAG_ITEM, outer,
4104 context, t.cs(), special);
4106 eat_whitespace(p, os, context, false);
4107 output_ert_inset(os, "\\framebox{", context);
4108 parse_text(p, os, FLAG_ITEM, outer, context);
4109 output_ert_inset(os, "}", context);
4114 //\makebox() is part of the picture environment and different from \makebox{}
4115 //\makebox{} will be parsed by parse_box
4116 else if (t.cs() == "makebox") {
4117 if (p.next_token().character() == '(') {
4118 //the syntax is: \makebox(x,y)[position]{content}
4119 string arg = t.asInput();
4120 arg += p.getFullParentheseArg();
4121 arg += p.getFullOpt();
4122 eat_whitespace(p, os, context, false);
4123 output_ert_inset(os, arg + '{', context);
4124 parse_text(p, os, FLAG_ITEM, outer, context);
4125 output_ert_inset(os, "}", context);
4127 //the syntax is: \makebox[width][position]{content}
4128 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4132 else if (t.cs() == "smallskip" ||
4133 t.cs() == "medskip" ||
4134 t.cs() == "bigskip" ||
4135 t.cs() == "vfill") {
4136 context.check_layout(os);
4137 begin_inset(os, "VSpace ");
4140 skip_spaces_braces(p);
4143 else if ((where = is_known(t.cs(), known_spaces))) {
4144 context.check_layout(os);
4145 begin_inset(os, "space ");
4146 os << '\\' << known_coded_spaces[where - known_spaces]
4149 // LaTeX swallows whitespace after all spaces except
4150 // "\\,". We have to do that here, too, because LyX
4151 // adds "{}" which would make the spaces significant.
4153 eat_whitespace(p, os, context, false);
4154 // LyX adds "{}" after all spaces except "\\ " and
4155 // "\\,", so we have to remove "{}".
4156 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4157 // remove the braces after "\\,", too.
4162 else if (t.cs() == "newpage" ||
4163 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4164 t.cs() == "clearpage" ||
4165 t.cs() == "cleardoublepage") {
4166 context.check_layout(os);
4167 begin_inset(os, "Newpage ");
4170 skip_spaces_braces(p);
4173 else if (t.cs() == "DeclareRobustCommand" ||
4174 t.cs() == "DeclareRobustCommandx" ||
4175 t.cs() == "newcommand" ||
4176 t.cs() == "newcommandx" ||
4177 t.cs() == "providecommand" ||
4178 t.cs() == "providecommandx" ||
4179 t.cs() == "renewcommand" ||
4180 t.cs() == "renewcommandx") {
4181 // DeclareRobustCommand, DeclareRobustCommandx,
4182 // providecommand and providecommandx could be handled
4183 // by parse_command(), but we need to call
4184 // add_known_command() here.
4185 string name = t.asInput();
4186 if (p.next_token().asInput() == "*") {
4187 // Starred form. Eat '*'
4191 string const command = p.verbatim_item();
4192 string const opt1 = p.getFullOpt();
4193 string const opt2 = p.getFullOpt();
4194 add_known_command(command, opt1, !opt2.empty());
4195 string const ert = name + '{' + command + '}' +
4197 '{' + p.verbatim_item() + '}';
4199 if (t.cs() == "DeclareRobustCommand" ||
4200 t.cs() == "DeclareRobustCommandx" ||
4201 t.cs() == "providecommand" ||
4202 t.cs() == "providecommandx" ||
4203 name[name.length()-1] == '*')
4204 output_ert_inset(os, ert, context);
4206 context.check_layout(os);
4207 begin_inset(os, "FormulaMacro");
4213 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4214 // let could be handled by parse_command(),
4215 // but we need to call add_known_command() here.
4216 string ert = t.asInput();
4219 if (p.next_token().cat() == catBegin) {
4220 name = p.verbatim_item();
4221 ert += '{' + name + '}';
4223 name = p.verbatim_item();
4228 if (p.next_token().cat() == catBegin) {
4229 command = p.verbatim_item();
4230 ert += '{' + command + '}';
4232 command = p.verbatim_item();
4235 // If command is known, make name known too, to parse
4236 // its arguments correctly. For this reason we also
4237 // have commands in syntax.default that are hardcoded.
4238 CommandMap::iterator it = known_commands.find(command);
4239 if (it != known_commands.end())
4240 known_commands[t.asInput()] = it->second;
4241 output_ert_inset(os, ert, context);
4244 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4245 bool starred = false;
4246 if (p.next_token().asInput() == "*") {
4250 string name = t.asInput();
4251 string const length = p.verbatim_item();
4254 bool valid = splitLatexLength(length, valstring, unit);
4255 bool known_hspace = false;
4256 bool known_vspace = false;
4257 bool known_unit = false;
4260 istringstream iss(valstring);
4263 if (t.cs()[0] == 'h') {
4264 if (unit == "\\fill") {
4269 known_hspace = true;
4272 if (unit == "\\smallskipamount") {
4274 known_vspace = true;
4275 } else if (unit == "\\medskipamount") {
4277 known_vspace = true;
4278 } else if (unit == "\\bigskipamount") {
4280 known_vspace = true;
4281 } else if (unit == "\\fill") {
4283 known_vspace = true;
4287 if (!known_hspace && !known_vspace) {
4288 switch (unitFromString(unit)) {
4309 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4310 // Literal horizontal length or known variable
4311 context.check_layout(os);
4312 begin_inset(os, "space ");
4320 if (known_unit && !known_hspace)
4322 << translate_len(length);
4324 } else if (known_unit || known_vspace) {
4325 // Literal vertical length or known variable
4326 context.check_layout(os);
4327 begin_inset(os, "VSpace ");
4335 // LyX can't handle other length variables in Inset VSpace/space
4340 output_ert_inset(os, name + '{' + unit + '}', context);
4341 else if (value == -1.0)
4342 output_ert_inset(os, name + "{-" + unit + '}', context);
4344 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4346 output_ert_inset(os, name + '{' + length + '}', context);
4350 // The single '=' is meant here.
4351 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4353 context.check_layout(os);
4354 begin_inset(os, "Flex ");
4355 os << to_utf8(newinsetlayout->name()) << '\n'
4356 << "status collapsed\n";
4357 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4361 else if (t.cs() == "includepdf") {
4363 string const arg = p.getArg('[', ']');
4364 map<string, string> opts;
4365 vector<string> keys;
4366 split_map(arg, opts, keys);
4367 string name = normalize_filename(p.verbatim_item());
4368 string const path = getMasterFilePath(true);
4369 // We want to preserve relative / absolute filenames,
4370 // therefore path is only used for testing
4371 if (!makeAbsPath(name, path).exists()) {
4372 // The file extension is probably missing.
4373 // Now try to find it out.
4374 char const * const pdfpages_format[] = {"pdf", 0};
4375 string const pdftex_name =
4376 find_file(name, path, pdfpages_format);
4377 if (!pdftex_name.empty()) {
4382 FileName const absname = makeAbsPath(name, path);
4383 if (absname.exists())
4385 fix_child_filename(name);
4386 copy_file(absname, name);
4388 cerr << "Warning: Could not find file '"
4389 << name << "'." << endl;
4391 context.check_layout(os);
4392 begin_inset(os, "External\n\ttemplate ");
4393 os << "PDFPages\n\tfilename "
4395 // parse the options
4396 if (opts.find("pages") != opts.end())
4397 os << "\textra LaTeX \"pages="
4398 << opts["pages"] << "\"\n";
4399 if (opts.find("angle") != opts.end())
4400 os << "\trotateAngle "
4401 << opts["angle"] << '\n';
4402 if (opts.find("origin") != opts.end()) {
4404 string const opt = opts["origin"];
4405 if (opt == "tl") ss << "topleft";
4406 if (opt == "bl") ss << "bottomleft";
4407 if (opt == "Bl") ss << "baselineleft";
4408 if (opt == "c") ss << "center";
4409 if (opt == "tc") ss << "topcenter";
4410 if (opt == "bc") ss << "bottomcenter";
4411 if (opt == "Bc") ss << "baselinecenter";
4412 if (opt == "tr") ss << "topright";
4413 if (opt == "br") ss << "bottomright";
4414 if (opt == "Br") ss << "baselineright";
4415 if (!ss.str().empty())
4416 os << "\trotateOrigin " << ss.str() << '\n';
4418 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4420 if (opts.find("width") != opts.end())
4422 << translate_len(opts["width"]) << '\n';
4423 if (opts.find("height") != opts.end())
4425 << translate_len(opts["height"]) << '\n';
4426 if (opts.find("keepaspectratio") != opts.end())
4427 os << "\tkeepAspectRatio\n";
4429 context.check_layout(os);
4430 registerExternalTemplatePackages("PDFPages");
4433 else if (t.cs() == "loadgame") {
4435 string name = normalize_filename(p.verbatim_item());
4436 string const path = getMasterFilePath(true);
4437 // We want to preserve relative / absolute filenames,
4438 // therefore path is only used for testing
4439 if (!makeAbsPath(name, path).exists()) {
4440 // The file extension is probably missing.
4441 // Now try to find it out.
4442 char const * const lyxskak_format[] = {"fen", 0};
4443 string const lyxskak_name =
4444 find_file(name, path, lyxskak_format);
4445 if (!lyxskak_name.empty())
4446 name = lyxskak_name;
4448 FileName const absname = makeAbsPath(name, path);
4449 if (absname.exists())
4451 fix_child_filename(name);
4452 copy_file(absname, name);
4454 cerr << "Warning: Could not find file '"
4455 << name << "'." << endl;
4456 context.check_layout(os);
4457 begin_inset(os, "External\n\ttemplate ");
4458 os << "ChessDiagram\n\tfilename "
4461 context.check_layout(os);
4462 // after a \loadgame follows a \showboard
4463 if (p.get_token().asInput() == "showboard")
4465 registerExternalTemplatePackages("ChessDiagram");
4469 // try to see whether the string is in unicodesymbols
4470 // Only use text mode commands, since we are in text mode here,
4471 // and math commands may be invalid (bug 6797)
4475 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4476 Encodings::TEXT_CMD, termination, rem, &req);
4479 cerr << "When parsing " << t.cs()
4480 << ", result is " << to_utf8(s)
4481 << "+" << to_utf8(rem) << endl;
4482 context.check_layout(os);
4485 skip_spaces_braces(p);
4486 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4487 preamble.registerAutomaticallyLoadedPackage(*it);
4489 //cerr << "#: " << t << " mode: " << mode << endl;
4490 // heuristic: read up to next non-nested space
4492 string s = t.asInput();
4493 string z = p.verbatim_item();
4494 while (p.good() && z != " " && !z.empty()) {
4495 //cerr << "read: " << z << endl;
4497 z = p.verbatim_item();
4499 cerr << "found ERT: " << s << endl;
4500 output_ert_inset(os, s + ' ', context);
4503 string name = t.asInput();
4504 if (p.next_token().asInput() == "*") {
4505 // Starred commands like \vspace*{}
4506 p.get_token(); // Eat '*'
4509 if (!parse_command(name, p, os, outer, context))
4510 output_ert_inset(os, name, context);
4514 if (flags & FLAG_LEAVE) {
4515 flags &= ~FLAG_LEAVE;
4522 string guessLanguage(Parser & p, string const & lang)
4524 typedef std::map<std::string, size_t> LangMap;
4525 // map from language names to number of characters
4528 for (char const * const * i = supported_CJK_languages; *i; i++)
4529 used[string(*i)] = 0;
4532 Token const t = p.get_token();
4533 // comments are not counted for any language
4534 if (t.cat() == catComment)
4536 // commands are not counted as well, but we need to detect
4537 // \begin{CJK} and switch encoding if needed
4538 if (t.cat() == catEscape) {
4539 if (t.cs() == "inputencoding") {
4540 string const enc = subst(p.verbatim_item(), "\n", " ");
4541 p.setEncoding(enc, Encoding::inputenc);
4544 if (t.cs() != "begin")
4547 // Non-CJK content is counted for lang.
4548 // We do not care about the real language here:
4549 // If we have more non-CJK contents than CJK contents,
4550 // we simply use the language that was specified as
4551 // babel main language.
4552 used[lang] += t.asInput().length();
4555 // Now we are starting an environment
4557 string const name = p.getArg('{', '}');
4558 if (name != "CJK") {
4562 // It is a CJK environment
4564 /* name = */ p.getArg('{', '}');
4565 string const encoding = p.getArg('{', '}');
4566 /* mapping = */ p.getArg('{', '}');
4567 string const encoding_old = p.getEncoding();
4568 char const * const * const where =
4569 is_known(encoding, supported_CJK_encodings);
4571 p.setEncoding(encoding, Encoding::CJK);
4573 p.setEncoding("UTF-8");
4574 string const text = p.ertEnvironment("CJK");
4575 p.setEncoding(encoding_old);
4578 // ignore contents in unknown CJK encoding
4581 // the language of the text
4583 supported_CJK_languages[where - supported_CJK_encodings];
4584 used[cjk] += text.length();
4586 LangMap::const_iterator use = used.begin();
4587 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4588 if (it->second > use->second)