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[] = { "chapref", "corref", "eqref",
121 "enuref", "fnref", "lemref", "parref", "partref", "propref", "secref", "Staref",
122 "subref", "thmref", 0 };
124 char const * const known_refstyle_prefixes[] = { "chap", "cor", "eq",
125 "enu", "fn", "lem", "par", "part", "prop", "sec", "Sta",
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 handle_backslash(ostream & os, string const & s)
521 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
523 os << "\n\\backslash\n";
530 void handle_ert(ostream & os, string const & s, Context & context)
532 // We must have a valid layout before outputting the ERT inset.
533 context.check_layout(os);
534 Context newcontext(true, context.textclass);
535 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
536 if (layout.forcePlainLayout())
537 newcontext.layout = &context.textclass.plainLayout();
538 begin_inset(os, "ERT");
539 os << "\nstatus collapsed\n";
540 newcontext.check_layout(os);
541 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
543 os << "\n\\backslash\n";
544 else if (*it == '\n') {
545 newcontext.new_paragraph(os);
546 newcontext.check_layout(os);
550 newcontext.check_end_layout(os);
555 void handle_comment(ostream & os, string const & s, Context & context)
557 // TODO: Handle this better
558 Context newcontext(true, context.textclass);
559 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
560 if (layout.forcePlainLayout())
561 newcontext.layout = &context.textclass.plainLayout();
562 begin_inset(os, "ERT");
563 os << "\nstatus collapsed\n";
564 newcontext.check_layout(os);
565 handle_backslash(os, s);
566 // make sure that our comment is the last thing on the line
567 newcontext.new_paragraph(os);
568 newcontext.check_layout(os);
569 newcontext.check_end_layout(os);
574 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
576 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
579 if (checkModule(name, command))
580 return findLayoutWithoutModule(textclass, name, command);
585 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
587 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
590 if (checkModule(name, command))
591 return findInsetLayoutWithoutModule(textclass, name, command);
596 void eat_whitespace(Parser &, ostream &, Context &, bool);
600 * Skips whitespace and braces.
601 * This should be called after a command has been parsed that is not put into
602 * ERT, and where LyX adds "{}" if needed.
604 void skip_spaces_braces(Parser & p, bool keepws = false)
606 /* The following four examples produce the same typeset output and
607 should be handled by this function:
615 // Unfortunately we need to skip comments, too.
616 // We can't use eat_whitespace since writing them after the {}
617 // results in different output in some cases.
618 bool const skipped_spaces = p.skip_spaces(true);
619 bool const skipped_braces = skip_braces(p);
620 if (keepws && skipped_spaces && !skipped_braces)
621 // put back the space (it is better handled by check_space)
622 p.unskip_spaces(true);
626 void output_command_layout(ostream & os, Parser & p, bool outer,
627 Context & parent_context,
628 Layout const * newlayout)
630 TeXFont const oldFont = parent_context.font;
631 // save the current font size
632 string const size = oldFont.size;
633 // reset the font size to default, because the font size switches
634 // don't affect section headings and the like
635 parent_context.font.size = Context::normalfont.size;
636 // we only need to write the font change if we have an open layout
637 if (!parent_context.atParagraphStart())
638 output_font_change(os, oldFont, parent_context.font);
639 parent_context.check_end_layout(os);
640 Context context(true, parent_context.textclass, newlayout,
641 parent_context.layout, parent_context.font);
642 if (parent_context.deeper_paragraph) {
643 // We are beginning a nested environment after a
644 // deeper paragraph inside the outer list environment.
645 // Therefore we don't need to output a "begin deeper".
646 context.need_end_deeper = true;
648 context.check_deeper(os);
649 context.check_layout(os);
650 // FIXME: Adjust to format 446!
651 // Since format 446, layouts do not require anymore all optional
652 // arguments before the required ones. Needs to be implemented!
654 while (optargs < context.layout->optArgs()) {
655 eat_whitespace(p, os, context, false);
656 if (p.next_token().cat() == catEscape ||
657 p.next_token().character() != '[')
659 p.get_token(); // eat '['
660 // FIXME: Just a workaround. InsetArgument::updateBuffer
661 // will compute a proper ID for all "999" Arguments
662 // (which is also what lyx2lyx produces).
663 // However, tex2lyx should be able to output proper IDs
665 begin_inset(os, "Argument 999\n");
666 os << "status collapsed\n\n";
667 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
669 eat_whitespace(p, os, context, false);
673 while (reqargs < context.layout->requiredArgs()) {
674 eat_whitespace(p, os, context, false);
675 if (p.next_token().cat() != catBegin)
677 p.get_token(); // eat '{'
678 // FIXME: Just a workaround. InsetArgument::updateBuffer
679 // will compute a proper ID for all "999" Arguments
680 // (which is also what lyx2lyx produces).
681 // However, tex2lyx should be able to output proper IDs
683 begin_inset(os, "Argument 999\n");
684 os << "status collapsed\n\n";
685 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
687 eat_whitespace(p, os, context, false);
690 parse_text(p, os, FLAG_ITEM, outer, context);
691 context.check_end_layout(os);
692 if (parent_context.deeper_paragraph) {
693 // We must suppress the "end deeper" because we
694 // suppressed the "begin deeper" above.
695 context.need_end_deeper = false;
697 context.check_end_deeper(os);
698 // We don't need really a new paragraph, but
699 // we must make sure that the next item gets a \begin_layout.
700 parent_context.new_paragraph(os);
701 // Set the font size to the original value. No need to output it here
702 // (Context::begin_layout() will do that if needed)
703 parent_context.font.size = size;
708 * Output a space if necessary.
709 * This function gets called for every whitespace token.
711 * We have three cases here:
712 * 1. A space must be suppressed. Example: The lyxcode case below
713 * 2. A space may be suppressed. Example: Spaces before "\par"
714 * 3. A space must not be suppressed. Example: A space between two words
716 * We currently handle only 1. and 3 and from 2. only the case of
717 * spaces before newlines as a side effect.
719 * 2. could be used to suppress as many spaces as possible. This has two effects:
720 * - Reimporting LyX generated LaTeX files changes almost no whitespace
721 * - Superflous whitespace from non LyX generated LaTeX files is removed.
722 * The drawback is that the logic inside the function becomes
723 * complicated, and that is the reason why it is not implemented.
725 void check_space(Parser & p, ostream & os, Context & context)
727 Token const next = p.next_token();
728 Token const curr = p.curr_token();
729 // A space before a single newline and vice versa must be ignored
730 // LyX emits a newline before \end{lyxcode}.
731 // This newline must be ignored,
732 // otherwise LyX will add an additional protected space.
733 if (next.cat() == catSpace ||
734 next.cat() == catNewline ||
735 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
738 context.check_layout(os);
744 * Parse all arguments of \p command
746 void parse_arguments(string const & command,
747 vector<ArgumentType> const & template_arguments,
748 Parser & p, ostream & os, bool outer, Context & context)
750 string ert = command;
751 size_t no_arguments = template_arguments.size();
752 for (size_t i = 0; i < no_arguments; ++i) {
753 switch (template_arguments[i]) {
756 // This argument contains regular LaTeX
757 handle_ert(os, ert + '{', context);
758 eat_whitespace(p, os, context, false);
759 if (template_arguments[i] == required)
760 parse_text(p, os, FLAG_ITEM, outer, context);
762 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
766 // This argument consists only of a single item.
767 // The presence of '{' or not must be preserved.
769 if (p.next_token().cat() == catBegin)
770 ert += '{' + p.verbatim_item() + '}';
772 ert += p.verbatim_item();
776 // This argument may contain special characters
777 ert += '{' + p.verbatim_item() + '}';
781 // true because we must not eat whitespace
782 // if an optional arg follows we must not strip the
783 // brackets from this one
784 if (i < no_arguments - 1 &&
785 template_arguments[i+1] == optional)
786 ert += p.getFullOpt(true);
788 ert += p.getOpt(true);
792 handle_ert(os, ert, context);
797 * Check whether \p command is a known command. If yes,
798 * handle the command with all arguments.
799 * \return true if the command was parsed, false otherwise.
801 bool parse_command(string const & command, Parser & p, ostream & os,
802 bool outer, Context & context)
804 if (known_commands.find(command) != known_commands.end()) {
805 parse_arguments(command, known_commands[command], p, os,
813 /// Parses a minipage or parbox
814 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
815 unsigned inner_flags, bool outer, Context & parent_context,
816 string const & outer_type, string const & special,
817 string const & inner_type)
821 string hor_pos = "c";
822 // We need to set the height to the LaTeX default of 1\\totalheight
823 // for the case when no height argument is given
824 string height_value = "1";
825 string height_unit = "in";
826 string height_special = "totalheight";
831 string width_special = "none";
832 if (!inner_type.empty() && p.hasOpt()) {
833 if (inner_type != "makebox")
834 position = p.getArg('[', ']');
836 latex_width = p.getArg('[', ']');
837 translate_box_len(latex_width, width_value, width_unit, width_special);
840 if (position != "t" && position != "c" && position != "b") {
841 cerr << "invalid position " << position << " for "
842 << inner_type << endl;
846 if (inner_type != "makebox") {
847 latex_height = p.getArg('[', ']');
848 translate_box_len(latex_height, height_value, height_unit, height_special);
850 string const opt = p.getArg('[', ']');
853 if (hor_pos != "l" && hor_pos != "c" &&
854 hor_pos != "r" && hor_pos != "s") {
855 cerr << "invalid hor_pos " << hor_pos
856 << " for " << inner_type << endl;
863 inner_pos = p.getArg('[', ']');
864 if (inner_pos != "c" && inner_pos != "t" &&
865 inner_pos != "b" && inner_pos != "s") {
866 cerr << "invalid inner_pos "
867 << inner_pos << " for "
868 << inner_type << endl;
869 inner_pos = position;
874 if (inner_type.empty()) {
875 if (special.empty() && outer_type != "framebox")
876 latex_width = "1\\columnwidth";
879 latex_width = p2.getArg('[', ']');
880 string const opt = p2.getArg('[', ']');
883 if (hor_pos != "l" && hor_pos != "c" &&
884 hor_pos != "r" && hor_pos != "s") {
885 cerr << "invalid hor_pos " << hor_pos
886 << " for " << outer_type << endl;
891 } else if (inner_type != "makebox")
892 latex_width = p.verbatim_item();
893 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
894 // as this is LyX's standard for such cases (except for makebox)
895 // \framebox is more special and handled below
896 if (latex_width.empty() && inner_type != "makebox"
897 && outer_type != "framebox")
898 latex_width = "1\\columnwidth";
900 translate_len(latex_width, width_value, width_unit);
902 bool shadedparbox = false;
903 if (inner_type == "shaded") {
904 eat_whitespace(p, os, parent_context, false);
905 if (outer_type == "parbox") {
907 if (p.next_token().cat() == catBegin)
909 eat_whitespace(p, os, parent_context, false);
915 // If we already read the inner box we have to push the inner env
916 if (!outer_type.empty() && !inner_type.empty() &&
917 (inner_flags & FLAG_END))
918 active_environments.push_back(inner_type);
919 // LyX can't handle length variables
920 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
921 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
922 // Look whether there is some content after the end of the
923 // inner box, but before the end of the outer box.
924 // If yes, we need to output ERT.
926 if (inner_flags & FLAG_END)
927 p.verbatimEnvironment(inner_type);
931 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
932 if ((outer_env && p.next_token().asInput() != "\\end") ||
933 (!outer_env && p.next_token().cat() != catEnd)) {
934 // something is between the end of the inner box and
935 // the end of the outer box, so we need to use ERT.
940 // if only \makebox{content} was used we can set its width to 1\width
941 // because this identic and also identic to \mbox
942 // this doesn't work for \framebox{content}, thus we have to use ERT for this
943 if (latex_width.empty() && inner_type == "makebox") {
946 width_special = "width";
947 } else if (latex_width.empty() && outer_type == "framebox") {
952 if (!outer_type.empty()) {
953 if (outer_flags & FLAG_END)
954 ss << "\\begin{" << outer_type << '}';
956 ss << '\\' << outer_type << '{';
957 if (!special.empty())
961 if (!inner_type.empty()) {
962 if (inner_type != "shaded") {
963 if (inner_flags & FLAG_END)
964 ss << "\\begin{" << inner_type << '}';
966 ss << '\\' << inner_type;
968 if (!position.empty())
969 ss << '[' << position << ']';
970 if (!latex_height.empty())
971 ss << '[' << latex_height << ']';
972 if (!inner_pos.empty())
973 ss << '[' << inner_pos << ']';
974 ss << '{' << latex_width << '}';
975 if (!(inner_flags & FLAG_END))
978 if (inner_type == "shaded")
979 ss << "\\begin{shaded}";
980 handle_ert(os, ss.str(), parent_context);
981 if (!inner_type.empty()) {
982 parse_text(p, os, inner_flags, outer, parent_context);
983 if (inner_flags & FLAG_END)
984 handle_ert(os, "\\end{" + inner_type + '}',
987 handle_ert(os, "}", parent_context);
989 if (!outer_type.empty()) {
990 // If we already read the inner box we have to pop
992 if (!inner_type.empty() && (inner_flags & FLAG_END))
993 active_environments.pop_back();
995 // Ensure that the end of the outer box is parsed correctly:
996 // The opening brace has been eaten by parse_outer_box()
997 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
998 outer_flags &= ~FLAG_ITEM;
999 outer_flags |= FLAG_BRACE_LAST;
1001 parse_text(p, os, outer_flags, outer, parent_context);
1002 if (outer_flags & FLAG_END)
1003 handle_ert(os, "\\end{" + outer_type + '}',
1005 else if (inner_type.empty() && outer_type == "framebox")
1006 // in this case it is already closed later
1009 handle_ert(os, "}", parent_context);
1012 // LyX does not like empty positions, so we have
1013 // to set them to the LaTeX default values here.
1014 if (position.empty())
1016 if (inner_pos.empty())
1017 inner_pos = position;
1018 parent_context.check_layout(os);
1019 begin_inset(os, "Box ");
1020 if (outer_type == "framed")
1022 else if (outer_type == "framebox")
1024 else if (outer_type == "shadowbox")
1025 os << "Shadowbox\n";
1026 else if ((outer_type == "shaded" && inner_type.empty()) ||
1027 (outer_type == "minipage" && inner_type == "shaded") ||
1028 (outer_type == "parbox" && inner_type == "shaded")) {
1030 preamble.registerAutomaticallyLoadedPackage("color");
1031 } else if (outer_type == "doublebox")
1032 os << "Doublebox\n";
1033 else if (outer_type.empty())
1034 os << "Frameless\n";
1036 os << outer_type << '\n';
1037 os << "position \"" << position << "\"\n";
1038 os << "hor_pos \"" << hor_pos << "\"\n";
1039 os << "has_inner_box " << !inner_type.empty() << "\n";
1040 os << "inner_pos \"" << inner_pos << "\"\n";
1041 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1043 os << "use_makebox " << (inner_type == "makebox") << '\n';
1044 os << "width \"" << width_value << width_unit << "\"\n";
1045 os << "special \"" << width_special << "\"\n";
1046 os << "height \"" << height_value << height_unit << "\"\n";
1047 os << "height_special \"" << height_special << "\"\n";
1048 os << "status open\n\n";
1050 // Unfortunately we can't use parse_text_in_inset:
1051 // InsetBox::forcePlainLayout() is hard coded and does not
1052 // use the inset layout. Apart from that do we call parse_text
1053 // up to two times, but need only one check_end_layout.
1054 bool const forcePlainLayout =
1055 (!inner_type.empty() || inner_type == "makebox") &&
1056 outer_type != "shaded" && outer_type != "framed";
1057 Context context(true, parent_context.textclass);
1058 if (forcePlainLayout)
1059 context.layout = &context.textclass.plainLayout();
1061 context.font = parent_context.font;
1063 // If we have no inner box the contents will be read with the outer box
1064 if (!inner_type.empty())
1065 parse_text(p, os, inner_flags, outer, context);
1067 // Ensure that the end of the outer box is parsed correctly:
1068 // The opening brace has been eaten by parse_outer_box()
1069 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1070 outer_flags &= ~FLAG_ITEM;
1071 outer_flags |= FLAG_BRACE_LAST;
1074 // Find end of outer box, output contents if inner_type is
1075 // empty and output possible comments
1076 if (!outer_type.empty()) {
1077 // If we already read the inner box we have to pop
1079 if (!inner_type.empty() && (inner_flags & FLAG_END))
1080 active_environments.pop_back();
1081 // This does not output anything but comments if
1082 // inner_type is not empty (see use_ert)
1083 parse_text(p, os, outer_flags, outer, context);
1086 context.check_end_layout(os);
1088 #ifdef PRESERVE_LAYOUT
1089 // LyX puts a % after the end of the minipage
1090 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1092 //handle_comment(os, "%dummy", parent_context);
1095 parent_context.new_paragraph(os);
1097 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1098 //handle_comment(os, "%dummy", parent_context);
1101 // We add a protected space if something real follows
1102 if (p.good() && p.next_token().cat() != catComment) {
1103 begin_inset(os, "space ~\n");
1112 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1113 Context & parent_context, string const & outer_type,
1114 string const & special)
1116 eat_whitespace(p, os, parent_context, false);
1117 if (flags & FLAG_ITEM) {
1119 if (p.next_token().cat() == catBegin)
1122 cerr << "Warning: Ignoring missing '{' after \\"
1123 << outer_type << '.' << endl;
1124 eat_whitespace(p, os, parent_context, false);
1127 unsigned int inner_flags = 0;
1129 if (outer_type == "minipage" || outer_type == "parbox") {
1130 p.skip_spaces(true);
1131 while (p.hasOpt()) {
1133 p.skip_spaces(true);
1136 p.skip_spaces(true);
1137 if (outer_type == "parbox") {
1139 if (p.next_token().cat() == catBegin)
1141 p.skip_spaces(true);
1144 if (outer_type == "shaded") {
1145 // These boxes never have an inner box
1147 } else if (p.next_token().asInput() == "\\parbox") {
1148 inner = p.get_token().cs();
1149 inner_flags = FLAG_ITEM;
1150 } else if (p.next_token().asInput() == "\\begin") {
1151 // Is this a minipage or shaded box?
1154 inner = p.getArg('{', '}');
1156 if (inner == "minipage" || inner == "shaded")
1157 inner_flags = FLAG_END;
1162 if (inner_flags == FLAG_END) {
1163 if (inner != "shaded")
1167 eat_whitespace(p, os, parent_context, false);
1169 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1170 outer_type, special, inner);
1172 if (inner_flags == FLAG_ITEM) {
1174 eat_whitespace(p, os, parent_context, false);
1176 parse_box(p, os, flags, inner_flags, outer, parent_context,
1177 outer_type, special, inner);
1182 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1184 parent_context.check_layout(os);
1185 begin_inset(os, "listings\n");
1187 string arg = p.verbatimOption();
1188 os << "lstparams " << '"' << arg << '"' << '\n';
1189 if (arg.find("\\color") != string::npos)
1190 preamble.registerAutomaticallyLoadedPackage("color");
1193 os << "inline true\n";
1195 os << "inline false\n";
1196 os << "status collapsed\n";
1197 Context context(true, parent_context.textclass);
1198 context.layout = &parent_context.textclass.plainLayout();
1201 s = p.plainCommand('!', '!', "lstinline");
1202 context.new_paragraph(os);
1203 context.check_layout(os);
1205 s = p.plainEnvironment("lstlisting");
1206 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1208 os << "\n\\backslash\n";
1209 else if (*it == '\n') {
1210 // avoid adding an empty paragraph at the end
1212 context.new_paragraph(os);
1213 context.check_layout(os);
1218 context.check_end_layout(os);
1223 /// parse an unknown environment
1224 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1225 unsigned flags, bool outer,
1226 Context & parent_context)
1228 if (name == "tabbing")
1229 // We need to remember that we have to handle '\=' specially
1230 flags |= FLAG_TABBING;
1232 // We need to translate font changes and paragraphs inside the
1233 // environment to ERT if we have a non standard font.
1234 // Otherwise things like
1235 // \large\begin{foo}\huge bar\end{foo}
1237 bool const specialfont =
1238 (parent_context.font != parent_context.normalfont);
1239 bool const new_layout_allowed = parent_context.new_layout_allowed;
1241 parent_context.new_layout_allowed = false;
1242 handle_ert(os, "\\begin{" + name + "}", parent_context);
1243 parse_text_snippet(p, os, flags, outer, parent_context);
1244 handle_ert(os, "\\end{" + name + "}", parent_context);
1246 parent_context.new_layout_allowed = new_layout_allowed;
1250 void parse_environment(Parser & p, ostream & os, bool outer,
1251 string & last_env, Context & parent_context)
1253 Layout const * newlayout;
1254 InsetLayout const * newinsetlayout = 0;
1255 string const name = p.getArg('{', '}');
1256 const bool is_starred = suffixIs(name, '*');
1257 string const unstarred_name = rtrim(name, "*");
1258 active_environments.push_back(name);
1260 if (is_math_env(name)) {
1261 parent_context.check_layout(os);
1262 begin_inset(os, "Formula ");
1263 os << "\\begin{" << name << "}";
1264 parse_math(p, os, FLAG_END, MATH_MODE);
1265 os << "\\end{" << name << "}";
1267 if (is_display_math_env(name)) {
1268 // Prevent the conversion of a line break to a space
1269 // (bug 7668). This does not change the output, but
1270 // looks ugly in LyX.
1271 eat_whitespace(p, os, parent_context, false);
1275 else if (is_known(name, preamble.polyglossia_languages)) {
1276 // We must begin a new paragraph if not already done
1277 if (! parent_context.atParagraphStart()) {
1278 parent_context.check_end_layout(os);
1279 parent_context.new_paragraph(os);
1281 // save the language in the context so that it is
1282 // handled by parse_text
1283 parent_context.font.language = preamble.polyglossia2lyx(name);
1284 parse_text(p, os, FLAG_END, outer, parent_context);
1285 // Just in case the environment is empty
1286 parent_context.extra_stuff.erase();
1287 // We must begin a new paragraph to reset the language
1288 parent_context.new_paragraph(os);
1292 else if (unstarred_name == "tabular" || name == "longtable") {
1293 eat_whitespace(p, os, parent_context, false);
1294 string width = "0pt";
1295 if (name == "tabular*") {
1296 width = lyx::translate_len(p.getArg('{', '}'));
1297 eat_whitespace(p, os, parent_context, false);
1299 parent_context.check_layout(os);
1300 begin_inset(os, "Tabular ");
1301 handle_tabular(p, os, name, width, parent_context);
1306 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1307 eat_whitespace(p, os, parent_context, false);
1308 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1309 eat_whitespace(p, os, parent_context, false);
1310 parent_context.check_layout(os);
1311 begin_inset(os, "Float " + unstarred_name + "\n");
1312 // store the float type for subfloats
1313 // subfloats only work with figures and tables
1314 if (unstarred_name == "figure")
1315 float_type = unstarred_name;
1316 else if (unstarred_name == "table")
1317 float_type = unstarred_name;
1321 os << "placement " << opt << '\n';
1322 if (contains(opt, "H"))
1323 preamble.registerAutomaticallyLoadedPackage("float");
1325 Floating const & fl = parent_context.textclass.floats()
1326 .getType(unstarred_name);
1327 if (!fl.floattype().empty() && fl.usesFloatPkg())
1328 preamble.registerAutomaticallyLoadedPackage("float");
1331 os << "wide " << convert<string>(is_starred)
1332 << "\nsideways false"
1333 << "\nstatus open\n\n";
1334 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1336 // We don't need really a new paragraph, but
1337 // we must make sure that the next item gets a \begin_layout.
1338 parent_context.new_paragraph(os);
1340 // the float is parsed thus delete the type
1344 else if (unstarred_name == "sidewaysfigure"
1345 || unstarred_name == "sidewaystable") {
1346 eat_whitespace(p, os, parent_context, false);
1347 parent_context.check_layout(os);
1348 if (unstarred_name == "sidewaysfigure")
1349 begin_inset(os, "Float figure\n");
1351 begin_inset(os, "Float table\n");
1352 os << "wide " << convert<string>(is_starred)
1353 << "\nsideways true"
1354 << "\nstatus open\n\n";
1355 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1357 // We don't need really a new paragraph, but
1358 // we must make sure that the next item gets a \begin_layout.
1359 parent_context.new_paragraph(os);
1361 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1364 else if (name == "wrapfigure" || name == "wraptable") {
1365 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1366 eat_whitespace(p, os, parent_context, false);
1367 parent_context.check_layout(os);
1370 string overhang = "0col%";
1373 lines = p.getArg('[', ']');
1374 string const placement = p.getArg('{', '}');
1376 overhang = p.getArg('[', ']');
1377 string const width = p.getArg('{', '}');
1379 if (name == "wrapfigure")
1380 begin_inset(os, "Wrap figure\n");
1382 begin_inset(os, "Wrap table\n");
1383 os << "lines " << lines
1384 << "\nplacement " << placement
1385 << "\noverhang " << lyx::translate_len(overhang)
1386 << "\nwidth " << lyx::translate_len(width)
1387 << "\nstatus open\n\n";
1388 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1390 // We don't need really a new paragraph, but
1391 // we must make sure that the next item gets a \begin_layout.
1392 parent_context.new_paragraph(os);
1394 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1397 else if (name == "minipage") {
1398 eat_whitespace(p, os, parent_context, false);
1399 // Test whether this is an outer box of a shaded box
1401 // swallow arguments
1402 while (p.hasOpt()) {
1404 p.skip_spaces(true);
1407 p.skip_spaces(true);
1408 Token t = p.get_token();
1409 bool shaded = false;
1410 if (t.asInput() == "\\begin") {
1411 p.skip_spaces(true);
1412 if (p.getArg('{', '}') == "shaded")
1417 parse_outer_box(p, os, FLAG_END, outer,
1418 parent_context, name, "shaded");
1420 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1425 else if (name == "comment") {
1426 eat_whitespace(p, os, parent_context, false);
1427 parent_context.check_layout(os);
1428 begin_inset(os, "Note Comment\n");
1429 os << "status open\n";
1430 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1433 skip_braces(p); // eat {} that might by set by LyX behind comments
1434 preamble.registerAutomaticallyLoadedPackage("verbatim");
1437 else if (name == "verbatim") {
1438 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1439 string const s = p.plainEnvironment("verbatim");
1440 string::const_iterator it2 = s.begin();
1441 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1443 os << "\\backslash ";
1444 else if (*it == '\n') {
1446 // avoid adding an empty paragraph at the end
1447 // FIXME: if there are 2 consecutive spaces at the end ignore it
1448 // because LyX will re-add a \n
1449 // This hack must be removed once bug 8049 is fixed!
1450 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1451 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1455 os << "\n\\end_layout\n\n";
1457 // reset to Standard layout
1458 os << "\n\\begin_layout Standard\n";
1461 else if (name == "CJK") {
1462 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1463 // It is impossible to decide if a CJK environment was in its own paragraph or within
1464 // a line. We therefore always assume a paragraph since the latter is a rare case.
1465 eat_whitespace(p, os, parent_context, false);
1466 parent_context.check_end_layout(os);
1467 // store the encoding to be able to reset it
1468 string const encoding_old = p.getEncoding();
1469 string const encoding = p.getArg('{', '}');
1470 // FIXME: For some reason JIS does not work. Although the text
1471 // in tests/CJK.tex is identical with the SJIS version if you
1472 // convert both snippets using the recode command line utility,
1473 // the resulting .lyx file contains some extra characters if
1474 // you set buggy_encoding to false for JIS.
1475 bool const buggy_encoding = encoding == "JIS";
1476 if (!buggy_encoding)
1477 p.setEncoding(encoding, Encoding::CJK);
1479 // FIXME: This will read garbage, since the data is not encoded in utf8.
1480 p.setEncoding("UTF-8");
1482 // LyX only supports the same mapping for all CJK
1483 // environments, so we might need to output everything as ERT
1484 string const mapping = trim(p.getArg('{', '}'));
1485 char const * const * const where =
1486 is_known(encoding, supported_CJK_encodings);
1487 if (!buggy_encoding && !preamble.fontCJKSet())
1488 preamble.fontCJK(mapping);
1489 bool knownMapping = mapping == preamble.fontCJK();
1490 if (buggy_encoding || !knownMapping || !where) {
1491 parent_context.check_layout(os);
1492 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1494 // we must parse the content as verbatim because e.g. JIS can contain
1495 // normally invalid characters
1496 // FIXME: This works only for the most simple cases.
1497 // Since TeX control characters are not parsed,
1498 // things like comments are completely wrong.
1499 string const s = p.plainEnvironment("CJK");
1500 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1502 handle_ert(os, "\\", parent_context);
1503 else if (*it == '$')
1504 handle_ert(os, "$", parent_context);
1508 handle_ert(os, "\\end{" + name + "}",
1512 supported_CJK_languages[where - supported_CJK_encodings];
1513 // store the language because we must reset it at the end
1514 string const lang_old = parent_context.font.language;
1515 parent_context.font.language = lang;
1516 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1517 parent_context.font.language = lang_old;
1518 parent_context.new_paragraph(os);
1520 p.setEncoding(encoding_old);
1524 else if (name == "lyxgreyedout") {
1525 eat_whitespace(p, os, parent_context, false);
1526 parent_context.check_layout(os);
1527 begin_inset(os, "Note Greyedout\n");
1528 os << "status open\n";
1529 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1532 if (!preamble.notefontcolor().empty())
1533 preamble.registerAutomaticallyLoadedPackage("color");
1536 else if (name == "framed" || name == "shaded") {
1537 eat_whitespace(p, os, parent_context, false);
1538 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1542 else if (name == "lstlisting") {
1543 eat_whitespace(p, os, parent_context, false);
1544 parse_listings(p, os, parent_context, false);
1548 else if (!parent_context.new_layout_allowed)
1549 parse_unknown_environment(p, name, os, FLAG_END, outer,
1552 // Alignment and spacing settings
1553 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1554 // therefore are totally broken!
1555 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1556 // they are commands not environments. They are furthermore switches that
1557 // can be ended by another switches, but also by commands like \footnote or
1558 // \parbox. So the only safe way is to leave them untouched.
1559 else if (name == "center" || name == "centering" ||
1560 name == "flushleft" || name == "flushright" ||
1561 name == "singlespace" || name == "onehalfspace" ||
1562 name == "doublespace" || name == "spacing") {
1563 eat_whitespace(p, os, parent_context, false);
1564 // We must begin a new paragraph if not already done
1565 if (! parent_context.atParagraphStart()) {
1566 parent_context.check_end_layout(os);
1567 parent_context.new_paragraph(os);
1569 if (name == "flushleft")
1570 parent_context.add_extra_stuff("\\align left\n");
1571 else if (name == "flushright")
1572 parent_context.add_extra_stuff("\\align right\n");
1573 else if (name == "center" || name == "centering")
1574 parent_context.add_extra_stuff("\\align center\n");
1575 else if (name == "singlespace")
1576 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1577 else if (name == "onehalfspace") {
1578 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1579 preamble.registerAutomaticallyLoadedPackage("setspace");
1580 } else if (name == "doublespace") {
1581 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1582 preamble.registerAutomaticallyLoadedPackage("setspace");
1583 } else if (name == "spacing") {
1584 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1585 preamble.registerAutomaticallyLoadedPackage("setspace");
1587 parse_text(p, os, FLAG_END, outer, parent_context);
1588 // Just in case the environment is empty
1589 parent_context.extra_stuff.erase();
1590 // We must begin a new paragraph to reset the alignment
1591 parent_context.new_paragraph(os);
1595 // The single '=' is meant here.
1596 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1597 eat_whitespace(p, os, parent_context, false);
1598 Context context(true, parent_context.textclass, newlayout,
1599 parent_context.layout, parent_context.font);
1600 if (parent_context.deeper_paragraph) {
1601 // We are beginning a nested environment after a
1602 // deeper paragraph inside the outer list environment.
1603 // Therefore we don't need to output a "begin deeper".
1604 context.need_end_deeper = true;
1606 parent_context.check_end_layout(os);
1607 if (last_env == name) {
1608 // we need to output a separator since LyX would export
1609 // the two environments as one otherwise (bug 5716)
1610 docstring const sep = from_ascii("--Separator--");
1611 TeX2LyXDocClass const & textclass(parent_context.textclass);
1612 if (textclass.hasLayout(sep)) {
1613 Context newcontext(parent_context);
1614 newcontext.layout = &(textclass[sep]);
1615 newcontext.check_layout(os);
1616 newcontext.check_end_layout(os);
1618 parent_context.check_layout(os);
1619 begin_inset(os, "Note Note\n");
1620 os << "status closed\n";
1621 Context newcontext(true, textclass,
1622 &(textclass.defaultLayout()));
1623 newcontext.check_layout(os);
1624 newcontext.check_end_layout(os);
1626 parent_context.check_end_layout(os);
1629 switch (context.layout->latextype) {
1630 case LATEX_LIST_ENVIRONMENT:
1631 context.add_par_extra_stuff("\\labelwidthstring "
1632 + p.verbatim_item() + '\n');
1635 case LATEX_BIB_ENVIRONMENT:
1636 p.verbatim_item(); // swallow next arg
1642 context.check_deeper(os);
1643 // handle known optional and required arguments
1644 // FIXME: Since format 446, layouts do not require anymore all optional
1645 // arguments before the required ones. Needs to be implemented!
1646 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1647 // It is impossible to place anything after the environment name,
1648 // but before the first \\item.
1649 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1650 bool need_layout = true;
1652 while (optargs < context.layout->optArgs()) {
1653 eat_whitespace(p, os, context, false);
1654 if (p.next_token().cat() == catEscape ||
1655 p.next_token().character() != '[')
1657 p.get_token(); // eat '['
1659 context.check_layout(os);
1660 need_layout = false;
1662 // FIXME: Just a workaround. InsetArgument::updateBuffer
1663 // will compute a proper ID for all "999" Arguments
1664 // (which is also what lyx2lyx produces).
1665 // However, tex2lyx should be able to output proper IDs
1667 begin_inset(os, "Argument 999\n");
1668 os << "status collapsed\n\n";
1669 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1671 eat_whitespace(p, os, context, false);
1675 while (reqargs < context.layout->requiredArgs()) {
1676 eat_whitespace(p, os, context, false);
1677 if (p.next_token().cat() != catBegin)
1679 p.get_token(); // eat '{'
1681 context.check_layout(os);
1682 need_layout = false;
1684 // FIXME: Just a workaround. InsetArgument::updateBuffer
1685 // will compute a proper ID for all "999" Arguments
1686 // (which is also what lyx2lyx produces).
1687 // However, tex2lyx should be able to output proper IDs
1689 begin_inset(os, "Argument 999\n");
1690 os << "status collapsed\n\n";
1691 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1693 eat_whitespace(p, os, context, false);
1697 parse_text(p, os, FLAG_END, outer, context);
1698 context.check_end_layout(os);
1699 if (parent_context.deeper_paragraph) {
1700 // We must suppress the "end deeper" because we
1701 // suppressed the "begin deeper" above.
1702 context.need_end_deeper = false;
1704 context.check_end_deeper(os);
1705 parent_context.new_paragraph(os);
1707 if (!preamble.titleLayoutFound())
1708 preamble.titleLayoutFound(newlayout->intitle);
1709 set<string> const & req = newlayout->requires();
1710 set<string>::const_iterator it = req.begin();
1711 set<string>::const_iterator en = req.end();
1712 for (; it != en; ++it)
1713 preamble.registerAutomaticallyLoadedPackage(*it);
1716 // The single '=' is meant here.
1717 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1718 eat_whitespace(p, os, parent_context, false);
1719 parent_context.check_layout(os);
1720 begin_inset(os, "Flex ");
1721 os << to_utf8(newinsetlayout->name()) << '\n'
1722 << "status collapsed\n";
1723 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1727 else if (name == "appendix") {
1728 // This is no good latex style, but it works and is used in some documents...
1729 eat_whitespace(p, os, parent_context, false);
1730 parent_context.check_end_layout(os);
1731 Context context(true, parent_context.textclass, parent_context.layout,
1732 parent_context.layout, parent_context.font);
1733 context.check_layout(os);
1734 os << "\\start_of_appendix\n";
1735 parse_text(p, os, FLAG_END, outer, context);
1736 context.check_end_layout(os);
1740 else if (known_environments.find(name) != known_environments.end()) {
1741 vector<ArgumentType> arguments = known_environments[name];
1742 // The last "argument" denotes wether we may translate the
1743 // environment contents to LyX
1744 // The default required if no argument is given makes us
1745 // compatible with the reLyXre environment.
1746 ArgumentType contents = arguments.empty() ?
1749 if (!arguments.empty())
1750 arguments.pop_back();
1751 // See comment in parse_unknown_environment()
1752 bool const specialfont =
1753 (parent_context.font != parent_context.normalfont);
1754 bool const new_layout_allowed =
1755 parent_context.new_layout_allowed;
1757 parent_context.new_layout_allowed = false;
1758 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1759 outer, parent_context);
1760 if (contents == verbatim)
1761 handle_ert(os, p.verbatimEnvironment(name),
1764 parse_text_snippet(p, os, FLAG_END, outer,
1766 handle_ert(os, "\\end{" + name + "}", parent_context);
1768 parent_context.new_layout_allowed = new_layout_allowed;
1772 parse_unknown_environment(p, name, os, FLAG_END, outer,
1776 active_environments.pop_back();
1780 /// parses a comment and outputs it to \p os.
1781 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1783 LASSERT(t.cat() == catComment, return);
1784 if (!t.cs().empty()) {
1785 context.check_layout(os);
1786 handle_comment(os, '%' + t.cs(), context);
1787 if (p.next_token().cat() == catNewline) {
1788 // A newline after a comment line starts a new
1790 if (context.new_layout_allowed) {
1791 if(!context.atParagraphStart())
1792 // Only start a new paragraph if not already
1793 // done (we might get called recursively)
1794 context.new_paragraph(os);
1796 handle_ert(os, "\n", context);
1797 eat_whitespace(p, os, context, true);
1800 // "%\n" combination
1807 * Reads spaces and comments until the first non-space, non-comment token.
1808 * New paragraphs (double newlines or \\par) are handled like simple spaces
1809 * if \p eatParagraph is true.
1810 * Spaces are skipped, but comments are written to \p os.
1812 void eat_whitespace(Parser & p, ostream & os, Context & context,
1816 Token const & t = p.get_token();
1817 if (t.cat() == catComment)
1818 parse_comment(p, os, t, context);
1819 else if ((! eatParagraph && p.isParagraph()) ||
1820 (t.cat() != catSpace && t.cat() != catNewline)) {
1829 * Set a font attribute, parse text and reset the font attribute.
1830 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1831 * \param currentvalue Current value of the attribute. Is set to the new
1832 * value during parsing.
1833 * \param newvalue New value of the attribute
1835 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1836 Context & context, string const & attribute,
1837 string & currentvalue, string const & newvalue)
1839 context.check_layout(os);
1840 string const oldvalue = currentvalue;
1841 currentvalue = newvalue;
1842 os << '\n' << attribute << ' ' << newvalue << "\n";
1843 parse_text_snippet(p, os, flags, outer, context);
1844 context.check_layout(os);
1845 os << '\n' << attribute << ' ' << oldvalue << "\n";
1846 currentvalue = oldvalue;
1850 /// get the arguments of a natbib or jurabib citation command
1851 void get_cite_arguments(Parser & p, bool natbibOrder,
1852 string & before, string & after)
1854 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1856 // text before the citation
1858 // text after the citation
1859 after = p.getFullOpt();
1861 if (!after.empty()) {
1862 before = p.getFullOpt();
1863 if (natbibOrder && !before.empty())
1864 swap(before, after);
1869 /// Convert filenames with TeX macros and/or quotes to something LyX
1871 string const normalize_filename(string const & name)
1876 Token const & t = p.get_token();
1877 if (t.cat() != catEscape)
1879 else if (t.cs() == "lyxdot") {
1880 // This is used by LyX for simple dots in relative
1884 } else if (t.cs() == "space") {
1887 } else if (t.cs() == "string") {
1888 // Convert \string" to " and \string~ to ~
1889 Token const & n = p.next_token();
1890 if (n.asInput() != "\"" && n.asInput() != "~")
1895 // Strip quotes. This is a bit complicated (see latex_path()).
1896 string full = os.str();
1897 if (!full.empty() && full[0] == '"') {
1898 string base = removeExtension(full);
1899 string ext = getExtension(full);
1900 if (!base.empty() && base[base.length()-1] == '"')
1903 return addExtension(trim(base, "\""), ext);
1904 if (full[full.length()-1] == '"')
1907 return trim(full, "\"");
1913 /// Convert \p name from TeX convention (relative to master file) to LyX
1914 /// convention (relative to .lyx file) if it is relative
1915 void fix_child_filename(string & name)
1917 string const absMasterTeX = getMasterFilePath(true);
1918 bool const isabs = FileName::isAbsolute(name);
1919 // convert from "relative to .tex master" to absolute original path
1921 name = makeAbsPath(name, absMasterTeX).absFileName();
1922 bool copyfile = copyFiles();
1923 string const absParentLyX = getParentFilePath(false);
1926 // convert from absolute original path to "relative to master file"
1927 string const rel = to_utf8(makeRelPath(from_utf8(name),
1928 from_utf8(absMasterTeX)));
1929 // re-interpret "relative to .tex file" as "relative to .lyx file"
1930 // (is different if the master .lyx file resides in a
1931 // different path than the master .tex file)
1932 string const absMasterLyX = getMasterFilePath(false);
1933 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1934 // Do not copy if the new path is impossible to create. Example:
1935 // absMasterTeX = "/foo/bar/"
1936 // absMasterLyX = "/bar/"
1937 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1938 if (contains(name, "/../"))
1945 // convert from absolute original path to
1946 // "relative to .lyx file"
1947 name = to_utf8(makeRelPath(from_utf8(abs),
1948 from_utf8(absParentLyX)));
1952 // convert from absolute original path to "relative to .lyx file"
1953 name = to_utf8(makeRelPath(from_utf8(name),
1954 from_utf8(absParentLyX)));
1959 void copy_file(FileName const & src, string dstname)
1963 string const absParent = getParentFilePath(false);
1965 if (FileName::isAbsolute(dstname))
1966 dst = FileName(dstname);
1968 dst = makeAbsPath(dstname, absParent);
1969 string const absMaster = getMasterFilePath(false);
1970 FileName const srcpath = src.onlyPath();
1971 FileName const dstpath = dst.onlyPath();
1972 if (equivalent(srcpath, dstpath))
1974 if (!dstpath.isDirectory()) {
1975 if (!dstpath.createPath()) {
1976 cerr << "Warning: Could not create directory for file `"
1977 << dst.absFileName() << "´." << endl;
1981 if (dst.isReadableFile()) {
1982 if (overwriteFiles())
1983 cerr << "Warning: Overwriting existing file `"
1984 << dst.absFileName() << "´." << endl;
1986 cerr << "Warning: Not overwriting existing file `"
1987 << dst.absFileName() << "´." << endl;
1991 if (!src.copyTo(dst))
1992 cerr << "Warning: Could not copy file `" << src.absFileName()
1993 << "´ to `" << dst.absFileName() << "´." << endl;
1997 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1998 void parse_noweb(Parser & p, ostream & os, Context & context)
2000 // assemble the rest of the keyword
2004 Token const & t = p.get_token();
2005 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2008 chunk = (p.good() && p.next_token().asInput() == "=");
2010 name += p.get_token().asInput();
2013 name += t.asInput();
2016 if (!chunk || !context.new_layout_allowed ||
2017 !context.textclass.hasLayout(from_ascii("Chunk"))) {
2018 cerr << "Warning: Could not interpret '" << name
2019 << "'. Ignoring it." << endl;
2023 // We use new_paragraph instead of check_end_layout because the stuff
2024 // following the noweb chunk needs to start with a \begin_layout.
2025 // This may create a new paragraph even if there was none in the
2026 // noweb file, but the alternative is an invalid LyX file. Since
2027 // noweb code chunks are implemented with a layout style in LyX they
2028 // always must be in an own paragraph.
2029 context.new_paragraph(os);
2030 Context newcontext(true, context.textclass,
2031 &context.textclass[from_ascii("Chunk")]);
2032 newcontext.check_layout(os);
2035 Token const & t = p.get_token();
2036 // We abuse the parser a bit, because this is no TeX syntax
2038 if (t.cat() == catEscape)
2039 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2042 Context tmp(false, context.textclass,
2043 &context.textclass[from_ascii("Chunk")]);
2044 tmp.need_end_layout = true;
2045 tmp.check_layout(oss);
2046 os << subst(t.asInput(), "\n", oss.str());
2048 // The chunk is ended by an @ at the beginning of a line.
2049 // After the @ the line may contain a comment and/or
2050 // whitespace, but nothing else.
2051 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2052 (p.next_token().cat() == catSpace ||
2053 p.next_token().cat() == catNewline ||
2054 p.next_token().cat() == catComment)) {
2055 while (p.good() && p.next_token().cat() == catSpace)
2056 os << p.get_token().asInput();
2057 if (p.next_token().cat() == catComment)
2058 // The comment includes a final '\n'
2059 os << p.get_token().asInput();
2061 if (p.next_token().cat() == catNewline)
2068 newcontext.check_end_layout(os);
2072 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2073 bool is_macro(Parser & p)
2075 Token first = p.curr_token();
2076 if (first.cat() != catEscape || !p.good())
2078 if (first.cs() == "def")
2080 if (first.cs() != "global" && first.cs() != "long")
2082 Token second = p.get_token();
2084 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2085 second.cat() == catNewline || second.cat() == catComment)) {
2086 second = p.get_token();
2089 bool secondvalid = second.cat() == catEscape;
2091 bool thirdvalid = false;
2092 if (p.good() && first.cs() == "global" && secondvalid &&
2093 second.cs() == "long") {
2094 third = p.get_token();
2096 while (p.good() && !p.isParagraph() &&
2097 (third.cat() == catSpace ||
2098 third.cat() == catNewline ||
2099 third.cat() == catComment)) {
2100 third = p.get_token();
2103 thirdvalid = third.cat() == catEscape;
2105 for (int i = 0; i < pos; ++i)
2110 return (first.cs() == "global" || first.cs() == "long") &&
2111 second.cs() == "def";
2112 return first.cs() == "global" && second.cs() == "long" &&
2113 third.cs() == "def";
2117 /// Parse a macro definition (assumes that is_macro() returned true)
2118 void parse_macro(Parser & p, ostream & os, Context & context)
2120 context.check_layout(os);
2121 Token first = p.curr_token();
2124 string command = first.asInput();
2125 if (first.cs() != "def") {
2127 eat_whitespace(p, os, context, false);
2128 second = p.curr_token();
2129 command += second.asInput();
2130 if (second.cs() != "def") {
2132 eat_whitespace(p, os, context, false);
2133 third = p.curr_token();
2134 command += third.asInput();
2137 eat_whitespace(p, os, context, false);
2138 string const name = p.get_token().cs();
2139 eat_whitespace(p, os, context, false);
2145 while (p.next_token().cat() != catBegin) {
2146 if (p.next_token().cat() == catParameter) {
2151 // followed by number?
2152 if (p.next_token().cat() == catOther) {
2153 char c = p.getChar();
2155 // number = current arity + 1?
2156 if (c == arity + '0' + 1)
2161 paramtext += p.get_token().cs();
2163 paramtext += p.get_token().cs();
2168 // only output simple (i.e. compatible) macro as FormulaMacros
2169 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2171 context.check_layout(os);
2172 begin_inset(os, "FormulaMacro");
2173 os << "\n\\def" << ert;
2176 handle_ert(os, command + ert, context);
2180 void registerExternalTemplatePackages(string const & name)
2182 external::TemplateManager const & etm = external::TemplateManager::get();
2183 external::Template const * const et = etm.getTemplateByName(name);
2186 external::Template::Formats::const_iterator cit = et->formats.end();
2188 cit = et->formats.find("PDFLaTeX");
2189 if (cit == et->formats.end())
2190 // If the template has not specified a PDFLaTeX output,
2191 // we try the LaTeX format.
2192 cit = et->formats.find("LaTeX");
2193 if (cit == et->formats.end())
2195 vector<string>::const_iterator qit = cit->second.requirements.begin();
2196 vector<string>::const_iterator qend = cit->second.requirements.end();
2197 for (; qit != qend; ++qit)
2198 preamble.registerAutomaticallyLoadedPackage(*qit);
2201 } // anonymous namespace
2204 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2207 Layout const * newlayout = 0;
2208 InsetLayout const * newinsetlayout = 0;
2209 char const * const * where = 0;
2210 // Store the latest bibliographystyle and nocite{*} option
2211 // (needed for bibtex inset)
2213 string bibliographystyle = "default";
2214 bool const use_natbib = isProvided("natbib");
2215 bool const use_jurabib = isProvided("jurabib");
2218 Token const & t = p.get_token();
2220 // it is impossible to determine the correct encoding for non-CJK Japanese.
2221 // Therefore write a note at the beginning of the document
2222 if (is_nonCJKJapanese) {
2223 context.check_layout(os);
2224 begin_inset(os, "Note Note\n");
2225 os << "status open\n\\begin_layout Plain Layout\n"
2226 << "\\series bold\n"
2227 << "Important information:\n"
2228 << "\\end_layout\n\n"
2229 << "\\begin_layout Plain Layout\n"
2230 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2231 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2232 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2233 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2234 << " and specify the encoding using the -e command-line switch.\n"
2235 << " In addition, you might want to double check that the desired output encoding\n"
2236 << " is correctly selected in Document > Settings > Language.\n"
2237 << "\\end_layout\n";
2239 is_nonCJKJapanese = false;
2243 debugToken(cerr, t, flags);
2246 if (flags & FLAG_ITEM) {
2247 if (t.cat() == catSpace)
2250 flags &= ~FLAG_ITEM;
2251 if (t.cat() == catBegin) {
2252 // skip the brace and collect everything to the next matching
2254 flags |= FLAG_BRACE_LAST;
2258 // handle only this single token, leave the loop if done
2259 flags |= FLAG_LEAVE;
2262 if (t.cat() != catEscape && t.character() == ']' &&
2263 (flags & FLAG_BRACK_LAST))
2265 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2268 // If there is anything between \end{env} and \begin{env} we
2269 // don't need to output a separator.
2270 if (t.cat() != catSpace && t.cat() != catNewline &&
2271 t.asInput() != "\\begin")
2277 if (t.cat() == catMath) {
2278 // we are inside some text mode thingy, so opening new math is allowed
2279 context.check_layout(os);
2280 begin_inset(os, "Formula ");
2281 Token const & n = p.get_token();
2282 bool const display(n.cat() == catMath && outer);
2284 // TeX's $$...$$ syntax for displayed math
2286 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2288 p.get_token(); // skip the second '$' token
2290 // simple $...$ stuff
2293 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2298 // Prevent the conversion of a line break to a
2299 // space (bug 7668). This does not change the
2300 // output, but looks ugly in LyX.
2301 eat_whitespace(p, os, context, false);
2305 else if (t.cat() == catSuper || t.cat() == catSub)
2306 cerr << "catcode " << t << " illegal in text mode\n";
2308 // Basic support for english quotes. This should be
2309 // extended to other quotes, but is not so easy (a
2310 // left english quote is the same as a right german
2312 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2313 context.check_layout(os);
2314 begin_inset(os, "Quotes ");
2320 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2321 context.check_layout(os);
2322 begin_inset(os, "Quotes ");
2329 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2330 context.check_layout(os);
2331 begin_inset(os, "Quotes ");
2338 else if (t.asInput() == "<"
2339 && p.next_token().asInput() == "<" && noweb_mode) {
2341 parse_noweb(p, os, context);
2344 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2345 context.check_layout(os);
2346 begin_inset(os, "Quotes ");
2353 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2354 check_space(p, os, context);
2356 else if (t.character() == '[' && noweb_mode &&
2357 p.next_token().character() == '[') {
2358 // These can contain underscores
2360 string const s = p.getFullOpt() + ']';
2361 if (p.next_token().character() == ']')
2364 cerr << "Warning: Inserting missing ']' in '"
2365 << s << "'." << endl;
2366 handle_ert(os, s, context);
2369 else if (t.cat() == catLetter) {
2370 context.check_layout(os);
2371 // Workaround for bug 4752.
2372 // FIXME: This whole code block needs to be removed
2373 // when the bug is fixed and tex2lyx produces
2374 // the updated file format.
2375 // The replacement algorithm in LyX is so stupid that
2376 // it even translates a phrase if it is part of a word.
2377 bool handled = false;
2378 for (int const * l = known_phrase_lengths; *l; ++l) {
2379 string phrase = t.cs();
2380 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2381 phrase += p.get_token().cs();
2382 if (is_known(phrase, known_coded_phrases)) {
2383 handle_ert(os, phrase, context);
2387 for (size_t i = 1; i < phrase.length(); ++i)
2395 else if (t.cat() == catOther ||
2396 t.cat() == catAlign ||
2397 t.cat() == catParameter) {
2398 // This translates "&" to "\\&" which may be wrong...
2399 context.check_layout(os);
2403 else if (p.isParagraph()) {
2404 if (context.new_layout_allowed)
2405 context.new_paragraph(os);
2407 handle_ert(os, "\\par ", context);
2408 eat_whitespace(p, os, context, true);
2411 else if (t.cat() == catActive) {
2412 context.check_layout(os);
2413 if (t.character() == '~') {
2414 if (context.layout->free_spacing)
2417 begin_inset(os, "space ~\n");
2424 else if (t.cat() == catBegin) {
2425 Token const next = p.next_token();
2426 Token const end = p.next_next_token();
2427 if (next.cat() == catEnd) {
2429 Token const prev = p.prev_token();
2431 if (p.next_token().character() == '`' ||
2432 (prev.character() == '-' &&
2433 p.next_token().character() == '-'))
2434 ; // ignore it in {}`` or -{}-
2436 handle_ert(os, "{}", context);
2437 } else if (next.cat() == catEscape &&
2438 is_known(next.cs(), known_quotes) &&
2439 end.cat() == catEnd) {
2440 // Something like {\textquoteright} (e.g.
2441 // from writer2latex). LyX writes
2442 // \textquoteright{}, so we may skip the
2443 // braces here for better readability.
2444 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2447 context.check_layout(os);
2448 // special handling of font attribute changes
2449 Token const prev = p.prev_token();
2450 TeXFont const oldFont = context.font;
2451 if (next.character() == '[' ||
2452 next.character() == ']' ||
2453 next.character() == '*') {
2455 if (p.next_token().cat() == catEnd) {
2460 handle_ert(os, "{", context);
2461 parse_text_snippet(p, os,
2464 handle_ert(os, "}", context);
2466 } else if (! context.new_layout_allowed) {
2467 handle_ert(os, "{", context);
2468 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2470 handle_ert(os, "}", context);
2471 } else if (is_known(next.cs(), known_sizes)) {
2472 // next will change the size, so we must
2474 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2476 if (!context.atParagraphStart())
2478 << context.font.size << "\n";
2479 } else if (is_known(next.cs(), known_font_families)) {
2480 // next will change the font family, so we
2481 // must reset it here
2482 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2484 if (!context.atParagraphStart())
2486 << context.font.family << "\n";
2487 } else if (is_known(next.cs(), known_font_series)) {
2488 // next will change the font series, so we
2489 // must reset it here
2490 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2492 if (!context.atParagraphStart())
2494 << context.font.series << "\n";
2495 } else if (is_known(next.cs(), known_font_shapes)) {
2496 // next will change the font shape, so we
2497 // must reset it here
2498 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2500 if (!context.atParagraphStart())
2502 << context.font.shape << "\n";
2503 } else if (is_known(next.cs(), known_old_font_families) ||
2504 is_known(next.cs(), known_old_font_series) ||
2505 is_known(next.cs(), known_old_font_shapes)) {
2506 // next will change the font family, series
2507 // and shape, so we must reset it here
2508 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2510 if (!context.atParagraphStart())
2512 << context.font.family
2514 << context.font.series
2516 << context.font.shape << "\n";
2518 handle_ert(os, "{", context);
2519 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2521 handle_ert(os, "}", context);
2526 else if (t.cat() == catEnd) {
2527 if (flags & FLAG_BRACE_LAST) {
2530 cerr << "stray '}' in text\n";
2531 handle_ert(os, "}", context);
2534 else if (t.cat() == catComment)
2535 parse_comment(p, os, t, context);
2538 // control sequences
2541 else if (t.cs() == "(") {
2542 context.check_layout(os);
2543 begin_inset(os, "Formula");
2545 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2550 else if (t.cs() == "[") {
2551 context.check_layout(os);
2552 begin_inset(os, "Formula");
2554 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2557 // Prevent the conversion of a line break to a space
2558 // (bug 7668). This does not change the output, but
2559 // looks ugly in LyX.
2560 eat_whitespace(p, os, context, false);
2563 else if (t.cs() == "begin")
2564 parse_environment(p, os, outer, last_env,
2567 else if (t.cs() == "end") {
2568 if (flags & FLAG_END) {
2569 // eat environment name
2570 string const name = p.getArg('{', '}');
2571 if (name != active_environment())
2572 cerr << "\\end{" + name + "} does not match \\begin{"
2573 + active_environment() + "}\n";
2576 p.error("found 'end' unexpectedly");
2579 else if (t.cs() == "item") {
2581 bool const optarg = p.hasOpt();
2583 // FIXME: This swallows comments, but we cannot use
2584 // eat_whitespace() since we must not output
2585 // anything before the item.
2586 p.skip_spaces(true);
2587 s = p.verbatimOption();
2589 p.skip_spaces(false);
2591 context.check_layout(os);
2592 if (context.has_item) {
2593 // An item in an unknown list-like environment
2594 // FIXME: Do this in check_layout()!
2595 context.has_item = false;
2597 handle_ert(os, "\\item", context);
2599 handle_ert(os, "\\item ", context);
2602 if (context.layout->labeltype != LABEL_MANUAL) {
2603 // LyX does not support \item[\mybullet]
2604 // in itemize environments
2606 os << parse_text_snippet(p2,
2607 FLAG_BRACK_LAST, outer, context);
2608 } else if (!s.empty()) {
2609 // LyX adds braces around the argument,
2610 // so we need to remove them here.
2611 if (s.size() > 2 && s[0] == '{' &&
2612 s[s.size()-1] == '}')
2613 s = s.substr(1, s.size()-2);
2614 // If the argument contains a space we
2615 // must put it into ERT: Otherwise LyX
2616 // would misinterpret the space as
2617 // item delimiter (bug 7663)
2618 if (contains(s, ' ')) {
2619 handle_ert(os, s, context);
2622 os << parse_text_snippet(p2,
2626 // The space is needed to separate the
2627 // item from the rest of the sentence.
2629 eat_whitespace(p, os, context, false);
2634 else if (t.cs() == "bibitem") {
2636 context.check_layout(os);
2637 eat_whitespace(p, os, context, false);
2638 string label = convert_command_inset_arg(p.verbatimOption());
2639 string key = convert_command_inset_arg(p.verbatim_item());
2640 if (contains(label, '\\') || contains(key, '\\')) {
2641 // LyX can't handle LaTeX commands in labels or keys
2642 handle_ert(os, t.asInput() + '[' + label +
2643 "]{" + p.verbatim_item() + '}',
2646 begin_command_inset(os, "bibitem", "bibitem");
2647 os << "label \"" << label << "\"\n"
2648 "key \"" << key << "\"\n";
2653 else if (is_macro(p)) {
2654 // catch the case of \def\inputGnumericTable
2656 if (t.cs() == "def") {
2657 Token second = p.next_token();
2658 if (second.cs() == "inputGnumericTable") {
2662 Token third = p.get_token();
2664 if (third.cs() == "input") {
2668 string name = normalize_filename(p.verbatim_item());
2669 string const path = getMasterFilePath(true);
2670 // We want to preserve relative / absolute filenames,
2671 // therefore path is only used for testing
2672 // The file extension is in every case ".tex".
2673 // So we need to remove this extension and check for
2674 // the original one.
2675 name = removeExtension(name);
2676 if (!makeAbsPath(name, path).exists()) {
2677 char const * const Gnumeric_formats[] = {"gnumeric",
2679 string const Gnumeric_name =
2680 find_file(name, path, Gnumeric_formats);
2681 if (!Gnumeric_name.empty())
2682 name = Gnumeric_name;
2684 FileName const absname = makeAbsPath(name, path);
2685 if (absname.exists()) {
2686 fix_child_filename(name);
2687 copy_file(absname, name);
2689 cerr << "Warning: Could not find file '"
2690 << name << "'." << endl;
2691 context.check_layout(os);
2692 begin_inset(os, "External\n\ttemplate ");
2693 os << "GnumericSpreadsheet\n\tfilename "
2696 context.check_layout(os);
2698 // register the packages that are automatically loaded
2699 // by the Gnumeric template
2700 registerExternalTemplatePackages("GnumericSpreadsheet");
2705 parse_macro(p, os, context);
2708 else if (t.cs() == "noindent") {
2710 context.add_par_extra_stuff("\\noindent\n");
2713 else if (t.cs() == "appendix") {
2714 context.add_par_extra_stuff("\\start_of_appendix\n");
2715 // We need to start a new paragraph. Otherwise the
2716 // appendix in 'bla\appendix\chapter{' would start
2718 context.new_paragraph(os);
2719 // We need to make sure that the paragraph is
2720 // generated even if it is empty. Otherwise the
2721 // appendix in '\par\appendix\par\chapter{' would
2723 context.check_layout(os);
2724 // FIXME: This is a hack to prevent paragraph
2725 // deletion if it is empty. Handle this better!
2727 "%dummy comment inserted by tex2lyx to "
2728 "ensure that this paragraph is not empty",
2730 // Both measures above may generate an additional
2731 // empty paragraph, but that does not hurt, because
2732 // whitespace does not matter here.
2733 eat_whitespace(p, os, context, true);
2736 // Must catch empty dates before findLayout is called below
2737 else if (t.cs() == "date") {
2738 eat_whitespace(p, os, context, false);
2740 string const date = p.verbatim_item();
2743 preamble.suppressDate(true);
2746 preamble.suppressDate(false);
2747 if (context.new_layout_allowed &&
2748 (newlayout = findLayout(context.textclass,
2751 output_command_layout(os, p, outer,
2752 context, newlayout);
2753 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2754 if (!preamble.titleLayoutFound())
2755 preamble.titleLayoutFound(newlayout->intitle);
2756 set<string> const & req = newlayout->requires();
2757 set<string>::const_iterator it = req.begin();
2758 set<string>::const_iterator en = req.end();
2759 for (; it != en; ++it)
2760 preamble.registerAutomaticallyLoadedPackage(*it);
2763 "\\date{" + p.verbatim_item() + '}',
2768 // Starred section headings
2769 // Must attempt to parse "Section*" before "Section".
2770 else if ((p.next_token().asInput() == "*") &&
2771 context.new_layout_allowed &&
2772 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2775 output_command_layout(os, p, outer, context, newlayout);
2777 if (!preamble.titleLayoutFound())
2778 preamble.titleLayoutFound(newlayout->intitle);
2779 set<string> const & req = newlayout->requires();
2780 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2781 preamble.registerAutomaticallyLoadedPackage(*it);
2784 // Section headings and the like
2785 else if (context.new_layout_allowed &&
2786 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2788 output_command_layout(os, p, outer, context, newlayout);
2790 if (!preamble.titleLayoutFound())
2791 preamble.titleLayoutFound(newlayout->intitle);
2792 set<string> const & req = newlayout->requires();
2793 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2794 preamble.registerAutomaticallyLoadedPackage(*it);
2797 else if (t.cs() == "caption") {
2799 context.check_layout(os);
2801 begin_inset(os, "Caption Standard\n");
2802 Context newcontext(true, context.textclass, 0, 0, context.font);
2803 newcontext.check_layout(os);
2804 // FIXME InsetArgument is now properly implemented in InsetLayout
2805 // (for captions, but also for others)
2806 if (p.next_token().cat() != catEscape &&
2807 p.next_token().character() == '[') {
2808 p.get_token(); // eat '['
2809 begin_inset(os, "Argument 1\n");
2810 os << "status collapsed\n";
2811 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2813 eat_whitespace(p, os, context, false);
2815 parse_text(p, os, FLAG_ITEM, outer, context);
2816 context.check_end_layout(os);
2817 // We don't need really a new paragraph, but
2818 // we must make sure that the next item gets a \begin_layout.
2819 context.new_paragraph(os);
2822 newcontext.check_end_layout(os);
2825 else if (t.cs() == "subfloat") {
2826 // the syntax is \subfloat[caption]{content}
2827 // if it is a table of figure depends on the surrounding float
2828 bool has_caption = false;
2830 // do nothing if there is no outer float
2831 if (!float_type.empty()) {
2832 context.check_layout(os);
2834 begin_inset(os, "Float " + float_type + "\n");
2836 << "\nsideways false"
2837 << "\nstatus collapsed\n\n";
2840 if (p.next_token().cat() != catEscape &&
2841 p.next_token().character() == '[') {
2842 p.get_token(); // eat '['
2843 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2847 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2848 // the caption comes always as the last
2850 // we must make sure that the caption gets a \begin_layout
2851 os << "\n\\begin_layout Plain Layout";
2853 begin_inset(os, "Caption Standard\n");
2854 Context newcontext(true, context.textclass,
2855 0, 0, context.font);
2856 newcontext.check_layout(os);
2857 os << caption << "\n";
2858 newcontext.check_end_layout(os);
2859 // We don't need really a new paragraph, but
2860 // we must make sure that the next item gets a \begin_layout.
2861 //newcontext.new_paragraph(os);
2865 // We don't need really a new paragraph, but
2866 // we must make sure that the next item gets a \begin_layout.
2868 context.new_paragraph(os);
2871 context.check_end_layout(os);
2872 // close the layout we opened
2874 os << "\n\\end_layout\n";
2876 // if the float type is not supported or there is no surrounding float
2879 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2880 handle_ert(os, t.asInput() + '[' + opt_arg +
2881 "]{" + p.verbatim_item() + '}', context);
2883 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2887 else if (t.cs() == "includegraphics") {
2888 bool const clip = p.next_token().asInput() == "*";
2891 string const arg = p.getArg('[', ']');
2892 map<string, string> opts;
2893 vector<string> keys;
2894 split_map(arg, opts, keys);
2896 opts["clip"] = string();
2897 string name = normalize_filename(p.verbatim_item());
2899 string const path = getMasterFilePath(true);
2900 // We want to preserve relative / absolute filenames,
2901 // therefore path is only used for testing
2902 if (!makeAbsPath(name, path).exists()) {
2903 // The file extension is probably missing.
2904 // Now try to find it out.
2905 string const dvips_name =
2906 find_file(name, path,
2907 known_dvips_graphics_formats);
2908 string const pdftex_name =
2909 find_file(name, path,
2910 known_pdftex_graphics_formats);
2911 if (!dvips_name.empty()) {
2912 if (!pdftex_name.empty()) {
2913 cerr << "This file contains the "
2915 "\"\\includegraphics{"
2917 "However, files\n\""
2918 << dvips_name << "\" and\n\""
2919 << pdftex_name << "\"\n"
2920 "both exist, so I had to make a "
2921 "choice and took the first one.\n"
2922 "Please move the unwanted one "
2923 "someplace else and try again\n"
2924 "if my choice was wrong."
2928 } else if (!pdftex_name.empty()) {
2934 FileName const absname = makeAbsPath(name, path);
2935 if (absname.exists()) {
2936 fix_child_filename(name);
2937 copy_file(absname, name);
2939 cerr << "Warning: Could not find graphics file '"
2940 << name << "'." << endl;
2942 context.check_layout(os);
2943 begin_inset(os, "Graphics ");
2944 os << "\n\tfilename " << name << '\n';
2945 if (opts.find("width") != opts.end())
2947 << translate_len(opts["width"]) << '\n';
2948 if (opts.find("height") != opts.end())
2950 << translate_len(opts["height"]) << '\n';
2951 if (opts.find("scale") != opts.end()) {
2952 istringstream iss(opts["scale"]);
2956 os << "\tscale " << val << '\n';
2958 if (opts.find("angle") != opts.end()) {
2959 os << "\trotateAngle "
2960 << opts["angle"] << '\n';
2961 vector<string>::const_iterator a =
2962 find(keys.begin(), keys.end(), "angle");
2963 vector<string>::const_iterator s =
2964 find(keys.begin(), keys.end(), "width");
2965 if (s == keys.end())
2966 s = find(keys.begin(), keys.end(), "height");
2967 if (s == keys.end())
2968 s = find(keys.begin(), keys.end(), "scale");
2969 if (s != keys.end() && distance(s, a) > 0)
2970 os << "\tscaleBeforeRotation\n";
2972 if (opts.find("origin") != opts.end()) {
2974 string const opt = opts["origin"];
2975 if (opt.find('l') != string::npos) ss << "left";
2976 if (opt.find('r') != string::npos) ss << "right";
2977 if (opt.find('c') != string::npos) ss << "center";
2978 if (opt.find('t') != string::npos) ss << "Top";
2979 if (opt.find('b') != string::npos) ss << "Bottom";
2980 if (opt.find('B') != string::npos) ss << "Baseline";
2981 if (!ss.str().empty())
2982 os << "\trotateOrigin " << ss.str() << '\n';
2984 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2986 if (opts.find("keepaspectratio") != opts.end())
2987 os << "\tkeepAspectRatio\n";
2988 if (opts.find("clip") != opts.end())
2990 if (opts.find("draft") != opts.end())
2992 if (opts.find("bb") != opts.end())
2993 os << "\tBoundingBox "
2994 << opts["bb"] << '\n';
2995 int numberOfbbOptions = 0;
2996 if (opts.find("bbllx") != opts.end())
2997 numberOfbbOptions++;
2998 if (opts.find("bblly") != opts.end())
2999 numberOfbbOptions++;
3000 if (opts.find("bburx") != opts.end())
3001 numberOfbbOptions++;
3002 if (opts.find("bbury") != opts.end())
3003 numberOfbbOptions++;
3004 if (numberOfbbOptions == 4)
3005 os << "\tBoundingBox "
3006 << opts["bbllx"] << " " << opts["bblly"] << " "
3007 << opts["bburx"] << " " << opts["bbury"] << '\n';
3008 else if (numberOfbbOptions > 0)
3009 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3010 numberOfbbOptions = 0;
3011 if (opts.find("natwidth") != opts.end())
3012 numberOfbbOptions++;
3013 if (opts.find("natheight") != opts.end())
3014 numberOfbbOptions++;
3015 if (numberOfbbOptions == 2)
3016 os << "\tBoundingBox 0bp 0bp "
3017 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3018 else if (numberOfbbOptions > 0)
3019 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3020 ostringstream special;
3021 if (opts.find("hiresbb") != opts.end())
3022 special << "hiresbb,";
3023 if (opts.find("trim") != opts.end())
3025 if (opts.find("viewport") != opts.end())
3026 special << "viewport=" << opts["viewport"] << ',';
3027 if (opts.find("totalheight") != opts.end())
3028 special << "totalheight=" << opts["totalheight"] << ',';
3029 if (opts.find("type") != opts.end())
3030 special << "type=" << opts["type"] << ',';
3031 if (opts.find("ext") != opts.end())
3032 special << "ext=" << opts["ext"] << ',';
3033 if (opts.find("read") != opts.end())
3034 special << "read=" << opts["read"] << ',';
3035 if (opts.find("command") != opts.end())
3036 special << "command=" << opts["command"] << ',';
3037 string s_special = special.str();
3038 if (!s_special.empty()) {
3039 // We had special arguments. Remove the trailing ','.
3040 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3042 // TODO: Handle the unknown settings better.
3043 // Warn about invalid options.
3044 // Check whether some option was given twice.
3046 preamble.registerAutomaticallyLoadedPackage("graphicx");
3049 else if (t.cs() == "footnote" ||
3050 (t.cs() == "thanks" && context.layout->intitle)) {
3052 context.check_layout(os);
3053 begin_inset(os, "Foot\n");
3054 os << "status collapsed\n\n";
3055 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3059 else if (t.cs() == "marginpar") {
3061 context.check_layout(os);
3062 begin_inset(os, "Marginal\n");
3063 os << "status collapsed\n\n";
3064 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3068 else if (t.cs() == "lstinline") {
3070 parse_listings(p, os, context, true);
3073 else if (t.cs() == "ensuremath") {
3075 context.check_layout(os);
3076 string const s = p.verbatim_item();
3077 //FIXME: this never triggers in UTF8
3078 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3081 handle_ert(os, "\\ensuremath{" + s + "}",
3085 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3086 if (preamble.titleLayoutFound()) {
3088 skip_spaces_braces(p);
3090 handle_ert(os, t.asInput(), context);
3093 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3094 context.check_layout(os);
3095 begin_command_inset(os, "toc", t.cs());
3097 skip_spaces_braces(p);
3098 if (t.cs() == "lstlistoflistings")
3099 preamble.registerAutomaticallyLoadedPackage("listings");
3102 else if (t.cs() == "listoffigures") {
3103 context.check_layout(os);
3104 begin_inset(os, "FloatList figure\n");
3106 skip_spaces_braces(p);
3109 else if (t.cs() == "listoftables") {
3110 context.check_layout(os);
3111 begin_inset(os, "FloatList table\n");
3113 skip_spaces_braces(p);
3116 else if (t.cs() == "listof") {
3117 p.skip_spaces(true);
3118 string const name = p.get_token().cs();
3119 if (context.textclass.floats().typeExist(name)) {
3120 context.check_layout(os);
3121 begin_inset(os, "FloatList ");
3124 p.get_token(); // swallow second arg
3126 handle_ert(os, "\\listof{" + name + "}", context);
3129 else if ((where = is_known(t.cs(), known_text_font_families)))
3130 parse_text_attributes(p, os, FLAG_ITEM, outer,
3131 context, "\\family", context.font.family,
3132 known_coded_font_families[where - known_text_font_families]);
3134 else if ((where = is_known(t.cs(), known_text_font_series)))
3135 parse_text_attributes(p, os, FLAG_ITEM, outer,
3136 context, "\\series", context.font.series,
3137 known_coded_font_series[where - known_text_font_series]);
3139 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3140 parse_text_attributes(p, os, FLAG_ITEM, outer,
3141 context, "\\shape", context.font.shape,
3142 known_coded_font_shapes[where - known_text_font_shapes]);
3144 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3145 context.check_layout(os);
3146 TeXFont oldFont = context.font;
3147 context.font.init();
3148 context.font.size = oldFont.size;
3149 os << "\n\\family " << context.font.family << "\n";
3150 os << "\n\\series " << context.font.series << "\n";
3151 os << "\n\\shape " << context.font.shape << "\n";
3152 if (t.cs() == "textnormal") {
3153 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3154 output_font_change(os, context.font, oldFont);
3155 context.font = oldFont;
3157 eat_whitespace(p, os, context, false);
3160 else if (t.cs() == "textcolor") {
3161 // scheme is \textcolor{color name}{text}
3162 string const color = p.verbatim_item();
3163 // we only support the predefined colors of the color package
3164 if (color == "black" || color == "blue" || color == "cyan"
3165 || color == "green" || color == "magenta" || color == "red"
3166 || color == "white" || color == "yellow") {
3167 context.check_layout(os);
3168 os << "\n\\color " << color << "\n";
3169 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3170 context.check_layout(os);
3171 os << "\n\\color inherit\n";
3172 preamble.registerAutomaticallyLoadedPackage("color");
3174 // for custom defined colors
3175 handle_ert(os, t.asInput() + "{" + color + "}", context);
3178 else if (t.cs() == "underbar" || t.cs() == "uline") {
3179 // \underbar is not 100% correct (LyX outputs \uline
3180 // of ulem.sty). The difference is that \ulem allows
3181 // line breaks, and \underbar does not.
3182 // Do NOT handle \underline.
3183 // \underbar cuts through y, g, q, p etc.,
3184 // \underline does not.
3185 context.check_layout(os);
3186 os << "\n\\bar under\n";
3187 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3188 context.check_layout(os);
3189 os << "\n\\bar default\n";
3190 preamble.registerAutomaticallyLoadedPackage("ulem");
3193 else if (t.cs() == "sout") {
3194 context.check_layout(os);
3195 os << "\n\\strikeout on\n";
3196 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3197 context.check_layout(os);
3198 os << "\n\\strikeout default\n";
3199 preamble.registerAutomaticallyLoadedPackage("ulem");
3202 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3203 t.cs() == "emph" || t.cs() == "noun") {
3204 context.check_layout(os);
3205 os << "\n\\" << t.cs() << " on\n";
3206 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3207 context.check_layout(os);
3208 os << "\n\\" << t.cs() << " default\n";
3209 if (t.cs() == "uuline" || t.cs() == "uwave")
3210 preamble.registerAutomaticallyLoadedPackage("ulem");
3213 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3214 context.check_layout(os);
3215 string name = p.getArg('{', '}');
3216 string localtime = p.getArg('{', '}');
3217 preamble.registerAuthor(name);
3218 Author const & author = preamble.getAuthor(name);
3219 // from_asctime_utc() will fail if LyX decides to output the
3220 // time in the text language.
3221 time_t ptime = from_asctime_utc(localtime);
3222 if (ptime == static_cast<time_t>(-1)) {
3223 cerr << "Warning: Could not parse time `" << localtime
3224 << "´ for change tracking, using current time instead.\n";
3225 ptime = current_time();
3227 if (t.cs() == "lyxadded")
3228 os << "\n\\change_inserted ";
3230 os << "\n\\change_deleted ";
3231 os << author.bufferId() << ' ' << ptime << '\n';
3232 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3233 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3234 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3235 LaTeXPackages::isAvailable("xcolor");
3236 // No need to test for luatex, since luatex comes in
3237 // two flavours (dvi and pdf), like latex, and those
3238 // are detected by pdflatex.
3239 if (pdflatex || xetex) {
3241 preamble.registerAutomaticallyLoadedPackage("ulem");
3242 preamble.registerAutomaticallyLoadedPackage("xcolor");
3243 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3247 preamble.registerAutomaticallyLoadedPackage("dvipost");
3248 } else if (xcolorulem) {
3249 preamble.registerAutomaticallyLoadedPackage("ulem");
3250 preamble.registerAutomaticallyLoadedPackage("xcolor");
3255 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3256 t.cs() == "vphantom") {
3257 context.check_layout(os);
3258 if (t.cs() == "phantom")
3259 begin_inset(os, "Phantom Phantom\n");
3260 if (t.cs() == "hphantom")
3261 begin_inset(os, "Phantom HPhantom\n");
3262 if (t.cs() == "vphantom")
3263 begin_inset(os, "Phantom VPhantom\n");
3264 os << "status open\n";
3265 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3270 else if (t.cs() == "href") {
3271 context.check_layout(os);
3272 string target = convert_command_inset_arg(p.verbatim_item());
3273 string name = convert_command_inset_arg(p.verbatim_item());
3275 size_t i = target.find(':');
3276 if (i != string::npos) {
3277 type = target.substr(0, i + 1);
3278 if (type == "mailto:" || type == "file:")
3279 target = target.substr(i + 1);
3280 // handle the case that name is equal to target, except of "http://"
3281 else if (target.substr(i + 3) == name && type == "http:")
3284 begin_command_inset(os, "href", "href");
3286 os << "name \"" << name << "\"\n";
3287 os << "target \"" << target << "\"\n";
3288 if (type == "mailto:" || type == "file:")
3289 os << "type \"" << type << "\"\n";
3291 skip_spaces_braces(p);
3294 else if (t.cs() == "lyxline") {
3295 // swallow size argument (it is not used anyway)
3297 if (!context.atParagraphStart()) {
3298 // so our line is in the middle of a paragraph
3299 // we need to add a new line, lest this line
3300 // follow the other content on that line and
3301 // run off the side of the page
3302 // FIXME: This may create an empty paragraph,
3303 // but without that it would not be
3304 // possible to set noindent below.
3305 // Fortunately LaTeX does not care
3306 // about the empty paragraph.
3307 context.new_paragraph(os);
3309 if (preamble.indentParagraphs()) {
3310 // we need to unindent, lest the line be too long
3311 context.add_par_extra_stuff("\\noindent\n");
3313 context.check_layout(os);
3314 begin_command_inset(os, "line", "rule");
3315 os << "offset \"0.5ex\"\n"
3316 "width \"100line%\"\n"
3321 else if (t.cs() == "rule") {
3322 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3323 string const width = p.getArg('{', '}');
3324 string const thickness = p.getArg('{', '}');
3325 context.check_layout(os);
3326 begin_command_inset(os, "line", "rule");
3327 if (!offset.empty())
3328 os << "offset \"" << translate_len(offset) << "\"\n";
3329 os << "width \"" << translate_len(width) << "\"\n"
3330 "height \"" << translate_len(thickness) << "\"\n";
3334 else if (is_known(t.cs(), known_phrases) ||
3335 (t.cs() == "protect" &&
3336 p.next_token().cat() == catEscape &&
3337 is_known(p.next_token().cs(), known_phrases))) {
3338 // LyX sometimes puts a \protect in front, so we have to ignore it
3339 // FIXME: This needs to be changed when bug 4752 is fixed.
3341 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3343 context.check_layout(os);
3344 os << known_coded_phrases[where - known_phrases];
3345 skip_spaces_braces(p);
3348 else if ((where = is_known(t.cs(), known_ref_commands))) {
3349 // \eqref can also occur if refstyle is used
3350 if (t.cs() == "eqref" && preamble.refstyle() == "1") {
3351 context.check_layout(os);
3352 begin_command_inset(os, "ref", "formatted");
3353 os << "reference \"eq:"
3354 << convert_command_inset_arg(p.verbatim_item())
3357 preamble.registerAutomaticallyLoadedPackage("refstyle");
3359 string const opt = p.getOpt();
3361 context.check_layout(os);
3362 begin_command_inset(os, "ref",
3363 known_coded_ref_commands[where - known_ref_commands]);
3364 os << "reference \""
3365 << convert_command_inset_arg(p.verbatim_item())
3368 if (t.cs() == "vref" || t.cs() == "vpageref")
3369 preamble.registerAutomaticallyLoadedPackage("varioref");
3371 // LyX does not yet support optional arguments of ref commands
3372 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3373 p.verbatim_item() + "}", context);
3378 else if ((where = is_known(t.cs(), known_refstyle_commands))) {
3379 context.check_layout(os);
3380 // \eqref can also occur if refstyle is not used
3381 // this case is already handled in the previous else if
3382 begin_command_inset(os, "ref", "formatted");
3383 os << "reference \"";
3384 os << known_refstyle_prefixes[where - known_refstyle_commands]
3386 os << convert_command_inset_arg(p.verbatim_item())
3389 preamble.registerAutomaticallyLoadedPackage("refstyle");
3392 else if (use_natbib &&
3393 is_known(t.cs(), known_natbib_commands) &&
3394 ((t.cs() != "citefullauthor" &&
3395 t.cs() != "citeyear" &&
3396 t.cs() != "citeyearpar") ||
3397 p.next_token().asInput() != "*")) {
3398 context.check_layout(os);
3399 string command = t.cs();
3400 if (p.next_token().asInput() == "*") {
3404 if (command == "citefullauthor")
3405 // alternative name for "\\citeauthor*"
3406 command = "citeauthor*";
3408 // text before the citation
3410 // text after the citation
3412 get_cite_arguments(p, true, before, after);
3414 if (command == "cite") {
3415 // \cite without optional argument means
3416 // \citet, \cite with at least one optional
3417 // argument means \citep.
3418 if (before.empty() && after.empty())
3423 if (before.empty() && after == "[]")
3424 // avoid \citet[]{a}
3426 else if (before == "[]" && after == "[]") {
3427 // avoid \citet[][]{a}
3431 // remove the brackets around after and before
3432 if (!after.empty()) {
3434 after.erase(after.length() - 1, 1);
3435 after = convert_command_inset_arg(after);
3437 if (!before.empty()) {
3439 before.erase(before.length() - 1, 1);
3440 before = convert_command_inset_arg(before);
3442 begin_command_inset(os, "citation", command);
3443 os << "after " << '"' << after << '"' << "\n";
3444 os << "before " << '"' << before << '"' << "\n";
3446 << convert_command_inset_arg(p.verbatim_item())
3449 // Need to set the cite engine if natbib is loaded by
3450 // the document class directly
3451 if (preamble.citeEngine() == "basic")
3452 preamble.citeEngine("natbib");
3455 else if (use_jurabib &&
3456 is_known(t.cs(), known_jurabib_commands) &&
3457 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3458 context.check_layout(os);
3459 string command = t.cs();
3460 if (p.next_token().asInput() == "*") {
3464 char argumentOrder = '\0';
3465 vector<string> const options =
3466 preamble.getPackageOptions("jurabib");
3467 if (find(options.begin(), options.end(),
3468 "natbiborder") != options.end())
3469 argumentOrder = 'n';
3470 else if (find(options.begin(), options.end(),
3471 "jurabiborder") != options.end())
3472 argumentOrder = 'j';
3474 // text before the citation
3476 // text after the citation
3478 get_cite_arguments(p, argumentOrder != 'j', before, after);
3480 string const citation = p.verbatim_item();
3481 if (!before.empty() && argumentOrder == '\0') {
3482 cerr << "Warning: Assuming argument order "
3483 "of jurabib version 0.6 for\n'"
3484 << command << before << after << '{'
3485 << citation << "}'.\n"
3486 "Add 'jurabiborder' to the jurabib "
3487 "package options if you used an\n"
3488 "earlier jurabib version." << endl;
3490 if (!after.empty()) {
3492 after.erase(after.length() - 1, 1);
3494 if (!before.empty()) {
3496 before.erase(before.length() - 1, 1);
3498 begin_command_inset(os, "citation", command);
3499 os << "after " << '"' << after << '"' << "\n";
3500 os << "before " << '"' << before << '"' << "\n";
3501 os << "key " << '"' << citation << '"' << "\n";
3503 // Need to set the cite engine if jurabib is loaded by
3504 // the document class directly
3505 if (preamble.citeEngine() == "basic")
3506 preamble.citeEngine("jurabib");
3509 else if (t.cs() == "cite"
3510 || t.cs() == "nocite") {
3511 context.check_layout(os);
3512 string after = convert_command_inset_arg(p.getArg('[', ']'));
3513 string key = convert_command_inset_arg(p.verbatim_item());
3514 // store the case that it is "\nocite{*}" to use it later for
3517 begin_command_inset(os, "citation", t.cs());
3518 os << "after " << '"' << after << '"' << "\n";
3519 os << "key " << '"' << key << '"' << "\n";
3521 } else if (t.cs() == "nocite")
3525 else if (t.cs() == "index" ||
3526 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3527 context.check_layout(os);
3528 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3529 p.getArg('[', ']') : "";
3530 string const kind = arg.empty() ? "idx" : arg;
3531 begin_inset(os, "Index ");
3532 os << kind << "\nstatus collapsed\n";
3533 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3536 preamble.registerAutomaticallyLoadedPackage("splitidx");
3539 else if (t.cs() == "nomenclature") {
3540 context.check_layout(os);
3541 begin_command_inset(os, "nomenclature", "nomenclature");
3542 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3543 if (!prefix.empty())
3544 os << "prefix " << '"' << prefix << '"' << "\n";
3545 os << "symbol " << '"'
3546 << convert_command_inset_arg(p.verbatim_item());
3547 os << "\"\ndescription \""
3548 << convert_command_inset_arg(p.verbatim_item())
3551 preamble.registerAutomaticallyLoadedPackage("nomencl");
3554 else if (t.cs() == "label") {
3555 context.check_layout(os);
3556 begin_command_inset(os, "label", "label");
3558 << convert_command_inset_arg(p.verbatim_item())
3563 else if (t.cs() == "printindex") {
3564 context.check_layout(os);
3565 begin_command_inset(os, "index_print", "printindex");
3566 os << "type \"idx\"\n";
3568 skip_spaces_braces(p);
3569 preamble.registerAutomaticallyLoadedPackage("makeidx");
3570 if (preamble.use_indices() == "true")
3571 preamble.registerAutomaticallyLoadedPackage("splitidx");
3574 else if (t.cs() == "printnomenclature") {
3576 string width_type = "";
3577 context.check_layout(os);
3578 begin_command_inset(os, "nomencl_print", "printnomenclature");
3579 // case of a custom width
3581 width = p.getArg('[', ']');
3582 width = translate_len(width);
3583 width_type = "custom";
3585 // case of no custom width
3586 // the case of no custom width but the width set
3587 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3588 // because the user could have set anything, not only the width
3589 // of the longest label (which would be width_type = "auto")
3590 string label = convert_command_inset_arg(p.getArg('{', '}'));
3591 if (label.empty() && width_type.empty())
3592 width_type = "none";
3593 os << "set_width \"" << width_type << "\"\n";
3594 if (width_type == "custom")
3595 os << "width \"" << width << '\"';
3597 skip_spaces_braces(p);
3598 preamble.registerAutomaticallyLoadedPackage("nomencl");
3601 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3602 context.check_layout(os);
3603 begin_inset(os, "script ");
3604 os << t.cs().substr(4) << '\n';
3605 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3607 if (t.cs() == "textsubscript")
3608 preamble.registerAutomaticallyLoadedPackage("subscript");
3611 else if ((where = is_known(t.cs(), known_quotes))) {
3612 context.check_layout(os);
3613 begin_inset(os, "Quotes ");
3614 os << known_coded_quotes[where - known_quotes];
3616 // LyX adds {} after the quote, so we have to eat
3617 // spaces here if there are any before a possible
3619 eat_whitespace(p, os, context, false);
3623 else if ((where = is_known(t.cs(), known_sizes)) &&
3624 context.new_layout_allowed) {
3625 context.check_layout(os);
3626 TeXFont const oldFont = context.font;
3627 context.font.size = known_coded_sizes[where - known_sizes];
3628 output_font_change(os, oldFont, context.font);
3629 eat_whitespace(p, os, context, false);
3632 else if ((where = is_known(t.cs(), known_font_families)) &&
3633 context.new_layout_allowed) {
3634 context.check_layout(os);
3635 TeXFont const oldFont = context.font;
3636 context.font.family =
3637 known_coded_font_families[where - known_font_families];
3638 output_font_change(os, oldFont, context.font);
3639 eat_whitespace(p, os, context, false);
3642 else if ((where = is_known(t.cs(), known_font_series)) &&
3643 context.new_layout_allowed) {
3644 context.check_layout(os);
3645 TeXFont const oldFont = context.font;
3646 context.font.series =
3647 known_coded_font_series[where - known_font_series];
3648 output_font_change(os, oldFont, context.font);
3649 eat_whitespace(p, os, context, false);
3652 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3653 context.new_layout_allowed) {
3654 context.check_layout(os);
3655 TeXFont const oldFont = context.font;
3656 context.font.shape =
3657 known_coded_font_shapes[where - known_font_shapes];
3658 output_font_change(os, oldFont, context.font);
3659 eat_whitespace(p, os, context, false);
3661 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3662 context.new_layout_allowed) {
3663 context.check_layout(os);
3664 TeXFont const oldFont = context.font;
3665 context.font.init();
3666 context.font.size = oldFont.size;
3667 context.font.family =
3668 known_coded_font_families[where - known_old_font_families];
3669 output_font_change(os, oldFont, context.font);
3670 eat_whitespace(p, os, context, false);
3673 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3674 context.new_layout_allowed) {
3675 context.check_layout(os);
3676 TeXFont const oldFont = context.font;
3677 context.font.init();
3678 context.font.size = oldFont.size;
3679 context.font.series =
3680 known_coded_font_series[where - known_old_font_series];
3681 output_font_change(os, oldFont, context.font);
3682 eat_whitespace(p, os, context, false);
3685 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3686 context.new_layout_allowed) {
3687 context.check_layout(os);
3688 TeXFont const oldFont = context.font;
3689 context.font.init();
3690 context.font.size = oldFont.size;
3691 context.font.shape =
3692 known_coded_font_shapes[where - known_old_font_shapes];
3693 output_font_change(os, oldFont, context.font);
3694 eat_whitespace(p, os, context, false);
3697 else if (t.cs() == "selectlanguage") {
3698 context.check_layout(os);
3699 // save the language for the case that a
3700 // \foreignlanguage is used
3701 context.font.language = babel2lyx(p.verbatim_item());
3702 os << "\n\\lang " << context.font.language << "\n";
3705 else if (t.cs() == "foreignlanguage") {
3706 string const lang = babel2lyx(p.verbatim_item());
3707 parse_text_attributes(p, os, FLAG_ITEM, outer,
3709 context.font.language, lang);
3712 else if (prefixIs(t.cs(), "text")
3713 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3714 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3716 // We have to output the whole command if it has an option
3717 // because LyX doesn't support this yet, see bug #8214,
3718 // only if there is a single option specifying a variant, we can handle it.
3720 string langopts = p.getOpt();
3721 // check if the option contains a variant, if yes, extract it
3722 string::size_type pos_var = langopts.find("variant");
3723 string::size_type i = langopts.find(',');
3724 string::size_type k = langopts.find('=', pos_var);
3725 if (pos_var != string::npos && i == string::npos) {
3727 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3728 lang = preamble.polyglossia2lyx(variant);
3729 parse_text_attributes(p, os, FLAG_ITEM, outer,
3731 context.font.language, lang);
3733 handle_ert(os, t.asInput() + langopts, context);
3735 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3736 parse_text_attributes(p, os, FLAG_ITEM, outer,
3738 context.font.language, lang);
3742 else if (t.cs() == "inputencoding") {
3743 // nothing to write here
3744 string const enc = subst(p.verbatim_item(), "\n", " ");
3745 p.setEncoding(enc, Encoding::inputenc);
3748 else if ((where = is_known(t.cs(), known_special_chars))) {
3749 context.check_layout(os);
3750 os << "\\SpecialChar \\"
3751 << known_coded_special_chars[where - known_special_chars]
3753 skip_spaces_braces(p);
3756 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3757 context.check_layout(os);
3758 os << "\\SpecialChar \\nobreakdash-\n";
3762 else if (t.cs() == "textquotedbl") {
3763 context.check_layout(os);
3768 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3769 context.check_layout(os);
3770 os << "\\SpecialChar \\@.\n";
3774 else if (t.cs() == "-") {
3775 context.check_layout(os);
3776 os << "\\SpecialChar \\-\n";
3779 else if (t.cs() == "textasciitilde") {
3780 context.check_layout(os);
3782 skip_spaces_braces(p);
3785 else if (t.cs() == "textasciicircum") {
3786 context.check_layout(os);
3788 skip_spaces_braces(p);
3791 else if (t.cs() == "textbackslash") {
3792 context.check_layout(os);
3793 os << "\n\\backslash\n";
3794 skip_spaces_braces(p);
3797 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3798 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3800 context.check_layout(os);
3804 else if (t.cs() == "char") {
3805 context.check_layout(os);
3806 if (p.next_token().character() == '`') {
3808 if (p.next_token().cs() == "\"") {
3813 handle_ert(os, "\\char`", context);
3816 handle_ert(os, "\\char", context);
3820 else if (t.cs() == "verb") {
3821 context.check_layout(os);
3822 char const delimiter = p.next_token().character();
3823 // \verb is special: The usual escaping rules do not
3824 // apply, e.g. "\verb+\+" is valid and denotes a single
3825 // backslash (bug #4468). Therefore we do not allow
3826 // escaping in getArg().
3827 string const arg = p.getArg(delimiter, delimiter, false);
3829 oss << "\\verb" << delimiter << arg << delimiter;
3830 handle_ert(os, oss.str(), context);
3833 // Problem: \= creates a tabstop inside the tabbing environment
3834 // and else an accent. In the latter case we really would want
3835 // \={o} instead of \= o.
3836 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3837 handle_ert(os, t.asInput(), context);
3839 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3840 else if (t.cs().size() == 1
3841 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3842 context.check_layout(os);
3843 // try to see whether the string is in unicodesymbols
3846 string command = t.asInput() + "{"
3847 + trimSpaceAndEol(p.verbatim_item())
3850 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3851 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3852 termination, rem, &req);
3855 cerr << "When parsing " << command
3856 << ", result is " << to_utf8(s)
3857 << "+" << to_utf8(rem) << endl;
3859 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3860 preamble.registerAutomaticallyLoadedPackage(*it);
3862 // we did not find a non-ert version
3863 handle_ert(os, command, context);
3866 else if (t.cs() == "\\") {
3867 context.check_layout(os);
3869 handle_ert(os, "\\\\" + p.getOpt(), context);
3870 else if (p.next_token().asInput() == "*") {
3872 // getOpt() eats the following space if there
3873 // is no optional argument, but that is OK
3874 // here since it has no effect in the output.
3875 handle_ert(os, "\\\\*" + p.getOpt(), context);
3878 begin_inset(os, "Newline newline");
3883 else if (t.cs() == "newline" ||
3884 (t.cs() == "linebreak" && !p.hasOpt())) {
3885 context.check_layout(os);
3886 begin_inset(os, "Newline ");
3889 skip_spaces_braces(p);
3892 else if (t.cs() == "input" || t.cs() == "include"
3893 || t.cs() == "verbatiminput") {
3894 string name = t.cs();
3895 if (t.cs() == "verbatiminput"
3896 && p.next_token().asInput() == "*")
3897 name += p.get_token().asInput();
3898 context.check_layout(os);
3899 string filename(normalize_filename(p.getArg('{', '}')));
3900 string const path = getMasterFilePath(true);
3901 // We want to preserve relative / absolute filenames,
3902 // therefore path is only used for testing
3903 if ((t.cs() == "include" || t.cs() == "input") &&
3904 !makeAbsPath(filename, path).exists()) {
3905 // The file extension is probably missing.
3906 // Now try to find it out.
3907 string const tex_name =
3908 find_file(filename, path,
3909 known_tex_extensions);
3910 if (!tex_name.empty())
3911 filename = tex_name;
3913 bool external = false;
3915 if (makeAbsPath(filename, path).exists()) {
3916 string const abstexname =
3917 makeAbsPath(filename, path).absFileName();
3918 string const absfigname =
3919 changeExtension(abstexname, ".fig");
3920 fix_child_filename(filename);
3921 string const lyxname =
3922 changeExtension(filename, ".lyx");
3923 string const abslyxname = makeAbsPath(
3924 lyxname, getParentFilePath(false)).absFileName();
3926 if (!skipChildren())
3927 external = FileName(absfigname).exists();
3928 if (t.cs() == "input" && !skipChildren()) {
3929 string const ext = getExtension(abstexname);
3931 // Combined PS/LaTeX:
3932 // x.eps, x.pstex_t (old xfig)
3933 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3934 FileName const absepsname(
3935 changeExtension(abstexname, ".eps"));
3936 FileName const abspstexname(
3937 changeExtension(abstexname, ".pstex"));
3938 bool const xfigeps =
3939 (absepsname.exists() ||
3940 abspstexname.exists()) &&
3943 // Combined PDF/LaTeX:
3944 // x.pdf, x.pdftex_t (old xfig)
3945 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3946 FileName const abspdfname(
3947 changeExtension(abstexname, ".pdf"));
3948 bool const xfigpdf =
3949 abspdfname.exists() &&
3950 (ext == "pdftex_t" || ext == "pdf_t");
3954 // Combined PS/PDF/LaTeX:
3955 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3956 string const absbase2(
3957 removeExtension(abstexname) + "_pspdftex");
3958 FileName const abseps2name(
3959 addExtension(absbase2, ".eps"));
3960 FileName const abspdf2name(
3961 addExtension(absbase2, ".pdf"));
3962 bool const xfigboth =
3963 abspdf2name.exists() &&
3964 abseps2name.exists() && ext == "pspdftex";
3966 xfig = xfigpdf || xfigeps || xfigboth;
3967 external = external && xfig;
3970 outname = changeExtension(filename, ".fig");
3971 FileName abssrc(changeExtension(abstexname, ".fig"));
3972 copy_file(abssrc, outname);
3974 // Don't try to convert, the result
3975 // would be full of ERT.
3977 FileName abssrc(abstexname);
3978 copy_file(abssrc, outname);
3979 } else if (t.cs() != "verbatiminput" &&
3981 tex2lyx(abstexname, FileName(abslyxname),
3984 // no need to call copy_file
3985 // tex2lyx creates the file
3988 FileName abssrc(abstexname);
3989 copy_file(abssrc, outname);
3992 cerr << "Warning: Could not find included file '"
3993 << filename << "'." << endl;
3997 begin_inset(os, "External\n");
3998 os << "\ttemplate XFig\n"
3999 << "\tfilename " << outname << '\n';
4000 registerExternalTemplatePackages("XFig");
4002 begin_command_inset(os, "include", name);
4003 outname = subst(outname, "\"", "\\\"");
4004 os << "preview false\n"
4005 "filename \"" << outname << "\"\n";
4006 if (t.cs() == "verbatiminput")
4007 preamble.registerAutomaticallyLoadedPackage("verbatim");
4012 else if (t.cs() == "bibliographystyle") {
4013 // store new bibliographystyle
4014 bibliographystyle = p.verbatim_item();
4015 // If any other command than \bibliography and
4016 // \nocite{*} follows, we need to output the style
4017 // (because it might be used by that command).
4018 // Otherwise, it will automatically be output by LyX.
4021 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4022 if (t2.cat() == catBegin)
4024 if (t2.cat() != catEscape)
4026 if (t2.cs() == "nocite") {
4027 if (p.getArg('{', '}') == "*")
4029 } else if (t2.cs() == "bibliography")
4036 "\\bibliographystyle{" + bibliographystyle + '}',
4041 else if (t.cs() == "bibliography") {
4042 context.check_layout(os);
4043 begin_command_inset(os, "bibtex", "bibtex");
4044 if (!btprint.empty()) {
4045 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4046 // clear the string because the next BibTeX inset can be without the
4047 // \nocite{*} option
4050 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4051 // Do we have a bibliographystyle set?
4052 if (!bibliographystyle.empty())
4053 os << "options " << '"' << bibliographystyle << '"' << "\n";
4057 else if (t.cs() == "parbox") {
4058 // Test whether this is an outer box of a shaded box
4060 // swallow arguments
4061 while (p.hasOpt()) {
4063 p.skip_spaces(true);
4066 p.skip_spaces(true);
4068 if (p.next_token().cat() == catBegin)
4070 p.skip_spaces(true);
4071 Token to = p.get_token();
4072 bool shaded = false;
4073 if (to.asInput() == "\\begin") {
4074 p.skip_spaces(true);
4075 if (p.getArg('{', '}') == "shaded")
4080 parse_outer_box(p, os, FLAG_ITEM, outer,
4081 context, "parbox", "shaded");
4083 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4087 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4088 t.cs() == "shadowbox" || t.cs() == "doublebox")
4089 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4091 else if (t.cs() == "framebox") {
4092 if (p.next_token().character() == '(') {
4093 //the syntax is: \framebox(x,y)[position]{content}
4094 string arg = t.asInput();
4095 arg += p.getFullParentheseArg();
4096 arg += p.getFullOpt();
4097 eat_whitespace(p, os, context, false);
4098 handle_ert(os, arg + '{', context);
4099 parse_text(p, os, FLAG_ITEM, outer, context);
4100 handle_ert(os, "}", context);
4102 string special = p.getFullOpt();
4103 special += p.getOpt();
4104 // LyX does not yet support \framebox without any option
4105 if (!special.empty())
4106 parse_outer_box(p, os, FLAG_ITEM, outer,
4107 context, t.cs(), special);
4109 eat_whitespace(p, os, context, false);
4110 handle_ert(os, "\\framebox{", context);
4111 parse_text(p, os, FLAG_ITEM, outer, context);
4112 handle_ert(os, "}", context);
4117 //\makebox() is part of the picture environment and different from \makebox{}
4118 //\makebox{} will be parsed by parse_box
4119 else if (t.cs() == "makebox") {
4120 if (p.next_token().character() == '(') {
4121 //the syntax is: \makebox(x,y)[position]{content}
4122 string arg = t.asInput();
4123 arg += p.getFullParentheseArg();
4124 arg += p.getFullOpt();
4125 eat_whitespace(p, os, context, false);
4126 handle_ert(os, arg + '{', context);
4127 parse_text(p, os, FLAG_ITEM, outer, context);
4128 handle_ert(os, "}", context);
4130 //the syntax is: \makebox[width][position]{content}
4131 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4135 else if (t.cs() == "smallskip" ||
4136 t.cs() == "medskip" ||
4137 t.cs() == "bigskip" ||
4138 t.cs() == "vfill") {
4139 context.check_layout(os);
4140 begin_inset(os, "VSpace ");
4143 skip_spaces_braces(p);
4146 else if ((where = is_known(t.cs(), known_spaces))) {
4147 context.check_layout(os);
4148 begin_inset(os, "space ");
4149 os << '\\' << known_coded_spaces[where - known_spaces]
4152 // LaTeX swallows whitespace after all spaces except
4153 // "\\,". We have to do that here, too, because LyX
4154 // adds "{}" which would make the spaces significant.
4156 eat_whitespace(p, os, context, false);
4157 // LyX adds "{}" after all spaces except "\\ " and
4158 // "\\,", so we have to remove "{}".
4159 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4160 // remove the braces after "\\,", too.
4165 else if (t.cs() == "newpage" ||
4166 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4167 t.cs() == "clearpage" ||
4168 t.cs() == "cleardoublepage") {
4169 context.check_layout(os);
4170 begin_inset(os, "Newpage ");
4173 skip_spaces_braces(p);
4176 else if (t.cs() == "DeclareRobustCommand" ||
4177 t.cs() == "DeclareRobustCommandx" ||
4178 t.cs() == "newcommand" ||
4179 t.cs() == "newcommandx" ||
4180 t.cs() == "providecommand" ||
4181 t.cs() == "providecommandx" ||
4182 t.cs() == "renewcommand" ||
4183 t.cs() == "renewcommandx") {
4184 // DeclareRobustCommand, DeclareRobustCommandx,
4185 // providecommand and providecommandx could be handled
4186 // by parse_command(), but we need to call
4187 // add_known_command() here.
4188 string name = t.asInput();
4189 if (p.next_token().asInput() == "*") {
4190 // Starred form. Eat '*'
4194 string const command = p.verbatim_item();
4195 string const opt1 = p.getFullOpt();
4196 string const opt2 = p.getFullOpt();
4197 add_known_command(command, opt1, !opt2.empty());
4198 string const ert = name + '{' + command + '}' +
4200 '{' + p.verbatim_item() + '}';
4202 if (t.cs() == "DeclareRobustCommand" ||
4203 t.cs() == "DeclareRobustCommandx" ||
4204 t.cs() == "providecommand" ||
4205 t.cs() == "providecommandx" ||
4206 name[name.length()-1] == '*')
4207 handle_ert(os, ert, context);
4209 context.check_layout(os);
4210 begin_inset(os, "FormulaMacro");
4216 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4217 // let could be handled by parse_command(),
4218 // but we need to call add_known_command() here.
4219 string ert = t.asInput();
4222 if (p.next_token().cat() == catBegin) {
4223 name = p.verbatim_item();
4224 ert += '{' + name + '}';
4226 name = p.verbatim_item();
4231 if (p.next_token().cat() == catBegin) {
4232 command = p.verbatim_item();
4233 ert += '{' + command + '}';
4235 command = p.verbatim_item();
4238 // If command is known, make name known too, to parse
4239 // its arguments correctly. For this reason we also
4240 // have commands in syntax.default that are hardcoded.
4241 CommandMap::iterator it = known_commands.find(command);
4242 if (it != known_commands.end())
4243 known_commands[t.asInput()] = it->second;
4244 handle_ert(os, ert, context);
4247 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4248 bool starred = false;
4249 if (p.next_token().asInput() == "*") {
4253 string name = t.asInput();
4254 string const length = p.verbatim_item();
4257 bool valid = splitLatexLength(length, valstring, unit);
4258 bool known_hspace = false;
4259 bool known_vspace = false;
4260 bool known_unit = false;
4263 istringstream iss(valstring);
4266 if (t.cs()[0] == 'h') {
4267 if (unit == "\\fill") {
4272 known_hspace = true;
4275 if (unit == "\\smallskipamount") {
4277 known_vspace = true;
4278 } else if (unit == "\\medskipamount") {
4280 known_vspace = true;
4281 } else if (unit == "\\bigskipamount") {
4283 known_vspace = true;
4284 } else if (unit == "\\fill") {
4286 known_vspace = true;
4290 if (!known_hspace && !known_vspace) {
4291 switch (unitFromString(unit)) {
4312 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4313 // Literal horizontal length or known variable
4314 context.check_layout(os);
4315 begin_inset(os, "space ");
4323 if (known_unit && !known_hspace)
4325 << translate_len(length);
4327 } else if (known_unit || known_vspace) {
4328 // Literal vertical length or known variable
4329 context.check_layout(os);
4330 begin_inset(os, "VSpace ");
4338 // LyX can't handle other length variables in Inset VSpace/space
4343 handle_ert(os, name + '{' + unit + '}', context);
4344 else if (value == -1.0)
4345 handle_ert(os, name + "{-" + unit + '}', context);
4347 handle_ert(os, name + '{' + valstring + unit + '}', context);
4349 handle_ert(os, name + '{' + length + '}', context);
4353 // The single '=' is meant here.
4354 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4356 context.check_layout(os);
4357 begin_inset(os, "Flex ");
4358 os << to_utf8(newinsetlayout->name()) << '\n'
4359 << "status collapsed\n";
4360 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4364 else if (t.cs() == "includepdf") {
4366 string const arg = p.getArg('[', ']');
4367 map<string, string> opts;
4368 vector<string> keys;
4369 split_map(arg, opts, keys);
4370 string name = normalize_filename(p.verbatim_item());
4371 string const path = getMasterFilePath(true);
4372 // We want to preserve relative / absolute filenames,
4373 // therefore path is only used for testing
4374 if (!makeAbsPath(name, path).exists()) {
4375 // The file extension is probably missing.
4376 // Now try to find it out.
4377 char const * const pdfpages_format[] = {"pdf", 0};
4378 string const pdftex_name =
4379 find_file(name, path, pdfpages_format);
4380 if (!pdftex_name.empty()) {
4385 FileName const absname = makeAbsPath(name, path);
4386 if (absname.exists())
4388 fix_child_filename(name);
4389 copy_file(absname, name);
4391 cerr << "Warning: Could not find file '"
4392 << name << "'." << endl;
4394 context.check_layout(os);
4395 begin_inset(os, "External\n\ttemplate ");
4396 os << "PDFPages\n\tfilename "
4398 // parse the options
4399 if (opts.find("pages") != opts.end())
4400 os << "\textra LaTeX \"pages="
4401 << opts["pages"] << "\"\n";
4402 if (opts.find("angle") != opts.end())
4403 os << "\trotateAngle "
4404 << opts["angle"] << '\n';
4405 if (opts.find("origin") != opts.end()) {
4407 string const opt = opts["origin"];
4408 if (opt == "tl") ss << "topleft";
4409 if (opt == "bl") ss << "bottomleft";
4410 if (opt == "Bl") ss << "baselineleft";
4411 if (opt == "c") ss << "center";
4412 if (opt == "tc") ss << "topcenter";
4413 if (opt == "bc") ss << "bottomcenter";
4414 if (opt == "Bc") ss << "baselinecenter";
4415 if (opt == "tr") ss << "topright";
4416 if (opt == "br") ss << "bottomright";
4417 if (opt == "Br") ss << "baselineright";
4418 if (!ss.str().empty())
4419 os << "\trotateOrigin " << ss.str() << '\n';
4421 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4423 if (opts.find("width") != opts.end())
4425 << translate_len(opts["width"]) << '\n';
4426 if (opts.find("height") != opts.end())
4428 << translate_len(opts["height"]) << '\n';
4429 if (opts.find("keepaspectratio") != opts.end())
4430 os << "\tkeepAspectRatio\n";
4432 context.check_layout(os);
4433 registerExternalTemplatePackages("PDFPages");
4436 else if (t.cs() == "loadgame") {
4438 string name = normalize_filename(p.verbatim_item());
4439 string const path = getMasterFilePath(true);
4440 // We want to preserve relative / absolute filenames,
4441 // therefore path is only used for testing
4442 if (!makeAbsPath(name, path).exists()) {
4443 // The file extension is probably missing.
4444 // Now try to find it out.
4445 char const * const lyxskak_format[] = {"fen", 0};
4446 string const lyxskak_name =
4447 find_file(name, path, lyxskak_format);
4448 if (!lyxskak_name.empty())
4449 name = lyxskak_name;
4451 FileName const absname = makeAbsPath(name, path);
4452 if (absname.exists())
4454 fix_child_filename(name);
4455 copy_file(absname, name);
4457 cerr << "Warning: Could not find file '"
4458 << name << "'." << endl;
4459 context.check_layout(os);
4460 begin_inset(os, "External\n\ttemplate ");
4461 os << "ChessDiagram\n\tfilename "
4464 context.check_layout(os);
4465 // after a \loadgame follows a \showboard
4466 if (p.get_token().asInput() == "showboard")
4468 registerExternalTemplatePackages("ChessDiagram");
4472 // try to see whether the string is in unicodesymbols
4473 // Only use text mode commands, since we are in text mode here,
4474 // and math commands may be invalid (bug 6797)
4478 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4479 Encodings::TEXT_CMD, termination, rem, &req);
4482 cerr << "When parsing " << t.cs()
4483 << ", result is " << to_utf8(s)
4484 << "+" << to_utf8(rem) << endl;
4485 context.check_layout(os);
4488 skip_spaces_braces(p);
4489 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4490 preamble.registerAutomaticallyLoadedPackage(*it);
4492 //cerr << "#: " << t << " mode: " << mode << endl;
4493 // heuristic: read up to next non-nested space
4495 string s = t.asInput();
4496 string z = p.verbatim_item();
4497 while (p.good() && z != " " && !z.empty()) {
4498 //cerr << "read: " << z << endl;
4500 z = p.verbatim_item();
4502 cerr << "found ERT: " << s << endl;
4503 handle_ert(os, s + ' ', context);
4506 string name = t.asInput();
4507 if (p.next_token().asInput() == "*") {
4508 // Starred commands like \vspace*{}
4509 p.get_token(); // Eat '*'
4512 if (!parse_command(name, p, os, outer, context))
4513 handle_ert(os, name, context);
4517 if (flags & FLAG_LEAVE) {
4518 flags &= ~FLAG_LEAVE;
4525 string guessLanguage(Parser & p, string const & lang)
4527 typedef std::map<std::string, size_t> LangMap;
4528 // map from language names to number of characters
4531 for (char const * const * i = supported_CJK_languages; *i; i++)
4532 used[string(*i)] = 0;
4535 Token const t = p.get_token();
4536 // comments are not counted for any language
4537 if (t.cat() == catComment)
4539 // commands are not counted as well, but we need to detect
4540 // \begin{CJK} and switch encoding if needed
4541 if (t.cat() == catEscape) {
4542 if (t.cs() == "inputencoding") {
4543 string const enc = subst(p.verbatim_item(), "\n", " ");
4544 p.setEncoding(enc, Encoding::inputenc);
4547 if (t.cs() != "begin")
4550 // Non-CJK content is counted for lang.
4551 // We do not care about the real language here:
4552 // If we have more non-CJK contents than CJK contents,
4553 // we simply use the language that was specified as
4554 // babel main language.
4555 used[lang] += t.asInput().length();
4558 // Now we are starting an environment
4560 string const name = p.getArg('{', '}');
4561 if (name != "CJK") {
4565 // It is a CJK environment
4567 /* name = */ p.getArg('{', '}');
4568 string const encoding = p.getArg('{', '}');
4569 /* mapping = */ p.getArg('{', '}');
4570 string const encoding_old = p.getEncoding();
4571 char const * const * const where =
4572 is_known(encoding, supported_CJK_encodings);
4574 p.setEncoding(encoding, Encoding::CJK);
4576 p.setEncoding("UTF-8");
4577 string const text = p.verbatimEnvironment("CJK");
4578 p.setEncoding(encoding_old);
4581 // ignore contents in unknown CJK encoding
4584 // the language of the text
4586 supported_CJK_languages[where - supported_CJK_encodings];
4587 used[cjk] += text.length();
4589 LangMap::const_iterator use = used.begin();
4590 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4591 if (it->second > use->second)