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 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1423 preamble.registerAutomaticallyLoadedPackage("tipa");
1424 preamble.registerAutomaticallyLoadedPackage("tipx");
1427 else if (name == "CJK") {
1428 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1429 // It is impossible to decide if a CJK environment was in its own paragraph or within
1430 // a line. We therefore always assume a paragraph since the latter is a rare case.
1431 eat_whitespace(p, os, parent_context, false);
1432 parent_context.check_end_layout(os);
1433 // store the encoding to be able to reset it
1434 string const encoding_old = p.getEncoding();
1435 string const encoding = p.getArg('{', '}');
1436 // FIXME: For some reason JIS does not work. Although the text
1437 // in tests/CJK.tex is identical with the SJIS version if you
1438 // convert both snippets using the recode command line utility,
1439 // the resulting .lyx file contains some extra characters if
1440 // you set buggy_encoding to false for JIS.
1441 bool const buggy_encoding = encoding == "JIS";
1442 if (!buggy_encoding)
1443 p.setEncoding(encoding, Encoding::CJK);
1445 // FIXME: This will read garbage, since the data is not encoded in utf8.
1446 p.setEncoding("UTF-8");
1448 // LyX only supports the same mapping for all CJK
1449 // environments, so we might need to output everything as ERT
1450 string const mapping = trim(p.getArg('{', '}'));
1451 char const * const * const where =
1452 is_known(encoding, supported_CJK_encodings);
1453 if (!buggy_encoding && !preamble.fontCJKSet())
1454 preamble.fontCJK(mapping);
1455 bool knownMapping = mapping == preamble.fontCJK();
1456 if (buggy_encoding || !knownMapping || !where) {
1457 parent_context.check_layout(os);
1458 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1460 // we must parse the content as verbatim because e.g. JIS can contain
1461 // normally invalid characters
1462 // FIXME: This works only for the most simple cases.
1463 // Since TeX control characters are not parsed,
1464 // things like comments are completely wrong.
1465 string const s = p.plainEnvironment("CJK");
1466 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1468 output_ert_inset(os, "\\", parent_context);
1469 else if (*it == '$')
1470 output_ert_inset(os, "$", parent_context);
1474 output_ert_inset(os, "\\end{" + name + "}",
1478 supported_CJK_languages[where - supported_CJK_encodings];
1479 // store the language because we must reset it at the end
1480 string const lang_old = parent_context.font.language;
1481 parent_context.font.language = lang;
1482 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1483 parent_context.font.language = lang_old;
1484 parent_context.new_paragraph(os);
1486 p.setEncoding(encoding_old);
1490 else if (name == "lyxgreyedout") {
1491 eat_whitespace(p, os, parent_context, false);
1492 parent_context.check_layout(os);
1493 begin_inset(os, "Note Greyedout\n");
1494 os << "status open\n";
1495 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1498 if (!preamble.notefontcolor().empty())
1499 preamble.registerAutomaticallyLoadedPackage("color");
1502 else if (name == "framed" || name == "shaded") {
1503 eat_whitespace(p, os, parent_context, false);
1504 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1508 else if (name == "lstlisting") {
1509 eat_whitespace(p, os, parent_context, false);
1510 parse_listings(p, os, parent_context, false);
1514 else if (!parent_context.new_layout_allowed)
1515 parse_unknown_environment(p, name, os, FLAG_END, outer,
1518 // Alignment and spacing settings
1519 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1520 // therefore are totally broken!
1521 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1522 // they are commands not environments. They are furthermore switches that
1523 // can be ended by another switches, but also by commands like \footnote or
1524 // \parbox. So the only safe way is to leave them untouched.
1525 else if (name == "center" || name == "centering" ||
1526 name == "flushleft" || name == "flushright" ||
1527 name == "singlespace" || name == "onehalfspace" ||
1528 name == "doublespace" || name == "spacing") {
1529 eat_whitespace(p, os, parent_context, false);
1530 // We must begin a new paragraph if not already done
1531 if (! parent_context.atParagraphStart()) {
1532 parent_context.check_end_layout(os);
1533 parent_context.new_paragraph(os);
1535 if (name == "flushleft")
1536 parent_context.add_extra_stuff("\\align left\n");
1537 else if (name == "flushright")
1538 parent_context.add_extra_stuff("\\align right\n");
1539 else if (name == "center" || name == "centering")
1540 parent_context.add_extra_stuff("\\align center\n");
1541 else if (name == "singlespace")
1542 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1543 else if (name == "onehalfspace") {
1544 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1545 preamble.registerAutomaticallyLoadedPackage("setspace");
1546 } else if (name == "doublespace") {
1547 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1548 preamble.registerAutomaticallyLoadedPackage("setspace");
1549 } else if (name == "spacing") {
1550 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1551 preamble.registerAutomaticallyLoadedPackage("setspace");
1553 parse_text(p, os, FLAG_END, outer, parent_context);
1554 // Just in case the environment is empty
1555 parent_context.extra_stuff.erase();
1556 // We must begin a new paragraph to reset the alignment
1557 parent_context.new_paragraph(os);
1561 // The single '=' is meant here.
1562 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1563 eat_whitespace(p, os, parent_context, false);
1564 Context context(true, parent_context.textclass, newlayout,
1565 parent_context.layout, parent_context.font);
1566 if (parent_context.deeper_paragraph) {
1567 // We are beginning a nested environment after a
1568 // deeper paragraph inside the outer list environment.
1569 // Therefore we don't need to output a "begin deeper".
1570 context.need_end_deeper = true;
1572 parent_context.check_end_layout(os);
1573 if (last_env == name) {
1574 // we need to output a separator since LyX would export
1575 // the two environments as one otherwise (bug 5716)
1576 docstring const sep = from_ascii("--Separator--");
1577 TeX2LyXDocClass const & textclass(parent_context.textclass);
1578 if (textclass.hasLayout(sep)) {
1579 Context newcontext(parent_context);
1580 newcontext.layout = &(textclass[sep]);
1581 newcontext.check_layout(os);
1582 newcontext.check_end_layout(os);
1584 parent_context.check_layout(os);
1585 begin_inset(os, "Note Note\n");
1586 os << "status closed\n";
1587 Context newcontext(true, textclass,
1588 &(textclass.defaultLayout()));
1589 newcontext.check_layout(os);
1590 newcontext.check_end_layout(os);
1592 parent_context.check_end_layout(os);
1595 switch (context.layout->latextype) {
1596 case LATEX_LIST_ENVIRONMENT:
1597 context.add_par_extra_stuff("\\labelwidthstring "
1598 + p.verbatim_item() + '\n');
1601 case LATEX_BIB_ENVIRONMENT:
1602 p.verbatim_item(); // swallow next arg
1608 context.check_deeper(os);
1609 // handle known optional and required arguments
1610 // FIXME: Since format 446, layouts do not require anymore all optional
1611 // arguments before the required ones. Needs to be implemented!
1612 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1613 // It is impossible to place anything after the environment name,
1614 // but before the first \\item.
1615 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1616 bool need_layout = true;
1618 while (optargs < context.layout->optArgs()) {
1619 eat_whitespace(p, os, context, false);
1620 if (p.next_token().cat() == catEscape ||
1621 p.next_token().character() != '[')
1623 p.get_token(); // eat '['
1625 context.check_layout(os);
1626 need_layout = false;
1628 // FIXME: Just a workaround. InsetArgument::updateBuffer
1629 // will compute a proper ID for all "999" Arguments
1630 // (which is also what lyx2lyx produces).
1631 // However, tex2lyx should be able to output proper IDs
1633 begin_inset(os, "Argument 999\n");
1634 os << "status collapsed\n\n";
1635 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1637 eat_whitespace(p, os, context, false);
1641 while (reqargs < context.layout->requiredArgs()) {
1642 eat_whitespace(p, os, context, false);
1643 if (p.next_token().cat() != catBegin)
1645 p.get_token(); // eat '{'
1647 context.check_layout(os);
1648 need_layout = false;
1650 // FIXME: Just a workaround. InsetArgument::updateBuffer
1651 // will compute a proper ID for all "999" Arguments
1652 // (which is also what lyx2lyx produces).
1653 // However, tex2lyx should be able to output proper IDs
1655 begin_inset(os, "Argument 999\n");
1656 os << "status collapsed\n\n";
1657 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1659 eat_whitespace(p, os, context, false);
1663 parse_text(p, os, FLAG_END, outer, context);
1664 context.check_end_layout(os);
1665 if (parent_context.deeper_paragraph) {
1666 // We must suppress the "end deeper" because we
1667 // suppressed the "begin deeper" above.
1668 context.need_end_deeper = false;
1670 context.check_end_deeper(os);
1671 parent_context.new_paragraph(os);
1673 if (!preamble.titleLayoutFound())
1674 preamble.titleLayoutFound(newlayout->intitle);
1675 set<string> const & req = newlayout->requires();
1676 set<string>::const_iterator it = req.begin();
1677 set<string>::const_iterator en = req.end();
1678 for (; it != en; ++it)
1679 preamble.registerAutomaticallyLoadedPackage(*it);
1682 // The single '=' is meant here.
1683 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1684 eat_whitespace(p, os, parent_context, false);
1685 parent_context.check_layout(os);
1686 begin_inset(os, "Flex ");
1687 os << to_utf8(newinsetlayout->name()) << '\n'
1688 << "status collapsed\n";
1689 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1693 else if (name == "appendix") {
1694 // This is no good latex style, but it works and is used in some documents...
1695 eat_whitespace(p, os, parent_context, false);
1696 parent_context.check_end_layout(os);
1697 Context context(true, parent_context.textclass, parent_context.layout,
1698 parent_context.layout, parent_context.font);
1699 context.check_layout(os);
1700 os << "\\start_of_appendix\n";
1701 parse_text(p, os, FLAG_END, outer, context);
1702 context.check_end_layout(os);
1706 else if (known_environments.find(name) != known_environments.end()) {
1707 vector<ArgumentType> arguments = known_environments[name];
1708 // The last "argument" denotes wether we may translate the
1709 // environment contents to LyX
1710 // The default required if no argument is given makes us
1711 // compatible with the reLyXre environment.
1712 ArgumentType contents = arguments.empty() ?
1715 if (!arguments.empty())
1716 arguments.pop_back();
1717 // See comment in parse_unknown_environment()
1718 bool const specialfont =
1719 (parent_context.font != parent_context.normalfont);
1720 bool const new_layout_allowed =
1721 parent_context.new_layout_allowed;
1723 parent_context.new_layout_allowed = false;
1724 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1725 outer, parent_context);
1726 if (contents == verbatim)
1727 output_ert_inset(os, p.ertEnvironment(name),
1730 parse_text_snippet(p, os, FLAG_END, outer,
1732 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1734 parent_context.new_layout_allowed = new_layout_allowed;
1738 parse_unknown_environment(p, name, os, FLAG_END, outer,
1742 active_environments.pop_back();
1746 /// parses a comment and outputs it to \p os.
1747 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1749 LASSERT(t.cat() == catComment, return);
1750 if (!t.cs().empty()) {
1751 context.check_layout(os);
1752 output_ert_inset(os, '%' + t.cs(), context);
1753 if (p.next_token().cat() == catNewline) {
1754 // A newline after a comment line starts a new
1756 if (context.new_layout_allowed) {
1757 if(!context.atParagraphStart())
1758 // Only start a new paragraph if not already
1759 // done (we might get called recursively)
1760 context.new_paragraph(os);
1762 output_ert_inset(os, "\n", context);
1763 eat_whitespace(p, os, context, true);
1766 // "%\n" combination
1773 * Reads spaces and comments until the first non-space, non-comment token.
1774 * New paragraphs (double newlines or \\par) are handled like simple spaces
1775 * if \p eatParagraph is true.
1776 * Spaces are skipped, but comments are written to \p os.
1778 void eat_whitespace(Parser & p, ostream & os, Context & context,
1782 Token const & t = p.get_token();
1783 if (t.cat() == catComment)
1784 parse_comment(p, os, t, context);
1785 else if ((! eatParagraph && p.isParagraph()) ||
1786 (t.cat() != catSpace && t.cat() != catNewline)) {
1795 * Set a font attribute, parse text and reset the font attribute.
1796 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1797 * \param currentvalue Current value of the attribute. Is set to the new
1798 * value during parsing.
1799 * \param newvalue New value of the attribute
1801 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1802 Context & context, string const & attribute,
1803 string & currentvalue, string const & newvalue)
1805 context.check_layout(os);
1806 string const oldvalue = currentvalue;
1807 currentvalue = newvalue;
1808 os << '\n' << attribute << ' ' << newvalue << "\n";
1809 parse_text_snippet(p, os, flags, outer, context);
1810 context.check_layout(os);
1811 os << '\n' << attribute << ' ' << oldvalue << "\n";
1812 currentvalue = oldvalue;
1816 /// get the arguments of a natbib or jurabib citation command
1817 void get_cite_arguments(Parser & p, bool natbibOrder,
1818 string & before, string & after)
1820 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1822 // text before the citation
1824 // text after the citation
1825 after = p.getFullOpt();
1827 if (!after.empty()) {
1828 before = p.getFullOpt();
1829 if (natbibOrder && !before.empty())
1830 swap(before, after);
1835 /// Convert filenames with TeX macros and/or quotes to something LyX
1837 string const normalize_filename(string const & name)
1842 Token const & t = p.get_token();
1843 if (t.cat() != catEscape)
1845 else if (t.cs() == "lyxdot") {
1846 // This is used by LyX for simple dots in relative
1850 } else if (t.cs() == "space") {
1853 } else if (t.cs() == "string") {
1854 // Convert \string" to " and \string~ to ~
1855 Token const & n = p.next_token();
1856 if (n.asInput() != "\"" && n.asInput() != "~")
1861 // Strip quotes. This is a bit complicated (see latex_path()).
1862 string full = os.str();
1863 if (!full.empty() && full[0] == '"') {
1864 string base = removeExtension(full);
1865 string ext = getExtension(full);
1866 if (!base.empty() && base[base.length()-1] == '"')
1869 return addExtension(trim(base, "\""), ext);
1870 if (full[full.length()-1] == '"')
1873 return trim(full, "\"");
1879 /// Convert \p name from TeX convention (relative to master file) to LyX
1880 /// convention (relative to .lyx file) if it is relative
1881 void fix_child_filename(string & name)
1883 string const absMasterTeX = getMasterFilePath(true);
1884 bool const isabs = FileName::isAbsolute(name);
1885 // convert from "relative to .tex master" to absolute original path
1887 name = makeAbsPath(name, absMasterTeX).absFileName();
1888 bool copyfile = copyFiles();
1889 string const absParentLyX = getParentFilePath(false);
1892 // convert from absolute original path to "relative to master file"
1893 string const rel = to_utf8(makeRelPath(from_utf8(name),
1894 from_utf8(absMasterTeX)));
1895 // re-interpret "relative to .tex file" as "relative to .lyx file"
1896 // (is different if the master .lyx file resides in a
1897 // different path than the master .tex file)
1898 string const absMasterLyX = getMasterFilePath(false);
1899 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1900 // Do not copy if the new path is impossible to create. Example:
1901 // absMasterTeX = "/foo/bar/"
1902 // absMasterLyX = "/bar/"
1903 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1904 if (contains(name, "/../"))
1911 // convert from absolute original path to
1912 // "relative to .lyx file"
1913 name = to_utf8(makeRelPath(from_utf8(abs),
1914 from_utf8(absParentLyX)));
1918 // convert from absolute original path to "relative to .lyx file"
1919 name = to_utf8(makeRelPath(from_utf8(name),
1920 from_utf8(absParentLyX)));
1925 void copy_file(FileName const & src, string dstname)
1929 string const absParent = getParentFilePath(false);
1931 if (FileName::isAbsolute(dstname))
1932 dst = FileName(dstname);
1934 dst = makeAbsPath(dstname, absParent);
1935 string const absMaster = getMasterFilePath(false);
1936 FileName const srcpath = src.onlyPath();
1937 FileName const dstpath = dst.onlyPath();
1938 if (equivalent(srcpath, dstpath))
1940 if (!dstpath.isDirectory()) {
1941 if (!dstpath.createPath()) {
1942 cerr << "Warning: Could not create directory for file `"
1943 << dst.absFileName() << "´." << endl;
1947 if (dst.isReadableFile()) {
1948 if (overwriteFiles())
1949 cerr << "Warning: Overwriting existing file `"
1950 << dst.absFileName() << "´." << endl;
1952 cerr << "Warning: Not overwriting existing file `"
1953 << dst.absFileName() << "´." << endl;
1957 if (!src.copyTo(dst))
1958 cerr << "Warning: Could not copy file `" << src.absFileName()
1959 << "´ to `" << dst.absFileName() << "´." << endl;
1963 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1964 void parse_noweb(Parser & p, ostream & os, Context & context)
1966 // assemble the rest of the keyword
1970 Token const & t = p.get_token();
1971 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1974 chunk = (p.good() && p.next_token().asInput() == "=");
1976 name += p.get_token().asInput();
1979 name += t.asInput();
1982 if (!chunk || !context.new_layout_allowed ||
1983 !context.textclass.hasLayout(from_ascii("Chunk"))) {
1984 cerr << "Warning: Could not interpret '" << name
1985 << "'. Ignoring it." << endl;
1989 // We use new_paragraph instead of check_end_layout because the stuff
1990 // following the noweb chunk needs to start with a \begin_layout.
1991 // This may create a new paragraph even if there was none in the
1992 // noweb file, but the alternative is an invalid LyX file. Since
1993 // noweb code chunks are implemented with a layout style in LyX they
1994 // always must be in an own paragraph.
1995 context.new_paragraph(os);
1996 Context newcontext(true, context.textclass,
1997 &context.textclass[from_ascii("Chunk")]);
1998 newcontext.check_layout(os);
2001 Token const & t = p.get_token();
2002 // We abuse the parser a bit, because this is no TeX syntax
2004 if (t.cat() == catEscape)
2005 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2008 Context tmp(false, context.textclass,
2009 &context.textclass[from_ascii("Chunk")]);
2010 tmp.need_end_layout = true;
2011 tmp.check_layout(oss);
2012 os << subst(t.asInput(), "\n", oss.str());
2014 // The chunk is ended by an @ at the beginning of a line.
2015 // After the @ the line may contain a comment and/or
2016 // whitespace, but nothing else.
2017 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2018 (p.next_token().cat() == catSpace ||
2019 p.next_token().cat() == catNewline ||
2020 p.next_token().cat() == catComment)) {
2021 while (p.good() && p.next_token().cat() == catSpace)
2022 os << p.get_token().asInput();
2023 if (p.next_token().cat() == catComment)
2024 // The comment includes a final '\n'
2025 os << p.get_token().asInput();
2027 if (p.next_token().cat() == catNewline)
2034 newcontext.check_end_layout(os);
2038 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2039 bool is_macro(Parser & p)
2041 Token first = p.curr_token();
2042 if (first.cat() != catEscape || !p.good())
2044 if (first.cs() == "def")
2046 if (first.cs() != "global" && first.cs() != "long")
2048 Token second = p.get_token();
2050 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2051 second.cat() == catNewline || second.cat() == catComment)) {
2052 second = p.get_token();
2055 bool secondvalid = second.cat() == catEscape;
2057 bool thirdvalid = false;
2058 if (p.good() && first.cs() == "global" && secondvalid &&
2059 second.cs() == "long") {
2060 third = p.get_token();
2062 while (p.good() && !p.isParagraph() &&
2063 (third.cat() == catSpace ||
2064 third.cat() == catNewline ||
2065 third.cat() == catComment)) {
2066 third = p.get_token();
2069 thirdvalid = third.cat() == catEscape;
2071 for (int i = 0; i < pos; ++i)
2076 return (first.cs() == "global" || first.cs() == "long") &&
2077 second.cs() == "def";
2078 return first.cs() == "global" && second.cs() == "long" &&
2079 third.cs() == "def";
2083 /// Parse a macro definition (assumes that is_macro() returned true)
2084 void parse_macro(Parser & p, ostream & os, Context & context)
2086 context.check_layout(os);
2087 Token first = p.curr_token();
2090 string command = first.asInput();
2091 if (first.cs() != "def") {
2093 eat_whitespace(p, os, context, false);
2094 second = p.curr_token();
2095 command += second.asInput();
2096 if (second.cs() != "def") {
2098 eat_whitespace(p, os, context, false);
2099 third = p.curr_token();
2100 command += third.asInput();
2103 eat_whitespace(p, os, context, false);
2104 string const name = p.get_token().cs();
2105 eat_whitespace(p, os, context, false);
2111 while (p.next_token().cat() != catBegin) {
2112 if (p.next_token().cat() == catParameter) {
2117 // followed by number?
2118 if (p.next_token().cat() == catOther) {
2119 string s = p.get_token().asInput();
2121 // number = current arity + 1?
2122 if (s.size() == 1 && s[0] == arity + '0' + 1)
2127 paramtext += p.get_token().cs();
2129 paramtext += p.get_token().cs();
2134 // only output simple (i.e. compatible) macro as FormulaMacros
2135 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2137 context.check_layout(os);
2138 begin_inset(os, "FormulaMacro");
2139 os << "\n\\def" << ert;
2142 output_ert_inset(os, command + ert, context);
2146 void registerExternalTemplatePackages(string const & name)
2148 external::TemplateManager const & etm = external::TemplateManager::get();
2149 external::Template const * const et = etm.getTemplateByName(name);
2152 external::Template::Formats::const_iterator cit = et->formats.end();
2154 cit = et->formats.find("PDFLaTeX");
2155 if (cit == et->formats.end())
2156 // If the template has not specified a PDFLaTeX output,
2157 // we try the LaTeX format.
2158 cit = et->formats.find("LaTeX");
2159 if (cit == et->formats.end())
2161 vector<string>::const_iterator qit = cit->second.requirements.begin();
2162 vector<string>::const_iterator qend = cit->second.requirements.end();
2163 for (; qit != qend; ++qit)
2164 preamble.registerAutomaticallyLoadedPackage(*qit);
2167 } // anonymous namespace
2170 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2173 Layout const * newlayout = 0;
2174 InsetLayout const * newinsetlayout = 0;
2175 char const * const * where = 0;
2176 // Store the latest bibliographystyle, addcontentslineContent and
2177 // nocite{*} option (needed for bibtex inset)
2179 string contentslineContent;
2180 string bibliographystyle = "default";
2181 bool const use_natbib = isProvided("natbib");
2182 bool const use_jurabib = isProvided("jurabib");
2185 Token const & t = p.get_token();
2187 // it is impossible to determine the correct encoding for non-CJK Japanese.
2188 // Therefore write a note at the beginning of the document
2189 if (is_nonCJKJapanese) {
2190 context.check_layout(os);
2191 begin_inset(os, "Note Note\n");
2192 os << "status open\n\\begin_layout Plain Layout\n"
2193 << "\\series bold\n"
2194 << "Important information:\n"
2195 << "\\end_layout\n\n"
2196 << "\\begin_layout Plain Layout\n"
2197 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2198 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2199 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2200 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2201 << " and specify the encoding using the -e command-line switch.\n"
2202 << " In addition, you might want to double check that the desired output encoding\n"
2203 << " is correctly selected in Document > Settings > Language.\n"
2204 << "\\end_layout\n";
2206 is_nonCJKJapanese = false;
2210 debugToken(cerr, t, flags);
2213 if (flags & FLAG_ITEM) {
2214 if (t.cat() == catSpace)
2217 flags &= ~FLAG_ITEM;
2218 if (t.cat() == catBegin) {
2219 // skip the brace and collect everything to the next matching
2221 flags |= FLAG_BRACE_LAST;
2225 // handle only this single token, leave the loop if done
2226 flags |= FLAG_LEAVE;
2229 if (t.cat() != catEscape && t.character() == ']' &&
2230 (flags & FLAG_BRACK_LAST))
2232 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2235 // If there is anything between \end{env} and \begin{env} we
2236 // don't need to output a separator.
2237 if (t.cat() != catSpace && t.cat() != catNewline &&
2238 t.asInput() != "\\begin")
2244 if (t.cat() == catMath) {
2245 // we are inside some text mode thingy, so opening new math is allowed
2246 context.check_layout(os);
2247 begin_inset(os, "Formula ");
2248 Token const & n = p.get_token();
2249 bool const display(n.cat() == catMath && outer);
2251 // TeX's $$...$$ syntax for displayed math
2253 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2255 p.get_token(); // skip the second '$' token
2257 // simple $...$ stuff
2260 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2265 // Prevent the conversion of a line break to a
2266 // space (bug 7668). This does not change the
2267 // output, but looks ugly in LyX.
2268 eat_whitespace(p, os, context, false);
2272 else if (t.cat() == catSuper || t.cat() == catSub)
2273 cerr << "catcode " << t << " illegal in text mode\n";
2275 // Basic support for english quotes. This should be
2276 // extended to other quotes, but is not so easy (a
2277 // left english quote is the same as a right german
2279 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2280 context.check_layout(os);
2281 begin_inset(os, "Quotes ");
2287 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2288 context.check_layout(os);
2289 begin_inset(os, "Quotes ");
2296 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2297 context.check_layout(os);
2298 begin_inset(os, "Quotes ");
2305 else if (t.asInput() == "<"
2306 && p.next_token().asInput() == "<" && noweb_mode) {
2308 parse_noweb(p, os, context);
2311 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2312 context.check_layout(os);
2313 begin_inset(os, "Quotes ");
2320 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2321 check_space(p, os, context);
2323 else if (t.character() == '[' && noweb_mode &&
2324 p.next_token().character() == '[') {
2325 // These can contain underscores
2327 string const s = p.getFullOpt() + ']';
2328 if (p.next_token().character() == ']')
2331 cerr << "Warning: Inserting missing ']' in '"
2332 << s << "'." << endl;
2333 output_ert_inset(os, s, context);
2336 else if (t.cat() == catLetter) {
2337 context.check_layout(os);
2338 // Workaround for bug 4752.
2339 // FIXME: This whole code block needs to be removed
2340 // when the bug is fixed and tex2lyx produces
2341 // the updated file format.
2342 // The replacement algorithm in LyX is so stupid that
2343 // it even translates a phrase if it is part of a word.
2344 bool handled = false;
2345 for (int const * l = known_phrase_lengths; *l; ++l) {
2346 string phrase = t.cs();
2347 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2348 phrase += p.get_token().cs();
2349 if (is_known(phrase, known_coded_phrases)) {
2350 output_ert_inset(os, phrase, context);
2354 for (size_t i = 1; i < phrase.length(); ++i)
2362 else if (t.cat() == catOther ||
2363 t.cat() == catAlign ||
2364 t.cat() == catParameter) {
2365 // This translates "&" to "\\&" which may be wrong...
2366 context.check_layout(os);
2370 else if (p.isParagraph()) {
2371 if (context.new_layout_allowed)
2372 context.new_paragraph(os);
2374 output_ert_inset(os, "\\par ", context);
2375 eat_whitespace(p, os, context, true);
2378 else if (t.cat() == catActive) {
2379 context.check_layout(os);
2380 if (t.character() == '~') {
2381 if (context.layout->free_spacing)
2384 begin_inset(os, "space ~\n");
2391 else if (t.cat() == catBegin) {
2392 Token const next = p.next_token();
2393 Token const end = p.next_next_token();
2394 if (next.cat() == catEnd) {
2396 Token const prev = p.prev_token();
2398 if (p.next_token().character() == '`' ||
2399 (prev.character() == '-' &&
2400 p.next_token().character() == '-'))
2401 ; // ignore it in {}`` or -{}-
2403 output_ert_inset(os, "{}", context);
2404 } else if (next.cat() == catEscape &&
2405 is_known(next.cs(), known_quotes) &&
2406 end.cat() == catEnd) {
2407 // Something like {\textquoteright} (e.g.
2408 // from writer2latex). LyX writes
2409 // \textquoteright{}, so we may skip the
2410 // braces here for better readability.
2411 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2414 context.check_layout(os);
2415 // special handling of font attribute changes
2416 Token const prev = p.prev_token();
2417 TeXFont const oldFont = context.font;
2418 if (next.character() == '[' ||
2419 next.character() == ']' ||
2420 next.character() == '*') {
2422 if (p.next_token().cat() == catEnd) {
2427 output_ert_inset(os, "{", context);
2428 parse_text_snippet(p, os,
2431 output_ert_inset(os, "}", context);
2433 } else if (! context.new_layout_allowed) {
2434 output_ert_inset(os, "{", context);
2435 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2437 output_ert_inset(os, "}", context);
2438 } else if (is_known(next.cs(), known_sizes)) {
2439 // next will change the size, so we must
2441 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2443 if (!context.atParagraphStart())
2445 << context.font.size << "\n";
2446 } else if (is_known(next.cs(), known_font_families)) {
2447 // next will change the font family, so we
2448 // must reset it here
2449 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2451 if (!context.atParagraphStart())
2453 << context.font.family << "\n";
2454 } else if (is_known(next.cs(), known_font_series)) {
2455 // next will change the font series, so we
2456 // must reset it here
2457 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2459 if (!context.atParagraphStart())
2461 << context.font.series << "\n";
2462 } else if (is_known(next.cs(), known_font_shapes)) {
2463 // next will change the font shape, so we
2464 // must reset it here
2465 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2467 if (!context.atParagraphStart())
2469 << context.font.shape << "\n";
2470 } else if (is_known(next.cs(), known_old_font_families) ||
2471 is_known(next.cs(), known_old_font_series) ||
2472 is_known(next.cs(), known_old_font_shapes)) {
2473 // next will change the font family, series
2474 // and shape, so we must reset it here
2475 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2477 if (!context.atParagraphStart())
2479 << context.font.family
2481 << context.font.series
2483 << context.font.shape << "\n";
2485 output_ert_inset(os, "{", context);
2486 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2488 output_ert_inset(os, "}", context);
2493 else if (t.cat() == catEnd) {
2494 if (flags & FLAG_BRACE_LAST) {
2497 cerr << "stray '}' in text\n";
2498 output_ert_inset(os, "}", context);
2501 else if (t.cat() == catComment)
2502 parse_comment(p, os, t, context);
2505 // control sequences
2508 else if (t.cs() == "(") {
2509 context.check_layout(os);
2510 begin_inset(os, "Formula");
2512 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2517 else if (t.cs() == "[") {
2518 context.check_layout(os);
2519 begin_inset(os, "Formula");
2521 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2524 // Prevent the conversion of a line break to a space
2525 // (bug 7668). This does not change the output, but
2526 // looks ugly in LyX.
2527 eat_whitespace(p, os, context, false);
2530 else if (t.cs() == "begin")
2531 parse_environment(p, os, outer, last_env,
2534 else if (t.cs() == "end") {
2535 if (flags & FLAG_END) {
2536 // eat environment name
2537 string const name = p.getArg('{', '}');
2538 if (name != active_environment())
2539 cerr << "\\end{" + name + "} does not match \\begin{"
2540 + active_environment() + "}\n";
2543 p.error("found 'end' unexpectedly");
2546 else if (t.cs() == "item") {
2548 bool const optarg = p.hasOpt();
2550 // FIXME: This swallows comments, but we cannot use
2551 // eat_whitespace() since we must not output
2552 // anything before the item.
2553 p.skip_spaces(true);
2554 s = p.verbatimOption();
2556 p.skip_spaces(false);
2558 context.check_layout(os);
2559 if (context.has_item) {
2560 // An item in an unknown list-like environment
2561 // FIXME: Do this in check_layout()!
2562 context.has_item = false;
2564 output_ert_inset(os, "\\item", context);
2566 output_ert_inset(os, "\\item ", context);
2569 if (context.layout->labeltype != LABEL_MANUAL) {
2570 // LyX does not support \item[\mybullet]
2571 // in itemize environments
2573 os << parse_text_snippet(p2,
2574 FLAG_BRACK_LAST, outer, context);
2575 } else if (!s.empty()) {
2576 // LyX adds braces around the argument,
2577 // so we need to remove them here.
2578 if (s.size() > 2 && s[0] == '{' &&
2579 s[s.size()-1] == '}')
2580 s = s.substr(1, s.size()-2);
2581 // If the argument contains a space we
2582 // must put it into ERT: Otherwise LyX
2583 // would misinterpret the space as
2584 // item delimiter (bug 7663)
2585 if (contains(s, ' ')) {
2586 output_ert_inset(os, s, context);
2589 os << parse_text_snippet(p2,
2593 // The space is needed to separate the
2594 // item from the rest of the sentence.
2596 eat_whitespace(p, os, context, false);
2601 else if (t.cs() == "bibitem") {
2603 context.check_layout(os);
2604 eat_whitespace(p, os, context, false);
2605 string label = convert_command_inset_arg(p.verbatimOption());
2606 string key = convert_command_inset_arg(p.verbatim_item());
2607 if (contains(label, '\\') || contains(key, '\\')) {
2608 // LyX can't handle LaTeX commands in labels or keys
2609 output_ert_inset(os, t.asInput() + '[' + label +
2610 "]{" + p.verbatim_item() + '}',
2613 begin_command_inset(os, "bibitem", "bibitem");
2614 os << "label \"" << label << "\"\n"
2615 "key \"" << key << "\"\n";
2620 else if (is_macro(p)) {
2621 // catch the case of \def\inputGnumericTable
2623 if (t.cs() == "def") {
2624 Token second = p.next_token();
2625 if (second.cs() == "inputGnumericTable") {
2629 Token third = p.get_token();
2631 if (third.cs() == "input") {
2635 string name = normalize_filename(p.verbatim_item());
2636 string const path = getMasterFilePath(true);
2637 // We want to preserve relative / absolute filenames,
2638 // therefore path is only used for testing
2639 // The file extension is in every case ".tex".
2640 // So we need to remove this extension and check for
2641 // the original one.
2642 name = removeExtension(name);
2643 if (!makeAbsPath(name, path).exists()) {
2644 char const * const Gnumeric_formats[] = {"gnumeric",
2646 string const Gnumeric_name =
2647 find_file(name, path, Gnumeric_formats);
2648 if (!Gnumeric_name.empty())
2649 name = Gnumeric_name;
2651 FileName const absname = makeAbsPath(name, path);
2652 if (absname.exists()) {
2653 fix_child_filename(name);
2654 copy_file(absname, name);
2656 cerr << "Warning: Could not find file '"
2657 << name << "'." << endl;
2658 context.check_layout(os);
2659 begin_inset(os, "External\n\ttemplate ");
2660 os << "GnumericSpreadsheet\n\tfilename "
2663 context.check_layout(os);
2665 // register the packages that are automatically loaded
2666 // by the Gnumeric template
2667 registerExternalTemplatePackages("GnumericSpreadsheet");
2672 parse_macro(p, os, context);
2675 else if (t.cs() == "noindent") {
2677 context.add_par_extra_stuff("\\noindent\n");
2680 else if (t.cs() == "appendix") {
2681 context.add_par_extra_stuff("\\start_of_appendix\n");
2682 // We need to start a new paragraph. Otherwise the
2683 // appendix in 'bla\appendix\chapter{' would start
2685 context.new_paragraph(os);
2686 // We need to make sure that the paragraph is
2687 // generated even if it is empty. Otherwise the
2688 // appendix in '\par\appendix\par\chapter{' would
2690 context.check_layout(os);
2691 // FIXME: This is a hack to prevent paragraph
2692 // deletion if it is empty. Handle this better!
2693 output_ert_inset(os,
2694 "%dummy comment inserted by tex2lyx to "
2695 "ensure that this paragraph is not empty",
2697 // Both measures above may generate an additional
2698 // empty paragraph, but that does not hurt, because
2699 // whitespace does not matter here.
2700 eat_whitespace(p, os, context, true);
2703 // Must catch empty dates before findLayout is called below
2704 else if (t.cs() == "date") {
2705 eat_whitespace(p, os, context, false);
2707 string const date = p.verbatim_item();
2710 preamble.suppressDate(true);
2713 preamble.suppressDate(false);
2714 if (context.new_layout_allowed &&
2715 (newlayout = findLayout(context.textclass,
2718 output_command_layout(os, p, outer,
2719 context, newlayout);
2720 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2721 if (!preamble.titleLayoutFound())
2722 preamble.titleLayoutFound(newlayout->intitle);
2723 set<string> const & req = newlayout->requires();
2724 set<string>::const_iterator it = req.begin();
2725 set<string>::const_iterator en = req.end();
2726 for (; it != en; ++it)
2727 preamble.registerAutomaticallyLoadedPackage(*it);
2729 output_ert_inset(os,
2730 "\\date{" + p.verbatim_item() + '}',
2735 // Starred section headings
2736 // Must attempt to parse "Section*" before "Section".
2737 else if ((p.next_token().asInput() == "*") &&
2738 context.new_layout_allowed &&
2739 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2742 output_command_layout(os, p, outer, context, newlayout);
2744 if (!preamble.titleLayoutFound())
2745 preamble.titleLayoutFound(newlayout->intitle);
2746 set<string> const & req = newlayout->requires();
2747 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2748 preamble.registerAutomaticallyLoadedPackage(*it);
2751 // Section headings and the like
2752 else if (context.new_layout_allowed &&
2753 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2755 output_command_layout(os, p, outer, context, newlayout);
2757 if (!preamble.titleLayoutFound())
2758 preamble.titleLayoutFound(newlayout->intitle);
2759 set<string> const & req = newlayout->requires();
2760 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2761 preamble.registerAutomaticallyLoadedPackage(*it);
2764 else if (t.cs() == "caption") {
2766 context.check_layout(os);
2768 begin_inset(os, "Caption Standard\n");
2769 Context newcontext(true, context.textclass, 0, 0, context.font);
2770 newcontext.check_layout(os);
2771 // FIXME InsetArgument is now properly implemented in InsetLayout
2772 // (for captions, but also for others)
2773 if (p.next_token().cat() != catEscape &&
2774 p.next_token().character() == '[') {
2775 p.get_token(); // eat '['
2776 begin_inset(os, "Argument 1\n");
2777 os << "status collapsed\n";
2778 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2780 eat_whitespace(p, os, context, false);
2782 parse_text(p, os, FLAG_ITEM, outer, context);
2783 context.check_end_layout(os);
2784 // We don't need really a new paragraph, but
2785 // we must make sure that the next item gets a \begin_layout.
2786 context.new_paragraph(os);
2789 newcontext.check_end_layout(os);
2792 else if (t.cs() == "subfloat") {
2793 // the syntax is \subfloat[caption]{content}
2794 // if it is a table of figure depends on the surrounding float
2795 bool has_caption = false;
2797 // do nothing if there is no outer float
2798 if (!float_type.empty()) {
2799 context.check_layout(os);
2801 begin_inset(os, "Float " + float_type + "\n");
2803 << "\nsideways false"
2804 << "\nstatus collapsed\n\n";
2807 if (p.next_token().cat() != catEscape &&
2808 p.next_token().character() == '[') {
2809 p.get_token(); // eat '['
2810 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2814 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2815 // the caption comes always as the last
2817 // we must make sure that the caption gets a \begin_layout
2818 os << "\n\\begin_layout Plain Layout";
2820 begin_inset(os, "Caption Standard\n");
2821 Context newcontext(true, context.textclass,
2822 0, 0, context.font);
2823 newcontext.check_layout(os);
2824 os << caption << "\n";
2825 newcontext.check_end_layout(os);
2826 // We don't need really a new paragraph, but
2827 // we must make sure that the next item gets a \begin_layout.
2828 //newcontext.new_paragraph(os);
2832 // We don't need really a new paragraph, but
2833 // we must make sure that the next item gets a \begin_layout.
2835 context.new_paragraph(os);
2838 context.check_end_layout(os);
2839 // close the layout we opened
2841 os << "\n\\end_layout\n";
2843 // if the float type is not supported or there is no surrounding float
2846 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2847 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2848 "]{" + p.verbatim_item() + '}', context);
2850 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2854 else if (t.cs() == "includegraphics") {
2855 bool const clip = p.next_token().asInput() == "*";
2858 string const arg = p.getArg('[', ']');
2859 map<string, string> opts;
2860 vector<string> keys;
2861 split_map(arg, opts, keys);
2863 opts["clip"] = string();
2864 string name = normalize_filename(p.verbatim_item());
2866 string const path = getMasterFilePath(true);
2867 // We want to preserve relative / absolute filenames,
2868 // therefore path is only used for testing
2869 if (!makeAbsPath(name, path).exists()) {
2870 // The file extension is probably missing.
2871 // Now try to find it out.
2872 string const dvips_name =
2873 find_file(name, path,
2874 known_dvips_graphics_formats);
2875 string const pdftex_name =
2876 find_file(name, path,
2877 known_pdftex_graphics_formats);
2878 if (!dvips_name.empty()) {
2879 if (!pdftex_name.empty()) {
2880 cerr << "This file contains the "
2882 "\"\\includegraphics{"
2884 "However, files\n\""
2885 << dvips_name << "\" and\n\""
2886 << pdftex_name << "\"\n"
2887 "both exist, so I had to make a "
2888 "choice and took the first one.\n"
2889 "Please move the unwanted one "
2890 "someplace else and try again\n"
2891 "if my choice was wrong."
2895 } else if (!pdftex_name.empty()) {
2901 FileName const absname = makeAbsPath(name, path);
2902 if (absname.exists()) {
2903 fix_child_filename(name);
2904 copy_file(absname, name);
2906 cerr << "Warning: Could not find graphics file '"
2907 << name << "'." << endl;
2909 context.check_layout(os);
2910 begin_inset(os, "Graphics ");
2911 os << "\n\tfilename " << name << '\n';
2912 if (opts.find("width") != opts.end())
2914 << translate_len(opts["width"]) << '\n';
2915 if (opts.find("height") != opts.end())
2917 << translate_len(opts["height"]) << '\n';
2918 if (opts.find("scale") != opts.end()) {
2919 istringstream iss(opts["scale"]);
2923 os << "\tscale " << val << '\n';
2925 if (opts.find("angle") != opts.end()) {
2926 os << "\trotateAngle "
2927 << opts["angle"] << '\n';
2928 vector<string>::const_iterator a =
2929 find(keys.begin(), keys.end(), "angle");
2930 vector<string>::const_iterator s =
2931 find(keys.begin(), keys.end(), "width");
2932 if (s == keys.end())
2933 s = find(keys.begin(), keys.end(), "height");
2934 if (s == keys.end())
2935 s = find(keys.begin(), keys.end(), "scale");
2936 if (s != keys.end() && distance(s, a) > 0)
2937 os << "\tscaleBeforeRotation\n";
2939 if (opts.find("origin") != opts.end()) {
2941 string const opt = opts["origin"];
2942 if (opt.find('l') != string::npos) ss << "left";
2943 if (opt.find('r') != string::npos) ss << "right";
2944 if (opt.find('c') != string::npos) ss << "center";
2945 if (opt.find('t') != string::npos) ss << "Top";
2946 if (opt.find('b') != string::npos) ss << "Bottom";
2947 if (opt.find('B') != string::npos) ss << "Baseline";
2948 if (!ss.str().empty())
2949 os << "\trotateOrigin " << ss.str() << '\n';
2951 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2953 if (opts.find("keepaspectratio") != opts.end())
2954 os << "\tkeepAspectRatio\n";
2955 if (opts.find("clip") != opts.end())
2957 if (opts.find("draft") != opts.end())
2959 if (opts.find("bb") != opts.end())
2960 os << "\tBoundingBox "
2961 << opts["bb"] << '\n';
2962 int numberOfbbOptions = 0;
2963 if (opts.find("bbllx") != opts.end())
2964 numberOfbbOptions++;
2965 if (opts.find("bblly") != opts.end())
2966 numberOfbbOptions++;
2967 if (opts.find("bburx") != opts.end())
2968 numberOfbbOptions++;
2969 if (opts.find("bbury") != opts.end())
2970 numberOfbbOptions++;
2971 if (numberOfbbOptions == 4)
2972 os << "\tBoundingBox "
2973 << opts["bbllx"] << " " << opts["bblly"] << " "
2974 << opts["bburx"] << " " << opts["bbury"] << '\n';
2975 else if (numberOfbbOptions > 0)
2976 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2977 numberOfbbOptions = 0;
2978 if (opts.find("natwidth") != opts.end())
2979 numberOfbbOptions++;
2980 if (opts.find("natheight") != opts.end())
2981 numberOfbbOptions++;
2982 if (numberOfbbOptions == 2)
2983 os << "\tBoundingBox 0bp 0bp "
2984 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2985 else if (numberOfbbOptions > 0)
2986 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2987 ostringstream special;
2988 if (opts.find("hiresbb") != opts.end())
2989 special << "hiresbb,";
2990 if (opts.find("trim") != opts.end())
2992 if (opts.find("viewport") != opts.end())
2993 special << "viewport=" << opts["viewport"] << ',';
2994 if (opts.find("totalheight") != opts.end())
2995 special << "totalheight=" << opts["totalheight"] << ',';
2996 if (opts.find("type") != opts.end())
2997 special << "type=" << opts["type"] << ',';
2998 if (opts.find("ext") != opts.end())
2999 special << "ext=" << opts["ext"] << ',';
3000 if (opts.find("read") != opts.end())
3001 special << "read=" << opts["read"] << ',';
3002 if (opts.find("command") != opts.end())
3003 special << "command=" << opts["command"] << ',';
3004 string s_special = special.str();
3005 if (!s_special.empty()) {
3006 // We had special arguments. Remove the trailing ','.
3007 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3009 // TODO: Handle the unknown settings better.
3010 // Warn about invalid options.
3011 // Check whether some option was given twice.
3013 preamble.registerAutomaticallyLoadedPackage("graphicx");
3016 else if (t.cs() == "footnote" ||
3017 (t.cs() == "thanks" && context.layout->intitle)) {
3019 context.check_layout(os);
3020 begin_inset(os, "Foot\n");
3021 os << "status collapsed\n\n";
3022 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3026 else if (t.cs() == "marginpar") {
3028 context.check_layout(os);
3029 begin_inset(os, "Marginal\n");
3030 os << "status collapsed\n\n";
3031 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3035 else if (t.cs() == "lstinline") {
3037 parse_listings(p, os, context, true);
3040 else if (t.cs() == "ensuremath") {
3042 context.check_layout(os);
3043 string const s = p.verbatim_item();
3044 //FIXME: this never triggers in UTF8
3045 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3048 output_ert_inset(os, "\\ensuremath{" + s + "}",
3052 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3053 if (preamble.titleLayoutFound()) {
3055 skip_spaces_braces(p);
3057 output_ert_inset(os, t.asInput(), context);
3060 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3061 context.check_layout(os);
3062 begin_command_inset(os, "toc", t.cs());
3064 skip_spaces_braces(p);
3065 if (t.cs() == "lstlistoflistings")
3066 preamble.registerAutomaticallyLoadedPackage("listings");
3069 else if (t.cs() == "listoffigures") {
3070 context.check_layout(os);
3071 begin_inset(os, "FloatList figure\n");
3073 skip_spaces_braces(p);
3076 else if (t.cs() == "listoftables") {
3077 context.check_layout(os);
3078 begin_inset(os, "FloatList table\n");
3080 skip_spaces_braces(p);
3083 else if (t.cs() == "listof") {
3084 p.skip_spaces(true);
3085 string const name = p.get_token().cs();
3086 if (context.textclass.floats().typeExist(name)) {
3087 context.check_layout(os);
3088 begin_inset(os, "FloatList ");
3091 p.get_token(); // swallow second arg
3093 output_ert_inset(os, "\\listof{" + name + "}", context);
3096 else if ((where = is_known(t.cs(), known_text_font_families)))
3097 parse_text_attributes(p, os, FLAG_ITEM, outer,
3098 context, "\\family", context.font.family,
3099 known_coded_font_families[where - known_text_font_families]);
3101 else if ((where = is_known(t.cs(), known_text_font_series)))
3102 parse_text_attributes(p, os, FLAG_ITEM, outer,
3103 context, "\\series", context.font.series,
3104 known_coded_font_series[where - known_text_font_series]);
3106 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3107 parse_text_attributes(p, os, FLAG_ITEM, outer,
3108 context, "\\shape", context.font.shape,
3109 known_coded_font_shapes[where - known_text_font_shapes]);
3111 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3112 context.check_layout(os);
3113 TeXFont oldFont = context.font;
3114 context.font.init();
3115 context.font.size = oldFont.size;
3116 os << "\n\\family " << context.font.family << "\n";
3117 os << "\n\\series " << context.font.series << "\n";
3118 os << "\n\\shape " << context.font.shape << "\n";
3119 if (t.cs() == "textnormal") {
3120 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3121 output_font_change(os, context.font, oldFont);
3122 context.font = oldFont;
3124 eat_whitespace(p, os, context, false);
3127 else if (t.cs() == "textcolor") {
3128 // scheme is \textcolor{color name}{text}
3129 string const color = p.verbatim_item();
3130 // we only support the predefined colors of the color package
3131 if (color == "black" || color == "blue" || color == "cyan"
3132 || color == "green" || color == "magenta" || color == "red"
3133 || color == "white" || color == "yellow") {
3134 context.check_layout(os);
3135 os << "\n\\color " << color << "\n";
3136 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3137 context.check_layout(os);
3138 os << "\n\\color inherit\n";
3139 preamble.registerAutomaticallyLoadedPackage("color");
3141 // for custom defined colors
3142 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3145 else if (t.cs() == "underbar" || t.cs() == "uline") {
3146 // \underbar is not 100% correct (LyX outputs \uline
3147 // of ulem.sty). The difference is that \ulem allows
3148 // line breaks, and \underbar does not.
3149 // Do NOT handle \underline.
3150 // \underbar cuts through y, g, q, p etc.,
3151 // \underline does not.
3152 context.check_layout(os);
3153 os << "\n\\bar under\n";
3154 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3155 context.check_layout(os);
3156 os << "\n\\bar default\n";
3157 preamble.registerAutomaticallyLoadedPackage("ulem");
3160 else if (t.cs() == "sout") {
3161 context.check_layout(os);
3162 os << "\n\\strikeout on\n";
3163 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3164 context.check_layout(os);
3165 os << "\n\\strikeout default\n";
3166 preamble.registerAutomaticallyLoadedPackage("ulem");
3169 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3170 t.cs() == "emph" || t.cs() == "noun") {
3171 context.check_layout(os);
3172 os << "\n\\" << t.cs() << " on\n";
3173 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3174 context.check_layout(os);
3175 os << "\n\\" << t.cs() << " default\n";
3176 if (t.cs() == "uuline" || t.cs() == "uwave")
3177 preamble.registerAutomaticallyLoadedPackage("ulem");
3180 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3181 context.check_layout(os);
3182 string name = p.getArg('{', '}');
3183 string localtime = p.getArg('{', '}');
3184 preamble.registerAuthor(name);
3185 Author const & author = preamble.getAuthor(name);
3186 // from_asctime_utc() will fail if LyX decides to output the
3187 // time in the text language.
3188 time_t ptime = from_asctime_utc(localtime);
3189 if (ptime == static_cast<time_t>(-1)) {
3190 cerr << "Warning: Could not parse time `" << localtime
3191 << "´ for change tracking, using current time instead.\n";
3192 ptime = current_time();
3194 if (t.cs() == "lyxadded")
3195 os << "\n\\change_inserted ";
3197 os << "\n\\change_deleted ";
3198 os << author.bufferId() << ' ' << ptime << '\n';
3199 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3200 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3201 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3202 LaTeXPackages::isAvailable("xcolor");
3203 // No need to test for luatex, since luatex comes in
3204 // two flavours (dvi and pdf), like latex, and those
3205 // are detected by pdflatex.
3206 if (pdflatex || xetex) {
3208 preamble.registerAutomaticallyLoadedPackage("ulem");
3209 preamble.registerAutomaticallyLoadedPackage("xcolor");
3210 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3214 preamble.registerAutomaticallyLoadedPackage("dvipost");
3215 } else if (xcolorulem) {
3216 preamble.registerAutomaticallyLoadedPackage("ulem");
3217 preamble.registerAutomaticallyLoadedPackage("xcolor");
3222 else if (t.cs() == "textipa") {
3223 context.check_layout(os);
3224 begin_inset(os, "IPA\n");
3225 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3227 preamble.registerAutomaticallyLoadedPackage("tipa");
3228 preamble.registerAutomaticallyLoadedPackage("tipx");
3231 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3232 context.check_layout(os);
3233 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3234 os << "status open\n";
3235 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3240 // the TIPA Combining diacritical marks
3241 else if (t.cs() == "textsubwedge" || t.cs() == "textsubumlaut"
3242 || t.cs() == "textsubtilde" || t.cs() == "textseagull"
3243 || t.cs() == "textsubbridge" || t.cs() == "textinvsubbridge"
3244 || t.cs() == "textsubsquare" || t.cs() == "textsubrhalfring"
3245 || t.cs() == "textsublhalfring" || t.cs() == "textsubplus"
3246 || t.cs() == "textovercross" || t.cs() == "textsubarch"
3247 || t.cs() == "textsuperimposetilde" || t.cs() == "textraising"
3248 || t.cs() == "textlowering" || t.cs() == "textadvancing"
3249 || t.cs() == "textretracting" || t.cs() == "textdoublegrave"
3250 || t.cs() == "texthighrise" || t.cs() == "textlowrise"
3251 || t.cs() == "textrisefall" || t.cs() == "textsyllabic") {
3252 context.check_layout(os);
3253 // try to see whether the string is in unicodesymbols
3256 string content = trimSpaceAndEol(p.verbatim_item());
3257 string command = t.asInput() + "{"
3258 + trimSpaceAndEol(content)
3261 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3262 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3263 termination, rem, &req);
3266 cerr << "When parsing " << command
3267 << ", result is " << to_utf8(s)
3268 << "+" << to_utf8(rem) << endl;
3269 os << content << to_utf8(s);
3270 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3271 preamble.registerAutomaticallyLoadedPackage(*it);
3273 // we did not find a non-ert version
3274 output_ert_inset(os, command, context);
3277 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3278 t.cs() == "vphantom") {
3279 context.check_layout(os);
3280 if (t.cs() == "phantom")
3281 begin_inset(os, "Phantom Phantom\n");
3282 if (t.cs() == "hphantom")
3283 begin_inset(os, "Phantom HPhantom\n");
3284 if (t.cs() == "vphantom")
3285 begin_inset(os, "Phantom VPhantom\n");
3286 os << "status open\n";
3287 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3292 else if (t.cs() == "href") {
3293 context.check_layout(os);
3294 string target = convert_command_inset_arg(p.verbatim_item());
3295 string name = convert_command_inset_arg(p.verbatim_item());
3297 size_t i = target.find(':');
3298 if (i != string::npos) {
3299 type = target.substr(0, i + 1);
3300 if (type == "mailto:" || type == "file:")
3301 target = target.substr(i + 1);
3302 // handle the case that name is equal to target, except of "http://"
3303 else if (target.substr(i + 3) == name && type == "http:")
3306 begin_command_inset(os, "href", "href");
3308 os << "name \"" << name << "\"\n";
3309 os << "target \"" << target << "\"\n";
3310 if (type == "mailto:" || type == "file:")
3311 os << "type \"" << type << "\"\n";
3313 skip_spaces_braces(p);
3316 else if (t.cs() == "lyxline") {
3317 // swallow size argument (it is not used anyway)
3319 if (!context.atParagraphStart()) {
3320 // so our line is in the middle of a paragraph
3321 // we need to add a new line, lest this line
3322 // follow the other content on that line and
3323 // run off the side of the page
3324 // FIXME: This may create an empty paragraph,
3325 // but without that it would not be
3326 // possible to set noindent below.
3327 // Fortunately LaTeX does not care
3328 // about the empty paragraph.
3329 context.new_paragraph(os);
3331 if (preamble.indentParagraphs()) {
3332 // we need to unindent, lest the line be too long
3333 context.add_par_extra_stuff("\\noindent\n");
3335 context.check_layout(os);
3336 begin_command_inset(os, "line", "rule");
3337 os << "offset \"0.5ex\"\n"
3338 "width \"100line%\"\n"
3343 else if (t.cs() == "rule") {
3344 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3345 string const width = p.getArg('{', '}');
3346 string const thickness = p.getArg('{', '}');
3347 context.check_layout(os);
3348 begin_command_inset(os, "line", "rule");
3349 if (!offset.empty())
3350 os << "offset \"" << translate_len(offset) << "\"\n";
3351 os << "width \"" << translate_len(width) << "\"\n"
3352 "height \"" << translate_len(thickness) << "\"\n";
3356 else if (is_known(t.cs(), known_phrases) ||
3357 (t.cs() == "protect" &&
3358 p.next_token().cat() == catEscape &&
3359 is_known(p.next_token().cs(), known_phrases))) {
3360 // LyX sometimes puts a \protect in front, so we have to ignore it
3361 // FIXME: This needs to be changed when bug 4752 is fixed.
3363 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3365 context.check_layout(os);
3366 os << known_coded_phrases[where - known_phrases];
3367 skip_spaces_braces(p);
3370 else if ((where = is_known(t.cs(), known_ref_commands))) {
3371 // \eqref can also occur if refstyle is used
3372 if (t.cs() == "eqref" && preamble.refstyle() == "1") {
3373 context.check_layout(os);
3374 begin_command_inset(os, "ref", "formatted");
3375 os << "reference \"eq:"
3376 << convert_command_inset_arg(p.verbatim_item())
3379 preamble.registerAutomaticallyLoadedPackage("refstyle");
3381 string const opt = p.getOpt();
3383 context.check_layout(os);
3384 begin_command_inset(os, "ref",
3385 known_coded_ref_commands[where - known_ref_commands]);
3386 os << "reference \""
3387 << convert_command_inset_arg(p.verbatim_item())
3390 if (t.cs() == "vref" || t.cs() == "vpageref")
3391 preamble.registerAutomaticallyLoadedPackage("varioref");
3393 // LyX does not yet support optional arguments of ref commands
3394 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3395 p.verbatim_item() + "}", context);
3400 else if ((where = is_known(t.cs(), known_refstyle_commands))) {
3401 context.check_layout(os);
3402 // \eqref can also occur if refstyle is not used
3403 // this case is already handled in the previous else if
3404 begin_command_inset(os, "ref", "formatted");
3405 os << "reference \"";
3406 os << known_refstyle_prefixes[where - known_refstyle_commands]
3408 os << convert_command_inset_arg(p.verbatim_item())
3411 preamble.registerAutomaticallyLoadedPackage("refstyle");
3414 else if (use_natbib &&
3415 is_known(t.cs(), known_natbib_commands) &&
3416 ((t.cs() != "citefullauthor" &&
3417 t.cs() != "citeyear" &&
3418 t.cs() != "citeyearpar") ||
3419 p.next_token().asInput() != "*")) {
3420 context.check_layout(os);
3421 string command = t.cs();
3422 if (p.next_token().asInput() == "*") {
3426 if (command == "citefullauthor")
3427 // alternative name for "\\citeauthor*"
3428 command = "citeauthor*";
3430 // text before the citation
3432 // text after the citation
3434 get_cite_arguments(p, true, before, after);
3436 if (command == "cite") {
3437 // \cite without optional argument means
3438 // \citet, \cite with at least one optional
3439 // argument means \citep.
3440 if (before.empty() && after.empty())
3445 if (before.empty() && after == "[]")
3446 // avoid \citet[]{a}
3448 else if (before == "[]" && after == "[]") {
3449 // avoid \citet[][]{a}
3453 // remove the brackets around after and before
3454 if (!after.empty()) {
3456 after.erase(after.length() - 1, 1);
3457 after = convert_command_inset_arg(after);
3459 if (!before.empty()) {
3461 before.erase(before.length() - 1, 1);
3462 before = convert_command_inset_arg(before);
3464 begin_command_inset(os, "citation", command);
3465 os << "after " << '"' << after << '"' << "\n";
3466 os << "before " << '"' << before << '"' << "\n";
3468 << convert_command_inset_arg(p.verbatim_item())
3471 // Need to set the cite engine if natbib is loaded by
3472 // the document class directly
3473 if (preamble.citeEngine() == "basic")
3474 preamble.citeEngine("natbib");
3477 else if (use_jurabib &&
3478 is_known(t.cs(), known_jurabib_commands) &&
3479 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3480 context.check_layout(os);
3481 string command = t.cs();
3482 if (p.next_token().asInput() == "*") {
3486 char argumentOrder = '\0';
3487 vector<string> const options =
3488 preamble.getPackageOptions("jurabib");
3489 if (find(options.begin(), options.end(),
3490 "natbiborder") != options.end())
3491 argumentOrder = 'n';
3492 else if (find(options.begin(), options.end(),
3493 "jurabiborder") != options.end())
3494 argumentOrder = 'j';
3496 // text before the citation
3498 // text after the citation
3500 get_cite_arguments(p, argumentOrder != 'j', before, after);
3502 string const citation = p.verbatim_item();
3503 if (!before.empty() && argumentOrder == '\0') {
3504 cerr << "Warning: Assuming argument order "
3505 "of jurabib version 0.6 for\n'"
3506 << command << before << after << '{'
3507 << citation << "}'.\n"
3508 "Add 'jurabiborder' to the jurabib "
3509 "package options if you used an\n"
3510 "earlier jurabib version." << endl;
3512 if (!after.empty()) {
3514 after.erase(after.length() - 1, 1);
3516 if (!before.empty()) {
3518 before.erase(before.length() - 1, 1);
3520 begin_command_inset(os, "citation", command);
3521 os << "after " << '"' << after << '"' << "\n";
3522 os << "before " << '"' << before << '"' << "\n";
3523 os << "key " << '"' << citation << '"' << "\n";
3525 // Need to set the cite engine if jurabib is loaded by
3526 // the document class directly
3527 if (preamble.citeEngine() == "basic")
3528 preamble.citeEngine("jurabib");
3531 else if (t.cs() == "cite"
3532 || t.cs() == "nocite") {
3533 context.check_layout(os);
3534 string after = convert_command_inset_arg(p.getArg('[', ']'));
3535 string key = convert_command_inset_arg(p.verbatim_item());
3536 // store the case that it is "\nocite{*}" to use it later for
3539 begin_command_inset(os, "citation", t.cs());
3540 os << "after " << '"' << after << '"' << "\n";
3541 os << "key " << '"' << key << '"' << "\n";
3543 } else if (t.cs() == "nocite")
3547 else if (t.cs() == "index" ||
3548 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3549 context.check_layout(os);
3550 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3551 p.getArg('[', ']') : "";
3552 string const kind = arg.empty() ? "idx" : arg;
3553 begin_inset(os, "Index ");
3554 os << kind << "\nstatus collapsed\n";
3555 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3558 preamble.registerAutomaticallyLoadedPackage("splitidx");
3561 else if (t.cs() == "nomenclature") {
3562 context.check_layout(os);
3563 begin_command_inset(os, "nomenclature", "nomenclature");
3564 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3565 if (!prefix.empty())
3566 os << "prefix " << '"' << prefix << '"' << "\n";
3567 os << "symbol " << '"'
3568 << convert_command_inset_arg(p.verbatim_item());
3569 os << "\"\ndescription \""
3570 << convert_command_inset_arg(p.verbatim_item())
3573 preamble.registerAutomaticallyLoadedPackage("nomencl");
3576 else if (t.cs() == "label") {
3577 context.check_layout(os);
3578 begin_command_inset(os, "label", "label");
3580 << convert_command_inset_arg(p.verbatim_item())
3585 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3586 context.check_layout(os);
3587 string commandname = t.cs();
3589 if (p.next_token().asInput() == "*") {
3594 begin_command_inset(os, "index_print", commandname);
3595 string const indexname = p.getArg('[', ']');
3597 if (indexname.empty())
3598 os << "type \"idx\"\n";
3600 os << "type \"" << indexname << "\"\n";
3603 skip_spaces_braces(p);
3604 preamble.registerAutomaticallyLoadedPackage("makeidx");
3605 if (preamble.use_indices() == "true")
3606 preamble.registerAutomaticallyLoadedPackage("splitidx");
3609 else if (t.cs() == "printnomenclature") {
3611 string width_type = "";
3612 context.check_layout(os);
3613 begin_command_inset(os, "nomencl_print", "printnomenclature");
3614 // case of a custom width
3616 width = p.getArg('[', ']');
3617 width = translate_len(width);
3618 width_type = "custom";
3620 // case of no custom width
3621 // the case of no custom width but the width set
3622 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3623 // because the user could have set anything, not only the width
3624 // of the longest label (which would be width_type = "auto")
3625 string label = convert_command_inset_arg(p.getArg('{', '}'));
3626 if (label.empty() && width_type.empty())
3627 width_type = "none";
3628 os << "set_width \"" << width_type << "\"\n";
3629 if (width_type == "custom")
3630 os << "width \"" << width << '\"';
3632 skip_spaces_braces(p);
3633 preamble.registerAutomaticallyLoadedPackage("nomencl");
3636 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3637 context.check_layout(os);
3638 begin_inset(os, "script ");
3639 os << t.cs().substr(4) << '\n';
3640 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3642 if (t.cs() == "textsubscript")
3643 preamble.registerAutomaticallyLoadedPackage("subscript");
3646 else if ((where = is_known(t.cs(), known_quotes))) {
3647 context.check_layout(os);
3648 begin_inset(os, "Quotes ");
3649 os << known_coded_quotes[where - known_quotes];
3651 // LyX adds {} after the quote, so we have to eat
3652 // spaces here if there are any before a possible
3654 eat_whitespace(p, os, context, false);
3658 else if ((where = is_known(t.cs(), known_sizes)) &&
3659 context.new_layout_allowed) {
3660 context.check_layout(os);
3661 TeXFont const oldFont = context.font;
3662 context.font.size = known_coded_sizes[where - known_sizes];
3663 output_font_change(os, oldFont, context.font);
3664 eat_whitespace(p, os, context, false);
3667 else if ((where = is_known(t.cs(), known_font_families)) &&
3668 context.new_layout_allowed) {
3669 context.check_layout(os);
3670 TeXFont const oldFont = context.font;
3671 context.font.family =
3672 known_coded_font_families[where - known_font_families];
3673 output_font_change(os, oldFont, context.font);
3674 eat_whitespace(p, os, context, false);
3677 else if ((where = is_known(t.cs(), known_font_series)) &&
3678 context.new_layout_allowed) {
3679 context.check_layout(os);
3680 TeXFont const oldFont = context.font;
3681 context.font.series =
3682 known_coded_font_series[where - known_font_series];
3683 output_font_change(os, oldFont, context.font);
3684 eat_whitespace(p, os, context, false);
3687 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3688 context.new_layout_allowed) {
3689 context.check_layout(os);
3690 TeXFont const oldFont = context.font;
3691 context.font.shape =
3692 known_coded_font_shapes[where - known_font_shapes];
3693 output_font_change(os, oldFont, context.font);
3694 eat_whitespace(p, os, context, false);
3696 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3697 context.new_layout_allowed) {
3698 context.check_layout(os);
3699 TeXFont const oldFont = context.font;
3700 context.font.init();
3701 context.font.size = oldFont.size;
3702 context.font.family =
3703 known_coded_font_families[where - known_old_font_families];
3704 output_font_change(os, oldFont, context.font);
3705 eat_whitespace(p, os, context, false);
3708 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3709 context.new_layout_allowed) {
3710 context.check_layout(os);
3711 TeXFont const oldFont = context.font;
3712 context.font.init();
3713 context.font.size = oldFont.size;
3714 context.font.series =
3715 known_coded_font_series[where - known_old_font_series];
3716 output_font_change(os, oldFont, context.font);
3717 eat_whitespace(p, os, context, false);
3720 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3721 context.new_layout_allowed) {
3722 context.check_layout(os);
3723 TeXFont const oldFont = context.font;
3724 context.font.init();
3725 context.font.size = oldFont.size;
3726 context.font.shape =
3727 known_coded_font_shapes[where - known_old_font_shapes];
3728 output_font_change(os, oldFont, context.font);
3729 eat_whitespace(p, os, context, false);
3732 else if (t.cs() == "selectlanguage") {
3733 context.check_layout(os);
3734 // save the language for the case that a
3735 // \foreignlanguage is used
3736 context.font.language = babel2lyx(p.verbatim_item());
3737 os << "\n\\lang " << context.font.language << "\n";
3740 else if (t.cs() == "foreignlanguage") {
3741 string const lang = babel2lyx(p.verbatim_item());
3742 parse_text_attributes(p, os, FLAG_ITEM, outer,
3744 context.font.language, lang);
3747 else if (prefixIs(t.cs(), "text")
3748 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3749 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3751 // We have to output the whole command if it has an option
3752 // because LyX doesn't support this yet, see bug #8214,
3753 // only if there is a single option specifying a variant, we can handle it.
3755 string langopts = p.getOpt();
3756 // check if the option contains a variant, if yes, extract it
3757 string::size_type pos_var = langopts.find("variant");
3758 string::size_type i = langopts.find(',');
3759 string::size_type k = langopts.find('=', pos_var);
3760 if (pos_var != string::npos && i == string::npos) {
3762 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3763 lang = preamble.polyglossia2lyx(variant);
3764 parse_text_attributes(p, os, FLAG_ITEM, outer,
3766 context.font.language, lang);
3768 output_ert_inset(os, t.asInput() + langopts, context);
3770 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3771 parse_text_attributes(p, os, FLAG_ITEM, outer,
3773 context.font.language, lang);
3777 else if (t.cs() == "inputencoding") {
3778 // nothing to write here
3779 string const enc = subst(p.verbatim_item(), "\n", " ");
3780 p.setEncoding(enc, Encoding::inputenc);
3783 else if ((where = is_known(t.cs(), known_special_chars))) {
3784 context.check_layout(os);
3785 os << "\\SpecialChar \\"
3786 << known_coded_special_chars[where - known_special_chars]
3788 skip_spaces_braces(p);
3791 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3792 context.check_layout(os);
3793 os << "\\SpecialChar \\nobreakdash-\n";
3797 else if (t.cs() == "textquotedbl") {
3798 context.check_layout(os);
3803 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3804 context.check_layout(os);
3805 os << "\\SpecialChar \\@.\n";
3809 else if (t.cs() == "-") {
3810 context.check_layout(os);
3811 os << "\\SpecialChar \\-\n";
3814 else if (t.cs() == "textasciitilde") {
3815 context.check_layout(os);
3817 skip_spaces_braces(p);
3820 else if (t.cs() == "textasciicircum") {
3821 context.check_layout(os);
3823 skip_spaces_braces(p);
3826 else if (t.cs() == "textbackslash") {
3827 context.check_layout(os);
3828 os << "\n\\backslash\n";
3829 skip_spaces_braces(p);
3832 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3833 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3835 context.check_layout(os);
3839 else if (t.cs() == "char") {
3840 context.check_layout(os);
3841 if (p.next_token().character() == '`') {
3843 if (p.next_token().cs() == "\"") {
3848 output_ert_inset(os, "\\char`", context);
3851 output_ert_inset(os, "\\char", context);
3855 else if (t.cs() == "verb") {
3856 context.check_layout(os);
3857 // set catcodes to verbatim early, just in case.
3858 p.setCatcodes(VERBATIM_CATCODES);
3859 string delim = p.get_token().asInput();
3860 string const arg = p.verbatimStuff(delim);
3861 output_ert_inset(os, "\\verb" + delim + arg + delim, context);
3864 // Problem: \= creates a tabstop inside the tabbing environment
3865 // and else an accent. In the latter case we really would want
3866 // \={o} instead of \= o.
3867 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3868 output_ert_inset(os, t.asInput(), context);
3870 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3871 else if (t.cs().size() == 1
3872 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3873 context.check_layout(os);
3874 // try to see whether the string is in unicodesymbols
3877 string command = t.asInput() + "{"
3878 + trimSpaceAndEol(p.verbatim_item())
3881 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3882 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3883 termination, rem, &req);
3886 cerr << "When parsing " << command
3887 << ", result is " << to_utf8(s)
3888 << "+" << to_utf8(rem) << endl;
3890 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3891 preamble.registerAutomaticallyLoadedPackage(*it);
3893 // we did not find a non-ert version
3894 output_ert_inset(os, command, context);
3897 else if (t.cs() == "\\") {
3898 context.check_layout(os);
3900 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3901 else if (p.next_token().asInput() == "*") {
3903 // getOpt() eats the following space if there
3904 // is no optional argument, but that is OK
3905 // here since it has no effect in the output.
3906 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3909 begin_inset(os, "Newline newline");
3914 else if (t.cs() == "newline" ||
3915 (t.cs() == "linebreak" && !p.hasOpt())) {
3916 context.check_layout(os);
3917 begin_inset(os, "Newline ");
3920 skip_spaces_braces(p);
3923 else if (t.cs() == "input" || t.cs() == "include"
3924 || t.cs() == "verbatiminput") {
3925 string name = t.cs();
3926 if (t.cs() == "verbatiminput"
3927 && p.next_token().asInput() == "*")
3928 name += p.get_token().asInput();
3929 context.check_layout(os);
3930 string filename(normalize_filename(p.getArg('{', '}')));
3931 string const path = getMasterFilePath(true);
3932 // We want to preserve relative / absolute filenames,
3933 // therefore path is only used for testing
3934 if ((t.cs() == "include" || t.cs() == "input") &&
3935 !makeAbsPath(filename, path).exists()) {
3936 // The file extension is probably missing.
3937 // Now try to find it out.
3938 string const tex_name =
3939 find_file(filename, path,
3940 known_tex_extensions);
3941 if (!tex_name.empty())
3942 filename = tex_name;
3944 bool external = false;
3946 if (makeAbsPath(filename, path).exists()) {
3947 string const abstexname =
3948 makeAbsPath(filename, path).absFileName();
3949 string const absfigname =
3950 changeExtension(abstexname, ".fig");
3951 fix_child_filename(filename);
3952 string const lyxname =
3953 changeExtension(filename, ".lyx");
3954 string const abslyxname = makeAbsPath(
3955 lyxname, getParentFilePath(false)).absFileName();
3957 if (!skipChildren())
3958 external = FileName(absfigname).exists();
3959 if (t.cs() == "input" && !skipChildren()) {
3960 string const ext = getExtension(abstexname);
3962 // Combined PS/LaTeX:
3963 // x.eps, x.pstex_t (old xfig)
3964 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3965 FileName const absepsname(
3966 changeExtension(abstexname, ".eps"));
3967 FileName const abspstexname(
3968 changeExtension(abstexname, ".pstex"));
3969 bool const xfigeps =
3970 (absepsname.exists() ||
3971 abspstexname.exists()) &&
3974 // Combined PDF/LaTeX:
3975 // x.pdf, x.pdftex_t (old xfig)
3976 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3977 FileName const abspdfname(
3978 changeExtension(abstexname, ".pdf"));
3979 bool const xfigpdf =
3980 abspdfname.exists() &&
3981 (ext == "pdftex_t" || ext == "pdf_t");
3985 // Combined PS/PDF/LaTeX:
3986 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3987 string const absbase2(
3988 removeExtension(abstexname) + "_pspdftex");
3989 FileName const abseps2name(
3990 addExtension(absbase2, ".eps"));
3991 FileName const abspdf2name(
3992 addExtension(absbase2, ".pdf"));
3993 bool const xfigboth =
3994 abspdf2name.exists() &&
3995 abseps2name.exists() && ext == "pspdftex";
3997 xfig = xfigpdf || xfigeps || xfigboth;
3998 external = external && xfig;
4001 outname = changeExtension(filename, ".fig");
4002 FileName abssrc(changeExtension(abstexname, ".fig"));
4003 copy_file(abssrc, outname);
4005 // Don't try to convert, the result
4006 // would be full of ERT.
4008 FileName abssrc(abstexname);
4009 copy_file(abssrc, outname);
4010 } else if (t.cs() != "verbatiminput" &&
4012 tex2lyx(abstexname, FileName(abslyxname),
4015 // no need to call copy_file
4016 // tex2lyx creates the file
4019 FileName abssrc(abstexname);
4020 copy_file(abssrc, outname);
4023 cerr << "Warning: Could not find included file '"
4024 << filename << "'." << endl;
4028 begin_inset(os, "External\n");
4029 os << "\ttemplate XFig\n"
4030 << "\tfilename " << outname << '\n';
4031 registerExternalTemplatePackages("XFig");
4033 begin_command_inset(os, "include", name);
4034 outname = subst(outname, "\"", "\\\"");
4035 os << "preview false\n"
4036 "filename \"" << outname << "\"\n";
4037 if (t.cs() == "verbatiminput")
4038 preamble.registerAutomaticallyLoadedPackage("verbatim");
4043 else if (t.cs() == "bibliographystyle") {
4044 // store new bibliographystyle
4045 bibliographystyle = p.verbatim_item();
4046 // If any other command than \bibliography, \addcontentsline
4047 // and \nocite{*} follows, we need to output the style
4048 // (because it might be used by that command).
4049 // Otherwise, it will automatically be output by LyX.
4052 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4053 if (t2.cat() == catBegin)
4055 if (t2.cat() != catEscape)
4057 if (t2.cs() == "nocite") {
4058 if (p.getArg('{', '}') == "*")
4060 } else if (t2.cs() == "bibliography")
4062 else if (t2.cs() == "phantomsection") {
4066 else if (t2.cs() == "addcontentsline") {
4067 // get the 3 arguments of \addcontentsline
4070 contentslineContent = p.getArg('{', '}');
4071 // if the last argument is not \refname we must output
4072 if (contentslineContent == "\\refname")
4079 output_ert_inset(os,
4080 "\\bibliographystyle{" + bibliographystyle + '}',
4085 else if (t.cs() == "phantomsection") {
4086 // we only support this if it occurs between
4087 // \bibliographystyle and \bibliography
4088 if (bibliographystyle.empty())
4089 output_ert_inset(os, "\\phantomsection", context);
4092 else if (t.cs() == "addcontentsline") {
4093 context.check_layout(os);
4094 // get the 3 arguments of \addcontentsline
4095 string const one = p.getArg('{', '}');
4096 string const two = p.getArg('{', '}');
4097 string const three = p.getArg('{', '}');
4098 // only if it is a \refname, we support if for the bibtex inset
4099 if (contentslineContent != "\\refname") {
4100 output_ert_inset(os,
4101 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4106 else if (t.cs() == "bibliography") {
4107 context.check_layout(os);
4109 begin_command_inset(os, "bibtex", "bibtex");
4110 if (!btprint.empty()) {
4111 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4112 // clear the string because the next BibTeX inset can be without the
4113 // \nocite{*} option
4116 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4117 // Do we have addcontentsline?
4118 if (contentslineContent == "\\refname") {
4119 BibOpts = "bibtotoc";
4120 // clear string because next BibTeX inset can be without addcontentsline
4121 contentslineContent.clear();
4123 // Do we have a bibliographystyle set?
4124 if (!bibliographystyle.empty()) {
4125 if (BibOpts.empty())
4126 BibOpts = bibliographystyle;
4128 BibOpts = BibOpts + ',' + bibliographystyle;
4129 // clear it because each bibtex entry has its style
4130 // and we need an empty string to handle \phantomsection
4131 bibliographystyle.clear();
4133 os << "options " << '"' << BibOpts << '"' << "\n";
4137 else if (t.cs() == "parbox") {
4138 // Test whether this is an outer box of a shaded box
4140 // swallow arguments
4141 while (p.hasOpt()) {
4143 p.skip_spaces(true);
4146 p.skip_spaces(true);
4148 if (p.next_token().cat() == catBegin)
4150 p.skip_spaces(true);
4151 Token to = p.get_token();
4152 bool shaded = false;
4153 if (to.asInput() == "\\begin") {
4154 p.skip_spaces(true);
4155 if (p.getArg('{', '}') == "shaded")
4160 parse_outer_box(p, os, FLAG_ITEM, outer,
4161 context, "parbox", "shaded");
4163 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4167 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4168 t.cs() == "shadowbox" || t.cs() == "doublebox")
4169 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4171 else if (t.cs() == "framebox") {
4172 if (p.next_token().character() == '(') {
4173 //the syntax is: \framebox(x,y)[position]{content}
4174 string arg = t.asInput();
4175 arg += p.getFullParentheseArg();
4176 arg += p.getFullOpt();
4177 eat_whitespace(p, os, context, false);
4178 output_ert_inset(os, arg + '{', context);
4179 parse_text(p, os, FLAG_ITEM, outer, context);
4180 output_ert_inset(os, "}", context);
4182 string special = p.getFullOpt();
4183 special += p.getOpt();
4184 // LyX does not yet support \framebox without any option
4185 if (!special.empty())
4186 parse_outer_box(p, os, FLAG_ITEM, outer,
4187 context, t.cs(), special);
4189 eat_whitespace(p, os, context, false);
4190 output_ert_inset(os, "\\framebox{", context);
4191 parse_text(p, os, FLAG_ITEM, outer, context);
4192 output_ert_inset(os, "}", context);
4197 //\makebox() is part of the picture environment and different from \makebox{}
4198 //\makebox{} will be parsed by parse_box
4199 else if (t.cs() == "makebox") {
4200 if (p.next_token().character() == '(') {
4201 //the syntax is: \makebox(x,y)[position]{content}
4202 string arg = t.asInput();
4203 arg += p.getFullParentheseArg();
4204 arg += p.getFullOpt();
4205 eat_whitespace(p, os, context, false);
4206 output_ert_inset(os, arg + '{', context);
4207 parse_text(p, os, FLAG_ITEM, outer, context);
4208 output_ert_inset(os, "}", context);
4210 //the syntax is: \makebox[width][position]{content}
4211 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4215 else if (t.cs() == "smallskip" ||
4216 t.cs() == "medskip" ||
4217 t.cs() == "bigskip" ||
4218 t.cs() == "vfill") {
4219 context.check_layout(os);
4220 begin_inset(os, "VSpace ");
4223 skip_spaces_braces(p);
4226 else if ((where = is_known(t.cs(), known_spaces))) {
4227 context.check_layout(os);
4228 begin_inset(os, "space ");
4229 os << '\\' << known_coded_spaces[where - known_spaces]
4232 // LaTeX swallows whitespace after all spaces except
4233 // "\\,". We have to do that here, too, because LyX
4234 // adds "{}" which would make the spaces significant.
4236 eat_whitespace(p, os, context, false);
4237 // LyX adds "{}" after all spaces except "\\ " and
4238 // "\\,", so we have to remove "{}".
4239 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4240 // remove the braces after "\\,", too.
4245 else if (t.cs() == "newpage" ||
4246 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4247 t.cs() == "clearpage" ||
4248 t.cs() == "cleardoublepage") {
4249 context.check_layout(os);
4250 begin_inset(os, "Newpage ");
4253 skip_spaces_braces(p);
4256 else if (t.cs() == "DeclareRobustCommand" ||
4257 t.cs() == "DeclareRobustCommandx" ||
4258 t.cs() == "newcommand" ||
4259 t.cs() == "newcommandx" ||
4260 t.cs() == "providecommand" ||
4261 t.cs() == "providecommandx" ||
4262 t.cs() == "renewcommand" ||
4263 t.cs() == "renewcommandx") {
4264 // DeclareRobustCommand, DeclareRobustCommandx,
4265 // providecommand and providecommandx could be handled
4266 // by parse_command(), but we need to call
4267 // add_known_command() here.
4268 string name = t.asInput();
4269 if (p.next_token().asInput() == "*") {
4270 // Starred form. Eat '*'
4274 string const command = p.verbatim_item();
4275 string const opt1 = p.getFullOpt();
4276 string const opt2 = p.getFullOpt();
4277 add_known_command(command, opt1, !opt2.empty());
4278 string const ert = name + '{' + command + '}' +
4280 '{' + p.verbatim_item() + '}';
4282 if (t.cs() == "DeclareRobustCommand" ||
4283 t.cs() == "DeclareRobustCommandx" ||
4284 t.cs() == "providecommand" ||
4285 t.cs() == "providecommandx" ||
4286 name[name.length()-1] == '*')
4287 output_ert_inset(os, ert, context);
4289 context.check_layout(os);
4290 begin_inset(os, "FormulaMacro");
4296 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4297 // let could be handled by parse_command(),
4298 // but we need to call add_known_command() here.
4299 string ert = t.asInput();
4302 if (p.next_token().cat() == catBegin) {
4303 name = p.verbatim_item();
4304 ert += '{' + name + '}';
4306 name = p.verbatim_item();
4311 if (p.next_token().cat() == catBegin) {
4312 command = p.verbatim_item();
4313 ert += '{' + command + '}';
4315 command = p.verbatim_item();
4318 // If command is known, make name known too, to parse
4319 // its arguments correctly. For this reason we also
4320 // have commands in syntax.default that are hardcoded.
4321 CommandMap::iterator it = known_commands.find(command);
4322 if (it != known_commands.end())
4323 known_commands[t.asInput()] = it->second;
4324 output_ert_inset(os, ert, context);
4327 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4328 bool starred = false;
4329 if (p.next_token().asInput() == "*") {
4333 string name = t.asInput();
4334 string const length = p.verbatim_item();
4337 bool valid = splitLatexLength(length, valstring, unit);
4338 bool known_hspace = false;
4339 bool known_vspace = false;
4340 bool known_unit = false;
4343 istringstream iss(valstring);
4346 if (t.cs()[0] == 'h') {
4347 if (unit == "\\fill") {
4352 known_hspace = true;
4355 if (unit == "\\smallskipamount") {
4357 known_vspace = true;
4358 } else if (unit == "\\medskipamount") {
4360 known_vspace = true;
4361 } else if (unit == "\\bigskipamount") {
4363 known_vspace = true;
4364 } else if (unit == "\\fill") {
4366 known_vspace = true;
4370 if (!known_hspace && !known_vspace) {
4371 switch (unitFromString(unit)) {
4392 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4393 // Literal horizontal length or known variable
4394 context.check_layout(os);
4395 begin_inset(os, "space ");
4403 if (known_unit && !known_hspace)
4405 << translate_len(length);
4407 } else if (known_unit || known_vspace) {
4408 // Literal vertical length or known variable
4409 context.check_layout(os);
4410 begin_inset(os, "VSpace ");
4418 // LyX can't handle other length variables in Inset VSpace/space
4423 output_ert_inset(os, name + '{' + unit + '}', context);
4424 else if (value == -1.0)
4425 output_ert_inset(os, name + "{-" + unit + '}', context);
4427 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4429 output_ert_inset(os, name + '{' + length + '}', context);
4433 // The single '=' is meant here.
4434 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4436 context.check_layout(os);
4437 begin_inset(os, "Flex ");
4438 os << to_utf8(newinsetlayout->name()) << '\n'
4439 << "status collapsed\n";
4440 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4444 else if (t.cs() == "includepdf") {
4446 string const arg = p.getArg('[', ']');
4447 map<string, string> opts;
4448 vector<string> keys;
4449 split_map(arg, opts, keys);
4450 string name = normalize_filename(p.verbatim_item());
4451 string const path = getMasterFilePath(true);
4452 // We want to preserve relative / absolute filenames,
4453 // therefore path is only used for testing
4454 if (!makeAbsPath(name, path).exists()) {
4455 // The file extension is probably missing.
4456 // Now try to find it out.
4457 char const * const pdfpages_format[] = {"pdf", 0};
4458 string const pdftex_name =
4459 find_file(name, path, pdfpages_format);
4460 if (!pdftex_name.empty()) {
4465 FileName const absname = makeAbsPath(name, path);
4466 if (absname.exists())
4468 fix_child_filename(name);
4469 copy_file(absname, name);
4471 cerr << "Warning: Could not find file '"
4472 << name << "'." << endl;
4474 context.check_layout(os);
4475 begin_inset(os, "External\n\ttemplate ");
4476 os << "PDFPages\n\tfilename "
4478 // parse the options
4479 if (opts.find("pages") != opts.end())
4480 os << "\textra LaTeX \"pages="
4481 << opts["pages"] << "\"\n";
4482 if (opts.find("angle") != opts.end())
4483 os << "\trotateAngle "
4484 << opts["angle"] << '\n';
4485 if (opts.find("origin") != opts.end()) {
4487 string const opt = opts["origin"];
4488 if (opt == "tl") ss << "topleft";
4489 if (opt == "bl") ss << "bottomleft";
4490 if (opt == "Bl") ss << "baselineleft";
4491 if (opt == "c") ss << "center";
4492 if (opt == "tc") ss << "topcenter";
4493 if (opt == "bc") ss << "bottomcenter";
4494 if (opt == "Bc") ss << "baselinecenter";
4495 if (opt == "tr") ss << "topright";
4496 if (opt == "br") ss << "bottomright";
4497 if (opt == "Br") ss << "baselineright";
4498 if (!ss.str().empty())
4499 os << "\trotateOrigin " << ss.str() << '\n';
4501 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4503 if (opts.find("width") != opts.end())
4505 << translate_len(opts["width"]) << '\n';
4506 if (opts.find("height") != opts.end())
4508 << translate_len(opts["height"]) << '\n';
4509 if (opts.find("keepaspectratio") != opts.end())
4510 os << "\tkeepAspectRatio\n";
4512 context.check_layout(os);
4513 registerExternalTemplatePackages("PDFPages");
4516 else if (t.cs() == "loadgame") {
4518 string name = normalize_filename(p.verbatim_item());
4519 string const path = getMasterFilePath(true);
4520 // We want to preserve relative / absolute filenames,
4521 // therefore path is only used for testing
4522 if (!makeAbsPath(name, path).exists()) {
4523 // The file extension is probably missing.
4524 // Now try to find it out.
4525 char const * const lyxskak_format[] = {"fen", 0};
4526 string const lyxskak_name =
4527 find_file(name, path, lyxskak_format);
4528 if (!lyxskak_name.empty())
4529 name = lyxskak_name;
4531 FileName const absname = makeAbsPath(name, path);
4532 if (absname.exists())
4534 fix_child_filename(name);
4535 copy_file(absname, name);
4537 cerr << "Warning: Could not find file '"
4538 << name << "'." << endl;
4539 context.check_layout(os);
4540 begin_inset(os, "External\n\ttemplate ");
4541 os << "ChessDiagram\n\tfilename "
4544 context.check_layout(os);
4545 // after a \loadgame follows a \showboard
4546 if (p.get_token().asInput() == "showboard")
4548 registerExternalTemplatePackages("ChessDiagram");
4552 // try to see whether the string is in unicodesymbols
4553 // Only use text mode commands, since we are in text mode here,
4554 // and math commands may be invalid (bug 6797)
4558 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4559 Encodings::TEXT_CMD, termination, rem, &req);
4562 cerr << "When parsing " << t.cs()
4563 << ", result is " << to_utf8(s)
4564 << "+" << to_utf8(rem) << endl;
4565 context.check_layout(os);
4568 skip_spaces_braces(p);
4569 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4570 preamble.registerAutomaticallyLoadedPackage(*it);
4572 //cerr << "#: " << t << " mode: " << mode << endl;
4573 // heuristic: read up to next non-nested space
4575 string s = t.asInput();
4576 string z = p.verbatim_item();
4577 while (p.good() && z != " " && !z.empty()) {
4578 //cerr << "read: " << z << endl;
4580 z = p.verbatim_item();
4582 cerr << "found ERT: " << s << endl;
4583 output_ert_inset(os, s + ' ', context);
4586 string name = t.asInput();
4587 if (p.next_token().asInput() == "*") {
4588 // Starred commands like \vspace*{}
4589 p.get_token(); // Eat '*'
4592 if (!parse_command(name, p, os, outer, context))
4593 output_ert_inset(os, name, context);
4597 if (flags & FLAG_LEAVE) {
4598 flags &= ~FLAG_LEAVE;
4605 string guessLanguage(Parser & p, string const & lang)
4607 typedef std::map<std::string, size_t> LangMap;
4608 // map from language names to number of characters
4611 for (char const * const * i = supported_CJK_languages; *i; i++)
4612 used[string(*i)] = 0;
4615 Token const t = p.get_token();
4616 // comments are not counted for any language
4617 if (t.cat() == catComment)
4619 // commands are not counted as well, but we need to detect
4620 // \begin{CJK} and switch encoding if needed
4621 if (t.cat() == catEscape) {
4622 if (t.cs() == "inputencoding") {
4623 string const enc = subst(p.verbatim_item(), "\n", " ");
4624 p.setEncoding(enc, Encoding::inputenc);
4627 if (t.cs() != "begin")
4630 // Non-CJK content is counted for lang.
4631 // We do not care about the real language here:
4632 // If we have more non-CJK contents than CJK contents,
4633 // we simply use the language that was specified as
4634 // babel main language.
4635 used[lang] += t.asInput().length();
4638 // Now we are starting an environment
4640 string const name = p.getArg('{', '}');
4641 if (name != "CJK") {
4645 // It is a CJK environment
4647 /* name = */ p.getArg('{', '}');
4648 string const encoding = p.getArg('{', '}');
4649 /* mapping = */ p.getArg('{', '}');
4650 string const encoding_old = p.getEncoding();
4651 char const * const * const where =
4652 is_known(encoding, supported_CJK_encodings);
4654 p.setEncoding(encoding, Encoding::CJK);
4656 p.setEncoding("UTF-8");
4657 string const text = p.ertEnvironment("CJK");
4658 p.setEncoding(encoding_old);
4661 // ignore contents in unknown CJK encoding
4664 // the language of the text
4666 supported_CJK_languages[where - supported_CJK_encodings];
4667 used[cjk] += text.length();
4669 LangMap::const_iterator use = used.begin();
4670 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4671 if (it->second > use->second)