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.ertEnvironment(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 // FIXME: this should go in the generic code that
1439 // handles environments defined in layout file that
1440 // have "PassThru 1". However, the code there is
1441 // already too complicated for my taste.
1442 parent_context.new_paragraph(os);
1443 Context context(true, parent_context.textclass,
1444 &parent_context.textclass[from_ascii("Verbatim")]);
1445 context.check_layout(os);
1446 string s = p.verbatimStuff("\\end{verbatim}");
1447 // ignore one newline at beginning or end of string
1448 if (prefixIs(s, "\n"))
1450 if (suffixIs(s, "\n"))
1451 s.erase(s.length(),1);
1453 string::const_iterator it2 = s.begin();
1454 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1455 context.check_layout(os);
1457 os << "\n\\backslash\n";
1458 context.need_end_layout = true;
1459 } else if (*it == '\n') {
1460 context.new_paragraph(os);
1463 context.need_end_layout = true;
1466 context.new_paragraph(os);
1470 else if (name == "CJK") {
1471 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1472 // It is impossible to decide if a CJK environment was in its own paragraph or within
1473 // a line. We therefore always assume a paragraph since the latter is a rare case.
1474 eat_whitespace(p, os, parent_context, false);
1475 parent_context.check_end_layout(os);
1476 // store the encoding to be able to reset it
1477 string const encoding_old = p.getEncoding();
1478 string const encoding = p.getArg('{', '}');
1479 // FIXME: For some reason JIS does not work. Although the text
1480 // in tests/CJK.tex is identical with the SJIS version if you
1481 // convert both snippets using the recode command line utility,
1482 // the resulting .lyx file contains some extra characters if
1483 // you set buggy_encoding to false for JIS.
1484 bool const buggy_encoding = encoding == "JIS";
1485 if (!buggy_encoding)
1486 p.setEncoding(encoding, Encoding::CJK);
1488 // FIXME: This will read garbage, since the data is not encoded in utf8.
1489 p.setEncoding("UTF-8");
1491 // LyX only supports the same mapping for all CJK
1492 // environments, so we might need to output everything as ERT
1493 string const mapping = trim(p.getArg('{', '}'));
1494 char const * const * const where =
1495 is_known(encoding, supported_CJK_encodings);
1496 if (!buggy_encoding && !preamble.fontCJKSet())
1497 preamble.fontCJK(mapping);
1498 bool knownMapping = mapping == preamble.fontCJK();
1499 if (buggy_encoding || !knownMapping || !where) {
1500 parent_context.check_layout(os);
1501 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1503 // we must parse the content as verbatim because e.g. JIS can contain
1504 // normally invalid characters
1505 // FIXME: This works only for the most simple cases.
1506 // Since TeX control characters are not parsed,
1507 // things like comments are completely wrong.
1508 string const s = p.plainEnvironment("CJK");
1509 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1511 handle_ert(os, "\\", parent_context);
1512 else if (*it == '$')
1513 handle_ert(os, "$", parent_context);
1517 handle_ert(os, "\\end{" + name + "}",
1521 supported_CJK_languages[where - supported_CJK_encodings];
1522 // store the language because we must reset it at the end
1523 string const lang_old = parent_context.font.language;
1524 parent_context.font.language = lang;
1525 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1526 parent_context.font.language = lang_old;
1527 parent_context.new_paragraph(os);
1529 p.setEncoding(encoding_old);
1533 else if (name == "lyxgreyedout") {
1534 eat_whitespace(p, os, parent_context, false);
1535 parent_context.check_layout(os);
1536 begin_inset(os, "Note Greyedout\n");
1537 os << "status open\n";
1538 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1541 if (!preamble.notefontcolor().empty())
1542 preamble.registerAutomaticallyLoadedPackage("color");
1545 else if (name == "framed" || name == "shaded") {
1546 eat_whitespace(p, os, parent_context, false);
1547 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1551 else if (name == "lstlisting") {
1552 eat_whitespace(p, os, parent_context, false);
1553 parse_listings(p, os, parent_context, false);
1557 else if (!parent_context.new_layout_allowed)
1558 parse_unknown_environment(p, name, os, FLAG_END, outer,
1561 // Alignment and spacing settings
1562 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1563 // therefore are totally broken!
1564 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1565 // they are commands not environments. They are furthermore switches that
1566 // can be ended by another switches, but also by commands like \footnote or
1567 // \parbox. So the only safe way is to leave them untouched.
1568 else if (name == "center" || name == "centering" ||
1569 name == "flushleft" || name == "flushright" ||
1570 name == "singlespace" || name == "onehalfspace" ||
1571 name == "doublespace" || name == "spacing") {
1572 eat_whitespace(p, os, parent_context, false);
1573 // We must begin a new paragraph if not already done
1574 if (! parent_context.atParagraphStart()) {
1575 parent_context.check_end_layout(os);
1576 parent_context.new_paragraph(os);
1578 if (name == "flushleft")
1579 parent_context.add_extra_stuff("\\align left\n");
1580 else if (name == "flushright")
1581 parent_context.add_extra_stuff("\\align right\n");
1582 else if (name == "center" || name == "centering")
1583 parent_context.add_extra_stuff("\\align center\n");
1584 else if (name == "singlespace")
1585 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1586 else if (name == "onehalfspace") {
1587 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1588 preamble.registerAutomaticallyLoadedPackage("setspace");
1589 } else if (name == "doublespace") {
1590 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1591 preamble.registerAutomaticallyLoadedPackage("setspace");
1592 } else if (name == "spacing") {
1593 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1594 preamble.registerAutomaticallyLoadedPackage("setspace");
1596 parse_text(p, os, FLAG_END, outer, parent_context);
1597 // Just in case the environment is empty
1598 parent_context.extra_stuff.erase();
1599 // We must begin a new paragraph to reset the alignment
1600 parent_context.new_paragraph(os);
1604 // The single '=' is meant here.
1605 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1606 eat_whitespace(p, os, parent_context, false);
1607 Context context(true, parent_context.textclass, newlayout,
1608 parent_context.layout, parent_context.font);
1609 if (parent_context.deeper_paragraph) {
1610 // We are beginning a nested environment after a
1611 // deeper paragraph inside the outer list environment.
1612 // Therefore we don't need to output a "begin deeper".
1613 context.need_end_deeper = true;
1615 parent_context.check_end_layout(os);
1616 if (last_env == name) {
1617 // we need to output a separator since LyX would export
1618 // the two environments as one otherwise (bug 5716)
1619 docstring const sep = from_ascii("--Separator--");
1620 TeX2LyXDocClass const & textclass(parent_context.textclass);
1621 if (textclass.hasLayout(sep)) {
1622 Context newcontext(parent_context);
1623 newcontext.layout = &(textclass[sep]);
1624 newcontext.check_layout(os);
1625 newcontext.check_end_layout(os);
1627 parent_context.check_layout(os);
1628 begin_inset(os, "Note Note\n");
1629 os << "status closed\n";
1630 Context newcontext(true, textclass,
1631 &(textclass.defaultLayout()));
1632 newcontext.check_layout(os);
1633 newcontext.check_end_layout(os);
1635 parent_context.check_end_layout(os);
1638 switch (context.layout->latextype) {
1639 case LATEX_LIST_ENVIRONMENT:
1640 context.add_par_extra_stuff("\\labelwidthstring "
1641 + p.verbatim_item() + '\n');
1644 case LATEX_BIB_ENVIRONMENT:
1645 p.verbatim_item(); // swallow next arg
1651 context.check_deeper(os);
1652 // handle known optional and required arguments
1653 // FIXME: Since format 446, layouts do not require anymore all optional
1654 // arguments before the required ones. Needs to be implemented!
1655 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1656 // It is impossible to place anything after the environment name,
1657 // but before the first \\item.
1658 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1659 bool need_layout = true;
1661 while (optargs < context.layout->optArgs()) {
1662 eat_whitespace(p, os, context, false);
1663 if (p.next_token().cat() == catEscape ||
1664 p.next_token().character() != '[')
1666 p.get_token(); // eat '['
1668 context.check_layout(os);
1669 need_layout = false;
1671 // FIXME: Just a workaround. InsetArgument::updateBuffer
1672 // will compute a proper ID for all "999" Arguments
1673 // (which is also what lyx2lyx produces).
1674 // However, tex2lyx should be able to output proper IDs
1676 begin_inset(os, "Argument 999\n");
1677 os << "status collapsed\n\n";
1678 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1680 eat_whitespace(p, os, context, false);
1684 while (reqargs < context.layout->requiredArgs()) {
1685 eat_whitespace(p, os, context, false);
1686 if (p.next_token().cat() != catBegin)
1688 p.get_token(); // eat '{'
1690 context.check_layout(os);
1691 need_layout = false;
1693 // FIXME: Just a workaround. InsetArgument::updateBuffer
1694 // will compute a proper ID for all "999" Arguments
1695 // (which is also what lyx2lyx produces).
1696 // However, tex2lyx should be able to output proper IDs
1698 begin_inset(os, "Argument 999\n");
1699 os << "status collapsed\n\n";
1700 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1702 eat_whitespace(p, os, context, false);
1706 parse_text(p, os, FLAG_END, outer, context);
1707 context.check_end_layout(os);
1708 if (parent_context.deeper_paragraph) {
1709 // We must suppress the "end deeper" because we
1710 // suppressed the "begin deeper" above.
1711 context.need_end_deeper = false;
1713 context.check_end_deeper(os);
1714 parent_context.new_paragraph(os);
1716 if (!preamble.titleLayoutFound())
1717 preamble.titleLayoutFound(newlayout->intitle);
1718 set<string> const & req = newlayout->requires();
1719 set<string>::const_iterator it = req.begin();
1720 set<string>::const_iterator en = req.end();
1721 for (; it != en; ++it)
1722 preamble.registerAutomaticallyLoadedPackage(*it);
1725 // The single '=' is meant here.
1726 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1727 eat_whitespace(p, os, parent_context, false);
1728 parent_context.check_layout(os);
1729 begin_inset(os, "Flex ");
1730 os << to_utf8(newinsetlayout->name()) << '\n'
1731 << "status collapsed\n";
1732 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1736 else if (name == "appendix") {
1737 // This is no good latex style, but it works and is used in some documents...
1738 eat_whitespace(p, os, parent_context, false);
1739 parent_context.check_end_layout(os);
1740 Context context(true, parent_context.textclass, parent_context.layout,
1741 parent_context.layout, parent_context.font);
1742 context.check_layout(os);
1743 os << "\\start_of_appendix\n";
1744 parse_text(p, os, FLAG_END, outer, context);
1745 context.check_end_layout(os);
1749 else if (known_environments.find(name) != known_environments.end()) {
1750 vector<ArgumentType> arguments = known_environments[name];
1751 // The last "argument" denotes wether we may translate the
1752 // environment contents to LyX
1753 // The default required if no argument is given makes us
1754 // compatible with the reLyXre environment.
1755 ArgumentType contents = arguments.empty() ?
1758 if (!arguments.empty())
1759 arguments.pop_back();
1760 // See comment in parse_unknown_environment()
1761 bool const specialfont =
1762 (parent_context.font != parent_context.normalfont);
1763 bool const new_layout_allowed =
1764 parent_context.new_layout_allowed;
1766 parent_context.new_layout_allowed = false;
1767 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1768 outer, parent_context);
1769 if (contents == verbatim)
1770 handle_ert(os, p.ertEnvironment(name),
1773 parse_text_snippet(p, os, FLAG_END, outer,
1775 handle_ert(os, "\\end{" + name + "}", parent_context);
1777 parent_context.new_layout_allowed = new_layout_allowed;
1781 parse_unknown_environment(p, name, os, FLAG_END, outer,
1785 active_environments.pop_back();
1789 /// parses a comment and outputs it to \p os.
1790 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1792 LASSERT(t.cat() == catComment, return);
1793 if (!t.cs().empty()) {
1794 context.check_layout(os);
1795 handle_comment(os, '%' + t.cs(), context);
1796 if (p.next_token().cat() == catNewline) {
1797 // A newline after a comment line starts a new
1799 if (context.new_layout_allowed) {
1800 if(!context.atParagraphStart())
1801 // Only start a new paragraph if not already
1802 // done (we might get called recursively)
1803 context.new_paragraph(os);
1805 handle_ert(os, "\n", context);
1806 eat_whitespace(p, os, context, true);
1809 // "%\n" combination
1816 * Reads spaces and comments until the first non-space, non-comment token.
1817 * New paragraphs (double newlines or \\par) are handled like simple spaces
1818 * if \p eatParagraph is true.
1819 * Spaces are skipped, but comments are written to \p os.
1821 void eat_whitespace(Parser & p, ostream & os, Context & context,
1825 Token const & t = p.get_token();
1826 if (t.cat() == catComment)
1827 parse_comment(p, os, t, context);
1828 else if ((! eatParagraph && p.isParagraph()) ||
1829 (t.cat() != catSpace && t.cat() != catNewline)) {
1838 * Set a font attribute, parse text and reset the font attribute.
1839 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1840 * \param currentvalue Current value of the attribute. Is set to the new
1841 * value during parsing.
1842 * \param newvalue New value of the attribute
1844 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1845 Context & context, string const & attribute,
1846 string & currentvalue, string const & newvalue)
1848 context.check_layout(os);
1849 string const oldvalue = currentvalue;
1850 currentvalue = newvalue;
1851 os << '\n' << attribute << ' ' << newvalue << "\n";
1852 parse_text_snippet(p, os, flags, outer, context);
1853 context.check_layout(os);
1854 os << '\n' << attribute << ' ' << oldvalue << "\n";
1855 currentvalue = oldvalue;
1859 /// get the arguments of a natbib or jurabib citation command
1860 void get_cite_arguments(Parser & p, bool natbibOrder,
1861 string & before, string & after)
1863 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1865 // text before the citation
1867 // text after the citation
1868 after = p.getFullOpt();
1870 if (!after.empty()) {
1871 before = p.getFullOpt();
1872 if (natbibOrder && !before.empty())
1873 swap(before, after);
1878 /// Convert filenames with TeX macros and/or quotes to something LyX
1880 string const normalize_filename(string const & name)
1885 Token const & t = p.get_token();
1886 if (t.cat() != catEscape)
1888 else if (t.cs() == "lyxdot") {
1889 // This is used by LyX for simple dots in relative
1893 } else if (t.cs() == "space") {
1896 } else if (t.cs() == "string") {
1897 // Convert \string" to " and \string~ to ~
1898 Token const & n = p.next_token();
1899 if (n.asInput() != "\"" && n.asInput() != "~")
1904 // Strip quotes. This is a bit complicated (see latex_path()).
1905 string full = os.str();
1906 if (!full.empty() && full[0] == '"') {
1907 string base = removeExtension(full);
1908 string ext = getExtension(full);
1909 if (!base.empty() && base[base.length()-1] == '"')
1912 return addExtension(trim(base, "\""), ext);
1913 if (full[full.length()-1] == '"')
1916 return trim(full, "\"");
1922 /// Convert \p name from TeX convention (relative to master file) to LyX
1923 /// convention (relative to .lyx file) if it is relative
1924 void fix_child_filename(string & name)
1926 string const absMasterTeX = getMasterFilePath(true);
1927 bool const isabs = FileName::isAbsolute(name);
1928 // convert from "relative to .tex master" to absolute original path
1930 name = makeAbsPath(name, absMasterTeX).absFileName();
1931 bool copyfile = copyFiles();
1932 string const absParentLyX = getParentFilePath(false);
1935 // convert from absolute original path to "relative to master file"
1936 string const rel = to_utf8(makeRelPath(from_utf8(name),
1937 from_utf8(absMasterTeX)));
1938 // re-interpret "relative to .tex file" as "relative to .lyx file"
1939 // (is different if the master .lyx file resides in a
1940 // different path than the master .tex file)
1941 string const absMasterLyX = getMasterFilePath(false);
1942 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1943 // Do not copy if the new path is impossible to create. Example:
1944 // absMasterTeX = "/foo/bar/"
1945 // absMasterLyX = "/bar/"
1946 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1947 if (contains(name, "/../"))
1954 // convert from absolute original path to
1955 // "relative to .lyx file"
1956 name = to_utf8(makeRelPath(from_utf8(abs),
1957 from_utf8(absParentLyX)));
1961 // convert from absolute original path to "relative to .lyx file"
1962 name = to_utf8(makeRelPath(from_utf8(name),
1963 from_utf8(absParentLyX)));
1968 void copy_file(FileName const & src, string dstname)
1972 string const absParent = getParentFilePath(false);
1974 if (FileName::isAbsolute(dstname))
1975 dst = FileName(dstname);
1977 dst = makeAbsPath(dstname, absParent);
1978 string const absMaster = getMasterFilePath(false);
1979 FileName const srcpath = src.onlyPath();
1980 FileName const dstpath = dst.onlyPath();
1981 if (equivalent(srcpath, dstpath))
1983 if (!dstpath.isDirectory()) {
1984 if (!dstpath.createPath()) {
1985 cerr << "Warning: Could not create directory for file `"
1986 << dst.absFileName() << "´." << endl;
1990 if (dst.isReadableFile()) {
1991 if (overwriteFiles())
1992 cerr << "Warning: Overwriting existing file `"
1993 << dst.absFileName() << "´." << endl;
1995 cerr << "Warning: Not overwriting existing file `"
1996 << dst.absFileName() << "´." << endl;
2000 if (!src.copyTo(dst))
2001 cerr << "Warning: Could not copy file `" << src.absFileName()
2002 << "´ to `" << dst.absFileName() << "´." << endl;
2006 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
2007 void parse_noweb(Parser & p, ostream & os, Context & context)
2009 // assemble the rest of the keyword
2013 Token const & t = p.get_token();
2014 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2017 chunk = (p.good() && p.next_token().asInput() == "=");
2019 name += p.get_token().asInput();
2022 name += t.asInput();
2025 if (!chunk || !context.new_layout_allowed ||
2026 !context.textclass.hasLayout(from_ascii("Chunk"))) {
2027 cerr << "Warning: Could not interpret '" << name
2028 << "'. Ignoring it." << endl;
2032 // We use new_paragraph instead of check_end_layout because the stuff
2033 // following the noweb chunk needs to start with a \begin_layout.
2034 // This may create a new paragraph even if there was none in the
2035 // noweb file, but the alternative is an invalid LyX file. Since
2036 // noweb code chunks are implemented with a layout style in LyX they
2037 // always must be in an own paragraph.
2038 context.new_paragraph(os);
2039 Context newcontext(true, context.textclass,
2040 &context.textclass[from_ascii("Chunk")]);
2041 newcontext.check_layout(os);
2044 Token const & t = p.get_token();
2045 // We abuse the parser a bit, because this is no TeX syntax
2047 if (t.cat() == catEscape)
2048 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2051 Context tmp(false, context.textclass,
2052 &context.textclass[from_ascii("Chunk")]);
2053 tmp.need_end_layout = true;
2054 tmp.check_layout(oss);
2055 os << subst(t.asInput(), "\n", oss.str());
2057 // The chunk is ended by an @ at the beginning of a line.
2058 // After the @ the line may contain a comment and/or
2059 // whitespace, but nothing else.
2060 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2061 (p.next_token().cat() == catSpace ||
2062 p.next_token().cat() == catNewline ||
2063 p.next_token().cat() == catComment)) {
2064 while (p.good() && p.next_token().cat() == catSpace)
2065 os << p.get_token().asInput();
2066 if (p.next_token().cat() == catComment)
2067 // The comment includes a final '\n'
2068 os << p.get_token().asInput();
2070 if (p.next_token().cat() == catNewline)
2077 newcontext.check_end_layout(os);
2081 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2082 bool is_macro(Parser & p)
2084 Token first = p.curr_token();
2085 if (first.cat() != catEscape || !p.good())
2087 if (first.cs() == "def")
2089 if (first.cs() != "global" && first.cs() != "long")
2091 Token second = p.get_token();
2093 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2094 second.cat() == catNewline || second.cat() == catComment)) {
2095 second = p.get_token();
2098 bool secondvalid = second.cat() == catEscape;
2100 bool thirdvalid = false;
2101 if (p.good() && first.cs() == "global" && secondvalid &&
2102 second.cs() == "long") {
2103 third = p.get_token();
2105 while (p.good() && !p.isParagraph() &&
2106 (third.cat() == catSpace ||
2107 third.cat() == catNewline ||
2108 third.cat() == catComment)) {
2109 third = p.get_token();
2112 thirdvalid = third.cat() == catEscape;
2114 for (int i = 0; i < pos; ++i)
2119 return (first.cs() == "global" || first.cs() == "long") &&
2120 second.cs() == "def";
2121 return first.cs() == "global" && second.cs() == "long" &&
2122 third.cs() == "def";
2126 /// Parse a macro definition (assumes that is_macro() returned true)
2127 void parse_macro(Parser & p, ostream & os, Context & context)
2129 context.check_layout(os);
2130 Token first = p.curr_token();
2133 string command = first.asInput();
2134 if (first.cs() != "def") {
2136 eat_whitespace(p, os, context, false);
2137 second = p.curr_token();
2138 command += second.asInput();
2139 if (second.cs() != "def") {
2141 eat_whitespace(p, os, context, false);
2142 third = p.curr_token();
2143 command += third.asInput();
2146 eat_whitespace(p, os, context, false);
2147 string const name = p.get_token().cs();
2148 eat_whitespace(p, os, context, false);
2154 while (p.next_token().cat() != catBegin) {
2155 if (p.next_token().cat() == catParameter) {
2160 // followed by number?
2161 if (p.next_token().cat() == catOther) {
2162 char c = p.getChar();
2164 // number = current arity + 1?
2165 if (c == arity + '0' + 1)
2170 paramtext += p.get_token().cs();
2172 paramtext += p.get_token().cs();
2177 // only output simple (i.e. compatible) macro as FormulaMacros
2178 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2180 context.check_layout(os);
2181 begin_inset(os, "FormulaMacro");
2182 os << "\n\\def" << ert;
2185 handle_ert(os, command + ert, context);
2189 void registerExternalTemplatePackages(string const & name)
2191 external::TemplateManager const & etm = external::TemplateManager::get();
2192 external::Template const * const et = etm.getTemplateByName(name);
2195 external::Template::Formats::const_iterator cit = et->formats.end();
2197 cit = et->formats.find("PDFLaTeX");
2198 if (cit == et->formats.end())
2199 // If the template has not specified a PDFLaTeX output,
2200 // we try the LaTeX format.
2201 cit = et->formats.find("LaTeX");
2202 if (cit == et->formats.end())
2204 vector<string>::const_iterator qit = cit->second.requirements.begin();
2205 vector<string>::const_iterator qend = cit->second.requirements.end();
2206 for (; qit != qend; ++qit)
2207 preamble.registerAutomaticallyLoadedPackage(*qit);
2210 } // anonymous namespace
2213 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2216 Layout const * newlayout = 0;
2217 InsetLayout const * newinsetlayout = 0;
2218 char const * const * where = 0;
2219 // Store the latest bibliographystyle and nocite{*} option
2220 // (needed for bibtex inset)
2222 string bibliographystyle = "default";
2223 bool const use_natbib = isProvided("natbib");
2224 bool const use_jurabib = isProvided("jurabib");
2227 Token const & t = p.get_token();
2229 // it is impossible to determine the correct encoding for non-CJK Japanese.
2230 // Therefore write a note at the beginning of the document
2231 if (is_nonCJKJapanese) {
2232 context.check_layout(os);
2233 begin_inset(os, "Note Note\n");
2234 os << "status open\n\\begin_layout Plain Layout\n"
2235 << "\\series bold\n"
2236 << "Important information:\n"
2237 << "\\end_layout\n\n"
2238 << "\\begin_layout Plain Layout\n"
2239 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2240 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2241 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2242 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2243 << " and specify the encoding using the -e command-line switch.\n"
2244 << " In addition, you might want to double check that the desired output encoding\n"
2245 << " is correctly selected in Document > Settings > Language.\n"
2246 << "\\end_layout\n";
2248 is_nonCJKJapanese = false;
2252 debugToken(cerr, t, flags);
2255 if (flags & FLAG_ITEM) {
2256 if (t.cat() == catSpace)
2259 flags &= ~FLAG_ITEM;
2260 if (t.cat() == catBegin) {
2261 // skip the brace and collect everything to the next matching
2263 flags |= FLAG_BRACE_LAST;
2267 // handle only this single token, leave the loop if done
2268 flags |= FLAG_LEAVE;
2271 if (t.cat() != catEscape && t.character() == ']' &&
2272 (flags & FLAG_BRACK_LAST))
2274 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2277 // If there is anything between \end{env} and \begin{env} we
2278 // don't need to output a separator.
2279 if (t.cat() != catSpace && t.cat() != catNewline &&
2280 t.asInput() != "\\begin")
2286 if (t.cat() == catMath) {
2287 // we are inside some text mode thingy, so opening new math is allowed
2288 context.check_layout(os);
2289 begin_inset(os, "Formula ");
2290 Token const & n = p.get_token();
2291 bool const display(n.cat() == catMath && outer);
2293 // TeX's $$...$$ syntax for displayed math
2295 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2297 p.get_token(); // skip the second '$' token
2299 // simple $...$ stuff
2302 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2307 // Prevent the conversion of a line break to a
2308 // space (bug 7668). This does not change the
2309 // output, but looks ugly in LyX.
2310 eat_whitespace(p, os, context, false);
2314 else if (t.cat() == catSuper || t.cat() == catSub)
2315 cerr << "catcode " << t << " illegal in text mode\n";
2317 // Basic support for english quotes. This should be
2318 // extended to other quotes, but is not so easy (a
2319 // left english quote is the same as a right german
2321 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2322 context.check_layout(os);
2323 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() == ">" && p.next_token().asInput() == ">") {
2339 context.check_layout(os);
2340 begin_inset(os, "Quotes ");
2347 else if (t.asInput() == "<"
2348 && p.next_token().asInput() == "<" && noweb_mode) {
2350 parse_noweb(p, os, context);
2353 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2354 context.check_layout(os);
2355 begin_inset(os, "Quotes ");
2362 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2363 check_space(p, os, context);
2365 else if (t.character() == '[' && noweb_mode &&
2366 p.next_token().character() == '[') {
2367 // These can contain underscores
2369 string const s = p.getFullOpt() + ']';
2370 if (p.next_token().character() == ']')
2373 cerr << "Warning: Inserting missing ']' in '"
2374 << s << "'." << endl;
2375 handle_ert(os, s, context);
2378 else if (t.cat() == catLetter) {
2379 context.check_layout(os);
2380 // Workaround for bug 4752.
2381 // FIXME: This whole code block needs to be removed
2382 // when the bug is fixed and tex2lyx produces
2383 // the updated file format.
2384 // The replacement algorithm in LyX is so stupid that
2385 // it even translates a phrase if it is part of a word.
2386 bool handled = false;
2387 for (int const * l = known_phrase_lengths; *l; ++l) {
2388 string phrase = t.cs();
2389 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2390 phrase += p.get_token().cs();
2391 if (is_known(phrase, known_coded_phrases)) {
2392 handle_ert(os, phrase, context);
2396 for (size_t i = 1; i < phrase.length(); ++i)
2404 else if (t.cat() == catOther ||
2405 t.cat() == catAlign ||
2406 t.cat() == catParameter) {
2407 // This translates "&" to "\\&" which may be wrong...
2408 context.check_layout(os);
2412 else if (p.isParagraph()) {
2413 if (context.new_layout_allowed)
2414 context.new_paragraph(os);
2416 handle_ert(os, "\\par ", context);
2417 eat_whitespace(p, os, context, true);
2420 else if (t.cat() == catActive) {
2421 context.check_layout(os);
2422 if (t.character() == '~') {
2423 if (context.layout->free_spacing)
2426 begin_inset(os, "space ~\n");
2433 else if (t.cat() == catBegin) {
2434 Token const next = p.next_token();
2435 Token const end = p.next_next_token();
2436 if (next.cat() == catEnd) {
2438 Token const prev = p.prev_token();
2440 if (p.next_token().character() == '`' ||
2441 (prev.character() == '-' &&
2442 p.next_token().character() == '-'))
2443 ; // ignore it in {}`` or -{}-
2445 handle_ert(os, "{}", context);
2446 } else if (next.cat() == catEscape &&
2447 is_known(next.cs(), known_quotes) &&
2448 end.cat() == catEnd) {
2449 // Something like {\textquoteright} (e.g.
2450 // from writer2latex). LyX writes
2451 // \textquoteright{}, so we may skip the
2452 // braces here for better readability.
2453 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2456 context.check_layout(os);
2457 // special handling of font attribute changes
2458 Token const prev = p.prev_token();
2459 TeXFont const oldFont = context.font;
2460 if (next.character() == '[' ||
2461 next.character() == ']' ||
2462 next.character() == '*') {
2464 if (p.next_token().cat() == catEnd) {
2469 handle_ert(os, "{", context);
2470 parse_text_snippet(p, os,
2473 handle_ert(os, "}", context);
2475 } else if (! context.new_layout_allowed) {
2476 handle_ert(os, "{", context);
2477 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2479 handle_ert(os, "}", context);
2480 } else if (is_known(next.cs(), known_sizes)) {
2481 // next will change the size, so we must
2483 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2485 if (!context.atParagraphStart())
2487 << context.font.size << "\n";
2488 } else if (is_known(next.cs(), known_font_families)) {
2489 // next will change the font family, so we
2490 // must reset it here
2491 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2493 if (!context.atParagraphStart())
2495 << context.font.family << "\n";
2496 } else if (is_known(next.cs(), known_font_series)) {
2497 // next will change the font series, so we
2498 // must reset it here
2499 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2501 if (!context.atParagraphStart())
2503 << context.font.series << "\n";
2504 } else if (is_known(next.cs(), known_font_shapes)) {
2505 // next will change the font shape, so we
2506 // must reset it here
2507 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2509 if (!context.atParagraphStart())
2511 << context.font.shape << "\n";
2512 } else if (is_known(next.cs(), known_old_font_families) ||
2513 is_known(next.cs(), known_old_font_series) ||
2514 is_known(next.cs(), known_old_font_shapes)) {
2515 // next will change the font family, series
2516 // and shape, so we must reset it here
2517 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2519 if (!context.atParagraphStart())
2521 << context.font.family
2523 << context.font.series
2525 << context.font.shape << "\n";
2527 handle_ert(os, "{", context);
2528 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2530 handle_ert(os, "}", context);
2535 else if (t.cat() == catEnd) {
2536 if (flags & FLAG_BRACE_LAST) {
2539 cerr << "stray '}' in text\n";
2540 handle_ert(os, "}", context);
2543 else if (t.cat() == catComment)
2544 parse_comment(p, os, t, context);
2547 // control sequences
2550 else if (t.cs() == "(") {
2551 context.check_layout(os);
2552 begin_inset(os, "Formula");
2554 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2559 else if (t.cs() == "[") {
2560 context.check_layout(os);
2561 begin_inset(os, "Formula");
2563 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2566 // Prevent the conversion of a line break to a space
2567 // (bug 7668). This does not change the output, but
2568 // looks ugly in LyX.
2569 eat_whitespace(p, os, context, false);
2572 else if (t.cs() == "begin")
2573 parse_environment(p, os, outer, last_env,
2576 else if (t.cs() == "end") {
2577 if (flags & FLAG_END) {
2578 // eat environment name
2579 string const name = p.getArg('{', '}');
2580 if (name != active_environment())
2581 cerr << "\\end{" + name + "} does not match \\begin{"
2582 + active_environment() + "}\n";
2585 p.error("found 'end' unexpectedly");
2588 else if (t.cs() == "item") {
2590 bool const optarg = p.hasOpt();
2592 // FIXME: This swallows comments, but we cannot use
2593 // eat_whitespace() since we must not output
2594 // anything before the item.
2595 p.skip_spaces(true);
2596 s = p.verbatimOption();
2598 p.skip_spaces(false);
2600 context.check_layout(os);
2601 if (context.has_item) {
2602 // An item in an unknown list-like environment
2603 // FIXME: Do this in check_layout()!
2604 context.has_item = false;
2606 handle_ert(os, "\\item", context);
2608 handle_ert(os, "\\item ", context);
2611 if (context.layout->labeltype != LABEL_MANUAL) {
2612 // LyX does not support \item[\mybullet]
2613 // in itemize environments
2615 os << parse_text_snippet(p2,
2616 FLAG_BRACK_LAST, outer, context);
2617 } else if (!s.empty()) {
2618 // LyX adds braces around the argument,
2619 // so we need to remove them here.
2620 if (s.size() > 2 && s[0] == '{' &&
2621 s[s.size()-1] == '}')
2622 s = s.substr(1, s.size()-2);
2623 // If the argument contains a space we
2624 // must put it into ERT: Otherwise LyX
2625 // would misinterpret the space as
2626 // item delimiter (bug 7663)
2627 if (contains(s, ' ')) {
2628 handle_ert(os, s, context);
2631 os << parse_text_snippet(p2,
2635 // The space is needed to separate the
2636 // item from the rest of the sentence.
2638 eat_whitespace(p, os, context, false);
2643 else if (t.cs() == "bibitem") {
2645 context.check_layout(os);
2646 eat_whitespace(p, os, context, false);
2647 string label = convert_command_inset_arg(p.verbatimOption());
2648 string key = convert_command_inset_arg(p.verbatim_item());
2649 if (contains(label, '\\') || contains(key, '\\')) {
2650 // LyX can't handle LaTeX commands in labels or keys
2651 handle_ert(os, t.asInput() + '[' + label +
2652 "]{" + p.verbatim_item() + '}',
2655 begin_command_inset(os, "bibitem", "bibitem");
2656 os << "label \"" << label << "\"\n"
2657 "key \"" << key << "\"\n";
2662 else if (is_macro(p)) {
2663 // catch the case of \def\inputGnumericTable
2665 if (t.cs() == "def") {
2666 Token second = p.next_token();
2667 if (second.cs() == "inputGnumericTable") {
2671 Token third = p.get_token();
2673 if (third.cs() == "input") {
2677 string name = normalize_filename(p.verbatim_item());
2678 string const path = getMasterFilePath(true);
2679 // We want to preserve relative / absolute filenames,
2680 // therefore path is only used for testing
2681 // The file extension is in every case ".tex".
2682 // So we need to remove this extension and check for
2683 // the original one.
2684 name = removeExtension(name);
2685 if (!makeAbsPath(name, path).exists()) {
2686 char const * const Gnumeric_formats[] = {"gnumeric",
2688 string const Gnumeric_name =
2689 find_file(name, path, Gnumeric_formats);
2690 if (!Gnumeric_name.empty())
2691 name = Gnumeric_name;
2693 FileName const absname = makeAbsPath(name, path);
2694 if (absname.exists()) {
2695 fix_child_filename(name);
2696 copy_file(absname, name);
2698 cerr << "Warning: Could not find file '"
2699 << name << "'." << endl;
2700 context.check_layout(os);
2701 begin_inset(os, "External\n\ttemplate ");
2702 os << "GnumericSpreadsheet\n\tfilename "
2705 context.check_layout(os);
2707 // register the packages that are automatically loaded
2708 // by the Gnumeric template
2709 registerExternalTemplatePackages("GnumericSpreadsheet");
2714 parse_macro(p, os, context);
2717 else if (t.cs() == "noindent") {
2719 context.add_par_extra_stuff("\\noindent\n");
2722 else if (t.cs() == "appendix") {
2723 context.add_par_extra_stuff("\\start_of_appendix\n");
2724 // We need to start a new paragraph. Otherwise the
2725 // appendix in 'bla\appendix\chapter{' would start
2727 context.new_paragraph(os);
2728 // We need to make sure that the paragraph is
2729 // generated even if it is empty. Otherwise the
2730 // appendix in '\par\appendix\par\chapter{' would
2732 context.check_layout(os);
2733 // FIXME: This is a hack to prevent paragraph
2734 // deletion if it is empty. Handle this better!
2736 "%dummy comment inserted by tex2lyx to "
2737 "ensure that this paragraph is not empty",
2739 // Both measures above may generate an additional
2740 // empty paragraph, but that does not hurt, because
2741 // whitespace does not matter here.
2742 eat_whitespace(p, os, context, true);
2745 // Must catch empty dates before findLayout is called below
2746 else if (t.cs() == "date") {
2747 eat_whitespace(p, os, context, false);
2749 string const date = p.verbatim_item();
2752 preamble.suppressDate(true);
2755 preamble.suppressDate(false);
2756 if (context.new_layout_allowed &&
2757 (newlayout = findLayout(context.textclass,
2760 output_command_layout(os, p, outer,
2761 context, newlayout);
2762 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2763 if (!preamble.titleLayoutFound())
2764 preamble.titleLayoutFound(newlayout->intitle);
2765 set<string> const & req = newlayout->requires();
2766 set<string>::const_iterator it = req.begin();
2767 set<string>::const_iterator en = req.end();
2768 for (; it != en; ++it)
2769 preamble.registerAutomaticallyLoadedPackage(*it);
2772 "\\date{" + p.verbatim_item() + '}',
2777 // Starred section headings
2778 // Must attempt to parse "Section*" before "Section".
2779 else if ((p.next_token().asInput() == "*") &&
2780 context.new_layout_allowed &&
2781 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2784 output_command_layout(os, p, outer, context, newlayout);
2786 if (!preamble.titleLayoutFound())
2787 preamble.titleLayoutFound(newlayout->intitle);
2788 set<string> const & req = newlayout->requires();
2789 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2790 preamble.registerAutomaticallyLoadedPackage(*it);
2793 // Section headings and the like
2794 else if (context.new_layout_allowed &&
2795 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2797 output_command_layout(os, p, outer, context, newlayout);
2799 if (!preamble.titleLayoutFound())
2800 preamble.titleLayoutFound(newlayout->intitle);
2801 set<string> const & req = newlayout->requires();
2802 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2803 preamble.registerAutomaticallyLoadedPackage(*it);
2806 else if (t.cs() == "caption") {
2808 context.check_layout(os);
2810 begin_inset(os, "Caption Standard\n");
2811 Context newcontext(true, context.textclass, 0, 0, context.font);
2812 newcontext.check_layout(os);
2813 // FIXME InsetArgument is now properly implemented in InsetLayout
2814 // (for captions, but also for others)
2815 if (p.next_token().cat() != catEscape &&
2816 p.next_token().character() == '[') {
2817 p.get_token(); // eat '['
2818 begin_inset(os, "Argument 1\n");
2819 os << "status collapsed\n";
2820 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2822 eat_whitespace(p, os, context, false);
2824 parse_text(p, os, FLAG_ITEM, outer, context);
2825 context.check_end_layout(os);
2826 // We don't need really a new paragraph, but
2827 // we must make sure that the next item gets a \begin_layout.
2828 context.new_paragraph(os);
2831 newcontext.check_end_layout(os);
2834 else if (t.cs() == "subfloat") {
2835 // the syntax is \subfloat[caption]{content}
2836 // if it is a table of figure depends on the surrounding float
2837 bool has_caption = false;
2839 // do nothing if there is no outer float
2840 if (!float_type.empty()) {
2841 context.check_layout(os);
2843 begin_inset(os, "Float " + float_type + "\n");
2845 << "\nsideways false"
2846 << "\nstatus collapsed\n\n";
2849 if (p.next_token().cat() != catEscape &&
2850 p.next_token().character() == '[') {
2851 p.get_token(); // eat '['
2852 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2856 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2857 // the caption comes always as the last
2859 // we must make sure that the caption gets a \begin_layout
2860 os << "\n\\begin_layout Plain Layout";
2862 begin_inset(os, "Caption Standard\n");
2863 Context newcontext(true, context.textclass,
2864 0, 0, context.font);
2865 newcontext.check_layout(os);
2866 os << caption << "\n";
2867 newcontext.check_end_layout(os);
2868 // We don't need really a new paragraph, but
2869 // we must make sure that the next item gets a \begin_layout.
2870 //newcontext.new_paragraph(os);
2874 // We don't need really a new paragraph, but
2875 // we must make sure that the next item gets a \begin_layout.
2877 context.new_paragraph(os);
2880 context.check_end_layout(os);
2881 // close the layout we opened
2883 os << "\n\\end_layout\n";
2885 // if the float type is not supported or there is no surrounding float
2888 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2889 handle_ert(os, t.asInput() + '[' + opt_arg +
2890 "]{" + p.verbatim_item() + '}', context);
2892 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2896 else if (t.cs() == "includegraphics") {
2897 bool const clip = p.next_token().asInput() == "*";
2900 string const arg = p.getArg('[', ']');
2901 map<string, string> opts;
2902 vector<string> keys;
2903 split_map(arg, opts, keys);
2905 opts["clip"] = string();
2906 string name = normalize_filename(p.verbatim_item());
2908 string const path = getMasterFilePath(true);
2909 // We want to preserve relative / absolute filenames,
2910 // therefore path is only used for testing
2911 if (!makeAbsPath(name, path).exists()) {
2912 // The file extension is probably missing.
2913 // Now try to find it out.
2914 string const dvips_name =
2915 find_file(name, path,
2916 known_dvips_graphics_formats);
2917 string const pdftex_name =
2918 find_file(name, path,
2919 known_pdftex_graphics_formats);
2920 if (!dvips_name.empty()) {
2921 if (!pdftex_name.empty()) {
2922 cerr << "This file contains the "
2924 "\"\\includegraphics{"
2926 "However, files\n\""
2927 << dvips_name << "\" and\n\""
2928 << pdftex_name << "\"\n"
2929 "both exist, so I had to make a "
2930 "choice and took the first one.\n"
2931 "Please move the unwanted one "
2932 "someplace else and try again\n"
2933 "if my choice was wrong."
2937 } else if (!pdftex_name.empty()) {
2943 FileName const absname = makeAbsPath(name, path);
2944 if (absname.exists()) {
2945 fix_child_filename(name);
2946 copy_file(absname, name);
2948 cerr << "Warning: Could not find graphics file '"
2949 << name << "'." << endl;
2951 context.check_layout(os);
2952 begin_inset(os, "Graphics ");
2953 os << "\n\tfilename " << name << '\n';
2954 if (opts.find("width") != opts.end())
2956 << translate_len(opts["width"]) << '\n';
2957 if (opts.find("height") != opts.end())
2959 << translate_len(opts["height"]) << '\n';
2960 if (opts.find("scale") != opts.end()) {
2961 istringstream iss(opts["scale"]);
2965 os << "\tscale " << val << '\n';
2967 if (opts.find("angle") != opts.end()) {
2968 os << "\trotateAngle "
2969 << opts["angle"] << '\n';
2970 vector<string>::const_iterator a =
2971 find(keys.begin(), keys.end(), "angle");
2972 vector<string>::const_iterator s =
2973 find(keys.begin(), keys.end(), "width");
2974 if (s == keys.end())
2975 s = find(keys.begin(), keys.end(), "height");
2976 if (s == keys.end())
2977 s = find(keys.begin(), keys.end(), "scale");
2978 if (s != keys.end() && distance(s, a) > 0)
2979 os << "\tscaleBeforeRotation\n";
2981 if (opts.find("origin") != opts.end()) {
2983 string const opt = opts["origin"];
2984 if (opt.find('l') != string::npos) ss << "left";
2985 if (opt.find('r') != string::npos) ss << "right";
2986 if (opt.find('c') != string::npos) ss << "center";
2987 if (opt.find('t') != string::npos) ss << "Top";
2988 if (opt.find('b') != string::npos) ss << "Bottom";
2989 if (opt.find('B') != string::npos) ss << "Baseline";
2990 if (!ss.str().empty())
2991 os << "\trotateOrigin " << ss.str() << '\n';
2993 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2995 if (opts.find("keepaspectratio") != opts.end())
2996 os << "\tkeepAspectRatio\n";
2997 if (opts.find("clip") != opts.end())
2999 if (opts.find("draft") != opts.end())
3001 if (opts.find("bb") != opts.end())
3002 os << "\tBoundingBox "
3003 << opts["bb"] << '\n';
3004 int numberOfbbOptions = 0;
3005 if (opts.find("bbllx") != opts.end())
3006 numberOfbbOptions++;
3007 if (opts.find("bblly") != opts.end())
3008 numberOfbbOptions++;
3009 if (opts.find("bburx") != opts.end())
3010 numberOfbbOptions++;
3011 if (opts.find("bbury") != opts.end())
3012 numberOfbbOptions++;
3013 if (numberOfbbOptions == 4)
3014 os << "\tBoundingBox "
3015 << opts["bbllx"] << " " << opts["bblly"] << " "
3016 << opts["bburx"] << " " << opts["bbury"] << '\n';
3017 else if (numberOfbbOptions > 0)
3018 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3019 numberOfbbOptions = 0;
3020 if (opts.find("natwidth") != opts.end())
3021 numberOfbbOptions++;
3022 if (opts.find("natheight") != opts.end())
3023 numberOfbbOptions++;
3024 if (numberOfbbOptions == 2)
3025 os << "\tBoundingBox 0bp 0bp "
3026 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3027 else if (numberOfbbOptions > 0)
3028 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3029 ostringstream special;
3030 if (opts.find("hiresbb") != opts.end())
3031 special << "hiresbb,";
3032 if (opts.find("trim") != opts.end())
3034 if (opts.find("viewport") != opts.end())
3035 special << "viewport=" << opts["viewport"] << ',';
3036 if (opts.find("totalheight") != opts.end())
3037 special << "totalheight=" << opts["totalheight"] << ',';
3038 if (opts.find("type") != opts.end())
3039 special << "type=" << opts["type"] << ',';
3040 if (opts.find("ext") != opts.end())
3041 special << "ext=" << opts["ext"] << ',';
3042 if (opts.find("read") != opts.end())
3043 special << "read=" << opts["read"] << ',';
3044 if (opts.find("command") != opts.end())
3045 special << "command=" << opts["command"] << ',';
3046 string s_special = special.str();
3047 if (!s_special.empty()) {
3048 // We had special arguments. Remove the trailing ','.
3049 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3051 // TODO: Handle the unknown settings better.
3052 // Warn about invalid options.
3053 // Check whether some option was given twice.
3055 preamble.registerAutomaticallyLoadedPackage("graphicx");
3058 else if (t.cs() == "footnote" ||
3059 (t.cs() == "thanks" && context.layout->intitle)) {
3061 context.check_layout(os);
3062 begin_inset(os, "Foot\n");
3063 os << "status collapsed\n\n";
3064 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3068 else if (t.cs() == "marginpar") {
3070 context.check_layout(os);
3071 begin_inset(os, "Marginal\n");
3072 os << "status collapsed\n\n";
3073 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3077 else if (t.cs() == "lstinline") {
3079 parse_listings(p, os, context, true);
3082 else if (t.cs() == "ensuremath") {
3084 context.check_layout(os);
3085 string const s = p.verbatim_item();
3086 //FIXME: this never triggers in UTF8
3087 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3090 handle_ert(os, "\\ensuremath{" + s + "}",
3094 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3095 if (preamble.titleLayoutFound()) {
3097 skip_spaces_braces(p);
3099 handle_ert(os, t.asInput(), context);
3102 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3103 context.check_layout(os);
3104 begin_command_inset(os, "toc", t.cs());
3106 skip_spaces_braces(p);
3107 if (t.cs() == "lstlistoflistings")
3108 preamble.registerAutomaticallyLoadedPackage("listings");
3111 else if (t.cs() == "listoffigures") {
3112 context.check_layout(os);
3113 begin_inset(os, "FloatList figure\n");
3115 skip_spaces_braces(p);
3118 else if (t.cs() == "listoftables") {
3119 context.check_layout(os);
3120 begin_inset(os, "FloatList table\n");
3122 skip_spaces_braces(p);
3125 else if (t.cs() == "listof") {
3126 p.skip_spaces(true);
3127 string const name = p.get_token().cs();
3128 if (context.textclass.floats().typeExist(name)) {
3129 context.check_layout(os);
3130 begin_inset(os, "FloatList ");
3133 p.get_token(); // swallow second arg
3135 handle_ert(os, "\\listof{" + name + "}", context);
3138 else if ((where = is_known(t.cs(), known_text_font_families)))
3139 parse_text_attributes(p, os, FLAG_ITEM, outer,
3140 context, "\\family", context.font.family,
3141 known_coded_font_families[where - known_text_font_families]);
3143 else if ((where = is_known(t.cs(), known_text_font_series)))
3144 parse_text_attributes(p, os, FLAG_ITEM, outer,
3145 context, "\\series", context.font.series,
3146 known_coded_font_series[where - known_text_font_series]);
3148 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3149 parse_text_attributes(p, os, FLAG_ITEM, outer,
3150 context, "\\shape", context.font.shape,
3151 known_coded_font_shapes[where - known_text_font_shapes]);
3153 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3154 context.check_layout(os);
3155 TeXFont oldFont = context.font;
3156 context.font.init();
3157 context.font.size = oldFont.size;
3158 os << "\n\\family " << context.font.family << "\n";
3159 os << "\n\\series " << context.font.series << "\n";
3160 os << "\n\\shape " << context.font.shape << "\n";
3161 if (t.cs() == "textnormal") {
3162 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3163 output_font_change(os, context.font, oldFont);
3164 context.font = oldFont;
3166 eat_whitespace(p, os, context, false);
3169 else if (t.cs() == "textcolor") {
3170 // scheme is \textcolor{color name}{text}
3171 string const color = p.verbatim_item();
3172 // we only support the predefined colors of the color package
3173 if (color == "black" || color == "blue" || color == "cyan"
3174 || color == "green" || color == "magenta" || color == "red"
3175 || color == "white" || color == "yellow") {
3176 context.check_layout(os);
3177 os << "\n\\color " << color << "\n";
3178 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3179 context.check_layout(os);
3180 os << "\n\\color inherit\n";
3181 preamble.registerAutomaticallyLoadedPackage("color");
3183 // for custom defined colors
3184 handle_ert(os, t.asInput() + "{" + color + "}", context);
3187 else if (t.cs() == "underbar" || t.cs() == "uline") {
3188 // \underbar is not 100% correct (LyX outputs \uline
3189 // of ulem.sty). The difference is that \ulem allows
3190 // line breaks, and \underbar does not.
3191 // Do NOT handle \underline.
3192 // \underbar cuts through y, g, q, p etc.,
3193 // \underline does not.
3194 context.check_layout(os);
3195 os << "\n\\bar under\n";
3196 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3197 context.check_layout(os);
3198 os << "\n\\bar default\n";
3199 preamble.registerAutomaticallyLoadedPackage("ulem");
3202 else if (t.cs() == "sout") {
3203 context.check_layout(os);
3204 os << "\n\\strikeout on\n";
3205 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3206 context.check_layout(os);
3207 os << "\n\\strikeout default\n";
3208 preamble.registerAutomaticallyLoadedPackage("ulem");
3211 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3212 t.cs() == "emph" || t.cs() == "noun") {
3213 context.check_layout(os);
3214 os << "\n\\" << t.cs() << " on\n";
3215 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3216 context.check_layout(os);
3217 os << "\n\\" << t.cs() << " default\n";
3218 if (t.cs() == "uuline" || t.cs() == "uwave")
3219 preamble.registerAutomaticallyLoadedPackage("ulem");
3222 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3223 context.check_layout(os);
3224 string name = p.getArg('{', '}');
3225 string localtime = p.getArg('{', '}');
3226 preamble.registerAuthor(name);
3227 Author const & author = preamble.getAuthor(name);
3228 // from_asctime_utc() will fail if LyX decides to output the
3229 // time in the text language.
3230 time_t ptime = from_asctime_utc(localtime);
3231 if (ptime == static_cast<time_t>(-1)) {
3232 cerr << "Warning: Could not parse time `" << localtime
3233 << "´ for change tracking, using current time instead.\n";
3234 ptime = current_time();
3236 if (t.cs() == "lyxadded")
3237 os << "\n\\change_inserted ";
3239 os << "\n\\change_deleted ";
3240 os << author.bufferId() << ' ' << ptime << '\n';
3241 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3242 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3243 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3244 LaTeXPackages::isAvailable("xcolor");
3245 // No need to test for luatex, since luatex comes in
3246 // two flavours (dvi and pdf), like latex, and those
3247 // are detected by pdflatex.
3248 if (pdflatex || xetex) {
3250 preamble.registerAutomaticallyLoadedPackage("ulem");
3251 preamble.registerAutomaticallyLoadedPackage("xcolor");
3252 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3256 preamble.registerAutomaticallyLoadedPackage("dvipost");
3257 } else if (xcolorulem) {
3258 preamble.registerAutomaticallyLoadedPackage("ulem");
3259 preamble.registerAutomaticallyLoadedPackage("xcolor");
3264 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3265 t.cs() == "vphantom") {
3266 context.check_layout(os);
3267 if (t.cs() == "phantom")
3268 begin_inset(os, "Phantom Phantom\n");
3269 if (t.cs() == "hphantom")
3270 begin_inset(os, "Phantom HPhantom\n");
3271 if (t.cs() == "vphantom")
3272 begin_inset(os, "Phantom VPhantom\n");
3273 os << "status open\n";
3274 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3279 else if (t.cs() == "href") {
3280 context.check_layout(os);
3281 string target = convert_command_inset_arg(p.verbatim_item());
3282 string name = convert_command_inset_arg(p.verbatim_item());
3284 size_t i = target.find(':');
3285 if (i != string::npos) {
3286 type = target.substr(0, i + 1);
3287 if (type == "mailto:" || type == "file:")
3288 target = target.substr(i + 1);
3289 // handle the case that name is equal to target, except of "http://"
3290 else if (target.substr(i + 3) == name && type == "http:")
3293 begin_command_inset(os, "href", "href");
3295 os << "name \"" << name << "\"\n";
3296 os << "target \"" << target << "\"\n";
3297 if (type == "mailto:" || type == "file:")
3298 os << "type \"" << type << "\"\n";
3300 skip_spaces_braces(p);
3303 else if (t.cs() == "lyxline") {
3304 // swallow size argument (it is not used anyway)
3306 if (!context.atParagraphStart()) {
3307 // so our line is in the middle of a paragraph
3308 // we need to add a new line, lest this line
3309 // follow the other content on that line and
3310 // run off the side of the page
3311 // FIXME: This may create an empty paragraph,
3312 // but without that it would not be
3313 // possible to set noindent below.
3314 // Fortunately LaTeX does not care
3315 // about the empty paragraph.
3316 context.new_paragraph(os);
3318 if (preamble.indentParagraphs()) {
3319 // we need to unindent, lest the line be too long
3320 context.add_par_extra_stuff("\\noindent\n");
3322 context.check_layout(os);
3323 begin_command_inset(os, "line", "rule");
3324 os << "offset \"0.5ex\"\n"
3325 "width \"100line%\"\n"
3330 else if (t.cs() == "rule") {
3331 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3332 string const width = p.getArg('{', '}');
3333 string const thickness = p.getArg('{', '}');
3334 context.check_layout(os);
3335 begin_command_inset(os, "line", "rule");
3336 if (!offset.empty())
3337 os << "offset \"" << translate_len(offset) << "\"\n";
3338 os << "width \"" << translate_len(width) << "\"\n"
3339 "height \"" << translate_len(thickness) << "\"\n";
3343 else if (is_known(t.cs(), known_phrases) ||
3344 (t.cs() == "protect" &&
3345 p.next_token().cat() == catEscape &&
3346 is_known(p.next_token().cs(), known_phrases))) {
3347 // LyX sometimes puts a \protect in front, so we have to ignore it
3348 // FIXME: This needs to be changed when bug 4752 is fixed.
3350 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3352 context.check_layout(os);
3353 os << known_coded_phrases[where - known_phrases];
3354 skip_spaces_braces(p);
3357 else if ((where = is_known(t.cs(), known_ref_commands))) {
3358 // \eqref can also occur if refstyle is used
3359 if (t.cs() == "eqref" && preamble.refstyle() == "1") {
3360 context.check_layout(os);
3361 begin_command_inset(os, "ref", "formatted");
3362 os << "reference \"eq:"
3363 << convert_command_inset_arg(p.verbatim_item())
3366 preamble.registerAutomaticallyLoadedPackage("refstyle");
3368 string const opt = p.getOpt();
3370 context.check_layout(os);
3371 begin_command_inset(os, "ref",
3372 known_coded_ref_commands[where - known_ref_commands]);
3373 os << "reference \""
3374 << convert_command_inset_arg(p.verbatim_item())
3377 if (t.cs() == "vref" || t.cs() == "vpageref")
3378 preamble.registerAutomaticallyLoadedPackage("varioref");
3380 // LyX does not yet support optional arguments of ref commands
3381 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3382 p.verbatim_item() + "}", context);
3387 else if ((where = is_known(t.cs(), known_refstyle_commands))) {
3388 context.check_layout(os);
3389 // \eqref can also occur if refstyle is not used
3390 // this case is already handled in the previous else if
3391 begin_command_inset(os, "ref", "formatted");
3392 os << "reference \"";
3393 os << known_refstyle_prefixes[where - known_refstyle_commands]
3395 os << convert_command_inset_arg(p.verbatim_item())
3398 preamble.registerAutomaticallyLoadedPackage("refstyle");
3401 else if (use_natbib &&
3402 is_known(t.cs(), known_natbib_commands) &&
3403 ((t.cs() != "citefullauthor" &&
3404 t.cs() != "citeyear" &&
3405 t.cs() != "citeyearpar") ||
3406 p.next_token().asInput() != "*")) {
3407 context.check_layout(os);
3408 string command = t.cs();
3409 if (p.next_token().asInput() == "*") {
3413 if (command == "citefullauthor")
3414 // alternative name for "\\citeauthor*"
3415 command = "citeauthor*";
3417 // text before the citation
3419 // text after the citation
3421 get_cite_arguments(p, true, before, after);
3423 if (command == "cite") {
3424 // \cite without optional argument means
3425 // \citet, \cite with at least one optional
3426 // argument means \citep.
3427 if (before.empty() && after.empty())
3432 if (before.empty() && after == "[]")
3433 // avoid \citet[]{a}
3435 else if (before == "[]" && after == "[]") {
3436 // avoid \citet[][]{a}
3440 // remove the brackets around after and before
3441 if (!after.empty()) {
3443 after.erase(after.length() - 1, 1);
3444 after = convert_command_inset_arg(after);
3446 if (!before.empty()) {
3448 before.erase(before.length() - 1, 1);
3449 before = convert_command_inset_arg(before);
3451 begin_command_inset(os, "citation", command);
3452 os << "after " << '"' << after << '"' << "\n";
3453 os << "before " << '"' << before << '"' << "\n";
3455 << convert_command_inset_arg(p.verbatim_item())
3458 // Need to set the cite engine if natbib is loaded by
3459 // the document class directly
3460 if (preamble.citeEngine() == "basic")
3461 preamble.citeEngine("natbib");
3464 else if (use_jurabib &&
3465 is_known(t.cs(), known_jurabib_commands) &&
3466 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3467 context.check_layout(os);
3468 string command = t.cs();
3469 if (p.next_token().asInput() == "*") {
3473 char argumentOrder = '\0';
3474 vector<string> const options =
3475 preamble.getPackageOptions("jurabib");
3476 if (find(options.begin(), options.end(),
3477 "natbiborder") != options.end())
3478 argumentOrder = 'n';
3479 else if (find(options.begin(), options.end(),
3480 "jurabiborder") != options.end())
3481 argumentOrder = 'j';
3483 // text before the citation
3485 // text after the citation
3487 get_cite_arguments(p, argumentOrder != 'j', before, after);
3489 string const citation = p.verbatim_item();
3490 if (!before.empty() && argumentOrder == '\0') {
3491 cerr << "Warning: Assuming argument order "
3492 "of jurabib version 0.6 for\n'"
3493 << command << before << after << '{'
3494 << citation << "}'.\n"
3495 "Add 'jurabiborder' to the jurabib "
3496 "package options if you used an\n"
3497 "earlier jurabib version." << endl;
3499 if (!after.empty()) {
3501 after.erase(after.length() - 1, 1);
3503 if (!before.empty()) {
3505 before.erase(before.length() - 1, 1);
3507 begin_command_inset(os, "citation", command);
3508 os << "after " << '"' << after << '"' << "\n";
3509 os << "before " << '"' << before << '"' << "\n";
3510 os << "key " << '"' << citation << '"' << "\n";
3512 // Need to set the cite engine if jurabib is loaded by
3513 // the document class directly
3514 if (preamble.citeEngine() == "basic")
3515 preamble.citeEngine("jurabib");
3518 else if (t.cs() == "cite"
3519 || t.cs() == "nocite") {
3520 context.check_layout(os);
3521 string after = convert_command_inset_arg(p.getArg('[', ']'));
3522 string key = convert_command_inset_arg(p.verbatim_item());
3523 // store the case that it is "\nocite{*}" to use it later for
3526 begin_command_inset(os, "citation", t.cs());
3527 os << "after " << '"' << after << '"' << "\n";
3528 os << "key " << '"' << key << '"' << "\n";
3530 } else if (t.cs() == "nocite")
3534 else if (t.cs() == "index" ||
3535 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3536 context.check_layout(os);
3537 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3538 p.getArg('[', ']') : "";
3539 string const kind = arg.empty() ? "idx" : arg;
3540 begin_inset(os, "Index ");
3541 os << kind << "\nstatus collapsed\n";
3542 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3545 preamble.registerAutomaticallyLoadedPackage("splitidx");
3548 else if (t.cs() == "nomenclature") {
3549 context.check_layout(os);
3550 begin_command_inset(os, "nomenclature", "nomenclature");
3551 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3552 if (!prefix.empty())
3553 os << "prefix " << '"' << prefix << '"' << "\n";
3554 os << "symbol " << '"'
3555 << convert_command_inset_arg(p.verbatim_item());
3556 os << "\"\ndescription \""
3557 << convert_command_inset_arg(p.verbatim_item())
3560 preamble.registerAutomaticallyLoadedPackage("nomencl");
3563 else if (t.cs() == "label") {
3564 context.check_layout(os);
3565 begin_command_inset(os, "label", "label");
3567 << convert_command_inset_arg(p.verbatim_item())
3572 else if (t.cs() == "printindex") {
3573 context.check_layout(os);
3574 begin_command_inset(os, "index_print", "printindex");
3575 os << "type \"idx\"\n";
3577 skip_spaces_braces(p);
3578 preamble.registerAutomaticallyLoadedPackage("makeidx");
3579 if (preamble.use_indices() == "true")
3580 preamble.registerAutomaticallyLoadedPackage("splitidx");
3583 else if (t.cs() == "printnomenclature") {
3585 string width_type = "";
3586 context.check_layout(os);
3587 begin_command_inset(os, "nomencl_print", "printnomenclature");
3588 // case of a custom width
3590 width = p.getArg('[', ']');
3591 width = translate_len(width);
3592 width_type = "custom";
3594 // case of no custom width
3595 // the case of no custom width but the width set
3596 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3597 // because the user could have set anything, not only the width
3598 // of the longest label (which would be width_type = "auto")
3599 string label = convert_command_inset_arg(p.getArg('{', '}'));
3600 if (label.empty() && width_type.empty())
3601 width_type = "none";
3602 os << "set_width \"" << width_type << "\"\n";
3603 if (width_type == "custom")
3604 os << "width \"" << width << '\"';
3606 skip_spaces_braces(p);
3607 preamble.registerAutomaticallyLoadedPackage("nomencl");
3610 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3611 context.check_layout(os);
3612 begin_inset(os, "script ");
3613 os << t.cs().substr(4) << '\n';
3614 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3616 if (t.cs() == "textsubscript")
3617 preamble.registerAutomaticallyLoadedPackage("subscript");
3620 else if ((where = is_known(t.cs(), known_quotes))) {
3621 context.check_layout(os);
3622 begin_inset(os, "Quotes ");
3623 os << known_coded_quotes[where - known_quotes];
3625 // LyX adds {} after the quote, so we have to eat
3626 // spaces here if there are any before a possible
3628 eat_whitespace(p, os, context, false);
3632 else if ((where = is_known(t.cs(), known_sizes)) &&
3633 context.new_layout_allowed) {
3634 context.check_layout(os);
3635 TeXFont const oldFont = context.font;
3636 context.font.size = known_coded_sizes[where - known_sizes];
3637 output_font_change(os, oldFont, context.font);
3638 eat_whitespace(p, os, context, false);
3641 else if ((where = is_known(t.cs(), known_font_families)) &&
3642 context.new_layout_allowed) {
3643 context.check_layout(os);
3644 TeXFont const oldFont = context.font;
3645 context.font.family =
3646 known_coded_font_families[where - known_font_families];
3647 output_font_change(os, oldFont, context.font);
3648 eat_whitespace(p, os, context, false);
3651 else if ((where = is_known(t.cs(), known_font_series)) &&
3652 context.new_layout_allowed) {
3653 context.check_layout(os);
3654 TeXFont const oldFont = context.font;
3655 context.font.series =
3656 known_coded_font_series[where - known_font_series];
3657 output_font_change(os, oldFont, context.font);
3658 eat_whitespace(p, os, context, false);
3661 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3662 context.new_layout_allowed) {
3663 context.check_layout(os);
3664 TeXFont const oldFont = context.font;
3665 context.font.shape =
3666 known_coded_font_shapes[where - known_font_shapes];
3667 output_font_change(os, oldFont, context.font);
3668 eat_whitespace(p, os, context, false);
3670 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3671 context.new_layout_allowed) {
3672 context.check_layout(os);
3673 TeXFont const oldFont = context.font;
3674 context.font.init();
3675 context.font.size = oldFont.size;
3676 context.font.family =
3677 known_coded_font_families[where - known_old_font_families];
3678 output_font_change(os, oldFont, context.font);
3679 eat_whitespace(p, os, context, false);
3682 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3683 context.new_layout_allowed) {
3684 context.check_layout(os);
3685 TeXFont const oldFont = context.font;
3686 context.font.init();
3687 context.font.size = oldFont.size;
3688 context.font.series =
3689 known_coded_font_series[where - known_old_font_series];
3690 output_font_change(os, oldFont, context.font);
3691 eat_whitespace(p, os, context, false);
3694 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3695 context.new_layout_allowed) {
3696 context.check_layout(os);
3697 TeXFont const oldFont = context.font;
3698 context.font.init();
3699 context.font.size = oldFont.size;
3700 context.font.shape =
3701 known_coded_font_shapes[where - known_old_font_shapes];
3702 output_font_change(os, oldFont, context.font);
3703 eat_whitespace(p, os, context, false);
3706 else if (t.cs() == "selectlanguage") {
3707 context.check_layout(os);
3708 // save the language for the case that a
3709 // \foreignlanguage is used
3710 context.font.language = babel2lyx(p.verbatim_item());
3711 os << "\n\\lang " << context.font.language << "\n";
3714 else if (t.cs() == "foreignlanguage") {
3715 string const lang = babel2lyx(p.verbatim_item());
3716 parse_text_attributes(p, os, FLAG_ITEM, outer,
3718 context.font.language, lang);
3721 else if (prefixIs(t.cs(), "text")
3722 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3723 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3725 // We have to output the whole command if it has an option
3726 // because LyX doesn't support this yet, see bug #8214,
3727 // only if there is a single option specifying a variant, we can handle it.
3729 string langopts = p.getOpt();
3730 // check if the option contains a variant, if yes, extract it
3731 string::size_type pos_var = langopts.find("variant");
3732 string::size_type i = langopts.find(',');
3733 string::size_type k = langopts.find('=', pos_var);
3734 if (pos_var != string::npos && i == string::npos) {
3736 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3737 lang = preamble.polyglossia2lyx(variant);
3738 parse_text_attributes(p, os, FLAG_ITEM, outer,
3740 context.font.language, lang);
3742 handle_ert(os, t.asInput() + langopts, context);
3744 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3745 parse_text_attributes(p, os, FLAG_ITEM, outer,
3747 context.font.language, lang);
3751 else if (t.cs() == "inputencoding") {
3752 // nothing to write here
3753 string const enc = subst(p.verbatim_item(), "\n", " ");
3754 p.setEncoding(enc, Encoding::inputenc);
3757 else if ((where = is_known(t.cs(), known_special_chars))) {
3758 context.check_layout(os);
3759 os << "\\SpecialChar \\"
3760 << known_coded_special_chars[where - known_special_chars]
3762 skip_spaces_braces(p);
3765 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3766 context.check_layout(os);
3767 os << "\\SpecialChar \\nobreakdash-\n";
3771 else if (t.cs() == "textquotedbl") {
3772 context.check_layout(os);
3777 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3778 context.check_layout(os);
3779 os << "\\SpecialChar \\@.\n";
3783 else if (t.cs() == "-") {
3784 context.check_layout(os);
3785 os << "\\SpecialChar \\-\n";
3788 else if (t.cs() == "textasciitilde") {
3789 context.check_layout(os);
3791 skip_spaces_braces(p);
3794 else if (t.cs() == "textasciicircum") {
3795 context.check_layout(os);
3797 skip_spaces_braces(p);
3800 else if (t.cs() == "textbackslash") {
3801 context.check_layout(os);
3802 os << "\n\\backslash\n";
3803 skip_spaces_braces(p);
3806 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3807 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3809 context.check_layout(os);
3813 else if (t.cs() == "char") {
3814 context.check_layout(os);
3815 if (p.next_token().character() == '`') {
3817 if (p.next_token().cs() == "\"") {
3822 handle_ert(os, "\\char`", context);
3825 handle_ert(os, "\\char", context);
3829 else if (t.cs() == "verb") {
3830 context.check_layout(os);
3831 // set catcodes to verbatim early, just in case.
3832 p.setCatcodes(VERBATIM_CATCODES);
3833 string delim = p.get_token().asInput();
3834 string const arg = p.verbatimStuff(delim);
3835 handle_ert(os, "\\verb" + delim + arg + delim, context);
3838 // Problem: \= creates a tabstop inside the tabbing environment
3839 // and else an accent. In the latter case we really would want
3840 // \={o} instead of \= o.
3841 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3842 handle_ert(os, t.asInput(), context);
3844 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3845 else if (t.cs().size() == 1
3846 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3847 context.check_layout(os);
3848 // try to see whether the string is in unicodesymbols
3851 string command = t.asInput() + "{"
3852 + trimSpaceAndEol(p.verbatim_item())
3855 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3856 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3857 termination, rem, &req);
3860 cerr << "When parsing " << command
3861 << ", result is " << to_utf8(s)
3862 << "+" << to_utf8(rem) << endl;
3864 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3865 preamble.registerAutomaticallyLoadedPackage(*it);
3867 // we did not find a non-ert version
3868 handle_ert(os, command, context);
3871 else if (t.cs() == "\\") {
3872 context.check_layout(os);
3874 handle_ert(os, "\\\\" + p.getOpt(), context);
3875 else if (p.next_token().asInput() == "*") {
3877 // getOpt() eats the following space if there
3878 // is no optional argument, but that is OK
3879 // here since it has no effect in the output.
3880 handle_ert(os, "\\\\*" + p.getOpt(), context);
3883 begin_inset(os, "Newline newline");
3888 else if (t.cs() == "newline" ||
3889 (t.cs() == "linebreak" && !p.hasOpt())) {
3890 context.check_layout(os);
3891 begin_inset(os, "Newline ");
3894 skip_spaces_braces(p);
3897 else if (t.cs() == "input" || t.cs() == "include"
3898 || t.cs() == "verbatiminput") {
3899 string name = t.cs();
3900 if (t.cs() == "verbatiminput"
3901 && p.next_token().asInput() == "*")
3902 name += p.get_token().asInput();
3903 context.check_layout(os);
3904 string filename(normalize_filename(p.getArg('{', '}')));
3905 string const path = getMasterFilePath(true);
3906 // We want to preserve relative / absolute filenames,
3907 // therefore path is only used for testing
3908 if ((t.cs() == "include" || t.cs() == "input") &&
3909 !makeAbsPath(filename, path).exists()) {
3910 // The file extension is probably missing.
3911 // Now try to find it out.
3912 string const tex_name =
3913 find_file(filename, path,
3914 known_tex_extensions);
3915 if (!tex_name.empty())
3916 filename = tex_name;
3918 bool external = false;
3920 if (makeAbsPath(filename, path).exists()) {
3921 string const abstexname =
3922 makeAbsPath(filename, path).absFileName();
3923 string const absfigname =
3924 changeExtension(abstexname, ".fig");
3925 fix_child_filename(filename);
3926 string const lyxname =
3927 changeExtension(filename, ".lyx");
3928 string const abslyxname = makeAbsPath(
3929 lyxname, getParentFilePath(false)).absFileName();
3931 if (!skipChildren())
3932 external = FileName(absfigname).exists();
3933 if (t.cs() == "input" && !skipChildren()) {
3934 string const ext = getExtension(abstexname);
3936 // Combined PS/LaTeX:
3937 // x.eps, x.pstex_t (old xfig)
3938 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3939 FileName const absepsname(
3940 changeExtension(abstexname, ".eps"));
3941 FileName const abspstexname(
3942 changeExtension(abstexname, ".pstex"));
3943 bool const xfigeps =
3944 (absepsname.exists() ||
3945 abspstexname.exists()) &&
3948 // Combined PDF/LaTeX:
3949 // x.pdf, x.pdftex_t (old xfig)
3950 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3951 FileName const abspdfname(
3952 changeExtension(abstexname, ".pdf"));
3953 bool const xfigpdf =
3954 abspdfname.exists() &&
3955 (ext == "pdftex_t" || ext == "pdf_t");
3959 // Combined PS/PDF/LaTeX:
3960 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3961 string const absbase2(
3962 removeExtension(abstexname) + "_pspdftex");
3963 FileName const abseps2name(
3964 addExtension(absbase2, ".eps"));
3965 FileName const abspdf2name(
3966 addExtension(absbase2, ".pdf"));
3967 bool const xfigboth =
3968 abspdf2name.exists() &&
3969 abseps2name.exists() && ext == "pspdftex";
3971 xfig = xfigpdf || xfigeps || xfigboth;
3972 external = external && xfig;
3975 outname = changeExtension(filename, ".fig");
3976 FileName abssrc(changeExtension(abstexname, ".fig"));
3977 copy_file(abssrc, outname);
3979 // Don't try to convert, the result
3980 // would be full of ERT.
3982 FileName abssrc(abstexname);
3983 copy_file(abssrc, outname);
3984 } else if (t.cs() != "verbatiminput" &&
3986 tex2lyx(abstexname, FileName(abslyxname),
3989 // no need to call copy_file
3990 // tex2lyx creates the file
3993 FileName abssrc(abstexname);
3994 copy_file(abssrc, outname);
3997 cerr << "Warning: Could not find included file '"
3998 << filename << "'." << endl;
4002 begin_inset(os, "External\n");
4003 os << "\ttemplate XFig\n"
4004 << "\tfilename " << outname << '\n';
4005 registerExternalTemplatePackages("XFig");
4007 begin_command_inset(os, "include", name);
4008 outname = subst(outname, "\"", "\\\"");
4009 os << "preview false\n"
4010 "filename \"" << outname << "\"\n";
4011 if (t.cs() == "verbatiminput")
4012 preamble.registerAutomaticallyLoadedPackage("verbatim");
4017 else if (t.cs() == "bibliographystyle") {
4018 // store new bibliographystyle
4019 bibliographystyle = p.verbatim_item();
4020 // If any other command than \bibliography and
4021 // \nocite{*} follows, we need to output the style
4022 // (because it might be used by that command).
4023 // Otherwise, it will automatically be output by LyX.
4026 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4027 if (t2.cat() == catBegin)
4029 if (t2.cat() != catEscape)
4031 if (t2.cs() == "nocite") {
4032 if (p.getArg('{', '}') == "*")
4034 } else if (t2.cs() == "bibliography")
4041 "\\bibliographystyle{" + bibliographystyle + '}',
4046 else if (t.cs() == "bibliography") {
4047 context.check_layout(os);
4048 begin_command_inset(os, "bibtex", "bibtex");
4049 if (!btprint.empty()) {
4050 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4051 // clear the string because the next BibTeX inset can be without the
4052 // \nocite{*} option
4055 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4056 // Do we have a bibliographystyle set?
4057 if (!bibliographystyle.empty())
4058 os << "options " << '"' << bibliographystyle << '"' << "\n";
4062 else if (t.cs() == "parbox") {
4063 // Test whether this is an outer box of a shaded box
4065 // swallow arguments
4066 while (p.hasOpt()) {
4068 p.skip_spaces(true);
4071 p.skip_spaces(true);
4073 if (p.next_token().cat() == catBegin)
4075 p.skip_spaces(true);
4076 Token to = p.get_token();
4077 bool shaded = false;
4078 if (to.asInput() == "\\begin") {
4079 p.skip_spaces(true);
4080 if (p.getArg('{', '}') == "shaded")
4085 parse_outer_box(p, os, FLAG_ITEM, outer,
4086 context, "parbox", "shaded");
4088 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4092 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4093 t.cs() == "shadowbox" || t.cs() == "doublebox")
4094 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4096 else if (t.cs() == "framebox") {
4097 if (p.next_token().character() == '(') {
4098 //the syntax is: \framebox(x,y)[position]{content}
4099 string arg = t.asInput();
4100 arg += p.getFullParentheseArg();
4101 arg += p.getFullOpt();
4102 eat_whitespace(p, os, context, false);
4103 handle_ert(os, arg + '{', context);
4104 parse_text(p, os, FLAG_ITEM, outer, context);
4105 handle_ert(os, "}", context);
4107 string special = p.getFullOpt();
4108 special += p.getOpt();
4109 // LyX does not yet support \framebox without any option
4110 if (!special.empty())
4111 parse_outer_box(p, os, FLAG_ITEM, outer,
4112 context, t.cs(), special);
4114 eat_whitespace(p, os, context, false);
4115 handle_ert(os, "\\framebox{", context);
4116 parse_text(p, os, FLAG_ITEM, outer, context);
4117 handle_ert(os, "}", context);
4122 //\makebox() is part of the picture environment and different from \makebox{}
4123 //\makebox{} will be parsed by parse_box
4124 else if (t.cs() == "makebox") {
4125 if (p.next_token().character() == '(') {
4126 //the syntax is: \makebox(x,y)[position]{content}
4127 string arg = t.asInput();
4128 arg += p.getFullParentheseArg();
4129 arg += p.getFullOpt();
4130 eat_whitespace(p, os, context, false);
4131 handle_ert(os, arg + '{', context);
4132 parse_text(p, os, FLAG_ITEM, outer, context);
4133 handle_ert(os, "}", context);
4135 //the syntax is: \makebox[width][position]{content}
4136 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4140 else if (t.cs() == "smallskip" ||
4141 t.cs() == "medskip" ||
4142 t.cs() == "bigskip" ||
4143 t.cs() == "vfill") {
4144 context.check_layout(os);
4145 begin_inset(os, "VSpace ");
4148 skip_spaces_braces(p);
4151 else if ((where = is_known(t.cs(), known_spaces))) {
4152 context.check_layout(os);
4153 begin_inset(os, "space ");
4154 os << '\\' << known_coded_spaces[where - known_spaces]
4157 // LaTeX swallows whitespace after all spaces except
4158 // "\\,". We have to do that here, too, because LyX
4159 // adds "{}" which would make the spaces significant.
4161 eat_whitespace(p, os, context, false);
4162 // LyX adds "{}" after all spaces except "\\ " and
4163 // "\\,", so we have to remove "{}".
4164 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4165 // remove the braces after "\\,", too.
4170 else if (t.cs() == "newpage" ||
4171 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4172 t.cs() == "clearpage" ||
4173 t.cs() == "cleardoublepage") {
4174 context.check_layout(os);
4175 begin_inset(os, "Newpage ");
4178 skip_spaces_braces(p);
4181 else if (t.cs() == "DeclareRobustCommand" ||
4182 t.cs() == "DeclareRobustCommandx" ||
4183 t.cs() == "newcommand" ||
4184 t.cs() == "newcommandx" ||
4185 t.cs() == "providecommand" ||
4186 t.cs() == "providecommandx" ||
4187 t.cs() == "renewcommand" ||
4188 t.cs() == "renewcommandx") {
4189 // DeclareRobustCommand, DeclareRobustCommandx,
4190 // providecommand and providecommandx could be handled
4191 // by parse_command(), but we need to call
4192 // add_known_command() here.
4193 string name = t.asInput();
4194 if (p.next_token().asInput() == "*") {
4195 // Starred form. Eat '*'
4199 string const command = p.verbatim_item();
4200 string const opt1 = p.getFullOpt();
4201 string const opt2 = p.getFullOpt();
4202 add_known_command(command, opt1, !opt2.empty());
4203 string const ert = name + '{' + command + '}' +
4205 '{' + p.verbatim_item() + '}';
4207 if (t.cs() == "DeclareRobustCommand" ||
4208 t.cs() == "DeclareRobustCommandx" ||
4209 t.cs() == "providecommand" ||
4210 t.cs() == "providecommandx" ||
4211 name[name.length()-1] == '*')
4212 handle_ert(os, ert, context);
4214 context.check_layout(os);
4215 begin_inset(os, "FormulaMacro");
4221 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4222 // let could be handled by parse_command(),
4223 // but we need to call add_known_command() here.
4224 string ert = t.asInput();
4227 if (p.next_token().cat() == catBegin) {
4228 name = p.verbatim_item();
4229 ert += '{' + name + '}';
4231 name = p.verbatim_item();
4236 if (p.next_token().cat() == catBegin) {
4237 command = p.verbatim_item();
4238 ert += '{' + command + '}';
4240 command = p.verbatim_item();
4243 // If command is known, make name known too, to parse
4244 // its arguments correctly. For this reason we also
4245 // have commands in syntax.default that are hardcoded.
4246 CommandMap::iterator it = known_commands.find(command);
4247 if (it != known_commands.end())
4248 known_commands[t.asInput()] = it->second;
4249 handle_ert(os, ert, context);
4252 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4253 bool starred = false;
4254 if (p.next_token().asInput() == "*") {
4258 string name = t.asInput();
4259 string const length = p.verbatim_item();
4262 bool valid = splitLatexLength(length, valstring, unit);
4263 bool known_hspace = false;
4264 bool known_vspace = false;
4265 bool known_unit = false;
4268 istringstream iss(valstring);
4271 if (t.cs()[0] == 'h') {
4272 if (unit == "\\fill") {
4277 known_hspace = true;
4280 if (unit == "\\smallskipamount") {
4282 known_vspace = true;
4283 } else if (unit == "\\medskipamount") {
4285 known_vspace = true;
4286 } else if (unit == "\\bigskipamount") {
4288 known_vspace = true;
4289 } else if (unit == "\\fill") {
4291 known_vspace = true;
4295 if (!known_hspace && !known_vspace) {
4296 switch (unitFromString(unit)) {
4317 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4318 // Literal horizontal length or known variable
4319 context.check_layout(os);
4320 begin_inset(os, "space ");
4328 if (known_unit && !known_hspace)
4330 << translate_len(length);
4332 } else if (known_unit || known_vspace) {
4333 // Literal vertical length or known variable
4334 context.check_layout(os);
4335 begin_inset(os, "VSpace ");
4343 // LyX can't handle other length variables in Inset VSpace/space
4348 handle_ert(os, name + '{' + unit + '}', context);
4349 else if (value == -1.0)
4350 handle_ert(os, name + "{-" + unit + '}', context);
4352 handle_ert(os, name + '{' + valstring + unit + '}', context);
4354 handle_ert(os, name + '{' + length + '}', context);
4358 // The single '=' is meant here.
4359 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4361 context.check_layout(os);
4362 begin_inset(os, "Flex ");
4363 os << to_utf8(newinsetlayout->name()) << '\n'
4364 << "status collapsed\n";
4365 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4369 else if (t.cs() == "includepdf") {
4371 string const arg = p.getArg('[', ']');
4372 map<string, string> opts;
4373 vector<string> keys;
4374 split_map(arg, opts, keys);
4375 string name = normalize_filename(p.verbatim_item());
4376 string const path = getMasterFilePath(true);
4377 // We want to preserve relative / absolute filenames,
4378 // therefore path is only used for testing
4379 if (!makeAbsPath(name, path).exists()) {
4380 // The file extension is probably missing.
4381 // Now try to find it out.
4382 char const * const pdfpages_format[] = {"pdf", 0};
4383 string const pdftex_name =
4384 find_file(name, path, pdfpages_format);
4385 if (!pdftex_name.empty()) {
4390 FileName const absname = makeAbsPath(name, path);
4391 if (absname.exists())
4393 fix_child_filename(name);
4394 copy_file(absname, name);
4396 cerr << "Warning: Could not find file '"
4397 << name << "'." << endl;
4399 context.check_layout(os);
4400 begin_inset(os, "External\n\ttemplate ");
4401 os << "PDFPages\n\tfilename "
4403 // parse the options
4404 if (opts.find("pages") != opts.end())
4405 os << "\textra LaTeX \"pages="
4406 << opts["pages"] << "\"\n";
4407 if (opts.find("angle") != opts.end())
4408 os << "\trotateAngle "
4409 << opts["angle"] << '\n';
4410 if (opts.find("origin") != opts.end()) {
4412 string const opt = opts["origin"];
4413 if (opt == "tl") ss << "topleft";
4414 if (opt == "bl") ss << "bottomleft";
4415 if (opt == "Bl") ss << "baselineleft";
4416 if (opt == "c") ss << "center";
4417 if (opt == "tc") ss << "topcenter";
4418 if (opt == "bc") ss << "bottomcenter";
4419 if (opt == "Bc") ss << "baselinecenter";
4420 if (opt == "tr") ss << "topright";
4421 if (opt == "br") ss << "bottomright";
4422 if (opt == "Br") ss << "baselineright";
4423 if (!ss.str().empty())
4424 os << "\trotateOrigin " << ss.str() << '\n';
4426 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4428 if (opts.find("width") != opts.end())
4430 << translate_len(opts["width"]) << '\n';
4431 if (opts.find("height") != opts.end())
4433 << translate_len(opts["height"]) << '\n';
4434 if (opts.find("keepaspectratio") != opts.end())
4435 os << "\tkeepAspectRatio\n";
4437 context.check_layout(os);
4438 registerExternalTemplatePackages("PDFPages");
4441 else if (t.cs() == "loadgame") {
4443 string name = normalize_filename(p.verbatim_item());
4444 string const path = getMasterFilePath(true);
4445 // We want to preserve relative / absolute filenames,
4446 // therefore path is only used for testing
4447 if (!makeAbsPath(name, path).exists()) {
4448 // The file extension is probably missing.
4449 // Now try to find it out.
4450 char const * const lyxskak_format[] = {"fen", 0};
4451 string const lyxskak_name =
4452 find_file(name, path, lyxskak_format);
4453 if (!lyxskak_name.empty())
4454 name = lyxskak_name;
4456 FileName const absname = makeAbsPath(name, path);
4457 if (absname.exists())
4459 fix_child_filename(name);
4460 copy_file(absname, name);
4462 cerr << "Warning: Could not find file '"
4463 << name << "'." << endl;
4464 context.check_layout(os);
4465 begin_inset(os, "External\n\ttemplate ");
4466 os << "ChessDiagram\n\tfilename "
4469 context.check_layout(os);
4470 // after a \loadgame follows a \showboard
4471 if (p.get_token().asInput() == "showboard")
4473 registerExternalTemplatePackages("ChessDiagram");
4477 // try to see whether the string is in unicodesymbols
4478 // Only use text mode commands, since we are in text mode here,
4479 // and math commands may be invalid (bug 6797)
4483 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4484 Encodings::TEXT_CMD, termination, rem, &req);
4487 cerr << "When parsing " << t.cs()
4488 << ", result is " << to_utf8(s)
4489 << "+" << to_utf8(rem) << endl;
4490 context.check_layout(os);
4493 skip_spaces_braces(p);
4494 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4495 preamble.registerAutomaticallyLoadedPackage(*it);
4497 //cerr << "#: " << t << " mode: " << mode << endl;
4498 // heuristic: read up to next non-nested space
4500 string s = t.asInput();
4501 string z = p.verbatim_item();
4502 while (p.good() && z != " " && !z.empty()) {
4503 //cerr << "read: " << z << endl;
4505 z = p.verbatim_item();
4507 cerr << "found ERT: " << s << endl;
4508 handle_ert(os, s + ' ', context);
4511 string name = t.asInput();
4512 if (p.next_token().asInput() == "*") {
4513 // Starred commands like \vspace*{}
4514 p.get_token(); // Eat '*'
4517 if (!parse_command(name, p, os, outer, context))
4518 handle_ert(os, name, context);
4522 if (flags & FLAG_LEAVE) {
4523 flags &= ~FLAG_LEAVE;
4530 string guessLanguage(Parser & p, string const & lang)
4532 typedef std::map<std::string, size_t> LangMap;
4533 // map from language names to number of characters
4536 for (char const * const * i = supported_CJK_languages; *i; i++)
4537 used[string(*i)] = 0;
4540 Token const t = p.get_token();
4541 // comments are not counted for any language
4542 if (t.cat() == catComment)
4544 // commands are not counted as well, but we need to detect
4545 // \begin{CJK} and switch encoding if needed
4546 if (t.cat() == catEscape) {
4547 if (t.cs() == "inputencoding") {
4548 string const enc = subst(p.verbatim_item(), "\n", " ");
4549 p.setEncoding(enc, Encoding::inputenc);
4552 if (t.cs() != "begin")
4555 // Non-CJK content is counted for lang.
4556 // We do not care about the real language here:
4557 // If we have more non-CJK contents than CJK contents,
4558 // we simply use the language that was specified as
4559 // babel main language.
4560 used[lang] += t.asInput().length();
4563 // Now we are starting an environment
4565 string const name = p.getArg('{', '}');
4566 if (name != "CJK") {
4570 // It is a CJK environment
4572 /* name = */ p.getArg('{', '}');
4573 string const encoding = p.getArg('{', '}');
4574 /* mapping = */ p.getArg('{', '}');
4575 string const encoding_old = p.getEncoding();
4576 char const * const * const where =
4577 is_known(encoding, supported_CJK_encodings);
4579 p.setEncoding(encoding, Encoding::CJK);
4581 p.setEncoding("UTF-8");
4582 string const text = p.ertEnvironment("CJK");
4583 p.setEncoding(encoding_old);
4586 // ignore contents in unknown CJK encoding
4589 // the language of the text
4591 supported_CJK_languages[where - supported_CJK_encodings];
4592 used[cjk] += text.length();
4594 LangMap::const_iterator use = used.begin();
4595 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4596 if (it->second > use->second)