2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49 Context const & context, InsetLayout const * layout)
51 bool const forcePlainLayout =
52 layout ? layout->forcePlainLayout() : false;
53 Context newcontext(true, context.textclass);
55 newcontext.layout = &context.textclass.plainLayout();
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context const & context, string const & name)
68 InsetLayout const * layout = 0;
69 DocumentClass::InsetLayouts::const_iterator it =
70 context.textclass.insetLayouts().find(from_ascii(name));
71 if (it != context.textclass.insetLayouts().end())
72 layout = &(it->second);
73 parse_text_in_inset(p, os, flags, outer, context, layout);
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context newcontext(context);
81 // Don't inherit the paragraph-level extra stuff
82 newcontext.par_extra_stuff.clear();
83 parse_text(p, os, flags, outer, newcontext);
84 // Make sure that we don't create invalid .lyx files
85 context.need_layout = newcontext.need_layout;
86 context.need_end_layout = newcontext.need_end_layout;
91 * Thin wrapper around parse_text_snippet() using a string.
93 * We completely ignore \c context.need_layout and \c context.need_end_layout,
94 * because our return value is not used directly (otherwise the stream version
95 * of parse_text_snippet() could be used). That means that the caller needs
96 * to do layout management manually.
97 * This is intended to parse text that does not create any layout changes.
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
102 Context newcontext(context);
103 newcontext.need_layout = false;
104 newcontext.need_end_layout = false;
105 newcontext.new_layout_allowed = false;
106 // Avoid warning by Context::~Context()
107 newcontext.par_extra_stuff.clear();
109 parse_text_snippet(p, os, flags, outer, newcontext);
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115 "vpageref", "prettyref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "eqref", 0 };
120 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
121 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
122 "secref", "subref", "tabref", "thmref", 0 };
124 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
125 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
126 "sec", "sub", "tab", "thm", 0 };
130 * supported CJK encodings
131 * JIS does not work with LyX's encoding conversion
133 const char * const supported_CJK_encodings[] = {
134 "EUC-JP", "KS", "GB", "UTF8",
135 "Bg5", /*"JIS",*/ "SJIS", 0};
138 * the same as supported_CJK_encodings with their corresponding LyX language name
139 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
141 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
142 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
143 * please keep this in sync with supported_CJK_encodings line by line!
145 const char * const supported_CJK_languages[] = {
146 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
147 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
151 * The starred forms are also known except for "citefullauthor",
152 * "citeyear" and "citeyearpar".
154 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
155 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
156 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
160 * No starred form other than "cite*" known.
162 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
163 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
164 // jurabib commands not (yet) supported by LyX:
166 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
167 // "footciteauthor", "footciteyear", "footciteyearpar",
168 "citefield", "citetitle", 0 };
170 /// LaTeX names for quotes
171 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
172 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
173 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
174 "guilsinglleft", "frq", "guilsinglright", 0};
176 /// the same as known_quotes with .lyx names
177 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
178 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
179 "gld", "grd", "gls", "ers", "fls",
180 "fls", "frs", "frs", 0};
182 /// LaTeX names for font sizes
183 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
184 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
186 /// the same as known_sizes with .lyx names
187 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
188 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
190 /// LaTeX 2.09 names for font families
191 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
193 /// LaTeX names for font families
194 char const * const known_font_families[] = { "rmfamily", "sffamily",
197 /// LaTeX names for font family changing commands
198 char const * const known_text_font_families[] = { "textrm", "textsf",
201 /// The same as known_old_font_families, known_font_families and
202 /// known_text_font_families with .lyx names
203 char const * const known_coded_font_families[] = { "roman", "sans",
206 /// LaTeX 2.09 names for font series
207 char const * const known_old_font_series[] = { "bf", 0};
209 /// LaTeX names for font series
210 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
212 /// LaTeX names for font series changing commands
213 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
215 /// The same as known_old_font_series, known_font_series and
216 /// known_text_font_series with .lyx names
217 char const * const known_coded_font_series[] = { "bold", "medium", 0};
219 /// LaTeX 2.09 names for font shapes
220 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
222 /// LaTeX names for font shapes
223 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
226 /// LaTeX names for font shape changing commands
227 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
230 /// The same as known_old_font_shapes, known_font_shapes and
231 /// known_text_font_shapes with .lyx names
232 char const * const known_coded_font_shapes[] = { "italic", "slanted",
233 "smallcaps", "up", 0};
235 /// Known special characters which need skip_spaces_braces() afterwards
236 char const * const known_special_chars[] = {"ldots", "lyxarrow",
237 "textcompwordmark", "slash", 0};
239 /// the same as known_special_chars with .lyx names
240 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
241 "textcompwordmark{}", "slash{}", 0};
244 * Graphics file extensions known by the dvips driver of the graphics package.
245 * These extensions are used to complete the filename of an included
246 * graphics file if it does not contain an extension.
247 * The order must be the same that latex uses to find a file, because we
248 * will use the first extension that matches.
249 * This is only an approximation for the common cases. If we would want to
250 * do it right in all cases, we would need to know which graphics driver is
251 * used and know the extensions of every driver of the graphics package.
253 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
254 "ps.gz", "eps.Z", "ps.Z", 0};
257 * Graphics file extensions known by the pdftex driver of the graphics package.
258 * \sa known_dvips_graphics_formats
260 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
264 * Known file extensions for TeX files as used by \\include.
266 char const * const known_tex_extensions[] = {"tex", 0};
268 /// spaces known by InsetSpace
269 char const * const known_spaces[] = { " ", "space", ",",
270 "thinspace", "quad", "qquad", "enspace", "enskip",
271 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
272 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
273 "upbracefill", "downbracefill", 0};
275 /// the same as known_spaces with .lyx names
276 char const * const known_coded_spaces[] = { "space{}", "space{}",
277 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
278 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
279 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
280 "upbracefill{}", "downbracefill{}", 0};
282 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
283 /// them in ERT. "LaTeXe" must come before "LaTeX"!
284 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
285 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
286 int const known_phrase_lengths[] = {3, 5, 7, 0};
288 // string to store the float type to be able to determine the type of subfloats
289 string float_type = "";
292 /// splits "x=z, y=b" into a map and an ordered keyword vector
293 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
298 keys.resize(v.size());
299 for (size_t i = 0; i < v.size(); ++i) {
300 size_t const pos = v[i].find('=');
301 string const index = trimSpaceAndEol(v[i].substr(0, pos));
302 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
310 * Split a LaTeX length into value and unit.
311 * The latter can be a real unit like "pt", or a latex length variable
312 * like "\textwidth". The unit may contain additional stuff like glue
313 * lengths, but we don't care, because such lengths are ERT anyway.
314 * \returns true if \p value and \p unit are valid.
316 bool splitLatexLength(string const & len, string & value, string & unit)
320 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
321 //'4,5' is a valid LaTeX length number. Change it to '4.5'
322 string const length = subst(len, ',', '.');
323 if (i == string::npos)
326 if (len[0] == '\\') {
327 // We had something like \textwidth without a factor
333 value = trimSpaceAndEol(string(length, 0, i));
337 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
338 if (contains(len, '\\'))
339 unit = trimSpaceAndEol(string(len, i));
341 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
346 /// A simple function to translate a latex length to something LyX can
347 /// understand. Not perfect, but rather best-effort.
348 bool translate_len(string const & length, string & valstring, string & unit)
350 if (!splitLatexLength(length, valstring, unit))
352 // LyX uses percent values
354 istringstream iss(valstring);
359 string const percentval = oss.str();
361 if (unit.empty() || unit[0] != '\\')
363 string::size_type const i = unit.find(' ');
364 string const endlen = (i == string::npos) ? string() : string(unit, i);
365 if (unit == "\\textwidth") {
366 valstring = percentval;
367 unit = "text%" + endlen;
368 } else if (unit == "\\columnwidth") {
369 valstring = percentval;
370 unit = "col%" + endlen;
371 } else if (unit == "\\paperwidth") {
372 valstring = percentval;
373 unit = "page%" + endlen;
374 } else if (unit == "\\linewidth") {
375 valstring = percentval;
376 unit = "line%" + endlen;
377 } else if (unit == "\\paperheight") {
378 valstring = percentval;
379 unit = "pheight%" + endlen;
380 } else if (unit == "\\textheight") {
381 valstring = percentval;
382 unit = "theight%" + endlen;
390 string translate_len(string const & length)
394 if (translate_len(length, value, unit))
396 // If the input is invalid, return what we have.
404 * Translates a LaTeX length into \p value, \p unit and
405 * \p special parts suitable for a box inset.
406 * The difference from translate_len() is that a box inset knows about
407 * some special "units" that are stored in \p special.
409 void translate_box_len(string const & length, string & value, string & unit, string & special)
411 if (translate_len(length, value, unit)) {
412 if (unit == "\\height" || unit == "\\depth" ||
413 unit == "\\totalheight" || unit == "\\width") {
414 special = unit.substr(1);
415 // The unit is not used, but LyX requires a dummy setting
428 * Find a file with basename \p name in path \p path and an extension
431 string find_file(string const & name, string const & path,
432 char const * const * extensions)
434 for (char const * const * what = extensions; *what; ++what) {
435 string const trial = addExtension(name, *what);
436 if (makeAbsPath(trial, path).exists())
443 void begin_inset(ostream & os, string const & name)
445 os << "\n\\begin_inset " << name;
449 void begin_command_inset(ostream & os, string const & name,
450 string const & latexname)
452 begin_inset(os, "CommandInset ");
453 os << name << "\nLatexCommand " << latexname << '\n';
457 void end_inset(ostream & os)
459 os << "\n\\end_inset\n\n";
463 bool skip_braces(Parser & p)
465 if (p.next_token().cat() != catBegin)
468 if (p.next_token().cat() == catEnd) {
477 /// replace LaTeX commands in \p s from the unicodesymbols file with their
479 docstring convert_unicodesymbols(docstring s)
482 for (size_t i = 0; i < s.size();) {
491 docstring parsed = encodings.fromLaTeXCommand(s,
492 Encodings::TEXT_CMD, termination, rem, &req);
493 set<string>::const_iterator it = req.begin();
494 set<string>::const_iterator en = req.end();
495 for (; it != en; ++it)
496 preamble.registerAutomaticallyLoadedPackage(*it);
499 if (s.empty() || s[0] != '\\')
508 /// try to convert \p s to a valid InsetCommand argument
509 string convert_command_inset_arg(string s)
512 // since we don't know the input encoding we can't use from_utf8
513 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
514 // LyX cannot handle newlines in a latex command
515 return subst(s, "\n", " ");
519 void output_ert(ostream & os, string const & s, Context & context)
521 context.check_layout(os);
522 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
524 os << "\n\\backslash\n";
525 else if (*it == '\n') {
526 context.new_paragraph(os);
527 context.check_layout(os);
531 context.check_end_layout(os);
535 void output_ert_inset(ostream & os, string const & s, Context & context)
537 // We must have a valid layout before outputting the ERT inset.
538 context.check_layout(os);
539 Context newcontext(true, context.textclass);
540 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
541 if (layout.forcePlainLayout())
542 newcontext.layout = &context.textclass.plainLayout();
543 begin_inset(os, "ERT");
544 os << "\nstatus collapsed\n";
545 output_ert(os, s, newcontext);
550 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
552 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
555 if (checkModule(name, command))
556 return findLayoutWithoutModule(textclass, name, command);
561 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
563 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
566 if (checkModule(name, command))
567 return findInsetLayoutWithoutModule(textclass, name, command);
572 void eat_whitespace(Parser &, ostream &, Context &, bool);
576 * Skips whitespace and braces.
577 * This should be called after a command has been parsed that is not put into
578 * ERT, and where LyX adds "{}" if needed.
580 void skip_spaces_braces(Parser & p, bool keepws = false)
582 /* The following four examples produce the same typeset output and
583 should be handled by this function:
591 // Unfortunately we need to skip comments, too.
592 // We can't use eat_whitespace since writing them after the {}
593 // results in different output in some cases.
594 bool const skipped_spaces = p.skip_spaces(true);
595 bool const skipped_braces = skip_braces(p);
596 if (keepws && skipped_spaces && !skipped_braces)
597 // put back the space (it is better handled by check_space)
598 p.unskip_spaces(true);
602 void output_command_layout(ostream & os, Parser & p, bool outer,
603 Context & parent_context,
604 Layout const * newlayout)
606 TeXFont const oldFont = parent_context.font;
607 // save the current font size
608 string const size = oldFont.size;
609 // reset the font size to default, because the font size switches
610 // don't affect section headings and the like
611 parent_context.font.size = Context::normalfont.size;
612 // we only need to write the font change if we have an open layout
613 if (!parent_context.atParagraphStart())
614 output_font_change(os, oldFont, parent_context.font);
615 parent_context.check_end_layout(os);
616 Context context(true, parent_context.textclass, newlayout,
617 parent_context.layout, parent_context.font);
618 if (parent_context.deeper_paragraph) {
619 // We are beginning a nested environment after a
620 // deeper paragraph inside the outer list environment.
621 // Therefore we don't need to output a "begin deeper".
622 context.need_end_deeper = true;
624 context.check_deeper(os);
625 context.check_layout(os);
626 // FIXME: Adjust to format 446!
627 // Since format 446, layouts do not require anymore all optional
628 // arguments before the required ones. Needs to be implemented!
630 while (optargs < context.layout->optArgs()) {
631 eat_whitespace(p, os, context, false);
632 if (p.next_token().cat() == catEscape ||
633 p.next_token().character() != '[')
635 p.get_token(); // eat '['
636 // FIXME: Just a workaround. InsetArgument::updateBuffer
637 // will compute a proper ID for all "999" Arguments
638 // (which is also what lyx2lyx produces).
639 // However, tex2lyx should be able to output proper IDs
641 begin_inset(os, "Argument 999\n");
642 os << "status collapsed\n\n";
643 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
645 eat_whitespace(p, os, context, false);
649 while (reqargs < context.layout->requiredArgs()) {
650 eat_whitespace(p, os, context, false);
651 if (p.next_token().cat() != catBegin)
653 p.get_token(); // eat '{'
654 // FIXME: Just a workaround. InsetArgument::updateBuffer
655 // will compute a proper ID for all "999" Arguments
656 // (which is also what lyx2lyx produces).
657 // However, tex2lyx should be able to output proper IDs
659 begin_inset(os, "Argument 999\n");
660 os << "status collapsed\n\n";
661 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
663 eat_whitespace(p, os, context, false);
666 parse_text(p, os, FLAG_ITEM, outer, context);
667 context.check_end_layout(os);
668 if (parent_context.deeper_paragraph) {
669 // We must suppress the "end deeper" because we
670 // suppressed the "begin deeper" above.
671 context.need_end_deeper = false;
673 context.check_end_deeper(os);
674 // We don't need really a new paragraph, but
675 // we must make sure that the next item gets a \begin_layout.
676 parent_context.new_paragraph(os);
677 // Set the font size to the original value. No need to output it here
678 // (Context::begin_layout() will do that if needed)
679 parent_context.font.size = size;
684 * Output a space if necessary.
685 * This function gets called for every whitespace token.
687 * We have three cases here:
688 * 1. A space must be suppressed. Example: The lyxcode case below
689 * 2. A space may be suppressed. Example: Spaces before "\par"
690 * 3. A space must not be suppressed. Example: A space between two words
692 * We currently handle only 1. and 3 and from 2. only the case of
693 * spaces before newlines as a side effect.
695 * 2. could be used to suppress as many spaces as possible. This has two effects:
696 * - Reimporting LyX generated LaTeX files changes almost no whitespace
697 * - Superflous whitespace from non LyX generated LaTeX files is removed.
698 * The drawback is that the logic inside the function becomes
699 * complicated, and that is the reason why it is not implemented.
701 void check_space(Parser & p, ostream & os, Context & context)
703 Token const next = p.next_token();
704 Token const curr = p.curr_token();
705 // A space before a single newline and vice versa must be ignored
706 // LyX emits a newline before \end{lyxcode}.
707 // This newline must be ignored,
708 // otherwise LyX will add an additional protected space.
709 if (next.cat() == catSpace ||
710 next.cat() == catNewline ||
711 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
714 context.check_layout(os);
720 * Parse all arguments of \p command
722 void parse_arguments(string const & command,
723 vector<ArgumentType> const & template_arguments,
724 Parser & p, ostream & os, bool outer, Context & context)
726 string ert = command;
727 size_t no_arguments = template_arguments.size();
728 for (size_t i = 0; i < no_arguments; ++i) {
729 switch (template_arguments[i]) {
732 // This argument contains regular LaTeX
733 output_ert_inset(os, ert + '{', context);
734 eat_whitespace(p, os, context, false);
735 if (template_arguments[i] == required)
736 parse_text(p, os, FLAG_ITEM, outer, context);
738 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
742 // This argument consists only of a single item.
743 // The presence of '{' or not must be preserved.
745 if (p.next_token().cat() == catBegin)
746 ert += '{' + p.verbatim_item() + '}';
748 ert += p.verbatim_item();
752 // This argument may contain special characters
753 ert += '{' + p.verbatim_item() + '}';
757 // true because we must not eat whitespace
758 // if an optional arg follows we must not strip the
759 // brackets from this one
760 if (i < no_arguments - 1 &&
761 template_arguments[i+1] == optional)
762 ert += p.getFullOpt(true);
764 ert += p.getOpt(true);
768 output_ert_inset(os, ert, context);
773 * Check whether \p command is a known command. If yes,
774 * handle the command with all arguments.
775 * \return true if the command was parsed, false otherwise.
777 bool parse_command(string const & command, Parser & p, ostream & os,
778 bool outer, Context & context)
780 if (known_commands.find(command) != known_commands.end()) {
781 parse_arguments(command, known_commands[command], p, os,
789 /// Parses a minipage or parbox
790 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
791 unsigned inner_flags, bool outer, Context & parent_context,
792 string const & outer_type, string const & special,
793 string const & inner_type)
797 string hor_pos = "c";
798 // We need to set the height to the LaTeX default of 1\\totalheight
799 // for the case when no height argument is given
800 string height_value = "1";
801 string height_unit = "in";
802 string height_special = "totalheight";
807 string width_special = "none";
808 if (!inner_type.empty() && p.hasOpt()) {
809 if (inner_type != "makebox")
810 position = p.getArg('[', ']');
812 latex_width = p.getArg('[', ']');
813 translate_box_len(latex_width, width_value, width_unit, width_special);
816 if (position != "t" && position != "c" && position != "b") {
817 cerr << "invalid position " << position << " for "
818 << inner_type << endl;
822 if (inner_type != "makebox") {
823 latex_height = p.getArg('[', ']');
824 translate_box_len(latex_height, height_value, height_unit, height_special);
826 string const opt = p.getArg('[', ']');
829 if (hor_pos != "l" && hor_pos != "c" &&
830 hor_pos != "r" && hor_pos != "s") {
831 cerr << "invalid hor_pos " << hor_pos
832 << " for " << inner_type << endl;
839 inner_pos = p.getArg('[', ']');
840 if (inner_pos != "c" && inner_pos != "t" &&
841 inner_pos != "b" && inner_pos != "s") {
842 cerr << "invalid inner_pos "
843 << inner_pos << " for "
844 << inner_type << endl;
845 inner_pos = position;
850 if (inner_type.empty()) {
851 if (special.empty() && outer_type != "framebox")
852 latex_width = "1\\columnwidth";
855 latex_width = p2.getArg('[', ']');
856 string const opt = p2.getArg('[', ']');
859 if (hor_pos != "l" && hor_pos != "c" &&
860 hor_pos != "r" && hor_pos != "s") {
861 cerr << "invalid hor_pos " << hor_pos
862 << " for " << outer_type << endl;
867 } else if (inner_type != "makebox")
868 latex_width = p.verbatim_item();
869 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
870 // as this is LyX's standard for such cases (except for makebox)
871 // \framebox is more special and handled below
872 if (latex_width.empty() && inner_type != "makebox"
873 && outer_type != "framebox")
874 latex_width = "1\\columnwidth";
876 translate_len(latex_width, width_value, width_unit);
878 bool shadedparbox = false;
879 if (inner_type == "shaded") {
880 eat_whitespace(p, os, parent_context, false);
881 if (outer_type == "parbox") {
883 if (p.next_token().cat() == catBegin)
885 eat_whitespace(p, os, parent_context, false);
891 // If we already read the inner box we have to push the inner env
892 if (!outer_type.empty() && !inner_type.empty() &&
893 (inner_flags & FLAG_END))
894 active_environments.push_back(inner_type);
895 // LyX can't handle length variables
896 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
897 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
898 // Look whether there is some content after the end of the
899 // inner box, but before the end of the outer box.
900 // If yes, we need to output ERT.
902 if (inner_flags & FLAG_END)
903 p.ertEnvironment(inner_type);
907 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
908 if ((outer_env && p.next_token().asInput() != "\\end") ||
909 (!outer_env && p.next_token().cat() != catEnd)) {
910 // something is between the end of the inner box and
911 // the end of the outer box, so we need to use ERT.
916 // if only \makebox{content} was used we can set its width to 1\width
917 // because this identic and also identic to \mbox
918 // this doesn't work for \framebox{content}, thus we have to use ERT for this
919 if (latex_width.empty() && inner_type == "makebox") {
922 width_special = "width";
923 } else if (latex_width.empty() && outer_type == "framebox") {
928 if (!outer_type.empty()) {
929 if (outer_flags & FLAG_END)
930 ss << "\\begin{" << outer_type << '}';
932 ss << '\\' << outer_type << '{';
933 if (!special.empty())
937 if (!inner_type.empty()) {
938 if (inner_type != "shaded") {
939 if (inner_flags & FLAG_END)
940 ss << "\\begin{" << inner_type << '}';
942 ss << '\\' << inner_type;
944 if (!position.empty())
945 ss << '[' << position << ']';
946 if (!latex_height.empty())
947 ss << '[' << latex_height << ']';
948 if (!inner_pos.empty())
949 ss << '[' << inner_pos << ']';
950 ss << '{' << latex_width << '}';
951 if (!(inner_flags & FLAG_END))
954 if (inner_type == "shaded")
955 ss << "\\begin{shaded}";
956 output_ert_inset(os, ss.str(), parent_context);
957 if (!inner_type.empty()) {
958 parse_text(p, os, inner_flags, outer, parent_context);
959 if (inner_flags & FLAG_END)
960 output_ert_inset(os, "\\end{" + inner_type + '}',
963 output_ert_inset(os, "}", parent_context);
965 if (!outer_type.empty()) {
966 // If we already read the inner box we have to pop
968 if (!inner_type.empty() && (inner_flags & FLAG_END))
969 active_environments.pop_back();
971 // Ensure that the end of the outer box is parsed correctly:
972 // The opening brace has been eaten by parse_outer_box()
973 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
974 outer_flags &= ~FLAG_ITEM;
975 outer_flags |= FLAG_BRACE_LAST;
977 parse_text(p, os, outer_flags, outer, parent_context);
978 if (outer_flags & FLAG_END)
979 output_ert_inset(os, "\\end{" + outer_type + '}',
981 else if (inner_type.empty() && outer_type == "framebox")
982 // in this case it is already closed later
985 output_ert_inset(os, "}", parent_context);
988 // LyX does not like empty positions, so we have
989 // to set them to the LaTeX default values here.
990 if (position.empty())
992 if (inner_pos.empty())
993 inner_pos = position;
994 parent_context.check_layout(os);
995 begin_inset(os, "Box ");
996 if (outer_type == "framed")
998 else if (outer_type == "framebox")
1000 else if (outer_type == "shadowbox")
1001 os << "Shadowbox\n";
1002 else if ((outer_type == "shaded" && inner_type.empty()) ||
1003 (outer_type == "minipage" && inner_type == "shaded") ||
1004 (outer_type == "parbox" && inner_type == "shaded")) {
1006 preamble.registerAutomaticallyLoadedPackage("color");
1007 } else if (outer_type == "doublebox")
1008 os << "Doublebox\n";
1009 else if (outer_type.empty())
1010 os << "Frameless\n";
1012 os << outer_type << '\n';
1013 os << "position \"" << position << "\"\n";
1014 os << "hor_pos \"" << hor_pos << "\"\n";
1015 os << "has_inner_box " << !inner_type.empty() << "\n";
1016 os << "inner_pos \"" << inner_pos << "\"\n";
1017 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1019 os << "use_makebox " << (inner_type == "makebox") << '\n';
1020 os << "width \"" << width_value << width_unit << "\"\n";
1021 os << "special \"" << width_special << "\"\n";
1022 os << "height \"" << height_value << height_unit << "\"\n";
1023 os << "height_special \"" << height_special << "\"\n";
1024 os << "status open\n\n";
1026 // Unfortunately we can't use parse_text_in_inset:
1027 // InsetBox::forcePlainLayout() is hard coded and does not
1028 // use the inset layout. Apart from that do we call parse_text
1029 // up to two times, but need only one check_end_layout.
1030 bool const forcePlainLayout =
1031 (!inner_type.empty() || inner_type == "makebox") &&
1032 outer_type != "shaded" && outer_type != "framed";
1033 Context context(true, parent_context.textclass);
1034 if (forcePlainLayout)
1035 context.layout = &context.textclass.plainLayout();
1037 context.font = parent_context.font;
1039 // If we have no inner box the contents will be read with the outer box
1040 if (!inner_type.empty())
1041 parse_text(p, os, inner_flags, outer, context);
1043 // Ensure that the end of the outer box is parsed correctly:
1044 // The opening brace has been eaten by parse_outer_box()
1045 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1046 outer_flags &= ~FLAG_ITEM;
1047 outer_flags |= FLAG_BRACE_LAST;
1050 // Find end of outer box, output contents if inner_type is
1051 // empty and output possible comments
1052 if (!outer_type.empty()) {
1053 // If we already read the inner box we have to pop
1055 if (!inner_type.empty() && (inner_flags & FLAG_END))
1056 active_environments.pop_back();
1057 // This does not output anything but comments if
1058 // inner_type is not empty (see use_ert)
1059 parse_text(p, os, outer_flags, outer, context);
1062 context.check_end_layout(os);
1064 #ifdef PRESERVE_LAYOUT
1065 // LyX puts a % after the end of the minipage
1066 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1068 //output_ert_inset(os, "%dummy", parent_context);
1071 parent_context.new_paragraph(os);
1073 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1074 //output_ert_inset(os, "%dummy", parent_context);
1077 // We add a protected space if something real follows
1078 if (p.good() && p.next_token().cat() != catComment) {
1079 begin_inset(os, "space ~\n");
1088 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1089 Context & parent_context, string const & outer_type,
1090 string const & special)
1092 eat_whitespace(p, os, parent_context, false);
1093 if (flags & FLAG_ITEM) {
1095 if (p.next_token().cat() == catBegin)
1098 cerr << "Warning: Ignoring missing '{' after \\"
1099 << outer_type << '.' << endl;
1100 eat_whitespace(p, os, parent_context, false);
1103 unsigned int inner_flags = 0;
1105 if (outer_type == "minipage" || outer_type == "parbox") {
1106 p.skip_spaces(true);
1107 while (p.hasOpt()) {
1109 p.skip_spaces(true);
1112 p.skip_spaces(true);
1113 if (outer_type == "parbox") {
1115 if (p.next_token().cat() == catBegin)
1117 p.skip_spaces(true);
1120 if (outer_type == "shaded") {
1121 // These boxes never have an inner box
1123 } else if (p.next_token().asInput() == "\\parbox") {
1124 inner = p.get_token().cs();
1125 inner_flags = FLAG_ITEM;
1126 } else if (p.next_token().asInput() == "\\begin") {
1127 // Is this a minipage or shaded box?
1130 inner = p.getArg('{', '}');
1132 if (inner == "minipage" || inner == "shaded")
1133 inner_flags = FLAG_END;
1138 if (inner_flags == FLAG_END) {
1139 if (inner != "shaded")
1143 eat_whitespace(p, os, parent_context, false);
1145 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1146 outer_type, special, inner);
1148 if (inner_flags == FLAG_ITEM) {
1150 eat_whitespace(p, os, parent_context, false);
1152 parse_box(p, os, flags, inner_flags, outer, parent_context,
1153 outer_type, special, inner);
1158 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1160 parent_context.check_layout(os);
1161 begin_inset(os, "listings\n");
1163 string arg = p.verbatimOption();
1164 os << "lstparams " << '"' << arg << '"' << '\n';
1165 if (arg.find("\\color") != string::npos)
1166 preamble.registerAutomaticallyLoadedPackage("color");
1169 os << "inline true\n";
1171 os << "inline false\n";
1172 os << "status collapsed\n";
1173 Context context(true, parent_context.textclass);
1174 context.layout = &parent_context.textclass.plainLayout();
1177 // set catcodes to verbatim early, just in case.
1178 p.setCatcodes(VERBATIM_CATCODES);
1179 string delim = p.get_token().asInput();
1180 s = p.verbatimStuff(delim);
1181 // context.new_paragraph(os);
1183 s = p.verbatimEnvironment("lstlisting");
1184 output_ert(os, s, context);
1189 /// parse an unknown environment
1190 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1191 unsigned flags, bool outer,
1192 Context & parent_context)
1194 if (name == "tabbing")
1195 // We need to remember that we have to handle '\=' specially
1196 flags |= FLAG_TABBING;
1198 // We need to translate font changes and paragraphs inside the
1199 // environment to ERT if we have a non standard font.
1200 // Otherwise things like
1201 // \large\begin{foo}\huge bar\end{foo}
1203 bool const specialfont =
1204 (parent_context.font != parent_context.normalfont);
1205 bool const new_layout_allowed = parent_context.new_layout_allowed;
1207 parent_context.new_layout_allowed = false;
1208 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1209 parse_text_snippet(p, os, flags, outer, parent_context);
1210 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1212 parent_context.new_layout_allowed = new_layout_allowed;
1216 void parse_environment(Parser & p, ostream & os, bool outer,
1217 string & last_env, Context & parent_context)
1219 Layout const * newlayout;
1220 InsetLayout const * newinsetlayout = 0;
1221 string const name = p.getArg('{', '}');
1222 const bool is_starred = suffixIs(name, '*');
1223 string const unstarred_name = rtrim(name, "*");
1224 active_environments.push_back(name);
1226 if (is_math_env(name)) {
1227 parent_context.check_layout(os);
1228 begin_inset(os, "Formula ");
1229 os << "\\begin{" << name << "}";
1230 parse_math(p, os, FLAG_END, MATH_MODE);
1231 os << "\\end{" << name << "}";
1233 if (is_display_math_env(name)) {
1234 // Prevent the conversion of a line break to a space
1235 // (bug 7668). This does not change the output, but
1236 // looks ugly in LyX.
1237 eat_whitespace(p, os, parent_context, false);
1241 else if (is_known(name, preamble.polyglossia_languages)) {
1242 // We must begin a new paragraph if not already done
1243 if (! parent_context.atParagraphStart()) {
1244 parent_context.check_end_layout(os);
1245 parent_context.new_paragraph(os);
1247 // save the language in the context so that it is
1248 // handled by parse_text
1249 parent_context.font.language = preamble.polyglossia2lyx(name);
1250 parse_text(p, os, FLAG_END, outer, parent_context);
1251 // Just in case the environment is empty
1252 parent_context.extra_stuff.erase();
1253 // We must begin a new paragraph to reset the language
1254 parent_context.new_paragraph(os);
1258 else if (unstarred_name == "tabular" || name == "longtable") {
1259 eat_whitespace(p, os, parent_context, false);
1260 string width = "0pt";
1261 if (name == "tabular*") {
1262 width = lyx::translate_len(p.getArg('{', '}'));
1263 eat_whitespace(p, os, parent_context, false);
1265 parent_context.check_layout(os);
1266 begin_inset(os, "Tabular ");
1267 handle_tabular(p, os, name, width, parent_context);
1272 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1273 eat_whitespace(p, os, parent_context, false);
1274 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1275 eat_whitespace(p, os, parent_context, false);
1276 parent_context.check_layout(os);
1277 begin_inset(os, "Float " + unstarred_name + "\n");
1278 // store the float type for subfloats
1279 // subfloats only work with figures and tables
1280 if (unstarred_name == "figure")
1281 float_type = unstarred_name;
1282 else if (unstarred_name == "table")
1283 float_type = unstarred_name;
1287 os << "placement " << opt << '\n';
1288 if (contains(opt, "H"))
1289 preamble.registerAutomaticallyLoadedPackage("float");
1291 Floating const & fl = parent_context.textclass.floats()
1292 .getType(unstarred_name);
1293 if (!fl.floattype().empty() && fl.usesFloatPkg())
1294 preamble.registerAutomaticallyLoadedPackage("float");
1297 os << "wide " << convert<string>(is_starred)
1298 << "\nsideways false"
1299 << "\nstatus open\n\n";
1300 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1302 // We don't need really a new paragraph, but
1303 // we must make sure that the next item gets a \begin_layout.
1304 parent_context.new_paragraph(os);
1306 // the float is parsed thus delete the type
1310 else if (unstarred_name == "sidewaysfigure"
1311 || unstarred_name == "sidewaystable") {
1312 eat_whitespace(p, os, parent_context, false);
1313 parent_context.check_layout(os);
1314 if (unstarred_name == "sidewaysfigure")
1315 begin_inset(os, "Float figure\n");
1317 begin_inset(os, "Float table\n");
1318 os << "wide " << convert<string>(is_starred)
1319 << "\nsideways true"
1320 << "\nstatus open\n\n";
1321 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1323 // We don't need really a new paragraph, but
1324 // we must make sure that the next item gets a \begin_layout.
1325 parent_context.new_paragraph(os);
1327 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1330 else if (name == "wrapfigure" || name == "wraptable") {
1331 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1332 eat_whitespace(p, os, parent_context, false);
1333 parent_context.check_layout(os);
1336 string overhang = "0col%";
1339 lines = p.getArg('[', ']');
1340 string const placement = p.getArg('{', '}');
1342 overhang = p.getArg('[', ']');
1343 string const width = p.getArg('{', '}');
1345 if (name == "wrapfigure")
1346 begin_inset(os, "Wrap figure\n");
1348 begin_inset(os, "Wrap table\n");
1349 os << "lines " << lines
1350 << "\nplacement " << placement
1351 << "\noverhang " << lyx::translate_len(overhang)
1352 << "\nwidth " << lyx::translate_len(width)
1353 << "\nstatus open\n\n";
1354 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1356 // We don't need really a new paragraph, but
1357 // we must make sure that the next item gets a \begin_layout.
1358 parent_context.new_paragraph(os);
1360 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1363 else if (name == "minipage") {
1364 eat_whitespace(p, os, parent_context, false);
1365 // Test whether this is an outer box of a shaded box
1367 // swallow arguments
1368 while (p.hasOpt()) {
1370 p.skip_spaces(true);
1373 p.skip_spaces(true);
1374 Token t = p.get_token();
1375 bool shaded = false;
1376 if (t.asInput() == "\\begin") {
1377 p.skip_spaces(true);
1378 if (p.getArg('{', '}') == "shaded")
1383 parse_outer_box(p, os, FLAG_END, outer,
1384 parent_context, name, "shaded");
1386 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1391 else if (name == "comment") {
1392 eat_whitespace(p, os, parent_context, false);
1393 parent_context.check_layout(os);
1394 begin_inset(os, "Note Comment\n");
1395 os << "status open\n";
1396 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1399 skip_braces(p); // eat {} that might by set by LyX behind comments
1400 preamble.registerAutomaticallyLoadedPackage("verbatim");
1403 else if (name == "verbatim") {
1404 // FIXME: this should go in the generic code that
1405 // handles environments defined in layout file that
1406 // have "PassThru 1". However, the code over there is
1407 // already too complicated for my taste.
1408 parent_context.new_paragraph(os);
1409 Context context(true, parent_context.textclass,
1410 &parent_context.textclass[from_ascii("Verbatim")]);
1411 string s = p.verbatimEnvironment("verbatim");
1412 output_ert(os, s, context);
1416 else if (name == "IPA") {
1417 eat_whitespace(p, os, parent_context, false);
1418 parent_context.check_layout(os);
1419 begin_inset(os, "IPA\n");
1420 //os << "status open\n";
1421 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1424 preamble.registerAutomaticallyLoadedPackage("tipa");
1425 preamble.registerAutomaticallyLoadedPackage("tipx");
1428 else if (name == "CJK") {
1429 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1430 // It is impossible to decide if a CJK environment was in its own paragraph or within
1431 // a line. We therefore always assume a paragraph since the latter is a rare case.
1432 eat_whitespace(p, os, parent_context, false);
1433 parent_context.check_end_layout(os);
1434 // store the encoding to be able to reset it
1435 string const encoding_old = p.getEncoding();
1436 string const encoding = p.getArg('{', '}');
1437 // FIXME: For some reason JIS does not work. Although the text
1438 // in tests/CJK.tex is identical with the SJIS version if you
1439 // convert both snippets using the recode command line utility,
1440 // the resulting .lyx file contains some extra characters if
1441 // you set buggy_encoding to false for JIS.
1442 bool const buggy_encoding = encoding == "JIS";
1443 if (!buggy_encoding)
1444 p.setEncoding(encoding, Encoding::CJK);
1446 // FIXME: This will read garbage, since the data is not encoded in utf8.
1447 p.setEncoding("UTF-8");
1449 // LyX only supports the same mapping for all CJK
1450 // environments, so we might need to output everything as ERT
1451 string const mapping = trim(p.getArg('{', '}'));
1452 char const * const * const where =
1453 is_known(encoding, supported_CJK_encodings);
1454 if (!buggy_encoding && !preamble.fontCJKSet())
1455 preamble.fontCJK(mapping);
1456 bool knownMapping = mapping == preamble.fontCJK();
1457 if (buggy_encoding || !knownMapping || !where) {
1458 parent_context.check_layout(os);
1459 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1461 // we must parse the content as verbatim because e.g. JIS can contain
1462 // normally invalid characters
1463 // FIXME: This works only for the most simple cases.
1464 // Since TeX control characters are not parsed,
1465 // things like comments are completely wrong.
1466 string const s = p.plainEnvironment("CJK");
1467 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1469 output_ert_inset(os, "\\", parent_context);
1470 else if (*it == '$')
1471 output_ert_inset(os, "$", parent_context);
1475 output_ert_inset(os, "\\end{" + name + "}",
1479 supported_CJK_languages[where - supported_CJK_encodings];
1480 // store the language because we must reset it at the end
1481 string const lang_old = parent_context.font.language;
1482 parent_context.font.language = lang;
1483 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1484 parent_context.font.language = lang_old;
1485 parent_context.new_paragraph(os);
1487 p.setEncoding(encoding_old);
1491 else if (name == "lyxgreyedout") {
1492 eat_whitespace(p, os, parent_context, false);
1493 parent_context.check_layout(os);
1494 begin_inset(os, "Note Greyedout\n");
1495 os << "status open\n";
1496 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1499 if (!preamble.notefontcolor().empty())
1500 preamble.registerAutomaticallyLoadedPackage("color");
1503 else if (name == "framed" || name == "shaded") {
1504 eat_whitespace(p, os, parent_context, false);
1505 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1509 else if (name == "lstlisting") {
1510 eat_whitespace(p, os, parent_context, false);
1511 parse_listings(p, os, parent_context, false);
1515 else if (!parent_context.new_layout_allowed)
1516 parse_unknown_environment(p, name, os, FLAG_END, outer,
1519 // Alignment and spacing settings
1520 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1521 // therefore are totally broken!
1522 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1523 // they are commands not environments. They are furthermore switches that
1524 // can be ended by another switches, but also by commands like \footnote or
1525 // \parbox. So the only safe way is to leave them untouched.
1526 else if (name == "center" || name == "centering" ||
1527 name == "flushleft" || name == "flushright" ||
1528 name == "singlespace" || name == "onehalfspace" ||
1529 name == "doublespace" || name == "spacing") {
1530 eat_whitespace(p, os, parent_context, false);
1531 // We must begin a new paragraph if not already done
1532 if (! parent_context.atParagraphStart()) {
1533 parent_context.check_end_layout(os);
1534 parent_context.new_paragraph(os);
1536 if (name == "flushleft")
1537 parent_context.add_extra_stuff("\\align left\n");
1538 else if (name == "flushright")
1539 parent_context.add_extra_stuff("\\align right\n");
1540 else if (name == "center" || name == "centering")
1541 parent_context.add_extra_stuff("\\align center\n");
1542 else if (name == "singlespace")
1543 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1544 else if (name == "onehalfspace") {
1545 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1546 preamble.registerAutomaticallyLoadedPackage("setspace");
1547 } else if (name == "doublespace") {
1548 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1549 preamble.registerAutomaticallyLoadedPackage("setspace");
1550 } else if (name == "spacing") {
1551 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1552 preamble.registerAutomaticallyLoadedPackage("setspace");
1554 parse_text(p, os, FLAG_END, outer, parent_context);
1555 // Just in case the environment is empty
1556 parent_context.extra_stuff.erase();
1557 // We must begin a new paragraph to reset the alignment
1558 parent_context.new_paragraph(os);
1562 // The single '=' is meant here.
1563 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1564 eat_whitespace(p, os, parent_context, false);
1565 Context context(true, parent_context.textclass, newlayout,
1566 parent_context.layout, parent_context.font);
1567 if (parent_context.deeper_paragraph) {
1568 // We are beginning a nested environment after a
1569 // deeper paragraph inside the outer list environment.
1570 // Therefore we don't need to output a "begin deeper".
1571 context.need_end_deeper = true;
1573 parent_context.check_end_layout(os);
1574 if (last_env == name) {
1575 // we need to output a separator since LyX would export
1576 // the two environments as one otherwise (bug 5716)
1577 docstring const sep = from_ascii("--Separator--");
1578 TeX2LyXDocClass const & textclass(parent_context.textclass);
1579 if (textclass.hasLayout(sep)) {
1580 Context newcontext(parent_context);
1581 newcontext.layout = &(textclass[sep]);
1582 newcontext.check_layout(os);
1583 newcontext.check_end_layout(os);
1585 parent_context.check_layout(os);
1586 begin_inset(os, "Note Note\n");
1587 os << "status closed\n";
1588 Context newcontext(true, textclass,
1589 &(textclass.defaultLayout()));
1590 newcontext.check_layout(os);
1591 newcontext.check_end_layout(os);
1593 parent_context.check_end_layout(os);
1596 switch (context.layout->latextype) {
1597 case LATEX_LIST_ENVIRONMENT:
1598 context.add_par_extra_stuff("\\labelwidthstring "
1599 + p.verbatim_item() + '\n');
1602 case LATEX_BIB_ENVIRONMENT:
1603 p.verbatim_item(); // swallow next arg
1609 context.check_deeper(os);
1610 // handle known optional and required arguments
1611 // FIXME: Since format 446, layouts do not require anymore all optional
1612 // arguments before the required ones. Needs to be implemented!
1613 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1614 // It is impossible to place anything after the environment name,
1615 // but before the first \\item.
1616 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1617 bool need_layout = true;
1619 while (optargs < context.layout->optArgs()) {
1620 eat_whitespace(p, os, context, false);
1621 if (p.next_token().cat() == catEscape ||
1622 p.next_token().character() != '[')
1624 p.get_token(); // eat '['
1626 context.check_layout(os);
1627 need_layout = false;
1629 // FIXME: Just a workaround. InsetArgument::updateBuffer
1630 // will compute a proper ID for all "999" Arguments
1631 // (which is also what lyx2lyx produces).
1632 // However, tex2lyx should be able to output proper IDs
1634 begin_inset(os, "Argument 999\n");
1635 os << "status collapsed\n\n";
1636 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1638 eat_whitespace(p, os, context, false);
1642 while (reqargs < context.layout->requiredArgs()) {
1643 eat_whitespace(p, os, context, false);
1644 if (p.next_token().cat() != catBegin)
1646 p.get_token(); // eat '{'
1648 context.check_layout(os);
1649 need_layout = false;
1651 // FIXME: Just a workaround. InsetArgument::updateBuffer
1652 // will compute a proper ID for all "999" Arguments
1653 // (which is also what lyx2lyx produces).
1654 // However, tex2lyx should be able to output proper IDs
1656 begin_inset(os, "Argument 999\n");
1657 os << "status collapsed\n\n";
1658 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1660 eat_whitespace(p, os, context, false);
1664 parse_text(p, os, FLAG_END, outer, context);
1665 context.check_end_layout(os);
1666 if (parent_context.deeper_paragraph) {
1667 // We must suppress the "end deeper" because we
1668 // suppressed the "begin deeper" above.
1669 context.need_end_deeper = false;
1671 context.check_end_deeper(os);
1672 parent_context.new_paragraph(os);
1674 if (!preamble.titleLayoutFound())
1675 preamble.titleLayoutFound(newlayout->intitle);
1676 set<string> const & req = newlayout->requires();
1677 set<string>::const_iterator it = req.begin();
1678 set<string>::const_iterator en = req.end();
1679 for (; it != en; ++it)
1680 preamble.registerAutomaticallyLoadedPackage(*it);
1683 // The single '=' is meant here.
1684 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1685 eat_whitespace(p, os, parent_context, false);
1686 parent_context.check_layout(os);
1687 begin_inset(os, "Flex ");
1688 os << to_utf8(newinsetlayout->name()) << '\n'
1689 << "status collapsed\n";
1690 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1694 else if (name == "appendix") {
1695 // This is no good latex style, but it works and is used in some documents...
1696 eat_whitespace(p, os, parent_context, false);
1697 parent_context.check_end_layout(os);
1698 Context context(true, parent_context.textclass, parent_context.layout,
1699 parent_context.layout, parent_context.font);
1700 context.check_layout(os);
1701 os << "\\start_of_appendix\n";
1702 parse_text(p, os, FLAG_END, outer, context);
1703 context.check_end_layout(os);
1707 else if (known_environments.find(name) != known_environments.end()) {
1708 vector<ArgumentType> arguments = known_environments[name];
1709 // The last "argument" denotes wether we may translate the
1710 // environment contents to LyX
1711 // The default required if no argument is given makes us
1712 // compatible with the reLyXre environment.
1713 ArgumentType contents = arguments.empty() ?
1716 if (!arguments.empty())
1717 arguments.pop_back();
1718 // See comment in parse_unknown_environment()
1719 bool const specialfont =
1720 (parent_context.font != parent_context.normalfont);
1721 bool const new_layout_allowed =
1722 parent_context.new_layout_allowed;
1724 parent_context.new_layout_allowed = false;
1725 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1726 outer, parent_context);
1727 if (contents == verbatim)
1728 output_ert_inset(os, p.ertEnvironment(name),
1731 parse_text_snippet(p, os, FLAG_END, outer,
1733 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1735 parent_context.new_layout_allowed = new_layout_allowed;
1739 parse_unknown_environment(p, name, os, FLAG_END, outer,
1743 active_environments.pop_back();
1747 /// parses a comment and outputs it to \p os.
1748 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1750 LASSERT(t.cat() == catComment, return);
1751 if (!t.cs().empty()) {
1752 context.check_layout(os);
1753 output_ert_inset(os, '%' + t.cs(), context);
1754 if (p.next_token().cat() == catNewline) {
1755 // A newline after a comment line starts a new
1757 if (context.new_layout_allowed) {
1758 if(!context.atParagraphStart())
1759 // Only start a new paragraph if not already
1760 // done (we might get called recursively)
1761 context.new_paragraph(os);
1763 output_ert_inset(os, "\n", context);
1764 eat_whitespace(p, os, context, true);
1767 // "%\n" combination
1774 * Reads spaces and comments until the first non-space, non-comment token.
1775 * New paragraphs (double newlines or \\par) are handled like simple spaces
1776 * if \p eatParagraph is true.
1777 * Spaces are skipped, but comments are written to \p os.
1779 void eat_whitespace(Parser & p, ostream & os, Context & context,
1783 Token const & t = p.get_token();
1784 if (t.cat() == catComment)
1785 parse_comment(p, os, t, context);
1786 else if ((! eatParagraph && p.isParagraph()) ||
1787 (t.cat() != catSpace && t.cat() != catNewline)) {
1796 * Set a font attribute, parse text and reset the font attribute.
1797 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1798 * \param currentvalue Current value of the attribute. Is set to the new
1799 * value during parsing.
1800 * \param newvalue New value of the attribute
1802 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1803 Context & context, string const & attribute,
1804 string & currentvalue, string const & newvalue)
1806 context.check_layout(os);
1807 string const oldvalue = currentvalue;
1808 currentvalue = newvalue;
1809 os << '\n' << attribute << ' ' << newvalue << "\n";
1810 parse_text_snippet(p, os, flags, outer, context);
1811 context.check_layout(os);
1812 os << '\n' << attribute << ' ' << oldvalue << "\n";
1813 currentvalue = oldvalue;
1817 /// get the arguments of a natbib or jurabib citation command
1818 void get_cite_arguments(Parser & p, bool natbibOrder,
1819 string & before, string & after)
1821 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1823 // text before the citation
1825 // text after the citation
1826 after = p.getFullOpt();
1828 if (!after.empty()) {
1829 before = p.getFullOpt();
1830 if (natbibOrder && !before.empty())
1831 swap(before, after);
1836 /// Convert filenames with TeX macros and/or quotes to something LyX
1838 string const normalize_filename(string const & name)
1843 Token const & t = p.get_token();
1844 if (t.cat() != catEscape)
1846 else if (t.cs() == "lyxdot") {
1847 // This is used by LyX for simple dots in relative
1851 } else if (t.cs() == "space") {
1854 } else if (t.cs() == "string") {
1855 // Convert \string" to " and \string~ to ~
1856 Token const & n = p.next_token();
1857 if (n.asInput() != "\"" && n.asInput() != "~")
1862 // Strip quotes. This is a bit complicated (see latex_path()).
1863 string full = os.str();
1864 if (!full.empty() && full[0] == '"') {
1865 string base = removeExtension(full);
1866 string ext = getExtension(full);
1867 if (!base.empty() && base[base.length()-1] == '"')
1870 return addExtension(trim(base, "\""), ext);
1871 if (full[full.length()-1] == '"')
1874 return trim(full, "\"");
1880 /// Convert \p name from TeX convention (relative to master file) to LyX
1881 /// convention (relative to .lyx file) if it is relative
1882 void fix_child_filename(string & name)
1884 string const absMasterTeX = getMasterFilePath(true);
1885 bool const isabs = FileName::isAbsolute(name);
1886 // convert from "relative to .tex master" to absolute original path
1888 name = makeAbsPath(name, absMasterTeX).absFileName();
1889 bool copyfile = copyFiles();
1890 string const absParentLyX = getParentFilePath(false);
1893 // convert from absolute original path to "relative to master file"
1894 string const rel = to_utf8(makeRelPath(from_utf8(name),
1895 from_utf8(absMasterTeX)));
1896 // re-interpret "relative to .tex file" as "relative to .lyx file"
1897 // (is different if the master .lyx file resides in a
1898 // different path than the master .tex file)
1899 string const absMasterLyX = getMasterFilePath(false);
1900 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1901 // Do not copy if the new path is impossible to create. Example:
1902 // absMasterTeX = "/foo/bar/"
1903 // absMasterLyX = "/bar/"
1904 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1905 if (contains(name, "/../"))
1912 // convert from absolute original path to
1913 // "relative to .lyx file"
1914 name = to_utf8(makeRelPath(from_utf8(abs),
1915 from_utf8(absParentLyX)));
1919 // convert from absolute original path to "relative to .lyx file"
1920 name = to_utf8(makeRelPath(from_utf8(name),
1921 from_utf8(absParentLyX)));
1926 void copy_file(FileName const & src, string dstname)
1930 string const absParent = getParentFilePath(false);
1932 if (FileName::isAbsolute(dstname))
1933 dst = FileName(dstname);
1935 dst = makeAbsPath(dstname, absParent);
1936 string const absMaster = getMasterFilePath(false);
1937 FileName const srcpath = src.onlyPath();
1938 FileName const dstpath = dst.onlyPath();
1939 if (equivalent(srcpath, dstpath))
1941 if (!dstpath.isDirectory()) {
1942 if (!dstpath.createPath()) {
1943 cerr << "Warning: Could not create directory for file `"
1944 << dst.absFileName() << "´." << endl;
1948 if (dst.isReadableFile()) {
1949 if (overwriteFiles())
1950 cerr << "Warning: Overwriting existing file `"
1951 << dst.absFileName() << "´." << endl;
1953 cerr << "Warning: Not overwriting existing file `"
1954 << dst.absFileName() << "´." << endl;
1958 if (!src.copyTo(dst))
1959 cerr << "Warning: Could not copy file `" << src.absFileName()
1960 << "´ to `" << dst.absFileName() << "´." << endl;
1964 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1965 void parse_noweb(Parser & p, ostream & os, Context & context)
1967 // assemble the rest of the keyword
1971 Token const & t = p.get_token();
1972 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1975 chunk = (p.good() && p.next_token().asInput() == "=");
1977 name += p.get_token().asInput();
1980 name += t.asInput();
1983 if (!chunk || !context.new_layout_allowed ||
1984 !context.textclass.hasLayout(from_ascii("Chunk"))) {
1985 cerr << "Warning: Could not interpret '" << name
1986 << "'. Ignoring it." << endl;
1990 // We use new_paragraph instead of check_end_layout because the stuff
1991 // following the noweb chunk needs to start with a \begin_layout.
1992 // This may create a new paragraph even if there was none in the
1993 // noweb file, but the alternative is an invalid LyX file. Since
1994 // noweb code chunks are implemented with a layout style in LyX they
1995 // always must be in an own paragraph.
1996 context.new_paragraph(os);
1997 Context newcontext(true, context.textclass,
1998 &context.textclass[from_ascii("Chunk")]);
1999 newcontext.check_layout(os);
2002 Token const & t = p.get_token();
2003 // We abuse the parser a bit, because this is no TeX syntax
2005 if (t.cat() == catEscape)
2006 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2009 Context tmp(false, context.textclass,
2010 &context.textclass[from_ascii("Chunk")]);
2011 tmp.need_end_layout = true;
2012 tmp.check_layout(oss);
2013 os << subst(t.asInput(), "\n", oss.str());
2015 // The chunk is ended by an @ at the beginning of a line.
2016 // After the @ the line may contain a comment and/or
2017 // whitespace, but nothing else.
2018 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2019 (p.next_token().cat() == catSpace ||
2020 p.next_token().cat() == catNewline ||
2021 p.next_token().cat() == catComment)) {
2022 while (p.good() && p.next_token().cat() == catSpace)
2023 os << p.get_token().asInput();
2024 if (p.next_token().cat() == catComment)
2025 // The comment includes a final '\n'
2026 os << p.get_token().asInput();
2028 if (p.next_token().cat() == catNewline)
2035 newcontext.check_end_layout(os);
2039 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2040 bool is_macro(Parser & p)
2042 Token first = p.curr_token();
2043 if (first.cat() != catEscape || !p.good())
2045 if (first.cs() == "def")
2047 if (first.cs() != "global" && first.cs() != "long")
2049 Token second = p.get_token();
2051 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2052 second.cat() == catNewline || second.cat() == catComment)) {
2053 second = p.get_token();
2056 bool secondvalid = second.cat() == catEscape;
2058 bool thirdvalid = false;
2059 if (p.good() && first.cs() == "global" && secondvalid &&
2060 second.cs() == "long") {
2061 third = p.get_token();
2063 while (p.good() && !p.isParagraph() &&
2064 (third.cat() == catSpace ||
2065 third.cat() == catNewline ||
2066 third.cat() == catComment)) {
2067 third = p.get_token();
2070 thirdvalid = third.cat() == catEscape;
2072 for (int i = 0; i < pos; ++i)
2077 return (first.cs() == "global" || first.cs() == "long") &&
2078 second.cs() == "def";
2079 return first.cs() == "global" && second.cs() == "long" &&
2080 third.cs() == "def";
2084 /// Parse a macro definition (assumes that is_macro() returned true)
2085 void parse_macro(Parser & p, ostream & os, Context & context)
2087 context.check_layout(os);
2088 Token first = p.curr_token();
2091 string command = first.asInput();
2092 if (first.cs() != "def") {
2094 eat_whitespace(p, os, context, false);
2095 second = p.curr_token();
2096 command += second.asInput();
2097 if (second.cs() != "def") {
2099 eat_whitespace(p, os, context, false);
2100 third = p.curr_token();
2101 command += third.asInput();
2104 eat_whitespace(p, os, context, false);
2105 string const name = p.get_token().cs();
2106 eat_whitespace(p, os, context, false);
2112 while (p.next_token().cat() != catBegin) {
2113 if (p.next_token().cat() == catParameter) {
2118 // followed by number?
2119 if (p.next_token().cat() == catOther) {
2120 string s = p.get_token().asInput();
2122 // number = current arity + 1?
2123 if (s.size() == 1 && s[0] == arity + '0' + 1)
2128 paramtext += p.get_token().cs();
2130 paramtext += p.get_token().cs();
2135 // only output simple (i.e. compatible) macro as FormulaMacros
2136 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2138 context.check_layout(os);
2139 begin_inset(os, "FormulaMacro");
2140 os << "\n\\def" << ert;
2143 output_ert_inset(os, command + ert, context);
2147 void registerExternalTemplatePackages(string const & name)
2149 external::TemplateManager const & etm = external::TemplateManager::get();
2150 external::Template const * const et = etm.getTemplateByName(name);
2153 external::Template::Formats::const_iterator cit = et->formats.end();
2155 cit = et->formats.find("PDFLaTeX");
2156 if (cit == et->formats.end())
2157 // If the template has not specified a PDFLaTeX output,
2158 // we try the LaTeX format.
2159 cit = et->formats.find("LaTeX");
2160 if (cit == et->formats.end())
2162 vector<string>::const_iterator qit = cit->second.requirements.begin();
2163 vector<string>::const_iterator qend = cit->second.requirements.end();
2164 for (; qit != qend; ++qit)
2165 preamble.registerAutomaticallyLoadedPackage(*qit);
2168 } // anonymous namespace
2171 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2174 Layout const * newlayout = 0;
2175 InsetLayout const * newinsetlayout = 0;
2176 char const * const * where = 0;
2177 // Store the latest bibliographystyle, addcontentslineContent and
2178 // nocite{*} option (needed for bibtex inset)
2180 string contentslineContent;
2181 string bibliographystyle = "default";
2182 bool const use_natbib = isProvided("natbib");
2183 bool const use_jurabib = isProvided("jurabib");
2186 Token const & t = p.get_token();
2188 // it is impossible to determine the correct encoding for non-CJK Japanese.
2189 // Therefore write a note at the beginning of the document
2190 if (is_nonCJKJapanese) {
2191 context.check_layout(os);
2192 begin_inset(os, "Note Note\n");
2193 os << "status open\n\\begin_layout Plain Layout\n"
2194 << "\\series bold\n"
2195 << "Important information:\n"
2196 << "\\end_layout\n\n"
2197 << "\\begin_layout Plain Layout\n"
2198 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2199 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2200 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2201 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2202 << " and specify the encoding using the -e command-line switch.\n"
2203 << " In addition, you might want to double check that the desired output encoding\n"
2204 << " is correctly selected in Document > Settings > Language.\n"
2205 << "\\end_layout\n";
2207 is_nonCJKJapanese = false;
2211 debugToken(cerr, t, flags);
2214 if (flags & FLAG_ITEM) {
2215 if (t.cat() == catSpace)
2218 flags &= ~FLAG_ITEM;
2219 if (t.cat() == catBegin) {
2220 // skip the brace and collect everything to the next matching
2222 flags |= FLAG_BRACE_LAST;
2226 // handle only this single token, leave the loop if done
2227 flags |= FLAG_LEAVE;
2230 if (t.cat() != catEscape && t.character() == ']' &&
2231 (flags & FLAG_BRACK_LAST))
2233 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2236 // If there is anything between \end{env} and \begin{env} we
2237 // don't need to output a separator.
2238 if (t.cat() != catSpace && t.cat() != catNewline &&
2239 t.asInput() != "\\begin")
2245 if (t.cat() == catMath) {
2246 // we are inside some text mode thingy, so opening new math is allowed
2247 context.check_layout(os);
2248 begin_inset(os, "Formula ");
2249 Token const & n = p.get_token();
2250 bool const display(n.cat() == catMath && outer);
2252 // TeX's $$...$$ syntax for displayed math
2254 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2256 p.get_token(); // skip the second '$' token
2258 // simple $...$ stuff
2261 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2266 // Prevent the conversion of a line break to a
2267 // space (bug 7668). This does not change the
2268 // output, but looks ugly in LyX.
2269 eat_whitespace(p, os, context, false);
2273 else if (t.cat() == catSuper || t.cat() == catSub)
2274 cerr << "catcode " << t << " illegal in text mode\n";
2276 // Basic support for english quotes. This should be
2277 // extended to other quotes, but is not so easy (a
2278 // left english quote is the same as a right german
2280 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2281 context.check_layout(os);
2282 begin_inset(os, "Quotes ");
2288 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2289 context.check_layout(os);
2290 begin_inset(os, "Quotes ");
2297 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2298 context.check_layout(os);
2299 begin_inset(os, "Quotes ");
2306 else if (t.asInput() == "<"
2307 && p.next_token().asInput() == "<" && noweb_mode) {
2309 parse_noweb(p, os, context);
2312 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2313 context.check_layout(os);
2314 begin_inset(os, "Quotes ");
2321 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2322 check_space(p, os, context);
2324 else if (t.character() == '[' && noweb_mode &&
2325 p.next_token().character() == '[') {
2326 // These can contain underscores
2328 string const s = p.getFullOpt() + ']';
2329 if (p.next_token().character() == ']')
2332 cerr << "Warning: Inserting missing ']' in '"
2333 << s << "'." << endl;
2334 output_ert_inset(os, s, context);
2337 else if (t.cat() == catLetter) {
2338 context.check_layout(os);
2339 // Workaround for bug 4752.
2340 // FIXME: This whole code block needs to be removed
2341 // when the bug is fixed and tex2lyx produces
2342 // the updated file format.
2343 // The replacement algorithm in LyX is so stupid that
2344 // it even translates a phrase if it is part of a word.
2345 bool handled = false;
2346 for (int const * l = known_phrase_lengths; *l; ++l) {
2347 string phrase = t.cs();
2348 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2349 phrase += p.get_token().cs();
2350 if (is_known(phrase, known_coded_phrases)) {
2351 output_ert_inset(os, phrase, context);
2355 for (size_t i = 1; i < phrase.length(); ++i)
2363 else if (t.cat() == catOther ||
2364 t.cat() == catAlign ||
2365 t.cat() == catParameter) {
2366 // This translates "&" to "\\&" which may be wrong...
2367 context.check_layout(os);
2371 else if (p.isParagraph()) {
2372 if (context.new_layout_allowed)
2373 context.new_paragraph(os);
2375 output_ert_inset(os, "\\par ", context);
2376 eat_whitespace(p, os, context, true);
2379 else if (t.cat() == catActive) {
2380 context.check_layout(os);
2381 if (t.character() == '~') {
2382 if (context.layout->free_spacing)
2385 begin_inset(os, "space ~\n");
2392 else if (t.cat() == catBegin) {
2393 Token const next = p.next_token();
2394 Token const end = p.next_next_token();
2395 if (next.cat() == catEnd) {
2397 Token const prev = p.prev_token();
2399 if (p.next_token().character() == '`' ||
2400 (prev.character() == '-' &&
2401 p.next_token().character() == '-'))
2402 ; // ignore it in {}`` or -{}-
2404 output_ert_inset(os, "{}", context);
2405 } else if (next.cat() == catEscape &&
2406 is_known(next.cs(), known_quotes) &&
2407 end.cat() == catEnd) {
2408 // Something like {\textquoteright} (e.g.
2409 // from writer2latex). LyX writes
2410 // \textquoteright{}, so we may skip the
2411 // braces here for better readability.
2412 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2415 context.check_layout(os);
2416 // special handling of font attribute changes
2417 Token const prev = p.prev_token();
2418 TeXFont const oldFont = context.font;
2419 if (next.character() == '[' ||
2420 next.character() == ']' ||
2421 next.character() == '*') {
2423 if (p.next_token().cat() == catEnd) {
2428 output_ert_inset(os, "{", context);
2429 parse_text_snippet(p, os,
2432 output_ert_inset(os, "}", context);
2434 } else if (! context.new_layout_allowed) {
2435 output_ert_inset(os, "{", context);
2436 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2438 output_ert_inset(os, "}", context);
2439 } else if (is_known(next.cs(), known_sizes)) {
2440 // next will change the size, so we must
2442 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2444 if (!context.atParagraphStart())
2446 << context.font.size << "\n";
2447 } else if (is_known(next.cs(), known_font_families)) {
2448 // next will change the font family, so we
2449 // must reset it here
2450 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2452 if (!context.atParagraphStart())
2454 << context.font.family << "\n";
2455 } else if (is_known(next.cs(), known_font_series)) {
2456 // next will change the font series, so we
2457 // must reset it here
2458 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2460 if (!context.atParagraphStart())
2462 << context.font.series << "\n";
2463 } else if (is_known(next.cs(), known_font_shapes)) {
2464 // next will change the font shape, so we
2465 // must reset it here
2466 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2468 if (!context.atParagraphStart())
2470 << context.font.shape << "\n";
2471 } else if (is_known(next.cs(), known_old_font_families) ||
2472 is_known(next.cs(), known_old_font_series) ||
2473 is_known(next.cs(), known_old_font_shapes)) {
2474 // next will change the font family, series
2475 // and shape, so we must reset it here
2476 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2478 if (!context.atParagraphStart())
2480 << context.font.family
2482 << context.font.series
2484 << context.font.shape << "\n";
2486 output_ert_inset(os, "{", context);
2487 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2489 output_ert_inset(os, "}", context);
2494 else if (t.cat() == catEnd) {
2495 if (flags & FLAG_BRACE_LAST) {
2498 cerr << "stray '}' in text\n";
2499 output_ert_inset(os, "}", context);
2502 else if (t.cat() == catComment)
2503 parse_comment(p, os, t, context);
2506 // control sequences
2509 else if (t.cs() == "(") {
2510 context.check_layout(os);
2511 begin_inset(os, "Formula");
2513 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2518 else if (t.cs() == "[") {
2519 context.check_layout(os);
2520 begin_inset(os, "Formula");
2522 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2525 // Prevent the conversion of a line break to a space
2526 // (bug 7668). This does not change the output, but
2527 // looks ugly in LyX.
2528 eat_whitespace(p, os, context, false);
2531 else if (t.cs() == "begin")
2532 parse_environment(p, os, outer, last_env,
2535 else if (t.cs() == "end") {
2536 if (flags & FLAG_END) {
2537 // eat environment name
2538 string const name = p.getArg('{', '}');
2539 if (name != active_environment())
2540 cerr << "\\end{" + name + "} does not match \\begin{"
2541 + active_environment() + "}\n";
2544 p.error("found 'end' unexpectedly");
2547 else if (t.cs() == "item") {
2549 bool const optarg = p.hasOpt();
2551 // FIXME: This swallows comments, but we cannot use
2552 // eat_whitespace() since we must not output
2553 // anything before the item.
2554 p.skip_spaces(true);
2555 s = p.verbatimOption();
2557 p.skip_spaces(false);
2559 context.check_layout(os);
2560 if (context.has_item) {
2561 // An item in an unknown list-like environment
2562 // FIXME: Do this in check_layout()!
2563 context.has_item = false;
2565 output_ert_inset(os, "\\item", context);
2567 output_ert_inset(os, "\\item ", context);
2570 if (context.layout->labeltype != LABEL_MANUAL) {
2571 // LyX does not support \item[\mybullet]
2572 // in itemize environments
2574 os << parse_text_snippet(p2,
2575 FLAG_BRACK_LAST, outer, context);
2576 } else if (!s.empty()) {
2577 // LyX adds braces around the argument,
2578 // so we need to remove them here.
2579 if (s.size() > 2 && s[0] == '{' &&
2580 s[s.size()-1] == '}')
2581 s = s.substr(1, s.size()-2);
2582 // If the argument contains a space we
2583 // must put it into ERT: Otherwise LyX
2584 // would misinterpret the space as
2585 // item delimiter (bug 7663)
2586 if (contains(s, ' ')) {
2587 output_ert_inset(os, s, context);
2590 os << parse_text_snippet(p2,
2594 // The space is needed to separate the
2595 // item from the rest of the sentence.
2597 eat_whitespace(p, os, context, false);
2602 else if (t.cs() == "bibitem") {
2604 context.check_layout(os);
2605 eat_whitespace(p, os, context, false);
2606 string label = convert_command_inset_arg(p.verbatimOption());
2607 string key = convert_command_inset_arg(p.verbatim_item());
2608 if (contains(label, '\\') || contains(key, '\\')) {
2609 // LyX can't handle LaTeX commands in labels or keys
2610 output_ert_inset(os, t.asInput() + '[' + label +
2611 "]{" + p.verbatim_item() + '}',
2614 begin_command_inset(os, "bibitem", "bibitem");
2615 os << "label \"" << label << "\"\n"
2616 "key \"" << key << "\"\n";
2621 else if (is_macro(p)) {
2622 // catch the case of \def\inputGnumericTable
2624 if (t.cs() == "def") {
2625 Token second = p.next_token();
2626 if (second.cs() == "inputGnumericTable") {
2630 Token third = p.get_token();
2632 if (third.cs() == "input") {
2636 string name = normalize_filename(p.verbatim_item());
2637 string const path = getMasterFilePath(true);
2638 // We want to preserve relative / absolute filenames,
2639 // therefore path is only used for testing
2640 // The file extension is in every case ".tex".
2641 // So we need to remove this extension and check for
2642 // the original one.
2643 name = removeExtension(name);
2644 if (!makeAbsPath(name, path).exists()) {
2645 char const * const Gnumeric_formats[] = {"gnumeric",
2647 string const Gnumeric_name =
2648 find_file(name, path, Gnumeric_formats);
2649 if (!Gnumeric_name.empty())
2650 name = Gnumeric_name;
2652 FileName const absname = makeAbsPath(name, path);
2653 if (absname.exists()) {
2654 fix_child_filename(name);
2655 copy_file(absname, name);
2657 cerr << "Warning: Could not find file '"
2658 << name << "'." << endl;
2659 context.check_layout(os);
2660 begin_inset(os, "External\n\ttemplate ");
2661 os << "GnumericSpreadsheet\n\tfilename "
2664 context.check_layout(os);
2666 // register the packages that are automatically loaded
2667 // by the Gnumeric template
2668 registerExternalTemplatePackages("GnumericSpreadsheet");
2673 parse_macro(p, os, context);
2676 else if (t.cs() == "noindent") {
2678 context.add_par_extra_stuff("\\noindent\n");
2681 else if (t.cs() == "appendix") {
2682 context.add_par_extra_stuff("\\start_of_appendix\n");
2683 // We need to start a new paragraph. Otherwise the
2684 // appendix in 'bla\appendix\chapter{' would start
2686 context.new_paragraph(os);
2687 // We need to make sure that the paragraph is
2688 // generated even if it is empty. Otherwise the
2689 // appendix in '\par\appendix\par\chapter{' would
2691 context.check_layout(os);
2692 // FIXME: This is a hack to prevent paragraph
2693 // deletion if it is empty. Handle this better!
2694 output_ert_inset(os,
2695 "%dummy comment inserted by tex2lyx to "
2696 "ensure that this paragraph is not empty",
2698 // Both measures above may generate an additional
2699 // empty paragraph, but that does not hurt, because
2700 // whitespace does not matter here.
2701 eat_whitespace(p, os, context, true);
2704 // Must catch empty dates before findLayout is called below
2705 else if (t.cs() == "date") {
2706 eat_whitespace(p, os, context, false);
2708 string const date = p.verbatim_item();
2711 preamble.suppressDate(true);
2714 preamble.suppressDate(false);
2715 if (context.new_layout_allowed &&
2716 (newlayout = findLayout(context.textclass,
2719 output_command_layout(os, p, outer,
2720 context, newlayout);
2721 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2722 if (!preamble.titleLayoutFound())
2723 preamble.titleLayoutFound(newlayout->intitle);
2724 set<string> const & req = newlayout->requires();
2725 set<string>::const_iterator it = req.begin();
2726 set<string>::const_iterator en = req.end();
2727 for (; it != en; ++it)
2728 preamble.registerAutomaticallyLoadedPackage(*it);
2730 output_ert_inset(os,
2731 "\\date{" + p.verbatim_item() + '}',
2736 // Starred section headings
2737 // Must attempt to parse "Section*" before "Section".
2738 else if ((p.next_token().asInput() == "*") &&
2739 context.new_layout_allowed &&
2740 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2743 output_command_layout(os, p, outer, context, newlayout);
2745 if (!preamble.titleLayoutFound())
2746 preamble.titleLayoutFound(newlayout->intitle);
2747 set<string> const & req = newlayout->requires();
2748 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2749 preamble.registerAutomaticallyLoadedPackage(*it);
2752 // Section headings and the like
2753 else if (context.new_layout_allowed &&
2754 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2756 output_command_layout(os, p, outer, context, newlayout);
2758 if (!preamble.titleLayoutFound())
2759 preamble.titleLayoutFound(newlayout->intitle);
2760 set<string> const & req = newlayout->requires();
2761 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2762 preamble.registerAutomaticallyLoadedPackage(*it);
2765 else if (t.cs() == "caption") {
2767 context.check_layout(os);
2769 begin_inset(os, "Caption Standard\n");
2770 Context newcontext(true, context.textclass, 0, 0, context.font);
2771 newcontext.check_layout(os);
2772 // FIXME InsetArgument is now properly implemented in InsetLayout
2773 // (for captions, but also for others)
2774 if (p.next_token().cat() != catEscape &&
2775 p.next_token().character() == '[') {
2776 p.get_token(); // eat '['
2777 begin_inset(os, "Argument 1\n");
2778 os << "status collapsed\n";
2779 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2781 eat_whitespace(p, os, context, false);
2783 parse_text(p, os, FLAG_ITEM, outer, context);
2784 context.check_end_layout(os);
2785 // We don't need really a new paragraph, but
2786 // we must make sure that the next item gets a \begin_layout.
2787 context.new_paragraph(os);
2790 newcontext.check_end_layout(os);
2793 else if (t.cs() == "subfloat") {
2794 // the syntax is \subfloat[caption]{content}
2795 // if it is a table of figure depends on the surrounding float
2796 bool has_caption = false;
2798 // do nothing if there is no outer float
2799 if (!float_type.empty()) {
2800 context.check_layout(os);
2802 begin_inset(os, "Float " + float_type + "\n");
2804 << "\nsideways false"
2805 << "\nstatus collapsed\n\n";
2808 if (p.next_token().cat() != catEscape &&
2809 p.next_token().character() == '[') {
2810 p.get_token(); // eat '['
2811 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2815 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2816 // the caption comes always as the last
2818 // we must make sure that the caption gets a \begin_layout
2819 os << "\n\\begin_layout Plain Layout";
2821 begin_inset(os, "Caption Standard\n");
2822 Context newcontext(true, context.textclass,
2823 0, 0, context.font);
2824 newcontext.check_layout(os);
2825 os << caption << "\n";
2826 newcontext.check_end_layout(os);
2827 // We don't need really a new paragraph, but
2828 // we must make sure that the next item gets a \begin_layout.
2829 //newcontext.new_paragraph(os);
2833 // We don't need really a new paragraph, but
2834 // we must make sure that the next item gets a \begin_layout.
2836 context.new_paragraph(os);
2839 context.check_end_layout(os);
2840 // close the layout we opened
2842 os << "\n\\end_layout\n";
2844 // if the float type is not supported or there is no surrounding float
2847 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2848 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2849 "]{" + p.verbatim_item() + '}', context);
2851 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2855 else if (t.cs() == "includegraphics") {
2856 bool const clip = p.next_token().asInput() == "*";
2859 string const arg = p.getArg('[', ']');
2860 map<string, string> opts;
2861 vector<string> keys;
2862 split_map(arg, opts, keys);
2864 opts["clip"] = string();
2865 string name = normalize_filename(p.verbatim_item());
2867 string const path = getMasterFilePath(true);
2868 // We want to preserve relative / absolute filenames,
2869 // therefore path is only used for testing
2870 if (!makeAbsPath(name, path).exists()) {
2871 // The file extension is probably missing.
2872 // Now try to find it out.
2873 string const dvips_name =
2874 find_file(name, path,
2875 known_dvips_graphics_formats);
2876 string const pdftex_name =
2877 find_file(name, path,
2878 known_pdftex_graphics_formats);
2879 if (!dvips_name.empty()) {
2880 if (!pdftex_name.empty()) {
2881 cerr << "This file contains the "
2883 "\"\\includegraphics{"
2885 "However, files\n\""
2886 << dvips_name << "\" and\n\""
2887 << pdftex_name << "\"\n"
2888 "both exist, so I had to make a "
2889 "choice and took the first one.\n"
2890 "Please move the unwanted one "
2891 "someplace else and try again\n"
2892 "if my choice was wrong."
2896 } else if (!pdftex_name.empty()) {
2902 FileName const absname = makeAbsPath(name, path);
2903 if (absname.exists()) {
2904 fix_child_filename(name);
2905 copy_file(absname, name);
2907 cerr << "Warning: Could not find graphics file '"
2908 << name << "'." << endl;
2910 context.check_layout(os);
2911 begin_inset(os, "Graphics ");
2912 os << "\n\tfilename " << name << '\n';
2913 if (opts.find("width") != opts.end())
2915 << translate_len(opts["width"]) << '\n';
2916 if (opts.find("height") != opts.end())
2918 << translate_len(opts["height"]) << '\n';
2919 if (opts.find("scale") != opts.end()) {
2920 istringstream iss(opts["scale"]);
2924 os << "\tscale " << val << '\n';
2926 if (opts.find("angle") != opts.end()) {
2927 os << "\trotateAngle "
2928 << opts["angle"] << '\n';
2929 vector<string>::const_iterator a =
2930 find(keys.begin(), keys.end(), "angle");
2931 vector<string>::const_iterator s =
2932 find(keys.begin(), keys.end(), "width");
2933 if (s == keys.end())
2934 s = find(keys.begin(), keys.end(), "height");
2935 if (s == keys.end())
2936 s = find(keys.begin(), keys.end(), "scale");
2937 if (s != keys.end() && distance(s, a) > 0)
2938 os << "\tscaleBeforeRotation\n";
2940 if (opts.find("origin") != opts.end()) {
2942 string const opt = opts["origin"];
2943 if (opt.find('l') != string::npos) ss << "left";
2944 if (opt.find('r') != string::npos) ss << "right";
2945 if (opt.find('c') != string::npos) ss << "center";
2946 if (opt.find('t') != string::npos) ss << "Top";
2947 if (opt.find('b') != string::npos) ss << "Bottom";
2948 if (opt.find('B') != string::npos) ss << "Baseline";
2949 if (!ss.str().empty())
2950 os << "\trotateOrigin " << ss.str() << '\n';
2952 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2954 if (opts.find("keepaspectratio") != opts.end())
2955 os << "\tkeepAspectRatio\n";
2956 if (opts.find("clip") != opts.end())
2958 if (opts.find("draft") != opts.end())
2960 if (opts.find("bb") != opts.end())
2961 os << "\tBoundingBox "
2962 << opts["bb"] << '\n';
2963 int numberOfbbOptions = 0;
2964 if (opts.find("bbllx") != opts.end())
2965 numberOfbbOptions++;
2966 if (opts.find("bblly") != opts.end())
2967 numberOfbbOptions++;
2968 if (opts.find("bburx") != opts.end())
2969 numberOfbbOptions++;
2970 if (opts.find("bbury") != opts.end())
2971 numberOfbbOptions++;
2972 if (numberOfbbOptions == 4)
2973 os << "\tBoundingBox "
2974 << opts["bbllx"] << " " << opts["bblly"] << " "
2975 << opts["bburx"] << " " << opts["bbury"] << '\n';
2976 else if (numberOfbbOptions > 0)
2977 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2978 numberOfbbOptions = 0;
2979 if (opts.find("natwidth") != opts.end())
2980 numberOfbbOptions++;
2981 if (opts.find("natheight") != opts.end())
2982 numberOfbbOptions++;
2983 if (numberOfbbOptions == 2)
2984 os << "\tBoundingBox 0bp 0bp "
2985 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2986 else if (numberOfbbOptions > 0)
2987 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2988 ostringstream special;
2989 if (opts.find("hiresbb") != opts.end())
2990 special << "hiresbb,";
2991 if (opts.find("trim") != opts.end())
2993 if (opts.find("viewport") != opts.end())
2994 special << "viewport=" << opts["viewport"] << ',';
2995 if (opts.find("totalheight") != opts.end())
2996 special << "totalheight=" << opts["totalheight"] << ',';
2997 if (opts.find("type") != opts.end())
2998 special << "type=" << opts["type"] << ',';
2999 if (opts.find("ext") != opts.end())
3000 special << "ext=" << opts["ext"] << ',';
3001 if (opts.find("read") != opts.end())
3002 special << "read=" << opts["read"] << ',';
3003 if (opts.find("command") != opts.end())
3004 special << "command=" << opts["command"] << ',';
3005 string s_special = special.str();
3006 if (!s_special.empty()) {
3007 // We had special arguments. Remove the trailing ','.
3008 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3010 // TODO: Handle the unknown settings better.
3011 // Warn about invalid options.
3012 // Check whether some option was given twice.
3014 preamble.registerAutomaticallyLoadedPackage("graphicx");
3017 else if (t.cs() == "footnote" ||
3018 (t.cs() == "thanks" && context.layout->intitle)) {
3020 context.check_layout(os);
3021 begin_inset(os, "Foot\n");
3022 os << "status collapsed\n\n";
3023 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3027 else if (t.cs() == "marginpar") {
3029 context.check_layout(os);
3030 begin_inset(os, "Marginal\n");
3031 os << "status collapsed\n\n";
3032 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3036 else if (t.cs() == "lstinline") {
3038 parse_listings(p, os, context, true);
3041 else if (t.cs() == "ensuremath") {
3043 context.check_layout(os);
3044 string const s = p.verbatim_item();
3045 //FIXME: this never triggers in UTF8
3046 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3049 output_ert_inset(os, "\\ensuremath{" + s + "}",
3053 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3054 if (preamble.titleLayoutFound()) {
3056 skip_spaces_braces(p);
3058 output_ert_inset(os, t.asInput(), context);
3061 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3062 context.check_layout(os);
3063 begin_command_inset(os, "toc", t.cs());
3065 skip_spaces_braces(p);
3066 if (t.cs() == "lstlistoflistings")
3067 preamble.registerAutomaticallyLoadedPackage("listings");
3070 else if (t.cs() == "listoffigures") {
3071 context.check_layout(os);
3072 begin_inset(os, "FloatList figure\n");
3074 skip_spaces_braces(p);
3077 else if (t.cs() == "listoftables") {
3078 context.check_layout(os);
3079 begin_inset(os, "FloatList table\n");
3081 skip_spaces_braces(p);
3084 else if (t.cs() == "listof") {
3085 p.skip_spaces(true);
3086 string const name = p.get_token().cs();
3087 if (context.textclass.floats().typeExist(name)) {
3088 context.check_layout(os);
3089 begin_inset(os, "FloatList ");
3092 p.get_token(); // swallow second arg
3094 output_ert_inset(os, "\\listof{" + name + "}", context);
3097 else if ((where = is_known(t.cs(), known_text_font_families)))
3098 parse_text_attributes(p, os, FLAG_ITEM, outer,
3099 context, "\\family", context.font.family,
3100 known_coded_font_families[where - known_text_font_families]);
3102 else if ((where = is_known(t.cs(), known_text_font_series)))
3103 parse_text_attributes(p, os, FLAG_ITEM, outer,
3104 context, "\\series", context.font.series,
3105 known_coded_font_series[where - known_text_font_series]);
3107 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3108 parse_text_attributes(p, os, FLAG_ITEM, outer,
3109 context, "\\shape", context.font.shape,
3110 known_coded_font_shapes[where - known_text_font_shapes]);
3112 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3113 context.check_layout(os);
3114 TeXFont oldFont = context.font;
3115 context.font.init();
3116 context.font.size = oldFont.size;
3117 os << "\n\\family " << context.font.family << "\n";
3118 os << "\n\\series " << context.font.series << "\n";
3119 os << "\n\\shape " << context.font.shape << "\n";
3120 if (t.cs() == "textnormal") {
3121 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3122 output_font_change(os, context.font, oldFont);
3123 context.font = oldFont;
3125 eat_whitespace(p, os, context, false);
3128 else if (t.cs() == "textcolor") {
3129 // scheme is \textcolor{color name}{text}
3130 string const color = p.verbatim_item();
3131 // we only support the predefined colors of the color package
3132 if (color == "black" || color == "blue" || color == "cyan"
3133 || color == "green" || color == "magenta" || color == "red"
3134 || color == "white" || color == "yellow") {
3135 context.check_layout(os);
3136 os << "\n\\color " << color << "\n";
3137 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3138 context.check_layout(os);
3139 os << "\n\\color inherit\n";
3140 preamble.registerAutomaticallyLoadedPackage("color");
3142 // for custom defined colors
3143 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3146 else if (t.cs() == "underbar" || t.cs() == "uline") {
3147 // \underbar is not 100% correct (LyX outputs \uline
3148 // of ulem.sty). The difference is that \ulem allows
3149 // line breaks, and \underbar does not.
3150 // Do NOT handle \underline.
3151 // \underbar cuts through y, g, q, p etc.,
3152 // \underline does not.
3153 context.check_layout(os);
3154 os << "\n\\bar under\n";
3155 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3156 context.check_layout(os);
3157 os << "\n\\bar default\n";
3158 preamble.registerAutomaticallyLoadedPackage("ulem");
3161 else if (t.cs() == "sout") {
3162 context.check_layout(os);
3163 os << "\n\\strikeout on\n";
3164 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3165 context.check_layout(os);
3166 os << "\n\\strikeout default\n";
3167 preamble.registerAutomaticallyLoadedPackage("ulem");
3170 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3171 t.cs() == "emph" || t.cs() == "noun") {
3172 context.check_layout(os);
3173 os << "\n\\" << t.cs() << " on\n";
3174 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3175 context.check_layout(os);
3176 os << "\n\\" << t.cs() << " default\n";
3177 if (t.cs() == "uuline" || t.cs() == "uwave")
3178 preamble.registerAutomaticallyLoadedPackage("ulem");
3181 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3182 context.check_layout(os);
3183 string name = p.getArg('{', '}');
3184 string localtime = p.getArg('{', '}');
3185 preamble.registerAuthor(name);
3186 Author const & author = preamble.getAuthor(name);
3187 // from_asctime_utc() will fail if LyX decides to output the
3188 // time in the text language.
3189 time_t ptime = from_asctime_utc(localtime);
3190 if (ptime == static_cast<time_t>(-1)) {
3191 cerr << "Warning: Could not parse time `" << localtime
3192 << "´ for change tracking, using current time instead.\n";
3193 ptime = current_time();
3195 if (t.cs() == "lyxadded")
3196 os << "\n\\change_inserted ";
3198 os << "\n\\change_deleted ";
3199 os << author.bufferId() << ' ' << ptime << '\n';
3200 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3201 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3202 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3203 LaTeXPackages::isAvailable("xcolor");
3204 // No need to test for luatex, since luatex comes in
3205 // two flavours (dvi and pdf), like latex, and those
3206 // are detected by pdflatex.
3207 if (pdflatex || xetex) {
3209 preamble.registerAutomaticallyLoadedPackage("ulem");
3210 preamble.registerAutomaticallyLoadedPackage("xcolor");
3211 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3215 preamble.registerAutomaticallyLoadedPackage("dvipost");
3216 } else if (xcolorulem) {
3217 preamble.registerAutomaticallyLoadedPackage("ulem");
3218 preamble.registerAutomaticallyLoadedPackage("xcolor");
3223 else if (t.cs() == "textipa") {
3224 context.check_layout(os);
3225 begin_inset(os, "IPA\n");
3226 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3228 preamble.registerAutomaticallyLoadedPackage("tipa");
3229 preamble.registerAutomaticallyLoadedPackage("tipx");
3232 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3233 t.cs() == "vphantom") {
3234 context.check_layout(os);
3235 if (t.cs() == "phantom")
3236 begin_inset(os, "Phantom Phantom\n");
3237 if (t.cs() == "hphantom")
3238 begin_inset(os, "Phantom HPhantom\n");
3239 if (t.cs() == "vphantom")
3240 begin_inset(os, "Phantom VPhantom\n");
3241 os << "status open\n";
3242 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3247 else if (t.cs() == "href") {
3248 context.check_layout(os);
3249 string target = convert_command_inset_arg(p.verbatim_item());
3250 string name = convert_command_inset_arg(p.verbatim_item());
3252 size_t i = target.find(':');
3253 if (i != string::npos) {
3254 type = target.substr(0, i + 1);
3255 if (type == "mailto:" || type == "file:")
3256 target = target.substr(i + 1);
3257 // handle the case that name is equal to target, except of "http://"
3258 else if (target.substr(i + 3) == name && type == "http:")
3261 begin_command_inset(os, "href", "href");
3263 os << "name \"" << name << "\"\n";
3264 os << "target \"" << target << "\"\n";
3265 if (type == "mailto:" || type == "file:")
3266 os << "type \"" << type << "\"\n";
3268 skip_spaces_braces(p);
3271 else if (t.cs() == "lyxline") {
3272 // swallow size argument (it is not used anyway)
3274 if (!context.atParagraphStart()) {
3275 // so our line is in the middle of a paragraph
3276 // we need to add a new line, lest this line
3277 // follow the other content on that line and
3278 // run off the side of the page
3279 // FIXME: This may create an empty paragraph,
3280 // but without that it would not be
3281 // possible to set noindent below.
3282 // Fortunately LaTeX does not care
3283 // about the empty paragraph.
3284 context.new_paragraph(os);
3286 if (preamble.indentParagraphs()) {
3287 // we need to unindent, lest the line be too long
3288 context.add_par_extra_stuff("\\noindent\n");
3290 context.check_layout(os);
3291 begin_command_inset(os, "line", "rule");
3292 os << "offset \"0.5ex\"\n"
3293 "width \"100line%\"\n"
3298 else if (t.cs() == "rule") {
3299 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3300 string const width = p.getArg('{', '}');
3301 string const thickness = p.getArg('{', '}');
3302 context.check_layout(os);
3303 begin_command_inset(os, "line", "rule");
3304 if (!offset.empty())
3305 os << "offset \"" << translate_len(offset) << "\"\n";
3306 os << "width \"" << translate_len(width) << "\"\n"
3307 "height \"" << translate_len(thickness) << "\"\n";
3311 else if (is_known(t.cs(), known_phrases) ||
3312 (t.cs() == "protect" &&
3313 p.next_token().cat() == catEscape &&
3314 is_known(p.next_token().cs(), known_phrases))) {
3315 // LyX sometimes puts a \protect in front, so we have to ignore it
3316 // FIXME: This needs to be changed when bug 4752 is fixed.
3318 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3320 context.check_layout(os);
3321 os << known_coded_phrases[where - known_phrases];
3322 skip_spaces_braces(p);
3325 else if ((where = is_known(t.cs(), known_ref_commands))) {
3326 // \eqref can also occur if refstyle is used
3327 if (t.cs() == "eqref" && preamble.refstyle() == "1") {
3328 context.check_layout(os);
3329 begin_command_inset(os, "ref", "formatted");
3330 os << "reference \"eq:"
3331 << convert_command_inset_arg(p.verbatim_item())
3334 preamble.registerAutomaticallyLoadedPackage("refstyle");
3336 string const opt = p.getOpt();
3338 context.check_layout(os);
3339 begin_command_inset(os, "ref",
3340 known_coded_ref_commands[where - known_ref_commands]);
3341 os << "reference \""
3342 << convert_command_inset_arg(p.verbatim_item())
3345 if (t.cs() == "vref" || t.cs() == "vpageref")
3346 preamble.registerAutomaticallyLoadedPackage("varioref");
3348 // LyX does not yet support optional arguments of ref commands
3349 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3350 p.verbatim_item() + "}", context);
3355 else if ((where = is_known(t.cs(), known_refstyle_commands))) {
3356 context.check_layout(os);
3357 // \eqref can also occur if refstyle is not used
3358 // this case is already handled in the previous else if
3359 begin_command_inset(os, "ref", "formatted");
3360 os << "reference \"";
3361 os << known_refstyle_prefixes[where - known_refstyle_commands]
3363 os << convert_command_inset_arg(p.verbatim_item())
3366 preamble.registerAutomaticallyLoadedPackage("refstyle");
3369 else if (use_natbib &&
3370 is_known(t.cs(), known_natbib_commands) &&
3371 ((t.cs() != "citefullauthor" &&
3372 t.cs() != "citeyear" &&
3373 t.cs() != "citeyearpar") ||
3374 p.next_token().asInput() != "*")) {
3375 context.check_layout(os);
3376 string command = t.cs();
3377 if (p.next_token().asInput() == "*") {
3381 if (command == "citefullauthor")
3382 // alternative name for "\\citeauthor*"
3383 command = "citeauthor*";
3385 // text before the citation
3387 // text after the citation
3389 get_cite_arguments(p, true, before, after);
3391 if (command == "cite") {
3392 // \cite without optional argument means
3393 // \citet, \cite with at least one optional
3394 // argument means \citep.
3395 if (before.empty() && after.empty())
3400 if (before.empty() && after == "[]")
3401 // avoid \citet[]{a}
3403 else if (before == "[]" && after == "[]") {
3404 // avoid \citet[][]{a}
3408 // remove the brackets around after and before
3409 if (!after.empty()) {
3411 after.erase(after.length() - 1, 1);
3412 after = convert_command_inset_arg(after);
3414 if (!before.empty()) {
3416 before.erase(before.length() - 1, 1);
3417 before = convert_command_inset_arg(before);
3419 begin_command_inset(os, "citation", command);
3420 os << "after " << '"' << after << '"' << "\n";
3421 os << "before " << '"' << before << '"' << "\n";
3423 << convert_command_inset_arg(p.verbatim_item())
3426 // Need to set the cite engine if natbib is loaded by
3427 // the document class directly
3428 if (preamble.citeEngine() == "basic")
3429 preamble.citeEngine("natbib");
3432 else if (use_jurabib &&
3433 is_known(t.cs(), known_jurabib_commands) &&
3434 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3435 context.check_layout(os);
3436 string command = t.cs();
3437 if (p.next_token().asInput() == "*") {
3441 char argumentOrder = '\0';
3442 vector<string> const options =
3443 preamble.getPackageOptions("jurabib");
3444 if (find(options.begin(), options.end(),
3445 "natbiborder") != options.end())
3446 argumentOrder = 'n';
3447 else if (find(options.begin(), options.end(),
3448 "jurabiborder") != options.end())
3449 argumentOrder = 'j';
3451 // text before the citation
3453 // text after the citation
3455 get_cite_arguments(p, argumentOrder != 'j', before, after);
3457 string const citation = p.verbatim_item();
3458 if (!before.empty() && argumentOrder == '\0') {
3459 cerr << "Warning: Assuming argument order "
3460 "of jurabib version 0.6 for\n'"
3461 << command << before << after << '{'
3462 << citation << "}'.\n"
3463 "Add 'jurabiborder' to the jurabib "
3464 "package options if you used an\n"
3465 "earlier jurabib version." << endl;
3467 if (!after.empty()) {
3469 after.erase(after.length() - 1, 1);
3471 if (!before.empty()) {
3473 before.erase(before.length() - 1, 1);
3475 begin_command_inset(os, "citation", command);
3476 os << "after " << '"' << after << '"' << "\n";
3477 os << "before " << '"' << before << '"' << "\n";
3478 os << "key " << '"' << citation << '"' << "\n";
3480 // Need to set the cite engine if jurabib is loaded by
3481 // the document class directly
3482 if (preamble.citeEngine() == "basic")
3483 preamble.citeEngine("jurabib");
3486 else if (t.cs() == "cite"
3487 || t.cs() == "nocite") {
3488 context.check_layout(os);
3489 string after = convert_command_inset_arg(p.getArg('[', ']'));
3490 string key = convert_command_inset_arg(p.verbatim_item());
3491 // store the case that it is "\nocite{*}" to use it later for
3494 begin_command_inset(os, "citation", t.cs());
3495 os << "after " << '"' << after << '"' << "\n";
3496 os << "key " << '"' << key << '"' << "\n";
3498 } else if (t.cs() == "nocite")
3502 else if (t.cs() == "index" ||
3503 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3504 context.check_layout(os);
3505 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3506 p.getArg('[', ']') : "";
3507 string const kind = arg.empty() ? "idx" : arg;
3508 begin_inset(os, "Index ");
3509 os << kind << "\nstatus collapsed\n";
3510 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3513 preamble.registerAutomaticallyLoadedPackage("splitidx");
3516 else if (t.cs() == "nomenclature") {
3517 context.check_layout(os);
3518 begin_command_inset(os, "nomenclature", "nomenclature");
3519 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3520 if (!prefix.empty())
3521 os << "prefix " << '"' << prefix << '"' << "\n";
3522 os << "symbol " << '"'
3523 << convert_command_inset_arg(p.verbatim_item());
3524 os << "\"\ndescription \""
3525 << convert_command_inset_arg(p.verbatim_item())
3528 preamble.registerAutomaticallyLoadedPackage("nomencl");
3531 else if (t.cs() == "label") {
3532 context.check_layout(os);
3533 begin_command_inset(os, "label", "label");
3535 << convert_command_inset_arg(p.verbatim_item())
3540 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3541 context.check_layout(os);
3542 string commandname = t.cs();
3544 if (p.next_token().asInput() == "*") {
3549 begin_command_inset(os, "index_print", commandname);
3550 string const indexname = p.getArg('[', ']');
3552 if (indexname.empty())
3553 os << "type \"idx\"\n";
3555 os << "type \"" << indexname << "\"\n";
3558 skip_spaces_braces(p);
3559 preamble.registerAutomaticallyLoadedPackage("makeidx");
3560 if (preamble.use_indices() == "true")
3561 preamble.registerAutomaticallyLoadedPackage("splitidx");
3564 else if (t.cs() == "printnomenclature") {
3566 string width_type = "";
3567 context.check_layout(os);
3568 begin_command_inset(os, "nomencl_print", "printnomenclature");
3569 // case of a custom width
3571 width = p.getArg('[', ']');
3572 width = translate_len(width);
3573 width_type = "custom";
3575 // case of no custom width
3576 // the case of no custom width but the width set
3577 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3578 // because the user could have set anything, not only the width
3579 // of the longest label (which would be width_type = "auto")
3580 string label = convert_command_inset_arg(p.getArg('{', '}'));
3581 if (label.empty() && width_type.empty())
3582 width_type = "none";
3583 os << "set_width \"" << width_type << "\"\n";
3584 if (width_type == "custom")
3585 os << "width \"" << width << '\"';
3587 skip_spaces_braces(p);
3588 preamble.registerAutomaticallyLoadedPackage("nomencl");
3591 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3592 context.check_layout(os);
3593 begin_inset(os, "script ");
3594 os << t.cs().substr(4) << '\n';
3595 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3597 if (t.cs() == "textsubscript")
3598 preamble.registerAutomaticallyLoadedPackage("subscript");
3601 else if ((where = is_known(t.cs(), known_quotes))) {
3602 context.check_layout(os);
3603 begin_inset(os, "Quotes ");
3604 os << known_coded_quotes[where - known_quotes];
3606 // LyX adds {} after the quote, so we have to eat
3607 // spaces here if there are any before a possible
3609 eat_whitespace(p, os, context, false);
3613 else if ((where = is_known(t.cs(), known_sizes)) &&
3614 context.new_layout_allowed) {
3615 context.check_layout(os);
3616 TeXFont const oldFont = context.font;
3617 context.font.size = known_coded_sizes[where - known_sizes];
3618 output_font_change(os, oldFont, context.font);
3619 eat_whitespace(p, os, context, false);
3622 else if ((where = is_known(t.cs(), known_font_families)) &&
3623 context.new_layout_allowed) {
3624 context.check_layout(os);
3625 TeXFont const oldFont = context.font;
3626 context.font.family =
3627 known_coded_font_families[where - known_font_families];
3628 output_font_change(os, oldFont, context.font);
3629 eat_whitespace(p, os, context, false);
3632 else if ((where = is_known(t.cs(), known_font_series)) &&
3633 context.new_layout_allowed) {
3634 context.check_layout(os);
3635 TeXFont const oldFont = context.font;
3636 context.font.series =
3637 known_coded_font_series[where - known_font_series];
3638 output_font_change(os, oldFont, context.font);
3639 eat_whitespace(p, os, context, false);
3642 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3643 context.new_layout_allowed) {
3644 context.check_layout(os);
3645 TeXFont const oldFont = context.font;
3646 context.font.shape =
3647 known_coded_font_shapes[where - known_font_shapes];
3648 output_font_change(os, oldFont, context.font);
3649 eat_whitespace(p, os, context, false);
3651 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3652 context.new_layout_allowed) {
3653 context.check_layout(os);
3654 TeXFont const oldFont = context.font;
3655 context.font.init();
3656 context.font.size = oldFont.size;
3657 context.font.family =
3658 known_coded_font_families[where - known_old_font_families];
3659 output_font_change(os, oldFont, context.font);
3660 eat_whitespace(p, os, context, false);
3663 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3664 context.new_layout_allowed) {
3665 context.check_layout(os);
3666 TeXFont const oldFont = context.font;
3667 context.font.init();
3668 context.font.size = oldFont.size;
3669 context.font.series =
3670 known_coded_font_series[where - known_old_font_series];
3671 output_font_change(os, oldFont, context.font);
3672 eat_whitespace(p, os, context, false);
3675 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3676 context.new_layout_allowed) {
3677 context.check_layout(os);
3678 TeXFont const oldFont = context.font;
3679 context.font.init();
3680 context.font.size = oldFont.size;
3681 context.font.shape =
3682 known_coded_font_shapes[where - known_old_font_shapes];
3683 output_font_change(os, oldFont, context.font);
3684 eat_whitespace(p, os, context, false);
3687 else if (t.cs() == "selectlanguage") {
3688 context.check_layout(os);
3689 // save the language for the case that a
3690 // \foreignlanguage is used
3691 context.font.language = babel2lyx(p.verbatim_item());
3692 os << "\n\\lang " << context.font.language << "\n";
3695 else if (t.cs() == "foreignlanguage") {
3696 string const lang = babel2lyx(p.verbatim_item());
3697 parse_text_attributes(p, os, FLAG_ITEM, outer,
3699 context.font.language, lang);
3702 else if (prefixIs(t.cs(), "text")
3703 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3704 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3706 // We have to output the whole command if it has an option
3707 // because LyX doesn't support this yet, see bug #8214,
3708 // only if there is a single option specifying a variant, we can handle it.
3710 string langopts = p.getOpt();
3711 // check if the option contains a variant, if yes, extract it
3712 string::size_type pos_var = langopts.find("variant");
3713 string::size_type i = langopts.find(',');
3714 string::size_type k = langopts.find('=', pos_var);
3715 if (pos_var != string::npos && i == string::npos) {
3717 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3718 lang = preamble.polyglossia2lyx(variant);
3719 parse_text_attributes(p, os, FLAG_ITEM, outer,
3721 context.font.language, lang);
3723 output_ert_inset(os, t.asInput() + langopts, context);
3725 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3726 parse_text_attributes(p, os, FLAG_ITEM, outer,
3728 context.font.language, lang);
3732 else if (t.cs() == "inputencoding") {
3733 // nothing to write here
3734 string const enc = subst(p.verbatim_item(), "\n", " ");
3735 p.setEncoding(enc, Encoding::inputenc);
3738 else if ((where = is_known(t.cs(), known_special_chars))) {
3739 context.check_layout(os);
3740 os << "\\SpecialChar \\"
3741 << known_coded_special_chars[where - known_special_chars]
3743 skip_spaces_braces(p);
3746 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3747 context.check_layout(os);
3748 os << "\\SpecialChar \\nobreakdash-\n";
3752 else if (t.cs() == "textquotedbl") {
3753 context.check_layout(os);
3758 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3759 context.check_layout(os);
3760 os << "\\SpecialChar \\@.\n";
3764 else if (t.cs() == "-") {
3765 context.check_layout(os);
3766 os << "\\SpecialChar \\-\n";
3769 else if (t.cs() == "textasciitilde") {
3770 context.check_layout(os);
3772 skip_spaces_braces(p);
3775 else if (t.cs() == "textasciicircum") {
3776 context.check_layout(os);
3778 skip_spaces_braces(p);
3781 else if (t.cs() == "textbackslash") {
3782 context.check_layout(os);
3783 os << "\n\\backslash\n";
3784 skip_spaces_braces(p);
3787 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3788 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3790 context.check_layout(os);
3794 else if (t.cs() == "char") {
3795 context.check_layout(os);
3796 if (p.next_token().character() == '`') {
3798 if (p.next_token().cs() == "\"") {
3803 output_ert_inset(os, "\\char`", context);
3806 output_ert_inset(os, "\\char", context);
3810 else if (t.cs() == "verb") {
3811 context.check_layout(os);
3812 // set catcodes to verbatim early, just in case.
3813 p.setCatcodes(VERBATIM_CATCODES);
3814 string delim = p.get_token().asInput();
3815 string const arg = p.verbatimStuff(delim);
3816 output_ert_inset(os, "\\verb" + delim + arg + delim, context);
3819 // Problem: \= creates a tabstop inside the tabbing environment
3820 // and else an accent. In the latter case we really would want
3821 // \={o} instead of \= o.
3822 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3823 output_ert_inset(os, t.asInput(), context);
3825 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3826 else if (t.cs().size() == 1
3827 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3828 context.check_layout(os);
3829 // try to see whether the string is in unicodesymbols
3832 string command = t.asInput() + "{"
3833 + trimSpaceAndEol(p.verbatim_item())
3836 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3837 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3838 termination, rem, &req);
3841 cerr << "When parsing " << command
3842 << ", result is " << to_utf8(s)
3843 << "+" << to_utf8(rem) << endl;
3845 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3846 preamble.registerAutomaticallyLoadedPackage(*it);
3848 // we did not find a non-ert version
3849 output_ert_inset(os, command, context);
3852 else if (t.cs() == "\\") {
3853 context.check_layout(os);
3855 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3856 else if (p.next_token().asInput() == "*") {
3858 // getOpt() eats the following space if there
3859 // is no optional argument, but that is OK
3860 // here since it has no effect in the output.
3861 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3864 begin_inset(os, "Newline newline");
3869 else if (t.cs() == "newline" ||
3870 (t.cs() == "linebreak" && !p.hasOpt())) {
3871 context.check_layout(os);
3872 begin_inset(os, "Newline ");
3875 skip_spaces_braces(p);
3878 else if (t.cs() == "input" || t.cs() == "include"
3879 || t.cs() == "verbatiminput") {
3880 string name = t.cs();
3881 if (t.cs() == "verbatiminput"
3882 && p.next_token().asInput() == "*")
3883 name += p.get_token().asInput();
3884 context.check_layout(os);
3885 string filename(normalize_filename(p.getArg('{', '}')));
3886 string const path = getMasterFilePath(true);
3887 // We want to preserve relative / absolute filenames,
3888 // therefore path is only used for testing
3889 if ((t.cs() == "include" || t.cs() == "input") &&
3890 !makeAbsPath(filename, path).exists()) {
3891 // The file extension is probably missing.
3892 // Now try to find it out.
3893 string const tex_name =
3894 find_file(filename, path,
3895 known_tex_extensions);
3896 if (!tex_name.empty())
3897 filename = tex_name;
3899 bool external = false;
3901 if (makeAbsPath(filename, path).exists()) {
3902 string const abstexname =
3903 makeAbsPath(filename, path).absFileName();
3904 string const absfigname =
3905 changeExtension(abstexname, ".fig");
3906 fix_child_filename(filename);
3907 string const lyxname =
3908 changeExtension(filename, ".lyx");
3909 string const abslyxname = makeAbsPath(
3910 lyxname, getParentFilePath(false)).absFileName();
3912 if (!skipChildren())
3913 external = FileName(absfigname).exists();
3914 if (t.cs() == "input" && !skipChildren()) {
3915 string const ext = getExtension(abstexname);
3917 // Combined PS/LaTeX:
3918 // x.eps, x.pstex_t (old xfig)
3919 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3920 FileName const absepsname(
3921 changeExtension(abstexname, ".eps"));
3922 FileName const abspstexname(
3923 changeExtension(abstexname, ".pstex"));
3924 bool const xfigeps =
3925 (absepsname.exists() ||
3926 abspstexname.exists()) &&
3929 // Combined PDF/LaTeX:
3930 // x.pdf, x.pdftex_t (old xfig)
3931 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3932 FileName const abspdfname(
3933 changeExtension(abstexname, ".pdf"));
3934 bool const xfigpdf =
3935 abspdfname.exists() &&
3936 (ext == "pdftex_t" || ext == "pdf_t");
3940 // Combined PS/PDF/LaTeX:
3941 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3942 string const absbase2(
3943 removeExtension(abstexname) + "_pspdftex");
3944 FileName const abseps2name(
3945 addExtension(absbase2, ".eps"));
3946 FileName const abspdf2name(
3947 addExtension(absbase2, ".pdf"));
3948 bool const xfigboth =
3949 abspdf2name.exists() &&
3950 abseps2name.exists() && ext == "pspdftex";
3952 xfig = xfigpdf || xfigeps || xfigboth;
3953 external = external && xfig;
3956 outname = changeExtension(filename, ".fig");
3957 FileName abssrc(changeExtension(abstexname, ".fig"));
3958 copy_file(abssrc, outname);
3960 // Don't try to convert, the result
3961 // would be full of ERT.
3963 FileName abssrc(abstexname);
3964 copy_file(abssrc, outname);
3965 } else if (t.cs() != "verbatiminput" &&
3967 tex2lyx(abstexname, FileName(abslyxname),
3970 // no need to call copy_file
3971 // tex2lyx creates the file
3974 FileName abssrc(abstexname);
3975 copy_file(abssrc, outname);
3978 cerr << "Warning: Could not find included file '"
3979 << filename << "'." << endl;
3983 begin_inset(os, "External\n");
3984 os << "\ttemplate XFig\n"
3985 << "\tfilename " << outname << '\n';
3986 registerExternalTemplatePackages("XFig");
3988 begin_command_inset(os, "include", name);
3989 outname = subst(outname, "\"", "\\\"");
3990 os << "preview false\n"
3991 "filename \"" << outname << "\"\n";
3992 if (t.cs() == "verbatiminput")
3993 preamble.registerAutomaticallyLoadedPackage("verbatim");
3998 else if (t.cs() == "bibliographystyle") {
3999 // store new bibliographystyle
4000 bibliographystyle = p.verbatim_item();
4001 // If any other command than \bibliography, \addcontentsline
4002 // and \nocite{*} follows, we need to output the style
4003 // (because it might be used by that command).
4004 // Otherwise, it will automatically be output by LyX.
4007 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4008 if (t2.cat() == catBegin)
4010 if (t2.cat() != catEscape)
4012 if (t2.cs() == "nocite") {
4013 if (p.getArg('{', '}') == "*")
4015 } else if (t2.cs() == "bibliography")
4017 else if (t2.cs() == "phantomsection") {
4021 else if (t2.cs() == "addcontentsline") {
4022 // get the 3 arguments of \addcontentsline
4025 contentslineContent = p.getArg('{', '}');
4026 // if the last argument is not \refname we must output
4027 if (contentslineContent == "\\refname")
4034 output_ert_inset(os,
4035 "\\bibliographystyle{" + bibliographystyle + '}',
4040 else if (t.cs() == "phantomsection") {
4041 // we only support this if it occurs between
4042 // \bibliographystyle and \bibliography
4043 if (bibliographystyle.empty())
4044 output_ert_inset(os, "\\phantomsection", context);
4047 else if (t.cs() == "addcontentsline") {
4048 context.check_layout(os);
4049 // get the 3 arguments of \addcontentsline
4050 string const one = p.getArg('{', '}');
4051 string const two = p.getArg('{', '}');
4052 string const three = p.getArg('{', '}');
4053 // only if it is a \refname, we support if for the bibtex inset
4054 if (contentslineContent != "\\refname") {
4055 output_ert_inset(os,
4056 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4061 else if (t.cs() == "bibliography") {
4062 context.check_layout(os);
4064 begin_command_inset(os, "bibtex", "bibtex");
4065 if (!btprint.empty()) {
4066 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4067 // clear the string because the next BibTeX inset can be without the
4068 // \nocite{*} option
4071 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4072 // Do we have addcontentsline?
4073 if (contentslineContent == "\\refname") {
4074 BibOpts = "bibtotoc";
4075 // clear string because next BibTeX inset can be without addcontentsline
4076 contentslineContent.clear();
4078 // Do we have a bibliographystyle set?
4079 if (!bibliographystyle.empty()) {
4080 if (BibOpts.empty())
4081 BibOpts = bibliographystyle;
4083 BibOpts = BibOpts + ',' + bibliographystyle;
4084 // clear it because each bibtex entry has its style
4085 // and we need an empty string to handle \phantomsection
4086 bibliographystyle.clear();
4088 os << "options " << '"' << BibOpts << '"' << "\n";
4092 else if (t.cs() == "parbox") {
4093 // Test whether this is an outer box of a shaded box
4095 // swallow arguments
4096 while (p.hasOpt()) {
4098 p.skip_spaces(true);
4101 p.skip_spaces(true);
4103 if (p.next_token().cat() == catBegin)
4105 p.skip_spaces(true);
4106 Token to = p.get_token();
4107 bool shaded = false;
4108 if (to.asInput() == "\\begin") {
4109 p.skip_spaces(true);
4110 if (p.getArg('{', '}') == "shaded")
4115 parse_outer_box(p, os, FLAG_ITEM, outer,
4116 context, "parbox", "shaded");
4118 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4122 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4123 t.cs() == "shadowbox" || t.cs() == "doublebox")
4124 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4126 else if (t.cs() == "framebox") {
4127 if (p.next_token().character() == '(') {
4128 //the syntax is: \framebox(x,y)[position]{content}
4129 string arg = t.asInput();
4130 arg += p.getFullParentheseArg();
4131 arg += p.getFullOpt();
4132 eat_whitespace(p, os, context, false);
4133 output_ert_inset(os, arg + '{', context);
4134 parse_text(p, os, FLAG_ITEM, outer, context);
4135 output_ert_inset(os, "}", context);
4137 string special = p.getFullOpt();
4138 special += p.getOpt();
4139 // LyX does not yet support \framebox without any option
4140 if (!special.empty())
4141 parse_outer_box(p, os, FLAG_ITEM, outer,
4142 context, t.cs(), special);
4144 eat_whitespace(p, os, context, false);
4145 output_ert_inset(os, "\\framebox{", context);
4146 parse_text(p, os, FLAG_ITEM, outer, context);
4147 output_ert_inset(os, "}", context);
4152 //\makebox() is part of the picture environment and different from \makebox{}
4153 //\makebox{} will be parsed by parse_box
4154 else if (t.cs() == "makebox") {
4155 if (p.next_token().character() == '(') {
4156 //the syntax is: \makebox(x,y)[position]{content}
4157 string arg = t.asInput();
4158 arg += p.getFullParentheseArg();
4159 arg += p.getFullOpt();
4160 eat_whitespace(p, os, context, false);
4161 output_ert_inset(os, arg + '{', context);
4162 parse_text(p, os, FLAG_ITEM, outer, context);
4163 output_ert_inset(os, "}", context);
4165 //the syntax is: \makebox[width][position]{content}
4166 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4170 else if (t.cs() == "smallskip" ||
4171 t.cs() == "medskip" ||
4172 t.cs() == "bigskip" ||
4173 t.cs() == "vfill") {
4174 context.check_layout(os);
4175 begin_inset(os, "VSpace ");
4178 skip_spaces_braces(p);
4181 else if ((where = is_known(t.cs(), known_spaces))) {
4182 context.check_layout(os);
4183 begin_inset(os, "space ");
4184 os << '\\' << known_coded_spaces[where - known_spaces]
4187 // LaTeX swallows whitespace after all spaces except
4188 // "\\,". We have to do that here, too, because LyX
4189 // adds "{}" which would make the spaces significant.
4191 eat_whitespace(p, os, context, false);
4192 // LyX adds "{}" after all spaces except "\\ " and
4193 // "\\,", so we have to remove "{}".
4194 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4195 // remove the braces after "\\,", too.
4200 else if (t.cs() == "newpage" ||
4201 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4202 t.cs() == "clearpage" ||
4203 t.cs() == "cleardoublepage") {
4204 context.check_layout(os);
4205 begin_inset(os, "Newpage ");
4208 skip_spaces_braces(p);
4211 else if (t.cs() == "DeclareRobustCommand" ||
4212 t.cs() == "DeclareRobustCommandx" ||
4213 t.cs() == "newcommand" ||
4214 t.cs() == "newcommandx" ||
4215 t.cs() == "providecommand" ||
4216 t.cs() == "providecommandx" ||
4217 t.cs() == "renewcommand" ||
4218 t.cs() == "renewcommandx") {
4219 // DeclareRobustCommand, DeclareRobustCommandx,
4220 // providecommand and providecommandx could be handled
4221 // by parse_command(), but we need to call
4222 // add_known_command() here.
4223 string name = t.asInput();
4224 if (p.next_token().asInput() == "*") {
4225 // Starred form. Eat '*'
4229 string const command = p.verbatim_item();
4230 string const opt1 = p.getFullOpt();
4231 string const opt2 = p.getFullOpt();
4232 add_known_command(command, opt1, !opt2.empty());
4233 string const ert = name + '{' + command + '}' +
4235 '{' + p.verbatim_item() + '}';
4237 if (t.cs() == "DeclareRobustCommand" ||
4238 t.cs() == "DeclareRobustCommandx" ||
4239 t.cs() == "providecommand" ||
4240 t.cs() == "providecommandx" ||
4241 name[name.length()-1] == '*')
4242 output_ert_inset(os, ert, context);
4244 context.check_layout(os);
4245 begin_inset(os, "FormulaMacro");
4251 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4252 // let could be handled by parse_command(),
4253 // but we need to call add_known_command() here.
4254 string ert = t.asInput();
4257 if (p.next_token().cat() == catBegin) {
4258 name = p.verbatim_item();
4259 ert += '{' + name + '}';
4261 name = p.verbatim_item();
4266 if (p.next_token().cat() == catBegin) {
4267 command = p.verbatim_item();
4268 ert += '{' + command + '}';
4270 command = p.verbatim_item();
4273 // If command is known, make name known too, to parse
4274 // its arguments correctly. For this reason we also
4275 // have commands in syntax.default that are hardcoded.
4276 CommandMap::iterator it = known_commands.find(command);
4277 if (it != known_commands.end())
4278 known_commands[t.asInput()] = it->second;
4279 output_ert_inset(os, ert, context);
4282 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4283 bool starred = false;
4284 if (p.next_token().asInput() == "*") {
4288 string name = t.asInput();
4289 string const length = p.verbatim_item();
4292 bool valid = splitLatexLength(length, valstring, unit);
4293 bool known_hspace = false;
4294 bool known_vspace = false;
4295 bool known_unit = false;
4298 istringstream iss(valstring);
4301 if (t.cs()[0] == 'h') {
4302 if (unit == "\\fill") {
4307 known_hspace = true;
4310 if (unit == "\\smallskipamount") {
4312 known_vspace = true;
4313 } else if (unit == "\\medskipamount") {
4315 known_vspace = true;
4316 } else if (unit == "\\bigskipamount") {
4318 known_vspace = true;
4319 } else if (unit == "\\fill") {
4321 known_vspace = true;
4325 if (!known_hspace && !known_vspace) {
4326 switch (unitFromString(unit)) {
4347 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4348 // Literal horizontal length or known variable
4349 context.check_layout(os);
4350 begin_inset(os, "space ");
4358 if (known_unit && !known_hspace)
4360 << translate_len(length);
4362 } else if (known_unit || known_vspace) {
4363 // Literal vertical length or known variable
4364 context.check_layout(os);
4365 begin_inset(os, "VSpace ");
4373 // LyX can't handle other length variables in Inset VSpace/space
4378 output_ert_inset(os, name + '{' + unit + '}', context);
4379 else if (value == -1.0)
4380 output_ert_inset(os, name + "{-" + unit + '}', context);
4382 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4384 output_ert_inset(os, name + '{' + length + '}', context);
4388 // The single '=' is meant here.
4389 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4391 context.check_layout(os);
4392 begin_inset(os, "Flex ");
4393 os << to_utf8(newinsetlayout->name()) << '\n'
4394 << "status collapsed\n";
4395 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4399 else if (t.cs() == "includepdf") {
4401 string const arg = p.getArg('[', ']');
4402 map<string, string> opts;
4403 vector<string> keys;
4404 split_map(arg, opts, keys);
4405 string name = normalize_filename(p.verbatim_item());
4406 string const path = getMasterFilePath(true);
4407 // We want to preserve relative / absolute filenames,
4408 // therefore path is only used for testing
4409 if (!makeAbsPath(name, path).exists()) {
4410 // The file extension is probably missing.
4411 // Now try to find it out.
4412 char const * const pdfpages_format[] = {"pdf", 0};
4413 string const pdftex_name =
4414 find_file(name, path, pdfpages_format);
4415 if (!pdftex_name.empty()) {
4420 FileName const absname = makeAbsPath(name, path);
4421 if (absname.exists())
4423 fix_child_filename(name);
4424 copy_file(absname, name);
4426 cerr << "Warning: Could not find file '"
4427 << name << "'." << endl;
4429 context.check_layout(os);
4430 begin_inset(os, "External\n\ttemplate ");
4431 os << "PDFPages\n\tfilename "
4433 // parse the options
4434 if (opts.find("pages") != opts.end())
4435 os << "\textra LaTeX \"pages="
4436 << opts["pages"] << "\"\n";
4437 if (opts.find("angle") != opts.end())
4438 os << "\trotateAngle "
4439 << opts["angle"] << '\n';
4440 if (opts.find("origin") != opts.end()) {
4442 string const opt = opts["origin"];
4443 if (opt == "tl") ss << "topleft";
4444 if (opt == "bl") ss << "bottomleft";
4445 if (opt == "Bl") ss << "baselineleft";
4446 if (opt == "c") ss << "center";
4447 if (opt == "tc") ss << "topcenter";
4448 if (opt == "bc") ss << "bottomcenter";
4449 if (opt == "Bc") ss << "baselinecenter";
4450 if (opt == "tr") ss << "topright";
4451 if (opt == "br") ss << "bottomright";
4452 if (opt == "Br") ss << "baselineright";
4453 if (!ss.str().empty())
4454 os << "\trotateOrigin " << ss.str() << '\n';
4456 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4458 if (opts.find("width") != opts.end())
4460 << translate_len(opts["width"]) << '\n';
4461 if (opts.find("height") != opts.end())
4463 << translate_len(opts["height"]) << '\n';
4464 if (opts.find("keepaspectratio") != opts.end())
4465 os << "\tkeepAspectRatio\n";
4467 context.check_layout(os);
4468 registerExternalTemplatePackages("PDFPages");
4471 else if (t.cs() == "loadgame") {
4473 string name = normalize_filename(p.verbatim_item());
4474 string const path = getMasterFilePath(true);
4475 // We want to preserve relative / absolute filenames,
4476 // therefore path is only used for testing
4477 if (!makeAbsPath(name, path).exists()) {
4478 // The file extension is probably missing.
4479 // Now try to find it out.
4480 char const * const lyxskak_format[] = {"fen", 0};
4481 string const lyxskak_name =
4482 find_file(name, path, lyxskak_format);
4483 if (!lyxskak_name.empty())
4484 name = lyxskak_name;
4486 FileName const absname = makeAbsPath(name, path);
4487 if (absname.exists())
4489 fix_child_filename(name);
4490 copy_file(absname, name);
4492 cerr << "Warning: Could not find file '"
4493 << name << "'." << endl;
4494 context.check_layout(os);
4495 begin_inset(os, "External\n\ttemplate ");
4496 os << "ChessDiagram\n\tfilename "
4499 context.check_layout(os);
4500 // after a \loadgame follows a \showboard
4501 if (p.get_token().asInput() == "showboard")
4503 registerExternalTemplatePackages("ChessDiagram");
4507 // try to see whether the string is in unicodesymbols
4508 // Only use text mode commands, since we are in text mode here,
4509 // and math commands may be invalid (bug 6797)
4513 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4514 Encodings::TEXT_CMD, termination, rem, &req);
4517 cerr << "When parsing " << t.cs()
4518 << ", result is " << to_utf8(s)
4519 << "+" << to_utf8(rem) << endl;
4520 context.check_layout(os);
4523 skip_spaces_braces(p);
4524 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4525 preamble.registerAutomaticallyLoadedPackage(*it);
4527 //cerr << "#: " << t << " mode: " << mode << endl;
4528 // heuristic: read up to next non-nested space
4530 string s = t.asInput();
4531 string z = p.verbatim_item();
4532 while (p.good() && z != " " && !z.empty()) {
4533 //cerr << "read: " << z << endl;
4535 z = p.verbatim_item();
4537 cerr << "found ERT: " << s << endl;
4538 output_ert_inset(os, s + ' ', context);
4541 string name = t.asInput();
4542 if (p.next_token().asInput() == "*") {
4543 // Starred commands like \vspace*{}
4544 p.get_token(); // Eat '*'
4547 if (!parse_command(name, p, os, outer, context))
4548 output_ert_inset(os, name, context);
4552 if (flags & FLAG_LEAVE) {
4553 flags &= ~FLAG_LEAVE;
4560 string guessLanguage(Parser & p, string const & lang)
4562 typedef std::map<std::string, size_t> LangMap;
4563 // map from language names to number of characters
4566 for (char const * const * i = supported_CJK_languages; *i; i++)
4567 used[string(*i)] = 0;
4570 Token const t = p.get_token();
4571 // comments are not counted for any language
4572 if (t.cat() == catComment)
4574 // commands are not counted as well, but we need to detect
4575 // \begin{CJK} and switch encoding if needed
4576 if (t.cat() == catEscape) {
4577 if (t.cs() == "inputencoding") {
4578 string const enc = subst(p.verbatim_item(), "\n", " ");
4579 p.setEncoding(enc, Encoding::inputenc);
4582 if (t.cs() != "begin")
4585 // Non-CJK content is counted for lang.
4586 // We do not care about the real language here:
4587 // If we have more non-CJK contents than CJK contents,
4588 // we simply use the language that was specified as
4589 // babel main language.
4590 used[lang] += t.asInput().length();
4593 // Now we are starting an environment
4595 string const name = p.getArg('{', '}');
4596 if (name != "CJK") {
4600 // It is a CJK environment
4602 /* name = */ p.getArg('{', '}');
4603 string const encoding = p.getArg('{', '}');
4604 /* mapping = */ p.getArg('{', '}');
4605 string const encoding_old = p.getEncoding();
4606 char const * const * const where =
4607 is_known(encoding, supported_CJK_encodings);
4609 p.setEncoding(encoding, Encoding::CJK);
4611 p.setEncoding("UTF-8");
4612 string const text = p.ertEnvironment("CJK");
4613 p.setEncoding(encoding_old);
4616 // ignore contents in unknown CJK encoding
4619 // the language of the text
4621 supported_CJK_languages[where - supported_CJK_encodings];
4622 used[cjk] += text.length();
4624 LangMap::const_iterator use = used.begin();
4625 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4626 if (it->second > use->second)