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",
237 "lyxarrow", "textcompwordmark",
238 "slash", "textasciitilde", "textasciicircum", "textbackslash", 0};
240 /// the same as known_special_chars with .lyx names
241 char const * const known_coded_special_chars[] = {"\\SpecialChar \\ldots{}\n",
242 "\\SpecialChar \\menuseparator\n", "\\SpecialChar \\textcompwordmark{}\n",
243 "\\SpecialChar \\slash{}\n", "~", "^", "\n\\backslash\n", 0};
246 * Graphics file extensions known by the dvips driver of the graphics package.
247 * These extensions are used to complete the filename of an included
248 * graphics file if it does not contain an extension.
249 * The order must be the same that latex uses to find a file, because we
250 * will use the first extension that matches.
251 * This is only an approximation for the common cases. If we would want to
252 * do it right in all cases, we would need to know which graphics driver is
253 * used and know the extensions of every driver of the graphics package.
255 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
256 "ps.gz", "eps.Z", "ps.Z", 0};
259 * Graphics file extensions known by the pdftex driver of the graphics package.
260 * \sa known_dvips_graphics_formats
262 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
266 * Known file extensions for TeX files as used by \\include.
268 char const * const known_tex_extensions[] = {"tex", 0};
270 /// spaces known by InsetSpace
271 char const * const known_spaces[] = { " ", "space", ",",
272 "thinspace", "quad", "qquad", "enspace", "enskip",
273 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
274 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
275 "upbracefill", "downbracefill", 0};
277 /// the same as known_spaces with .lyx names
278 char const * const known_coded_spaces[] = { "space{}", "space{}",
279 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
280 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
281 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
282 "upbracefill{}", "downbracefill{}", 0};
284 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
285 /// them in ERT. "LaTeXe" must come before "LaTeX"!
286 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
287 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
288 int const known_phrase_lengths[] = {3, 5, 7, 0};
290 /// known TIPA combining diacritical marks
291 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
292 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
293 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
294 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
295 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
296 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
299 /// TIPA tones that need special handling
300 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
302 // string to store the float type to be able to determine the type of subfloats
303 string float_type = "";
306 /// splits "x=z, y=b" into a map and an ordered keyword vector
307 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
312 keys.resize(v.size());
313 for (size_t i = 0; i < v.size(); ++i) {
314 size_t const pos = v[i].find('=');
315 string const index = trimSpaceAndEol(v[i].substr(0, pos));
316 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
324 * Split a LaTeX length into value and unit.
325 * The latter can be a real unit like "pt", or a latex length variable
326 * like "\textwidth". The unit may contain additional stuff like glue
327 * lengths, but we don't care, because such lengths are ERT anyway.
328 * \returns true if \p value and \p unit are valid.
330 bool splitLatexLength(string const & len, string & value, string & unit)
334 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
335 //'4,5' is a valid LaTeX length number. Change it to '4.5'
336 string const length = subst(len, ',', '.');
337 if (i == string::npos)
340 if (len[0] == '\\') {
341 // We had something like \textwidth without a factor
347 value = trimSpaceAndEol(string(length, 0, i));
351 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
352 if (contains(len, '\\'))
353 unit = trimSpaceAndEol(string(len, i));
355 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
360 /// A simple function to translate a latex length to something LyX can
361 /// understand. Not perfect, but rather best-effort.
362 bool translate_len(string const & length, string & valstring, string & unit)
364 if (!splitLatexLength(length, valstring, unit))
366 // LyX uses percent values
368 istringstream iss(valstring);
373 string const percentval = oss.str();
375 if (unit.empty() || unit[0] != '\\')
377 string::size_type const i = unit.find(' ');
378 string const endlen = (i == string::npos) ? string() : string(unit, i);
379 if (unit == "\\textwidth") {
380 valstring = percentval;
381 unit = "text%" + endlen;
382 } else if (unit == "\\columnwidth") {
383 valstring = percentval;
384 unit = "col%" + endlen;
385 } else if (unit == "\\paperwidth") {
386 valstring = percentval;
387 unit = "page%" + endlen;
388 } else if (unit == "\\linewidth") {
389 valstring = percentval;
390 unit = "line%" + endlen;
391 } else if (unit == "\\paperheight") {
392 valstring = percentval;
393 unit = "pheight%" + endlen;
394 } else if (unit == "\\textheight") {
395 valstring = percentval;
396 unit = "theight%" + endlen;
404 string translate_len(string const & length)
408 if (translate_len(length, value, unit))
410 // If the input is invalid, return what we have.
418 * Translates a LaTeX length into \p value, \p unit and
419 * \p special parts suitable for a box inset.
420 * The difference from translate_len() is that a box inset knows about
421 * some special "units" that are stored in \p special.
423 void translate_box_len(string const & length, string & value, string & unit, string & special)
425 if (translate_len(length, value, unit)) {
426 if (unit == "\\height" || unit == "\\depth" ||
427 unit == "\\totalheight" || unit == "\\width") {
428 special = unit.substr(1);
429 // The unit is not used, but LyX requires a dummy setting
442 * Find a file with basename \p name in path \p path and an extension
445 string find_file(string const & name, string const & path,
446 char const * const * extensions)
448 for (char const * const * what = extensions; *what; ++what) {
449 string const trial = addExtension(name, *what);
450 if (makeAbsPath(trial, path).exists())
457 void begin_inset(ostream & os, string const & name)
459 os << "\n\\begin_inset " << name;
463 void begin_command_inset(ostream & os, string const & name,
464 string const & latexname)
466 begin_inset(os, "CommandInset ");
467 os << name << "\nLatexCommand " << latexname << '\n';
471 void end_inset(ostream & os)
473 os << "\n\\end_inset\n\n";
477 bool skip_braces(Parser & p)
479 if (p.next_token().cat() != catBegin)
482 if (p.next_token().cat() == catEnd) {
491 /// replace LaTeX commands in \p s from the unicodesymbols file with their
493 docstring convert_unicodesymbols(docstring s)
496 for (size_t i = 0; i < s.size();) {
505 docstring parsed = encodings.fromLaTeXCommand(s,
506 Encodings::TEXT_CMD, termination, rem, &req);
507 set<string>::const_iterator it = req.begin();
508 set<string>::const_iterator en = req.end();
509 for (; it != en; ++it)
510 preamble.registerAutomaticallyLoadedPackage(*it);
513 if (s.empty() || s[0] != '\\')
522 /// try to convert \p s to a valid InsetCommand argument
523 string convert_command_inset_arg(string s)
526 // since we don't know the input encoding we can't use from_utf8
527 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
528 // LyX cannot handle newlines in a latex command
529 return subst(s, "\n", " ");
533 void output_ert(ostream & os, string const & s, Context & context)
535 context.check_layout(os);
536 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
538 os << "\n\\backslash\n";
539 else if (*it == '\n') {
540 context.new_paragraph(os);
541 context.check_layout(os);
545 context.check_end_layout(os);
549 void output_ert_inset(ostream & os, string const & s, Context & context)
551 // We must have a valid layout before outputting the ERT inset.
552 context.check_layout(os);
553 Context newcontext(true, context.textclass);
554 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
555 if (layout.forcePlainLayout())
556 newcontext.layout = &context.textclass.plainLayout();
557 begin_inset(os, "ERT");
558 os << "\nstatus collapsed\n";
559 output_ert(os, s, newcontext);
564 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
566 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
569 if (checkModule(name, command))
570 return findLayoutWithoutModule(textclass, name, command);
575 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
577 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
580 if (checkModule(name, command))
581 return findInsetLayoutWithoutModule(textclass, name, command);
586 void eat_whitespace(Parser &, ostream &, Context &, bool);
590 * Skips whitespace and braces.
591 * This should be called after a command has been parsed that is not put into
592 * ERT, and where LyX adds "{}" if needed.
594 void skip_spaces_braces(Parser & p, bool keepws = false)
596 /* The following four examples produce the same typeset output and
597 should be handled by this function:
605 // Unfortunately we need to skip comments, too.
606 // We can't use eat_whitespace since writing them after the {}
607 // results in different output in some cases.
608 bool const skipped_spaces = p.skip_spaces(true);
609 bool const skipped_braces = skip_braces(p);
610 if (keepws && skipped_spaces && !skipped_braces)
611 // put back the space (it is better handled by check_space)
612 p.unskip_spaces(true);
616 void output_command_layout(ostream & os, Parser & p, bool outer,
617 Context & parent_context,
618 Layout const * newlayout)
620 TeXFont const oldFont = parent_context.font;
621 // save the current font size
622 string const size = oldFont.size;
623 // reset the font size to default, because the font size switches
624 // don't affect section headings and the like
625 parent_context.font.size = Context::normalfont.size;
626 // we only need to write the font change if we have an open layout
627 if (!parent_context.atParagraphStart())
628 output_font_change(os, oldFont, parent_context.font);
629 parent_context.check_end_layout(os);
630 Context context(true, parent_context.textclass, newlayout,
631 parent_context.layout, parent_context.font);
632 if (parent_context.deeper_paragraph) {
633 // We are beginning a nested environment after a
634 // deeper paragraph inside the outer list environment.
635 // Therefore we don't need to output a "begin deeper".
636 context.need_end_deeper = true;
638 context.check_deeper(os);
639 context.check_layout(os);
640 // FIXME: Adjust to format 446!
641 // Since format 446, layouts do not require anymore all optional
642 // arguments before the required ones. Needs to be implemented!
644 while (optargs < context.layout->optArgs()) {
645 eat_whitespace(p, os, context, false);
646 if (p.next_token().cat() == catEscape ||
647 p.next_token().character() != '[')
649 p.get_token(); // eat '['
650 // FIXME: Just a workaround. InsetArgument::updateBuffer
651 // will compute a proper ID for all "999" Arguments
652 // (which is also what lyx2lyx produces).
653 // However, tex2lyx should be able to output proper IDs
655 begin_inset(os, "Argument 999\n");
656 os << "status collapsed\n\n";
657 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
659 eat_whitespace(p, os, context, false);
663 while (reqargs < context.layout->requiredArgs()) {
664 eat_whitespace(p, os, context, false);
665 if (p.next_token().cat() != catBegin)
667 p.get_token(); // eat '{'
668 // FIXME: Just a workaround. InsetArgument::updateBuffer
669 // will compute a proper ID for all "999" Arguments
670 // (which is also what lyx2lyx produces).
671 // However, tex2lyx should be able to output proper IDs
673 begin_inset(os, "Argument 999\n");
674 os << "status collapsed\n\n";
675 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
677 eat_whitespace(p, os, context, false);
680 parse_text(p, os, FLAG_ITEM, outer, context);
681 context.check_end_layout(os);
682 if (parent_context.deeper_paragraph) {
683 // We must suppress the "end deeper" because we
684 // suppressed the "begin deeper" above.
685 context.need_end_deeper = false;
687 context.check_end_deeper(os);
688 // We don't need really a new paragraph, but
689 // we must make sure that the next item gets a \begin_layout.
690 parent_context.new_paragraph(os);
691 // Set the font size to the original value. No need to output it here
692 // (Context::begin_layout() will do that if needed)
693 parent_context.font.size = size;
698 * Output a space if necessary.
699 * This function gets called for every whitespace token.
701 * We have three cases here:
702 * 1. A space must be suppressed. Example: The lyxcode case below
703 * 2. A space may be suppressed. Example: Spaces before "\par"
704 * 3. A space must not be suppressed. Example: A space between two words
706 * We currently handle only 1. and 3 and from 2. only the case of
707 * spaces before newlines as a side effect.
709 * 2. could be used to suppress as many spaces as possible. This has two effects:
710 * - Reimporting LyX generated LaTeX files changes almost no whitespace
711 * - Superflous whitespace from non LyX generated LaTeX files is removed.
712 * The drawback is that the logic inside the function becomes
713 * complicated, and that is the reason why it is not implemented.
715 void check_space(Parser & p, ostream & os, Context & context)
717 Token const next = p.next_token();
718 Token const curr = p.curr_token();
719 // A space before a single newline and vice versa must be ignored
720 // LyX emits a newline before \end{lyxcode}.
721 // This newline must be ignored,
722 // otherwise LyX will add an additional protected space.
723 if (next.cat() == catSpace ||
724 next.cat() == catNewline ||
725 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
728 context.check_layout(os);
734 * Parse all arguments of \p command
736 void parse_arguments(string const & command,
737 vector<ArgumentType> const & template_arguments,
738 Parser & p, ostream & os, bool outer, Context & context)
740 string ert = command;
741 size_t no_arguments = template_arguments.size();
742 for (size_t i = 0; i < no_arguments; ++i) {
743 switch (template_arguments[i]) {
746 // This argument contains regular LaTeX
747 output_ert_inset(os, ert + '{', context);
748 eat_whitespace(p, os, context, false);
749 if (template_arguments[i] == required)
750 parse_text(p, os, FLAG_ITEM, outer, context);
752 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
756 // This argument consists only of a single item.
757 // The presence of '{' or not must be preserved.
759 if (p.next_token().cat() == catBegin)
760 ert += '{' + p.verbatim_item() + '}';
762 ert += p.verbatim_item();
766 // This argument may contain special characters
767 ert += '{' + p.verbatim_item() + '}';
771 // true because we must not eat whitespace
772 // if an optional arg follows we must not strip the
773 // brackets from this one
774 if (i < no_arguments - 1 &&
775 template_arguments[i+1] == optional)
776 ert += p.getFullOpt(true);
778 ert += p.getOpt(true);
782 output_ert_inset(os, ert, context);
787 * Check whether \p command is a known command. If yes,
788 * handle the command with all arguments.
789 * \return true if the command was parsed, false otherwise.
791 bool parse_command(string const & command, Parser & p, ostream & os,
792 bool outer, Context & context)
794 if (known_commands.find(command) != known_commands.end()) {
795 parse_arguments(command, known_commands[command], p, os,
803 /// Parses a minipage or parbox
804 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
805 unsigned inner_flags, bool outer, Context & parent_context,
806 string const & outer_type, string const & special,
807 string const & inner_type)
811 string hor_pos = "c";
812 // We need to set the height to the LaTeX default of 1\\totalheight
813 // for the case when no height argument is given
814 string height_value = "1";
815 string height_unit = "in";
816 string height_special = "totalheight";
821 string width_special = "none";
822 if (!inner_type.empty() && p.hasOpt()) {
823 if (inner_type != "makebox")
824 position = p.getArg('[', ']');
826 latex_width = p.getArg('[', ']');
827 translate_box_len(latex_width, width_value, width_unit, width_special);
830 if (position != "t" && position != "c" && position != "b") {
831 cerr << "invalid position " << position << " for "
832 << inner_type << endl;
836 if (inner_type != "makebox") {
837 latex_height = p.getArg('[', ']');
838 translate_box_len(latex_height, height_value, height_unit, height_special);
840 string const opt = p.getArg('[', ']');
843 if (hor_pos != "l" && hor_pos != "c" &&
844 hor_pos != "r" && hor_pos != "s") {
845 cerr << "invalid hor_pos " << hor_pos
846 << " for " << inner_type << endl;
853 inner_pos = p.getArg('[', ']');
854 if (inner_pos != "c" && inner_pos != "t" &&
855 inner_pos != "b" && inner_pos != "s") {
856 cerr << "invalid inner_pos "
857 << inner_pos << " for "
858 << inner_type << endl;
859 inner_pos = position;
864 if (inner_type.empty()) {
865 if (special.empty() && outer_type != "framebox")
866 latex_width = "1\\columnwidth";
869 latex_width = p2.getArg('[', ']');
870 string const opt = p2.getArg('[', ']');
873 if (hor_pos != "l" && hor_pos != "c" &&
874 hor_pos != "r" && hor_pos != "s") {
875 cerr << "invalid hor_pos " << hor_pos
876 << " for " << outer_type << endl;
881 } else if (inner_type != "makebox")
882 latex_width = p.verbatim_item();
883 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
884 // as this is LyX's standard for such cases (except for makebox)
885 // \framebox is more special and handled below
886 if (latex_width.empty() && inner_type != "makebox"
887 && outer_type != "framebox")
888 latex_width = "1\\columnwidth";
890 translate_len(latex_width, width_value, width_unit);
892 bool shadedparbox = false;
893 if (inner_type == "shaded") {
894 eat_whitespace(p, os, parent_context, false);
895 if (outer_type == "parbox") {
897 if (p.next_token().cat() == catBegin)
899 eat_whitespace(p, os, parent_context, false);
905 // If we already read the inner box we have to push the inner env
906 if (!outer_type.empty() && !inner_type.empty() &&
907 (inner_flags & FLAG_END))
908 active_environments.push_back(inner_type);
909 // LyX can't handle length variables
910 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
911 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
912 // Look whether there is some content after the end of the
913 // inner box, but before the end of the outer box.
914 // If yes, we need to output ERT.
916 if (inner_flags & FLAG_END)
917 p.ertEnvironment(inner_type);
921 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
922 if ((outer_env && p.next_token().asInput() != "\\end") ||
923 (!outer_env && p.next_token().cat() != catEnd)) {
924 // something is between the end of the inner box and
925 // the end of the outer box, so we need to use ERT.
930 // if only \makebox{content} was used we can set its width to 1\width
931 // because this identic and also identic to \mbox
932 // this doesn't work for \framebox{content}, thus we have to use ERT for this
933 if (latex_width.empty() && inner_type == "makebox") {
936 width_special = "width";
937 } else if (latex_width.empty() && outer_type == "framebox") {
942 if (!outer_type.empty()) {
943 if (outer_flags & FLAG_END)
944 ss << "\\begin{" << outer_type << '}';
946 ss << '\\' << outer_type << '{';
947 if (!special.empty())
951 if (!inner_type.empty()) {
952 if (inner_type != "shaded") {
953 if (inner_flags & FLAG_END)
954 ss << "\\begin{" << inner_type << '}';
956 ss << '\\' << inner_type;
958 if (!position.empty())
959 ss << '[' << position << ']';
960 if (!latex_height.empty())
961 ss << '[' << latex_height << ']';
962 if (!inner_pos.empty())
963 ss << '[' << inner_pos << ']';
964 ss << '{' << latex_width << '}';
965 if (!(inner_flags & FLAG_END))
968 if (inner_type == "shaded")
969 ss << "\\begin{shaded}";
970 output_ert_inset(os, ss.str(), parent_context);
971 if (!inner_type.empty()) {
972 parse_text(p, os, inner_flags, outer, parent_context);
973 if (inner_flags & FLAG_END)
974 output_ert_inset(os, "\\end{" + inner_type + '}',
977 output_ert_inset(os, "}", parent_context);
979 if (!outer_type.empty()) {
980 // If we already read the inner box we have to pop
982 if (!inner_type.empty() && (inner_flags & FLAG_END))
983 active_environments.pop_back();
985 // Ensure that the end of the outer box is parsed correctly:
986 // The opening brace has been eaten by parse_outer_box()
987 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
988 outer_flags &= ~FLAG_ITEM;
989 outer_flags |= FLAG_BRACE_LAST;
991 parse_text(p, os, outer_flags, outer, parent_context);
992 if (outer_flags & FLAG_END)
993 output_ert_inset(os, "\\end{" + outer_type + '}',
995 else if (inner_type.empty() && outer_type == "framebox")
996 // in this case it is already closed later
999 output_ert_inset(os, "}", parent_context);
1002 // LyX does not like empty positions, so we have
1003 // to set them to the LaTeX default values here.
1004 if (position.empty())
1006 if (inner_pos.empty())
1007 inner_pos = position;
1008 parent_context.check_layout(os);
1009 begin_inset(os, "Box ");
1010 if (outer_type == "framed")
1012 else if (outer_type == "framebox")
1014 else if (outer_type == "shadowbox")
1015 os << "Shadowbox\n";
1016 else if ((outer_type == "shaded" && inner_type.empty()) ||
1017 (outer_type == "minipage" && inner_type == "shaded") ||
1018 (outer_type == "parbox" && inner_type == "shaded")) {
1020 preamble.registerAutomaticallyLoadedPackage("color");
1021 } else if (outer_type == "doublebox")
1022 os << "Doublebox\n";
1023 else if (outer_type.empty())
1024 os << "Frameless\n";
1026 os << outer_type << '\n';
1027 os << "position \"" << position << "\"\n";
1028 os << "hor_pos \"" << hor_pos << "\"\n";
1029 os << "has_inner_box " << !inner_type.empty() << "\n";
1030 os << "inner_pos \"" << inner_pos << "\"\n";
1031 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1033 os << "use_makebox " << (inner_type == "makebox") << '\n';
1034 os << "width \"" << width_value << width_unit << "\"\n";
1035 os << "special \"" << width_special << "\"\n";
1036 os << "height \"" << height_value << height_unit << "\"\n";
1037 os << "height_special \"" << height_special << "\"\n";
1038 os << "status open\n\n";
1040 // Unfortunately we can't use parse_text_in_inset:
1041 // InsetBox::forcePlainLayout() is hard coded and does not
1042 // use the inset layout. Apart from that do we call parse_text
1043 // up to two times, but need only one check_end_layout.
1044 bool const forcePlainLayout =
1045 (!inner_type.empty() || inner_type == "makebox") &&
1046 outer_type != "shaded" && outer_type != "framed";
1047 Context context(true, parent_context.textclass);
1048 if (forcePlainLayout)
1049 context.layout = &context.textclass.plainLayout();
1051 context.font = parent_context.font;
1053 // If we have no inner box the contents will be read with the outer box
1054 if (!inner_type.empty())
1055 parse_text(p, os, inner_flags, outer, context);
1057 // Ensure that the end of the outer box is parsed correctly:
1058 // The opening brace has been eaten by parse_outer_box()
1059 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1060 outer_flags &= ~FLAG_ITEM;
1061 outer_flags |= FLAG_BRACE_LAST;
1064 // Find end of outer box, output contents if inner_type is
1065 // empty and output possible comments
1066 if (!outer_type.empty()) {
1067 // If we already read the inner box we have to pop
1069 if (!inner_type.empty() && (inner_flags & FLAG_END))
1070 active_environments.pop_back();
1071 // This does not output anything but comments if
1072 // inner_type is not empty (see use_ert)
1073 parse_text(p, os, outer_flags, outer, context);
1076 context.check_end_layout(os);
1078 #ifdef PRESERVE_LAYOUT
1079 // LyX puts a % after the end of the minipage
1080 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1082 //output_ert_inset(os, "%dummy", parent_context);
1085 parent_context.new_paragraph(os);
1087 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1088 //output_ert_inset(os, "%dummy", parent_context);
1091 // We add a protected space if something real follows
1092 if (p.good() && p.next_token().cat() != catComment) {
1093 begin_inset(os, "space ~\n");
1102 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1103 Context & parent_context, string const & outer_type,
1104 string const & special)
1106 eat_whitespace(p, os, parent_context, false);
1107 if (flags & FLAG_ITEM) {
1109 if (p.next_token().cat() == catBegin)
1112 cerr << "Warning: Ignoring missing '{' after \\"
1113 << outer_type << '.' << endl;
1114 eat_whitespace(p, os, parent_context, false);
1117 unsigned int inner_flags = 0;
1119 if (outer_type == "minipage" || outer_type == "parbox") {
1120 p.skip_spaces(true);
1121 while (p.hasOpt()) {
1123 p.skip_spaces(true);
1126 p.skip_spaces(true);
1127 if (outer_type == "parbox") {
1129 if (p.next_token().cat() == catBegin)
1131 p.skip_spaces(true);
1134 if (outer_type == "shaded") {
1135 // These boxes never have an inner box
1137 } else if (p.next_token().asInput() == "\\parbox") {
1138 inner = p.get_token().cs();
1139 inner_flags = FLAG_ITEM;
1140 } else if (p.next_token().asInput() == "\\begin") {
1141 // Is this a minipage or shaded box?
1144 inner = p.getArg('{', '}');
1146 if (inner == "minipage" || inner == "shaded")
1147 inner_flags = FLAG_END;
1152 if (inner_flags == FLAG_END) {
1153 if (inner != "shaded")
1157 eat_whitespace(p, os, parent_context, false);
1159 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1160 outer_type, special, inner);
1162 if (inner_flags == FLAG_ITEM) {
1164 eat_whitespace(p, os, parent_context, false);
1166 parse_box(p, os, flags, inner_flags, outer, parent_context,
1167 outer_type, special, inner);
1172 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1174 parent_context.check_layout(os);
1175 begin_inset(os, "listings\n");
1177 string arg = p.verbatimOption();
1178 os << "lstparams " << '"' << arg << '"' << '\n';
1179 if (arg.find("\\color") != string::npos)
1180 preamble.registerAutomaticallyLoadedPackage("color");
1183 os << "inline true\n";
1185 os << "inline false\n";
1186 os << "status collapsed\n";
1187 Context context(true, parent_context.textclass);
1188 context.layout = &parent_context.textclass.plainLayout();
1191 // set catcodes to verbatim early, just in case.
1192 p.setCatcodes(VERBATIM_CATCODES);
1193 string delim = p.get_token().asInput();
1194 //FIXME: handler error condition
1195 s = p.verbatimStuff(delim).second;
1196 // context.new_paragraph(os);
1198 s = p.verbatimEnvironment("lstlisting");
1199 output_ert(os, s, context);
1204 /// parse an unknown environment
1205 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1206 unsigned flags, bool outer,
1207 Context & parent_context)
1209 if (name == "tabbing")
1210 // We need to remember that we have to handle '\=' specially
1211 flags |= FLAG_TABBING;
1213 // We need to translate font changes and paragraphs inside the
1214 // environment to ERT if we have a non standard font.
1215 // Otherwise things like
1216 // \large\begin{foo}\huge bar\end{foo}
1218 bool const specialfont =
1219 (parent_context.font != parent_context.normalfont);
1220 bool const new_layout_allowed = parent_context.new_layout_allowed;
1222 parent_context.new_layout_allowed = false;
1223 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1224 parse_text_snippet(p, os, flags, outer, parent_context);
1225 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1227 parent_context.new_layout_allowed = new_layout_allowed;
1231 void parse_environment(Parser & p, ostream & os, bool outer,
1232 string & last_env, Context & parent_context)
1234 Layout const * newlayout;
1235 InsetLayout const * newinsetlayout = 0;
1236 string const name = p.getArg('{', '}');
1237 const bool is_starred = suffixIs(name, '*');
1238 string const unstarred_name = rtrim(name, "*");
1239 active_environments.push_back(name);
1241 if (is_math_env(name)) {
1242 parent_context.check_layout(os);
1243 begin_inset(os, "Formula ");
1244 os << "\\begin{" << name << "}";
1245 parse_math(p, os, FLAG_END, MATH_MODE);
1246 os << "\\end{" << name << "}";
1248 if (is_display_math_env(name)) {
1249 // Prevent the conversion of a line break to a space
1250 // (bug 7668). This does not change the output, but
1251 // looks ugly in LyX.
1252 eat_whitespace(p, os, parent_context, false);
1256 else if (is_known(name, preamble.polyglossia_languages)) {
1257 // We must begin a new paragraph if not already done
1258 if (! parent_context.atParagraphStart()) {
1259 parent_context.check_end_layout(os);
1260 parent_context.new_paragraph(os);
1262 // save the language in the context so that it is
1263 // handled by parse_text
1264 parent_context.font.language = preamble.polyglossia2lyx(name);
1265 parse_text(p, os, FLAG_END, outer, parent_context);
1266 // Just in case the environment is empty
1267 parent_context.extra_stuff.erase();
1268 // We must begin a new paragraph to reset the language
1269 parent_context.new_paragraph(os);
1273 else if (unstarred_name == "tabular" || name == "longtable") {
1274 eat_whitespace(p, os, parent_context, false);
1275 string width = "0pt";
1276 if (name == "tabular*") {
1277 width = lyx::translate_len(p.getArg('{', '}'));
1278 eat_whitespace(p, os, parent_context, false);
1280 parent_context.check_layout(os);
1281 begin_inset(os, "Tabular ");
1282 handle_tabular(p, os, name, width, parent_context);
1287 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1288 eat_whitespace(p, os, parent_context, false);
1289 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1290 eat_whitespace(p, os, parent_context, false);
1291 parent_context.check_layout(os);
1292 begin_inset(os, "Float " + unstarred_name + "\n");
1293 // store the float type for subfloats
1294 // subfloats only work with figures and tables
1295 if (unstarred_name == "figure")
1296 float_type = unstarred_name;
1297 else if (unstarred_name == "table")
1298 float_type = unstarred_name;
1302 os << "placement " << opt << '\n';
1303 if (contains(opt, "H"))
1304 preamble.registerAutomaticallyLoadedPackage("float");
1306 Floating const & fl = parent_context.textclass.floats()
1307 .getType(unstarred_name);
1308 if (!fl.floattype().empty() && fl.usesFloatPkg())
1309 preamble.registerAutomaticallyLoadedPackage("float");
1312 os << "wide " << convert<string>(is_starred)
1313 << "\nsideways false"
1314 << "\nstatus open\n\n";
1315 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1317 // We don't need really a new paragraph, but
1318 // we must make sure that the next item gets a \begin_layout.
1319 parent_context.new_paragraph(os);
1321 // the float is parsed thus delete the type
1325 else if (unstarred_name == "sidewaysfigure"
1326 || unstarred_name == "sidewaystable") {
1327 eat_whitespace(p, os, parent_context, false);
1328 parent_context.check_layout(os);
1329 if (unstarred_name == "sidewaysfigure")
1330 begin_inset(os, "Float figure\n");
1332 begin_inset(os, "Float table\n");
1333 os << "wide " << convert<string>(is_starred)
1334 << "\nsideways true"
1335 << "\nstatus open\n\n";
1336 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1338 // We don't need really a new paragraph, but
1339 // we must make sure that the next item gets a \begin_layout.
1340 parent_context.new_paragraph(os);
1342 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1345 else if (name == "wrapfigure" || name == "wraptable") {
1346 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1347 eat_whitespace(p, os, parent_context, false);
1348 parent_context.check_layout(os);
1351 string overhang = "0col%";
1354 lines = p.getArg('[', ']');
1355 string const placement = p.getArg('{', '}');
1357 overhang = p.getArg('[', ']');
1358 string const width = p.getArg('{', '}');
1360 if (name == "wrapfigure")
1361 begin_inset(os, "Wrap figure\n");
1363 begin_inset(os, "Wrap table\n");
1364 os << "lines " << lines
1365 << "\nplacement " << placement
1366 << "\noverhang " << lyx::translate_len(overhang)
1367 << "\nwidth " << lyx::translate_len(width)
1368 << "\nstatus open\n\n";
1369 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1371 // We don't need really a new paragraph, but
1372 // we must make sure that the next item gets a \begin_layout.
1373 parent_context.new_paragraph(os);
1375 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1378 else if (name == "minipage") {
1379 eat_whitespace(p, os, parent_context, false);
1380 // Test whether this is an outer box of a shaded box
1382 // swallow arguments
1383 while (p.hasOpt()) {
1385 p.skip_spaces(true);
1388 p.skip_spaces(true);
1389 Token t = p.get_token();
1390 bool shaded = false;
1391 if (t.asInput() == "\\begin") {
1392 p.skip_spaces(true);
1393 if (p.getArg('{', '}') == "shaded")
1398 parse_outer_box(p, os, FLAG_END, outer,
1399 parent_context, name, "shaded");
1401 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1406 else if (name == "comment") {
1407 eat_whitespace(p, os, parent_context, false);
1408 parent_context.check_layout(os);
1409 begin_inset(os, "Note Comment\n");
1410 os << "status open\n";
1411 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1414 skip_braces(p); // eat {} that might by set by LyX behind comments
1415 preamble.registerAutomaticallyLoadedPackage("verbatim");
1418 else if (name == "verbatim") {
1419 // FIXME: this should go in the generic code that
1420 // handles environments defined in layout file that
1421 // have "PassThru 1". However, the code over there is
1422 // already too complicated for my taste.
1423 parent_context.new_paragraph(os);
1424 Context context(true, parent_context.textclass,
1425 &parent_context.textclass[from_ascii("Verbatim")]);
1426 string s = p.verbatimEnvironment("verbatim");
1427 output_ert(os, s, context);
1431 else if (name == "IPA") {
1432 eat_whitespace(p, os, parent_context, false);
1433 parent_context.check_layout(os);
1434 begin_inset(os, "IPA\n");
1435 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1438 preamble.registerAutomaticallyLoadedPackage("tipa");
1439 preamble.registerAutomaticallyLoadedPackage("tipx");
1442 else if (name == "CJK") {
1443 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1444 // It is impossible to decide if a CJK environment was in its own paragraph or within
1445 // a line. We therefore always assume a paragraph since the latter is a rare case.
1446 eat_whitespace(p, os, parent_context, false);
1447 parent_context.check_end_layout(os);
1448 // store the encoding to be able to reset it
1449 string const encoding_old = p.getEncoding();
1450 string const encoding = p.getArg('{', '}');
1451 // FIXME: For some reason JIS does not work. Although the text
1452 // in tests/CJK.tex is identical with the SJIS version if you
1453 // convert both snippets using the recode command line utility,
1454 // the resulting .lyx file contains some extra characters if
1455 // you set buggy_encoding to false for JIS.
1456 bool const buggy_encoding = encoding == "JIS";
1457 if (!buggy_encoding)
1458 p.setEncoding(encoding, Encoding::CJK);
1460 // FIXME: This will read garbage, since the data is not encoded in utf8.
1461 p.setEncoding("UTF-8");
1463 // LyX only supports the same mapping for all CJK
1464 // environments, so we might need to output everything as ERT
1465 string const mapping = trim(p.getArg('{', '}'));
1466 char const * const * const where =
1467 is_known(encoding, supported_CJK_encodings);
1468 if (!buggy_encoding && !preamble.fontCJKSet())
1469 preamble.fontCJK(mapping);
1470 bool knownMapping = mapping == preamble.fontCJK();
1471 if (buggy_encoding || !knownMapping || !where) {
1472 parent_context.check_layout(os);
1473 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1475 // we must parse the content as verbatim because e.g. JIS can contain
1476 // normally invalid characters
1477 // FIXME: This works only for the most simple cases.
1478 // Since TeX control characters are not parsed,
1479 // things like comments are completely wrong.
1480 string const s = p.plainEnvironment("CJK");
1481 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1483 output_ert_inset(os, "\\", parent_context);
1484 else if (*it == '$')
1485 output_ert_inset(os, "$", parent_context);
1486 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1491 output_ert_inset(os, "\\end{" + name + "}",
1495 supported_CJK_languages[where - supported_CJK_encodings];
1496 // store the language because we must reset it at the end
1497 string const lang_old = parent_context.font.language;
1498 parent_context.font.language = lang;
1499 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1500 parent_context.font.language = lang_old;
1501 parent_context.new_paragraph(os);
1503 p.setEncoding(encoding_old);
1507 else if (name == "lyxgreyedout") {
1508 eat_whitespace(p, os, parent_context, false);
1509 parent_context.check_layout(os);
1510 begin_inset(os, "Note Greyedout\n");
1511 os << "status open\n";
1512 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1515 if (!preamble.notefontcolor().empty())
1516 preamble.registerAutomaticallyLoadedPackage("color");
1519 else if (name == "framed" || name == "shaded") {
1520 eat_whitespace(p, os, parent_context, false);
1521 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1525 else if (name == "lstlisting") {
1526 eat_whitespace(p, os, parent_context, false);
1527 parse_listings(p, os, parent_context, false);
1531 else if (!parent_context.new_layout_allowed)
1532 parse_unknown_environment(p, name, os, FLAG_END, outer,
1535 // Alignment and spacing settings
1536 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1537 // therefore are totally broken!
1538 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1539 // they are commands not environments. They are furthermore switches that
1540 // can be ended by another switches, but also by commands like \footnote or
1541 // \parbox. So the only safe way is to leave them untouched.
1542 else if (name == "center" || name == "centering" ||
1543 name == "flushleft" || name == "flushright" ||
1544 name == "singlespace" || name == "onehalfspace" ||
1545 name == "doublespace" || name == "spacing") {
1546 eat_whitespace(p, os, parent_context, false);
1547 // We must begin a new paragraph if not already done
1548 if (! parent_context.atParagraphStart()) {
1549 parent_context.check_end_layout(os);
1550 parent_context.new_paragraph(os);
1552 if (name == "flushleft")
1553 parent_context.add_extra_stuff("\\align left\n");
1554 else if (name == "flushright")
1555 parent_context.add_extra_stuff("\\align right\n");
1556 else if (name == "center" || name == "centering")
1557 parent_context.add_extra_stuff("\\align center\n");
1558 else if (name == "singlespace")
1559 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1560 else if (name == "onehalfspace") {
1561 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1562 preamble.registerAutomaticallyLoadedPackage("setspace");
1563 } else if (name == "doublespace") {
1564 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1565 preamble.registerAutomaticallyLoadedPackage("setspace");
1566 } else if (name == "spacing") {
1567 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1568 preamble.registerAutomaticallyLoadedPackage("setspace");
1570 parse_text(p, os, FLAG_END, outer, parent_context);
1571 // Just in case the environment is empty
1572 parent_context.extra_stuff.erase();
1573 // We must begin a new paragraph to reset the alignment
1574 parent_context.new_paragraph(os);
1578 // The single '=' is meant here.
1579 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1580 eat_whitespace(p, os, parent_context, false);
1581 Context context(true, parent_context.textclass, newlayout,
1582 parent_context.layout, parent_context.font);
1583 if (parent_context.deeper_paragraph) {
1584 // We are beginning a nested environment after a
1585 // deeper paragraph inside the outer list environment.
1586 // Therefore we don't need to output a "begin deeper".
1587 context.need_end_deeper = true;
1589 parent_context.check_end_layout(os);
1590 if (last_env == name) {
1591 // we need to output a separator since LyX would export
1592 // the two environments as one otherwise (bug 5716)
1593 docstring const sep = from_ascii("--Separator--");
1594 TeX2LyXDocClass const & textclass(parent_context.textclass);
1595 if (textclass.hasLayout(sep)) {
1596 Context newcontext(parent_context);
1597 newcontext.layout = &(textclass[sep]);
1598 newcontext.check_layout(os);
1599 newcontext.check_end_layout(os);
1601 parent_context.check_layout(os);
1602 begin_inset(os, "Note Note\n");
1603 os << "status closed\n";
1604 Context newcontext(true, textclass,
1605 &(textclass.defaultLayout()));
1606 newcontext.check_layout(os);
1607 newcontext.check_end_layout(os);
1609 parent_context.check_end_layout(os);
1612 switch (context.layout->latextype) {
1613 case LATEX_LIST_ENVIRONMENT:
1614 context.add_par_extra_stuff("\\labelwidthstring "
1615 + p.verbatim_item() + '\n');
1618 case LATEX_BIB_ENVIRONMENT:
1619 p.verbatim_item(); // swallow next arg
1625 context.check_deeper(os);
1626 // handle known optional and required arguments
1627 // FIXME: Since format 446, layouts do not require anymore all optional
1628 // arguments before the required ones. Needs to be implemented!
1629 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1630 // It is impossible to place anything after the environment name,
1631 // but before the first \\item.
1632 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1633 bool need_layout = true;
1635 while (optargs < context.layout->optArgs()) {
1636 eat_whitespace(p, os, context, false);
1637 if (p.next_token().cat() == catEscape ||
1638 p.next_token().character() != '[')
1640 p.get_token(); // eat '['
1642 context.check_layout(os);
1643 need_layout = false;
1645 // FIXME: Just a workaround. InsetArgument::updateBuffer
1646 // will compute a proper ID for all "999" Arguments
1647 // (which is also what lyx2lyx produces).
1648 // However, tex2lyx should be able to output proper IDs
1650 begin_inset(os, "Argument 999\n");
1651 os << "status collapsed\n\n";
1652 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1654 eat_whitespace(p, os, context, false);
1658 while (reqargs < context.layout->requiredArgs()) {
1659 eat_whitespace(p, os, context, false);
1660 if (p.next_token().cat() != catBegin)
1662 p.get_token(); // eat '{'
1664 context.check_layout(os);
1665 need_layout = false;
1667 // FIXME: Just a workaround. InsetArgument::updateBuffer
1668 // will compute a proper ID for all "999" Arguments
1669 // (which is also what lyx2lyx produces).
1670 // However, tex2lyx should be able to output proper IDs
1672 begin_inset(os, "Argument 999\n");
1673 os << "status collapsed\n\n";
1674 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1676 eat_whitespace(p, os, context, false);
1680 parse_text(p, os, FLAG_END, outer, context);
1681 context.check_end_layout(os);
1682 if (parent_context.deeper_paragraph) {
1683 // We must suppress the "end deeper" because we
1684 // suppressed the "begin deeper" above.
1685 context.need_end_deeper = false;
1687 context.check_end_deeper(os);
1688 parent_context.new_paragraph(os);
1690 if (!preamble.titleLayoutFound())
1691 preamble.titleLayoutFound(newlayout->intitle);
1692 set<string> const & req = newlayout->requires();
1693 set<string>::const_iterator it = req.begin();
1694 set<string>::const_iterator en = req.end();
1695 for (; it != en; ++it)
1696 preamble.registerAutomaticallyLoadedPackage(*it);
1699 // The single '=' is meant here.
1700 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1701 eat_whitespace(p, os, parent_context, false);
1702 parent_context.check_layout(os);
1703 begin_inset(os, "Flex ");
1704 os << to_utf8(newinsetlayout->name()) << '\n'
1705 << "status collapsed\n";
1706 if (newinsetlayout->isPassThru()) {
1707 string const arg = p.verbatimEnvironment(name);
1708 Context context(true, parent_context.textclass,
1709 &parent_context.textclass.plainLayout(),
1710 parent_context.layout);
1711 output_ert(os, arg, parent_context);
1713 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1717 else if (name == "appendix") {
1718 // This is no good latex style, but it works and is used in some documents...
1719 eat_whitespace(p, os, parent_context, false);
1720 parent_context.check_end_layout(os);
1721 Context context(true, parent_context.textclass, parent_context.layout,
1722 parent_context.layout, parent_context.font);
1723 context.check_layout(os);
1724 os << "\\start_of_appendix\n";
1725 parse_text(p, os, FLAG_END, outer, context);
1726 context.check_end_layout(os);
1730 else if (known_environments.find(name) != known_environments.end()) {
1731 vector<ArgumentType> arguments = known_environments[name];
1732 // The last "argument" denotes wether we may translate the
1733 // environment contents to LyX
1734 // The default required if no argument is given makes us
1735 // compatible with the reLyXre environment.
1736 ArgumentType contents = arguments.empty() ?
1739 if (!arguments.empty())
1740 arguments.pop_back();
1741 // See comment in parse_unknown_environment()
1742 bool const specialfont =
1743 (parent_context.font != parent_context.normalfont);
1744 bool const new_layout_allowed =
1745 parent_context.new_layout_allowed;
1747 parent_context.new_layout_allowed = false;
1748 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1749 outer, parent_context);
1750 if (contents == verbatim)
1751 output_ert_inset(os, p.ertEnvironment(name),
1754 parse_text_snippet(p, os, FLAG_END, outer,
1756 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1758 parent_context.new_layout_allowed = new_layout_allowed;
1762 parse_unknown_environment(p, name, os, FLAG_END, outer,
1766 active_environments.pop_back();
1770 /// parses a comment and outputs it to \p os.
1771 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1773 LASSERT(t.cat() == catComment, return);
1774 if (!t.cs().empty()) {
1775 context.check_layout(os);
1776 output_ert_inset(os, '%' + t.cs(), context);
1777 if (p.next_token().cat() == catNewline) {
1778 // A newline after a comment line starts a new
1780 if (context.new_layout_allowed) {
1781 if(!context.atParagraphStart())
1782 // Only start a new paragraph if not already
1783 // done (we might get called recursively)
1784 context.new_paragraph(os);
1786 output_ert_inset(os, "\n", context);
1787 eat_whitespace(p, os, context, true);
1790 // "%\n" combination
1797 * Reads spaces and comments until the first non-space, non-comment token.
1798 * New paragraphs (double newlines or \\par) are handled like simple spaces
1799 * if \p eatParagraph is true.
1800 * Spaces are skipped, but comments are written to \p os.
1802 void eat_whitespace(Parser & p, ostream & os, Context & context,
1806 Token const & t = p.get_token();
1807 if (t.cat() == catComment)
1808 parse_comment(p, os, t, context);
1809 else if ((! eatParagraph && p.isParagraph()) ||
1810 (t.cat() != catSpace && t.cat() != catNewline)) {
1819 * Set a font attribute, parse text and reset the font attribute.
1820 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1821 * \param currentvalue Current value of the attribute. Is set to the new
1822 * value during parsing.
1823 * \param newvalue New value of the attribute
1825 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1826 Context & context, string const & attribute,
1827 string & currentvalue, string const & newvalue)
1829 context.check_layout(os);
1830 string const oldvalue = currentvalue;
1831 currentvalue = newvalue;
1832 os << '\n' << attribute << ' ' << newvalue << "\n";
1833 parse_text_snippet(p, os, flags, outer, context);
1834 context.check_layout(os);
1835 os << '\n' << attribute << ' ' << oldvalue << "\n";
1836 currentvalue = oldvalue;
1840 /// get the arguments of a natbib or jurabib citation command
1841 void get_cite_arguments(Parser & p, bool natbibOrder,
1842 string & before, string & after)
1844 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1846 // text before the citation
1848 // text after the citation
1849 after = p.getFullOpt();
1851 if (!after.empty()) {
1852 before = p.getFullOpt();
1853 if (natbibOrder && !before.empty())
1854 swap(before, after);
1859 /// Convert filenames with TeX macros and/or quotes to something LyX
1861 string const normalize_filename(string const & name)
1866 Token const & t = p.get_token();
1867 if (t.cat() != catEscape)
1869 else if (t.cs() == "lyxdot") {
1870 // This is used by LyX for simple dots in relative
1874 } else if (t.cs() == "space") {
1877 } else if (t.cs() == "string") {
1878 // Convert \string" to " and \string~ to ~
1879 Token const & n = p.next_token();
1880 if (n.asInput() != "\"" && n.asInput() != "~")
1885 // Strip quotes. This is a bit complicated (see latex_path()).
1886 string full = os.str();
1887 if (!full.empty() && full[0] == '"') {
1888 string base = removeExtension(full);
1889 string ext = getExtension(full);
1890 if (!base.empty() && base[base.length()-1] == '"')
1893 return addExtension(trim(base, "\""), ext);
1894 if (full[full.length()-1] == '"')
1897 return trim(full, "\"");
1903 /// Convert \p name from TeX convention (relative to master file) to LyX
1904 /// convention (relative to .lyx file) if it is relative
1905 void fix_child_filename(string & name)
1907 string const absMasterTeX = getMasterFilePath(true);
1908 bool const isabs = FileName::isAbsolute(name);
1909 // convert from "relative to .tex master" to absolute original path
1911 name = makeAbsPath(name, absMasterTeX).absFileName();
1912 bool copyfile = copyFiles();
1913 string const absParentLyX = getParentFilePath(false);
1916 // convert from absolute original path to "relative to master file"
1917 string const rel = to_utf8(makeRelPath(from_utf8(name),
1918 from_utf8(absMasterTeX)));
1919 // re-interpret "relative to .tex file" as "relative to .lyx file"
1920 // (is different if the master .lyx file resides in a
1921 // different path than the master .tex file)
1922 string const absMasterLyX = getMasterFilePath(false);
1923 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1924 // Do not copy if the new path is impossible to create. Example:
1925 // absMasterTeX = "/foo/bar/"
1926 // absMasterLyX = "/bar/"
1927 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1928 if (contains(name, "/../"))
1935 // convert from absolute original path to
1936 // "relative to .lyx file"
1937 name = to_utf8(makeRelPath(from_utf8(abs),
1938 from_utf8(absParentLyX)));
1942 // convert from absolute original path to "relative to .lyx file"
1943 name = to_utf8(makeRelPath(from_utf8(name),
1944 from_utf8(absParentLyX)));
1949 void copy_file(FileName const & src, string dstname)
1953 string const absParent = getParentFilePath(false);
1955 if (FileName::isAbsolute(dstname))
1956 dst = FileName(dstname);
1958 dst = makeAbsPath(dstname, absParent);
1959 string const absMaster = getMasterFilePath(false);
1960 FileName const srcpath = src.onlyPath();
1961 FileName const dstpath = dst.onlyPath();
1962 if (equivalent(srcpath, dstpath))
1964 if (!dstpath.isDirectory()) {
1965 if (!dstpath.createPath()) {
1966 cerr << "Warning: Could not create directory for file `"
1967 << dst.absFileName() << "´." << endl;
1971 if (dst.isReadableFile()) {
1972 if (overwriteFiles())
1973 cerr << "Warning: Overwriting existing file `"
1974 << dst.absFileName() << "´." << endl;
1976 cerr << "Warning: Not overwriting existing file `"
1977 << dst.absFileName() << "´." << endl;
1981 if (!src.copyTo(dst))
1982 cerr << "Warning: Could not copy file `" << src.absFileName()
1983 << "´ to `" << dst.absFileName() << "´." << endl;
1987 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1988 bool parse_noweb(Parser & p, ostream & os, Context & context)
1990 // check whether a chunk is possible here.
1991 if (!context.new_layout_allowed ||
1992 !context.textclass.hasLayout(from_ascii("Chunk"))) {
1998 // read the parameters
1999 Parser::Arg stuff = p.verbatimStuff(">>=", false);
2004 string chunk = "<<" + stuff.second + ">>="
2005 + p.verbatimStuff("\n").second + '\n';
2007 stuff = p.verbatimStuff("\n@");
2012 chunk += stuff.second + "\n@";
2013 string post_chunk = p.verbatimStuff("\n").second + '\n';
2014 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2018 chunk += post_chunk;
2020 context.new_paragraph(os);
2021 Context newcontext(true, context.textclass,
2022 &context.textclass[from_ascii("Chunk")]);
2023 output_ert(os, chunk, newcontext);
2030 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2031 bool is_macro(Parser & p)
2033 Token first = p.curr_token();
2034 if (first.cat() != catEscape || !p.good())
2036 if (first.cs() == "def")
2038 if (first.cs() != "global" && first.cs() != "long")
2040 Token second = p.get_token();
2042 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2043 second.cat() == catNewline || second.cat() == catComment)) {
2044 second = p.get_token();
2047 bool secondvalid = second.cat() == catEscape;
2049 bool thirdvalid = false;
2050 if (p.good() && first.cs() == "global" && secondvalid &&
2051 second.cs() == "long") {
2052 third = p.get_token();
2054 while (p.good() && !p.isParagraph() &&
2055 (third.cat() == catSpace ||
2056 third.cat() == catNewline ||
2057 third.cat() == catComment)) {
2058 third = p.get_token();
2061 thirdvalid = third.cat() == catEscape;
2063 for (int i = 0; i < pos; ++i)
2068 return (first.cs() == "global" || first.cs() == "long") &&
2069 second.cs() == "def";
2070 return first.cs() == "global" && second.cs() == "long" &&
2071 third.cs() == "def";
2075 /// Parse a macro definition (assumes that is_macro() returned true)
2076 void parse_macro(Parser & p, ostream & os, Context & context)
2078 context.check_layout(os);
2079 Token first = p.curr_token();
2082 string command = first.asInput();
2083 if (first.cs() != "def") {
2085 eat_whitespace(p, os, context, false);
2086 second = p.curr_token();
2087 command += second.asInput();
2088 if (second.cs() != "def") {
2090 eat_whitespace(p, os, context, false);
2091 third = p.curr_token();
2092 command += third.asInput();
2095 eat_whitespace(p, os, context, false);
2096 string const name = p.get_token().cs();
2097 eat_whitespace(p, os, context, false);
2103 while (p.next_token().cat() != catBegin) {
2104 if (p.next_token().cat() == catParameter) {
2109 // followed by number?
2110 if (p.next_token().cat() == catOther) {
2111 string s = p.get_token().asInput();
2113 // number = current arity + 1?
2114 if (s.size() == 1 && s[0] == arity + '0' + 1)
2119 paramtext += p.get_token().cs();
2121 paramtext += p.get_token().cs();
2126 // only output simple (i.e. compatible) macro as FormulaMacros
2127 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2129 context.check_layout(os);
2130 begin_inset(os, "FormulaMacro");
2131 os << "\n\\def" << ert;
2134 output_ert_inset(os, command + ert, context);
2138 void registerExternalTemplatePackages(string const & name)
2140 external::TemplateManager const & etm = external::TemplateManager::get();
2141 external::Template const * const et = etm.getTemplateByName(name);
2144 external::Template::Formats::const_iterator cit = et->formats.end();
2146 cit = et->formats.find("PDFLaTeX");
2147 if (cit == et->formats.end())
2148 // If the template has not specified a PDFLaTeX output,
2149 // we try the LaTeX format.
2150 cit = et->formats.find("LaTeX");
2151 if (cit == et->formats.end())
2153 vector<string>::const_iterator qit = cit->second.requirements.begin();
2154 vector<string>::const_iterator qend = cit->second.requirements.end();
2155 for (; qit != qend; ++qit)
2156 preamble.registerAutomaticallyLoadedPackage(*qit);
2159 } // anonymous namespace
2162 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2165 Layout const * newlayout = 0;
2166 InsetLayout const * newinsetlayout = 0;
2167 char const * const * where = 0;
2168 // Store the latest bibliographystyle, addcontentslineContent and
2169 // nocite{*} option (needed for bibtex inset)
2171 string contentslineContent;
2172 string bibliographystyle = "default";
2173 bool const use_natbib = isProvided("natbib");
2174 bool const use_jurabib = isProvided("jurabib");
2177 Token const & t = p.get_token();
2179 // it is impossible to determine the correct encoding for non-CJK Japanese.
2180 // Therefore write a note at the beginning of the document
2181 if (is_nonCJKJapanese) {
2182 context.check_layout(os);
2183 begin_inset(os, "Note Note\n");
2184 os << "status open\n\\begin_layout Plain Layout\n"
2185 << "\\series bold\n"
2186 << "Important information:\n"
2187 << "\\end_layout\n\n"
2188 << "\\begin_layout Plain Layout\n"
2189 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2190 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2191 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2192 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2193 << " and specify the encoding using the -e command-line switch.\n"
2194 << " In addition, you might want to double check that the desired output encoding\n"
2195 << " is correctly selected in Document > Settings > Language.\n"
2196 << "\\end_layout\n";
2198 is_nonCJKJapanese = false;
2202 debugToken(cerr, t, flags);
2205 if (flags & FLAG_ITEM) {
2206 if (t.cat() == catSpace)
2209 flags &= ~FLAG_ITEM;
2210 if (t.cat() == catBegin) {
2211 // skip the brace and collect everything to the next matching
2213 flags |= FLAG_BRACE_LAST;
2217 // handle only this single token, leave the loop if done
2218 flags |= FLAG_LEAVE;
2221 if (t.cat() != catEscape && t.character() == ']' &&
2222 (flags & FLAG_BRACK_LAST))
2224 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2227 // If there is anything between \end{env} and \begin{env} we
2228 // don't need to output a separator.
2229 if (t.cat() != catSpace && t.cat() != catNewline &&
2230 t.asInput() != "\\begin")
2236 if (t.cat() == catMath) {
2237 // we are inside some text mode thingy, so opening new math is allowed
2238 context.check_layout(os);
2239 begin_inset(os, "Formula ");
2240 Token const & n = p.get_token();
2241 bool const display(n.cat() == catMath && outer);
2243 // TeX's $$...$$ syntax for displayed math
2245 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2247 p.get_token(); // skip the second '$' token
2249 // simple $...$ stuff
2252 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2257 // Prevent the conversion of a line break to a
2258 // space (bug 7668). This does not change the
2259 // output, but looks ugly in LyX.
2260 eat_whitespace(p, os, context, false);
2264 else if (t.cat() == catSuper || t.cat() == catSub)
2265 cerr << "catcode " << t << " illegal in text mode\n";
2267 // Basic support for english quotes. This should be
2268 // extended to other quotes, but is not so easy (a
2269 // left english quote is the same as a right german
2271 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2272 context.check_layout(os);
2273 begin_inset(os, "Quotes ");
2279 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2280 context.check_layout(os);
2281 begin_inset(os, "Quotes ");
2288 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2289 context.check_layout(os);
2290 begin_inset(os, "Quotes ");
2297 else if (t.asInput() == "<"
2298 && p.next_token().asInput() == "<") {
2299 bool has_noweb = false;
2303 has_noweb = parse_noweb(p, os, context);
2309 context.check_layout(os);
2310 begin_inset(os, "Quotes ");
2311 //FIXME: this is a right danish quote;
2312 // why not a left french quote?
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,
2413 } else if (p.next_token().asInput() == "\\ascii") {
2414 // handle the \ascii characters
2415 // (the case without braces is handled later)
2416 // the code is "{\ascii\xxx}"
2417 p.get_token(); // eat \ascii
2418 string name2 = p.get_token().asInput();
2419 p.get_token(); // eat the final '}'
2420 string const name = "{\\ascii" + name2 + "}";
2424 // get the character from unicodesymbols
2425 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2426 Encodings::TEXT_CMD, termination, rem, &req);
2428 context.check_layout(os);
2431 output_ert_inset(os,
2432 to_utf8(rem), context);
2433 for (set<string>::const_iterator it = req.begin();
2434 it != req.end(); ++it)
2435 preamble.registerAutomaticallyLoadedPackage(*it);
2437 // we did not find a non-ert version
2438 output_ert_inset(os, name, context);
2440 context.check_layout(os);
2441 // special handling of font attribute changes
2442 Token const prev = p.prev_token();
2443 TeXFont const oldFont = context.font;
2444 if (next.character() == '[' ||
2445 next.character() == ']' ||
2446 next.character() == '*') {
2448 if (p.next_token().cat() == catEnd) {
2453 output_ert_inset(os, "{", context);
2454 parse_text_snippet(p, os,
2457 output_ert_inset(os, "}", context);
2459 } else if (! context.new_layout_allowed) {
2460 output_ert_inset(os, "{", context);
2461 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2463 output_ert_inset(os, "}", context);
2464 } else if (is_known(next.cs(), known_sizes)) {
2465 // next will change the size, so we must
2467 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2469 if (!context.atParagraphStart())
2471 << context.font.size << "\n";
2472 } else if (is_known(next.cs(), known_font_families)) {
2473 // next will change the font family, so we
2474 // must reset it here
2475 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2477 if (!context.atParagraphStart())
2479 << context.font.family << "\n";
2480 } else if (is_known(next.cs(), known_font_series)) {
2481 // next will change the font series, so we
2482 // must reset it here
2483 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2485 if (!context.atParagraphStart())
2487 << context.font.series << "\n";
2488 } else if (is_known(next.cs(), known_font_shapes)) {
2489 // next will change the font shape, so we
2490 // must reset it here
2491 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2493 if (!context.atParagraphStart())
2495 << context.font.shape << "\n";
2496 } else if (is_known(next.cs(), known_old_font_families) ||
2497 is_known(next.cs(), known_old_font_series) ||
2498 is_known(next.cs(), known_old_font_shapes)) {
2499 // next will change the font family, series
2500 // and shape, so we must reset it here
2501 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2503 if (!context.atParagraphStart())
2505 << context.font.family
2507 << context.font.series
2509 << context.font.shape << "\n";
2511 output_ert_inset(os, "{", context);
2512 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2514 output_ert_inset(os, "}", context);
2519 else if (t.cat() == catEnd) {
2520 if (flags & FLAG_BRACE_LAST) {
2523 cerr << "stray '}' in text\n";
2524 output_ert_inset(os, "}", context);
2527 else if (t.cat() == catComment)
2528 parse_comment(p, os, t, context);
2531 // control sequences
2534 else if (t.cs() == "(" || t.cs() == "[") {
2535 bool const simple = t.cs() == "(";
2536 context.check_layout(os);
2537 begin_inset(os, "Formula");
2538 os << " \\" << t.cs();
2539 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2540 os << '\\' << (simple ? ')' : ']');
2543 // Prevent the conversion of a line break to a
2544 // space (bug 7668). This does not change the
2545 // output, but looks ugly in LyX.
2546 eat_whitespace(p, os, context, false);
2550 else if (t.cs() == "begin")
2551 parse_environment(p, os, outer, last_env,
2554 else if (t.cs() == "end") {
2555 if (flags & FLAG_END) {
2556 // eat environment name
2557 string const name = p.getArg('{', '}');
2558 if (name != active_environment())
2559 cerr << "\\end{" + name + "} does not match \\begin{"
2560 + active_environment() + "}\n";
2563 p.error("found 'end' unexpectedly");
2566 else if (t.cs() == "item") {
2568 bool const optarg = p.hasOpt();
2570 // FIXME: This swallows comments, but we cannot use
2571 // eat_whitespace() since we must not output
2572 // anything before the item.
2573 p.skip_spaces(true);
2574 s = p.verbatimOption();
2576 p.skip_spaces(false);
2578 context.check_layout(os);
2579 if (context.has_item) {
2580 // An item in an unknown list-like environment
2581 // FIXME: Do this in check_layout()!
2582 context.has_item = false;
2584 output_ert_inset(os, "\\item", context);
2586 output_ert_inset(os, "\\item ", context);
2589 if (context.layout->labeltype != LABEL_MANUAL) {
2590 // LyX does not support \item[\mybullet]
2591 // in itemize environments
2593 os << parse_text_snippet(p2,
2594 FLAG_BRACK_LAST, outer, context);
2595 } else if (!s.empty()) {
2596 // LyX adds braces around the argument,
2597 // so we need to remove them here.
2598 if (s.size() > 2 && s[0] == '{' &&
2599 s[s.size()-1] == '}')
2600 s = s.substr(1, s.size()-2);
2601 // If the argument contains a space we
2602 // must put it into ERT: Otherwise LyX
2603 // would misinterpret the space as
2604 // item delimiter (bug 7663)
2605 if (contains(s, ' ')) {
2606 output_ert_inset(os, s, context);
2609 os << parse_text_snippet(p2,
2613 // The space is needed to separate the
2614 // item from the rest of the sentence.
2616 eat_whitespace(p, os, context, false);
2621 else if (t.cs() == "bibitem") {
2623 context.check_layout(os);
2624 eat_whitespace(p, os, context, false);
2625 string label = convert_command_inset_arg(p.verbatimOption());
2626 string key = convert_command_inset_arg(p.verbatim_item());
2627 if (contains(label, '\\') || contains(key, '\\')) {
2628 // LyX can't handle LaTeX commands in labels or keys
2629 output_ert_inset(os, t.asInput() + '[' + label +
2630 "]{" + p.verbatim_item() + '}',
2633 begin_command_inset(os, "bibitem", "bibitem");
2634 os << "label \"" << label << "\"\n"
2635 "key \"" << key << "\"\n";
2640 else if (is_macro(p)) {
2641 // catch the case of \def\inputGnumericTable
2643 if (t.cs() == "def") {
2644 Token second = p.next_token();
2645 if (second.cs() == "inputGnumericTable") {
2649 Token third = p.get_token();
2651 if (third.cs() == "input") {
2655 string name = normalize_filename(p.verbatim_item());
2656 string const path = getMasterFilePath(true);
2657 // We want to preserve relative / absolute filenames,
2658 // therefore path is only used for testing
2659 // The file extension is in every case ".tex".
2660 // So we need to remove this extension and check for
2661 // the original one.
2662 name = removeExtension(name);
2663 if (!makeAbsPath(name, path).exists()) {
2664 char const * const Gnumeric_formats[] = {"gnumeric",
2666 string const Gnumeric_name =
2667 find_file(name, path, Gnumeric_formats);
2668 if (!Gnumeric_name.empty())
2669 name = Gnumeric_name;
2671 FileName const absname = makeAbsPath(name, path);
2672 if (absname.exists()) {
2673 fix_child_filename(name);
2674 copy_file(absname, name);
2676 cerr << "Warning: Could not find file '"
2677 << name << "'." << endl;
2678 context.check_layout(os);
2679 begin_inset(os, "External\n\ttemplate ");
2680 os << "GnumericSpreadsheet\n\tfilename "
2683 context.check_layout(os);
2685 // register the packages that are automatically loaded
2686 // by the Gnumeric template
2687 registerExternalTemplatePackages("GnumericSpreadsheet");
2692 parse_macro(p, os, context);
2695 else if (t.cs() == "noindent") {
2697 context.add_par_extra_stuff("\\noindent\n");
2700 else if (t.cs() == "appendix") {
2701 context.add_par_extra_stuff("\\start_of_appendix\n");
2702 // We need to start a new paragraph. Otherwise the
2703 // appendix in 'bla\appendix\chapter{' would start
2705 context.new_paragraph(os);
2706 // We need to make sure that the paragraph is
2707 // generated even if it is empty. Otherwise the
2708 // appendix in '\par\appendix\par\chapter{' would
2710 context.check_layout(os);
2711 // FIXME: This is a hack to prevent paragraph
2712 // deletion if it is empty. Handle this better!
2713 output_ert_inset(os,
2714 "%dummy comment inserted by tex2lyx to "
2715 "ensure that this paragraph is not empty",
2717 // Both measures above may generate an additional
2718 // empty paragraph, but that does not hurt, because
2719 // whitespace does not matter here.
2720 eat_whitespace(p, os, context, true);
2723 // Must catch empty dates before findLayout is called below
2724 else if (t.cs() == "date") {
2725 eat_whitespace(p, os, context, false);
2727 string const date = p.verbatim_item();
2730 preamble.suppressDate(true);
2733 preamble.suppressDate(false);
2734 if (context.new_layout_allowed &&
2735 (newlayout = findLayout(context.textclass,
2738 output_command_layout(os, p, outer,
2739 context, newlayout);
2740 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2741 if (!preamble.titleLayoutFound())
2742 preamble.titleLayoutFound(newlayout->intitle);
2743 set<string> const & req = newlayout->requires();
2744 set<string>::const_iterator it = req.begin();
2745 set<string>::const_iterator en = req.end();
2746 for (; it != en; ++it)
2747 preamble.registerAutomaticallyLoadedPackage(*it);
2749 output_ert_inset(os,
2750 "\\date{" + p.verbatim_item() + '}',
2755 // Starred section headings
2756 // Must attempt to parse "Section*" before "Section".
2757 else if ((p.next_token().asInput() == "*") &&
2758 context.new_layout_allowed &&
2759 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2762 output_command_layout(os, p, outer, context, newlayout);
2764 if (!preamble.titleLayoutFound())
2765 preamble.titleLayoutFound(newlayout->intitle);
2766 set<string> const & req = newlayout->requires();
2767 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2768 preamble.registerAutomaticallyLoadedPackage(*it);
2771 // Section headings and the like
2772 else if (context.new_layout_allowed &&
2773 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2775 output_command_layout(os, p, outer, context, newlayout);
2777 if (!preamble.titleLayoutFound())
2778 preamble.titleLayoutFound(newlayout->intitle);
2779 set<string> const & req = newlayout->requires();
2780 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2781 preamble.registerAutomaticallyLoadedPackage(*it);
2784 else if (t.cs() == "caption") {
2786 context.check_layout(os);
2788 begin_inset(os, "Caption Standard\n");
2789 Context newcontext(true, context.textclass, 0, 0, context.font);
2790 newcontext.check_layout(os);
2791 // FIXME InsetArgument is now properly implemented in InsetLayout
2792 // (for captions, but also for others)
2793 if (p.next_token().cat() != catEscape &&
2794 p.next_token().character() == '[') {
2795 p.get_token(); // eat '['
2796 begin_inset(os, "Argument 1\n");
2797 os << "status collapsed\n";
2798 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2800 eat_whitespace(p, os, context, false);
2802 parse_text(p, os, FLAG_ITEM, outer, context);
2803 context.check_end_layout(os);
2804 // We don't need really a new paragraph, but
2805 // we must make sure that the next item gets a \begin_layout.
2806 context.new_paragraph(os);
2809 newcontext.check_end_layout(os);
2812 else if (t.cs() == "subfloat") {
2813 // the syntax is \subfloat[caption]{content}
2814 // if it is a table of figure depends on the surrounding float
2815 bool has_caption = false;
2817 // do nothing if there is no outer float
2818 if (!float_type.empty()) {
2819 context.check_layout(os);
2821 begin_inset(os, "Float " + float_type + "\n");
2823 << "\nsideways false"
2824 << "\nstatus collapsed\n\n";
2827 if (p.next_token().cat() != catEscape &&
2828 p.next_token().character() == '[') {
2829 p.get_token(); // eat '['
2830 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2834 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2835 // the caption comes always as the last
2837 // we must make sure that the caption gets a \begin_layout
2838 os << "\n\\begin_layout Plain Layout";
2840 begin_inset(os, "Caption Standard\n");
2841 Context newcontext(true, context.textclass,
2842 0, 0, context.font);
2843 newcontext.check_layout(os);
2844 os << caption << "\n";
2845 newcontext.check_end_layout(os);
2846 // We don't need really a new paragraph, but
2847 // we must make sure that the next item gets a \begin_layout.
2848 //newcontext.new_paragraph(os);
2852 // We don't need really a new paragraph, but
2853 // we must make sure that the next item gets a \begin_layout.
2855 context.new_paragraph(os);
2858 context.check_end_layout(os);
2859 // close the layout we opened
2861 os << "\n\\end_layout\n";
2863 // if the float type is not supported or there is no surrounding float
2866 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2867 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2868 "]{" + p.verbatim_item() + '}', context);
2870 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2874 else if (t.cs() == "includegraphics") {
2875 bool const clip = p.next_token().asInput() == "*";
2878 string const arg = p.getArg('[', ']');
2879 map<string, string> opts;
2880 vector<string> keys;
2881 split_map(arg, opts, keys);
2883 opts["clip"] = string();
2884 string name = normalize_filename(p.verbatim_item());
2886 string const path = getMasterFilePath(true);
2887 // We want to preserve relative / absolute filenames,
2888 // therefore path is only used for testing
2889 if (!makeAbsPath(name, path).exists()) {
2890 // The file extension is probably missing.
2891 // Now try to find it out.
2892 string const dvips_name =
2893 find_file(name, path,
2894 known_dvips_graphics_formats);
2895 string const pdftex_name =
2896 find_file(name, path,
2897 known_pdftex_graphics_formats);
2898 if (!dvips_name.empty()) {
2899 if (!pdftex_name.empty()) {
2900 cerr << "This file contains the "
2902 "\"\\includegraphics{"
2904 "However, files\n\""
2905 << dvips_name << "\" and\n\""
2906 << pdftex_name << "\"\n"
2907 "both exist, so I had to make a "
2908 "choice and took the first one.\n"
2909 "Please move the unwanted one "
2910 "someplace else and try again\n"
2911 "if my choice was wrong."
2915 } else if (!pdftex_name.empty()) {
2921 FileName const absname = makeAbsPath(name, path);
2922 if (absname.exists()) {
2923 fix_child_filename(name);
2924 copy_file(absname, name);
2926 cerr << "Warning: Could not find graphics file '"
2927 << name << "'." << endl;
2929 context.check_layout(os);
2930 begin_inset(os, "Graphics ");
2931 os << "\n\tfilename " << name << '\n';
2932 if (opts.find("width") != opts.end())
2934 << translate_len(opts["width"]) << '\n';
2935 if (opts.find("height") != opts.end())
2937 << translate_len(opts["height"]) << '\n';
2938 if (opts.find("scale") != opts.end()) {
2939 istringstream iss(opts["scale"]);
2943 os << "\tscale " << val << '\n';
2945 if (opts.find("angle") != opts.end()) {
2946 os << "\trotateAngle "
2947 << opts["angle"] << '\n';
2948 vector<string>::const_iterator a =
2949 find(keys.begin(), keys.end(), "angle");
2950 vector<string>::const_iterator s =
2951 find(keys.begin(), keys.end(), "width");
2952 if (s == keys.end())
2953 s = find(keys.begin(), keys.end(), "height");
2954 if (s == keys.end())
2955 s = find(keys.begin(), keys.end(), "scale");
2956 if (s != keys.end() && distance(s, a) > 0)
2957 os << "\tscaleBeforeRotation\n";
2959 if (opts.find("origin") != opts.end()) {
2961 string const opt = opts["origin"];
2962 if (opt.find('l') != string::npos) ss << "left";
2963 if (opt.find('r') != string::npos) ss << "right";
2964 if (opt.find('c') != string::npos) ss << "center";
2965 if (opt.find('t') != string::npos) ss << "Top";
2966 if (opt.find('b') != string::npos) ss << "Bottom";
2967 if (opt.find('B') != string::npos) ss << "Baseline";
2968 if (!ss.str().empty())
2969 os << "\trotateOrigin " << ss.str() << '\n';
2971 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2973 if (opts.find("keepaspectratio") != opts.end())
2974 os << "\tkeepAspectRatio\n";
2975 if (opts.find("clip") != opts.end())
2977 if (opts.find("draft") != opts.end())
2979 if (opts.find("bb") != opts.end())
2980 os << "\tBoundingBox "
2981 << opts["bb"] << '\n';
2982 int numberOfbbOptions = 0;
2983 if (opts.find("bbllx") != opts.end())
2984 numberOfbbOptions++;
2985 if (opts.find("bblly") != opts.end())
2986 numberOfbbOptions++;
2987 if (opts.find("bburx") != opts.end())
2988 numberOfbbOptions++;
2989 if (opts.find("bbury") != opts.end())
2990 numberOfbbOptions++;
2991 if (numberOfbbOptions == 4)
2992 os << "\tBoundingBox "
2993 << opts["bbllx"] << " " << opts["bblly"] << " "
2994 << opts["bburx"] << " " << opts["bbury"] << '\n';
2995 else if (numberOfbbOptions > 0)
2996 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2997 numberOfbbOptions = 0;
2998 if (opts.find("natwidth") != opts.end())
2999 numberOfbbOptions++;
3000 if (opts.find("natheight") != opts.end())
3001 numberOfbbOptions++;
3002 if (numberOfbbOptions == 2)
3003 os << "\tBoundingBox 0bp 0bp "
3004 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3005 else if (numberOfbbOptions > 0)
3006 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3007 ostringstream special;
3008 if (opts.find("hiresbb") != opts.end())
3009 special << "hiresbb,";
3010 if (opts.find("trim") != opts.end())
3012 if (opts.find("viewport") != opts.end())
3013 special << "viewport=" << opts["viewport"] << ',';
3014 if (opts.find("totalheight") != opts.end())
3015 special << "totalheight=" << opts["totalheight"] << ',';
3016 if (opts.find("type") != opts.end())
3017 special << "type=" << opts["type"] << ',';
3018 if (opts.find("ext") != opts.end())
3019 special << "ext=" << opts["ext"] << ',';
3020 if (opts.find("read") != opts.end())
3021 special << "read=" << opts["read"] << ',';
3022 if (opts.find("command") != opts.end())
3023 special << "command=" << opts["command"] << ',';
3024 string s_special = special.str();
3025 if (!s_special.empty()) {
3026 // We had special arguments. Remove the trailing ','.
3027 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3029 // TODO: Handle the unknown settings better.
3030 // Warn about invalid options.
3031 // Check whether some option was given twice.
3033 preamble.registerAutomaticallyLoadedPackage("graphicx");
3036 else if (t.cs() == "footnote" ||
3037 (t.cs() == "thanks" && context.layout->intitle)) {
3039 context.check_layout(os);
3040 begin_inset(os, "Foot\n");
3041 os << "status collapsed\n\n";
3042 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3046 else if (t.cs() == "marginpar") {
3048 context.check_layout(os);
3049 begin_inset(os, "Marginal\n");
3050 os << "status collapsed\n\n";
3051 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3055 else if (t.cs() == "lstinline") {
3057 parse_listings(p, os, context, true);
3060 else if (t.cs() == "ensuremath") {
3062 context.check_layout(os);
3063 string const s = p.verbatim_item();
3064 //FIXME: this never triggers in UTF8
3065 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3068 output_ert_inset(os, "\\ensuremath{" + s + "}",
3072 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3073 if (preamble.titleLayoutFound()) {
3075 skip_spaces_braces(p);
3077 output_ert_inset(os, t.asInput(), context);
3080 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3081 context.check_layout(os);
3082 begin_command_inset(os, "toc", t.cs());
3084 skip_spaces_braces(p);
3085 if (t.cs() == "lstlistoflistings")
3086 preamble.registerAutomaticallyLoadedPackage("listings");
3089 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3090 context.check_layout(os);
3091 if (t.cs() == "listoffigures")
3092 begin_inset(os, "FloatList figure\n");
3094 begin_inset(os, "FloatList table\n");
3096 skip_spaces_braces(p);
3099 else if (t.cs() == "listof") {
3100 p.skip_spaces(true);
3101 string const name = p.get_token().cs();
3102 if (context.textclass.floats().typeExist(name)) {
3103 context.check_layout(os);
3104 begin_inset(os, "FloatList ");
3107 p.get_token(); // swallow second arg
3109 output_ert_inset(os, "\\listof{" + name + "}", context);
3112 else if ((where = is_known(t.cs(), known_text_font_families)))
3113 parse_text_attributes(p, os, FLAG_ITEM, outer,
3114 context, "\\family", context.font.family,
3115 known_coded_font_families[where - known_text_font_families]);
3117 else if ((where = is_known(t.cs(), known_text_font_series)))
3118 parse_text_attributes(p, os, FLAG_ITEM, outer,
3119 context, "\\series", context.font.series,
3120 known_coded_font_series[where - known_text_font_series]);
3122 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3123 parse_text_attributes(p, os, FLAG_ITEM, outer,
3124 context, "\\shape", context.font.shape,
3125 known_coded_font_shapes[where - known_text_font_shapes]);
3127 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3128 context.check_layout(os);
3129 TeXFont oldFont = context.font;
3130 context.font.init();
3131 context.font.size = oldFont.size;
3132 os << "\n\\family " << context.font.family << "\n";
3133 os << "\n\\series " << context.font.series << "\n";
3134 os << "\n\\shape " << context.font.shape << "\n";
3135 if (t.cs() == "textnormal") {
3136 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3137 output_font_change(os, context.font, oldFont);
3138 context.font = oldFont;
3140 eat_whitespace(p, os, context, false);
3143 else if (t.cs() == "textcolor") {
3144 // scheme is \textcolor{color name}{text}
3145 string const color = p.verbatim_item();
3146 // we only support the predefined colors of the color package
3147 if (color == "black" || color == "blue" || color == "cyan"
3148 || color == "green" || color == "magenta" || color == "red"
3149 || color == "white" || color == "yellow") {
3150 context.check_layout(os);
3151 os << "\n\\color " << color << "\n";
3152 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3153 context.check_layout(os);
3154 os << "\n\\color inherit\n";
3155 preamble.registerAutomaticallyLoadedPackage("color");
3157 // for custom defined colors
3158 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3161 else if (t.cs() == "underbar" || t.cs() == "uline") {
3162 // \underbar is not 100% correct (LyX outputs \uline
3163 // of ulem.sty). The difference is that \ulem allows
3164 // line breaks, and \underbar does not.
3165 // Do NOT handle \underline.
3166 // \underbar cuts through y, g, q, p etc.,
3167 // \underline does not.
3168 context.check_layout(os);
3169 os << "\n\\bar under\n";
3170 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3171 context.check_layout(os);
3172 os << "\n\\bar default\n";
3173 preamble.registerAutomaticallyLoadedPackage("ulem");
3176 else if (t.cs() == "sout") {
3177 context.check_layout(os);
3178 os << "\n\\strikeout on\n";
3179 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3180 context.check_layout(os);
3181 os << "\n\\strikeout default\n";
3182 preamble.registerAutomaticallyLoadedPackage("ulem");
3185 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3186 t.cs() == "emph" || t.cs() == "noun") {
3187 context.check_layout(os);
3188 os << "\n\\" << t.cs() << " on\n";
3189 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3190 context.check_layout(os);
3191 os << "\n\\" << t.cs() << " default\n";
3192 if (t.cs() == "uuline" || t.cs() == "uwave")
3193 preamble.registerAutomaticallyLoadedPackage("ulem");
3196 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3197 context.check_layout(os);
3198 string name = p.getArg('{', '}');
3199 string localtime = p.getArg('{', '}');
3200 preamble.registerAuthor(name);
3201 Author const & author = preamble.getAuthor(name);
3202 // from_asctime_utc() will fail if LyX decides to output the
3203 // time in the text language.
3204 time_t ptime = from_asctime_utc(localtime);
3205 if (ptime == static_cast<time_t>(-1)) {
3206 cerr << "Warning: Could not parse time `" << localtime
3207 << "´ for change tracking, using current time instead.\n";
3208 ptime = current_time();
3210 if (t.cs() == "lyxadded")
3211 os << "\n\\change_inserted ";
3213 os << "\n\\change_deleted ";
3214 os << author.bufferId() << ' ' << ptime << '\n';
3215 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3216 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3217 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3218 LaTeXPackages::isAvailable("xcolor");
3219 // No need to test for luatex, since luatex comes in
3220 // two flavours (dvi and pdf), like latex, and those
3221 // are detected by pdflatex.
3222 if (pdflatex || xetex) {
3224 preamble.registerAutomaticallyLoadedPackage("ulem");
3225 preamble.registerAutomaticallyLoadedPackage("xcolor");
3226 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3230 preamble.registerAutomaticallyLoadedPackage("dvipost");
3231 } else if (xcolorulem) {
3232 preamble.registerAutomaticallyLoadedPackage("ulem");
3233 preamble.registerAutomaticallyLoadedPackage("xcolor");
3238 else if (t.cs() == "textipa") {
3239 context.check_layout(os);
3240 begin_inset(os, "IPA\n");
3241 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3243 preamble.registerAutomaticallyLoadedPackage("tipa");
3244 preamble.registerAutomaticallyLoadedPackage("tipx");
3247 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3248 context.check_layout(os);
3249 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3250 os << "status open\n";
3251 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3256 else if (t.cs() == "textvertline") {
3257 // FIXME: This is not correct, \textvertline is higher than |
3263 else if (t.cs() == "tone" ) {
3264 context.check_layout(os);
3265 // register the tone package
3266 preamble.registerAutomaticallyLoadedPackage("tone");
3267 string content = trimSpaceAndEol(p.verbatim_item());
3268 string command = t.asInput() + "{" + content + "}";
3269 // some tones can be detected by unicodesymbols, some need special code
3270 if (is_known(content, known_tones)) {
3271 os << "\\IPAChar " << command << "\n";
3274 // try to see whether the string is in unicodesymbols
3278 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3279 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3280 termination, rem, &req);
3284 output_ert_inset(os, to_utf8(rem), context);
3285 for (set<string>::const_iterator it = req.begin();
3286 it != req.end(); ++it)
3287 preamble.registerAutomaticallyLoadedPackage(*it);
3289 // we did not find a non-ert version
3290 output_ert_inset(os, command, context);
3293 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3294 t.cs() == "vphantom") {
3295 context.check_layout(os);
3296 if (t.cs() == "phantom")
3297 begin_inset(os, "Phantom Phantom\n");
3298 if (t.cs() == "hphantom")
3299 begin_inset(os, "Phantom HPhantom\n");
3300 if (t.cs() == "vphantom")
3301 begin_inset(os, "Phantom VPhantom\n");
3302 os << "status open\n";
3303 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3308 else if (t.cs() == "href") {
3309 context.check_layout(os);
3310 string target = convert_command_inset_arg(p.verbatim_item());
3311 string name = convert_command_inset_arg(p.verbatim_item());
3313 size_t i = target.find(':');
3314 if (i != string::npos) {
3315 type = target.substr(0, i + 1);
3316 if (type == "mailto:" || type == "file:")
3317 target = target.substr(i + 1);
3318 // handle the case that name is equal to target, except of "http://"
3319 else if (target.substr(i + 3) == name && type == "http:")
3322 begin_command_inset(os, "href", "href");
3324 os << "name \"" << name << "\"\n";
3325 os << "target \"" << target << "\"\n";
3326 if (type == "mailto:" || type == "file:")
3327 os << "type \"" << type << "\"\n";
3329 skip_spaces_braces(p);
3332 else if (t.cs() == "lyxline") {
3333 // swallow size argument (it is not used anyway)
3335 if (!context.atParagraphStart()) {
3336 // so our line is in the middle of a paragraph
3337 // we need to add a new line, lest this line
3338 // follow the other content on that line and
3339 // run off the side of the page
3340 // FIXME: This may create an empty paragraph,
3341 // but without that it would not be
3342 // possible to set noindent below.
3343 // Fortunately LaTeX does not care
3344 // about the empty paragraph.
3345 context.new_paragraph(os);
3347 if (preamble.indentParagraphs()) {
3348 // we need to unindent, lest the line be too long
3349 context.add_par_extra_stuff("\\noindent\n");
3351 context.check_layout(os);
3352 begin_command_inset(os, "line", "rule");
3353 os << "offset \"0.5ex\"\n"
3354 "width \"100line%\"\n"
3359 else if (t.cs() == "rule") {
3360 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3361 string const width = p.getArg('{', '}');
3362 string const thickness = p.getArg('{', '}');
3363 context.check_layout(os);
3364 begin_command_inset(os, "line", "rule");
3365 if (!offset.empty())
3366 os << "offset \"" << translate_len(offset) << "\"\n";
3367 os << "width \"" << translate_len(width) << "\"\n"
3368 "height \"" << translate_len(thickness) << "\"\n";
3372 else if (is_known(t.cs(), known_phrases) ||
3373 (t.cs() == "protect" &&
3374 p.next_token().cat() == catEscape &&
3375 is_known(p.next_token().cs(), known_phrases))) {
3376 // LyX sometimes puts a \protect in front, so we have to ignore it
3377 // FIXME: This needs to be changed when bug 4752 is fixed.
3379 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3381 context.check_layout(os);
3382 os << known_coded_phrases[where - known_phrases];
3383 skip_spaces_braces(p);
3386 // handle refstyle first to catch \eqref which can also occur
3387 // without refstyle. Only recognize these commands if
3388 // refstyle.sty was found in the preamble (otherwise \eqref
3389 // and user defined ref commands could be misdetected).
3390 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3391 preamble.refstyle()) {
3392 context.check_layout(os);
3393 begin_command_inset(os, "ref", "formatted");
3394 os << "reference \"";
3395 os << known_refstyle_prefixes[where - known_refstyle_commands]
3397 os << convert_command_inset_arg(p.verbatim_item())
3400 preamble.registerAutomaticallyLoadedPackage("refstyle");
3403 // if refstyle is used, we must not convert \prettyref to a
3404 // formatted reference, since that would result in a refstyle command.
3405 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3406 (t.cs() != "prettyref" || !preamble.refstyle())) {
3407 string const opt = p.getOpt();
3409 context.check_layout(os);
3410 begin_command_inset(os, "ref",
3411 known_coded_ref_commands[where - known_ref_commands]);
3412 os << "reference \""
3413 << convert_command_inset_arg(p.verbatim_item())
3416 if (t.cs() == "vref" || t.cs() == "vpageref")
3417 preamble.registerAutomaticallyLoadedPackage("varioref");
3418 else if (t.cs() == "prettyref")
3419 preamble.registerAutomaticallyLoadedPackage("prettyref");
3421 // LyX does not yet support optional arguments of ref commands
3422 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3423 p.verbatim_item() + '}', context);
3427 else if (use_natbib &&
3428 is_known(t.cs(), known_natbib_commands) &&
3429 ((t.cs() != "citefullauthor" &&
3430 t.cs() != "citeyear" &&
3431 t.cs() != "citeyearpar") ||
3432 p.next_token().asInput() != "*")) {
3433 context.check_layout(os);
3434 string command = t.cs();
3435 if (p.next_token().asInput() == "*") {
3439 if (command == "citefullauthor")
3440 // alternative name for "\\citeauthor*"
3441 command = "citeauthor*";
3443 // text before the citation
3445 // text after the citation
3447 get_cite_arguments(p, true, before, after);
3449 if (command == "cite") {
3450 // \cite without optional argument means
3451 // \citet, \cite with at least one optional
3452 // argument means \citep.
3453 if (before.empty() && after.empty())
3458 if (before.empty() && after == "[]")
3459 // avoid \citet[]{a}
3461 else if (before == "[]" && after == "[]") {
3462 // avoid \citet[][]{a}
3466 // remove the brackets around after and before
3467 if (!after.empty()) {
3469 after.erase(after.length() - 1, 1);
3470 after = convert_command_inset_arg(after);
3472 if (!before.empty()) {
3474 before.erase(before.length() - 1, 1);
3475 before = convert_command_inset_arg(before);
3477 begin_command_inset(os, "citation", command);
3478 os << "after " << '"' << after << '"' << "\n";
3479 os << "before " << '"' << before << '"' << "\n";
3481 << convert_command_inset_arg(p.verbatim_item())
3484 // Need to set the cite engine if natbib is loaded by
3485 // the document class directly
3486 if (preamble.citeEngine() == "basic")
3487 preamble.citeEngine("natbib");
3490 else if (use_jurabib &&
3491 is_known(t.cs(), known_jurabib_commands) &&
3492 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3493 context.check_layout(os);
3494 string command = t.cs();
3495 if (p.next_token().asInput() == "*") {
3499 char argumentOrder = '\0';
3500 vector<string> const options =
3501 preamble.getPackageOptions("jurabib");
3502 if (find(options.begin(), options.end(),
3503 "natbiborder") != options.end())
3504 argumentOrder = 'n';
3505 else if (find(options.begin(), options.end(),
3506 "jurabiborder") != options.end())
3507 argumentOrder = 'j';
3509 // text before the citation
3511 // text after the citation
3513 get_cite_arguments(p, argumentOrder != 'j', before, after);
3515 string const citation = p.verbatim_item();
3516 if (!before.empty() && argumentOrder == '\0') {
3517 cerr << "Warning: Assuming argument order "
3518 "of jurabib version 0.6 for\n'"
3519 << command << before << after << '{'
3520 << citation << "}'.\n"
3521 "Add 'jurabiborder' to the jurabib "
3522 "package options if you used an\n"
3523 "earlier jurabib version." << endl;
3525 if (!after.empty()) {
3527 after.erase(after.length() - 1, 1);
3529 if (!before.empty()) {
3531 before.erase(before.length() - 1, 1);
3533 begin_command_inset(os, "citation", command);
3534 os << "after " << '"' << after << '"' << "\n";
3535 os << "before " << '"' << before << '"' << "\n";
3536 os << "key " << '"' << citation << '"' << "\n";
3538 // Need to set the cite engine if jurabib is loaded by
3539 // the document class directly
3540 if (preamble.citeEngine() == "basic")
3541 preamble.citeEngine("jurabib");
3544 else if (t.cs() == "cite"
3545 || t.cs() == "nocite") {
3546 context.check_layout(os);
3547 string after = convert_command_inset_arg(p.getArg('[', ']'));
3548 string key = convert_command_inset_arg(p.verbatim_item());
3549 // store the case that it is "\nocite{*}" to use it later for
3552 begin_command_inset(os, "citation", t.cs());
3553 os << "after " << '"' << after << '"' << "\n";
3554 os << "key " << '"' << key << '"' << "\n";
3556 } else if (t.cs() == "nocite")
3560 else if (t.cs() == "index" ||
3561 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3562 context.check_layout(os);
3563 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3564 p.getArg('[', ']') : "";
3565 string const kind = arg.empty() ? "idx" : arg;
3566 begin_inset(os, "Index ");
3567 os << kind << "\nstatus collapsed\n";
3568 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3571 preamble.registerAutomaticallyLoadedPackage("splitidx");
3574 else if (t.cs() == "nomenclature") {
3575 context.check_layout(os);
3576 begin_command_inset(os, "nomenclature", "nomenclature");
3577 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3578 if (!prefix.empty())
3579 os << "prefix " << '"' << prefix << '"' << "\n";
3580 os << "symbol " << '"'
3581 << convert_command_inset_arg(p.verbatim_item());
3582 os << "\"\ndescription \""
3583 << convert_command_inset_arg(p.verbatim_item())
3586 preamble.registerAutomaticallyLoadedPackage("nomencl");
3589 else if (t.cs() == "label") {
3590 context.check_layout(os);
3591 begin_command_inset(os, "label", "label");
3593 << convert_command_inset_arg(p.verbatim_item())
3598 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3599 context.check_layout(os);
3600 string commandname = t.cs();
3602 if (p.next_token().asInput() == "*") {
3607 begin_command_inset(os, "index_print", commandname);
3608 string const indexname = p.getArg('[', ']');
3610 if (indexname.empty())
3611 os << "type \"idx\"\n";
3613 os << "type \"" << indexname << "\"\n";
3616 skip_spaces_braces(p);
3617 preamble.registerAutomaticallyLoadedPackage("makeidx");
3618 if (preamble.use_indices() == "true")
3619 preamble.registerAutomaticallyLoadedPackage("splitidx");
3622 else if (t.cs() == "printnomenclature") {
3624 string width_type = "";
3625 context.check_layout(os);
3626 begin_command_inset(os, "nomencl_print", "printnomenclature");
3627 // case of a custom width
3629 width = p.getArg('[', ']');
3630 width = translate_len(width);
3631 width_type = "custom";
3633 // case of no custom width
3634 // the case of no custom width but the width set
3635 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3636 // because the user could have set anything, not only the width
3637 // of the longest label (which would be width_type = "auto")
3638 string label = convert_command_inset_arg(p.getArg('{', '}'));
3639 if (label.empty() && width_type.empty())
3640 width_type = "none";
3641 os << "set_width \"" << width_type << "\"\n";
3642 if (width_type == "custom")
3643 os << "width \"" << width << '\"';
3645 skip_spaces_braces(p);
3646 preamble.registerAutomaticallyLoadedPackage("nomencl");
3649 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3650 context.check_layout(os);
3651 begin_inset(os, "script ");
3652 os << t.cs().substr(4) << '\n';
3653 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3655 if (t.cs() == "textsubscript")
3656 preamble.registerAutomaticallyLoadedPackage("subscript");
3659 else if ((where = is_known(t.cs(), known_quotes))) {
3660 context.check_layout(os);
3661 begin_inset(os, "Quotes ");
3662 os << known_coded_quotes[where - known_quotes];
3664 // LyX adds {} after the quote, so we have to eat
3665 // spaces here if there are any before a possible
3667 eat_whitespace(p, os, context, false);
3671 else if ((where = is_known(t.cs(), known_sizes)) &&
3672 context.new_layout_allowed) {
3673 context.check_layout(os);
3674 TeXFont const oldFont = context.font;
3675 context.font.size = known_coded_sizes[where - known_sizes];
3676 output_font_change(os, oldFont, context.font);
3677 eat_whitespace(p, os, context, false);
3680 else if ((where = is_known(t.cs(), known_font_families)) &&
3681 context.new_layout_allowed) {
3682 context.check_layout(os);
3683 TeXFont const oldFont = context.font;
3684 context.font.family =
3685 known_coded_font_families[where - known_font_families];
3686 output_font_change(os, oldFont, context.font);
3687 eat_whitespace(p, os, context, false);
3690 else if ((where = is_known(t.cs(), known_font_series)) &&
3691 context.new_layout_allowed) {
3692 context.check_layout(os);
3693 TeXFont const oldFont = context.font;
3694 context.font.series =
3695 known_coded_font_series[where - known_font_series];
3696 output_font_change(os, oldFont, context.font);
3697 eat_whitespace(p, os, context, false);
3700 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3701 context.new_layout_allowed) {
3702 context.check_layout(os);
3703 TeXFont const oldFont = context.font;
3704 context.font.shape =
3705 known_coded_font_shapes[where - known_font_shapes];
3706 output_font_change(os, oldFont, context.font);
3707 eat_whitespace(p, os, context, false);
3709 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3710 context.new_layout_allowed) {
3711 context.check_layout(os);
3712 TeXFont const oldFont = context.font;
3713 context.font.init();
3714 context.font.size = oldFont.size;
3715 context.font.family =
3716 known_coded_font_families[where - known_old_font_families];
3717 output_font_change(os, oldFont, context.font);
3718 eat_whitespace(p, os, context, false);
3721 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3722 context.new_layout_allowed) {
3723 context.check_layout(os);
3724 TeXFont const oldFont = context.font;
3725 context.font.init();
3726 context.font.size = oldFont.size;
3727 context.font.series =
3728 known_coded_font_series[where - known_old_font_series];
3729 output_font_change(os, oldFont, context.font);
3730 eat_whitespace(p, os, context, false);
3733 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3734 context.new_layout_allowed) {
3735 context.check_layout(os);
3736 TeXFont const oldFont = context.font;
3737 context.font.init();
3738 context.font.size = oldFont.size;
3739 context.font.shape =
3740 known_coded_font_shapes[where - known_old_font_shapes];
3741 output_font_change(os, oldFont, context.font);
3742 eat_whitespace(p, os, context, false);
3745 else if (t.cs() == "selectlanguage") {
3746 context.check_layout(os);
3747 // save the language for the case that a
3748 // \foreignlanguage is used
3749 context.font.language = babel2lyx(p.verbatim_item());
3750 os << "\n\\lang " << context.font.language << "\n";
3753 else if (t.cs() == "foreignlanguage") {
3754 string const lang = babel2lyx(p.verbatim_item());
3755 parse_text_attributes(p, os, FLAG_ITEM, outer,
3757 context.font.language, lang);
3760 else if (prefixIs(t.cs(), "text")
3761 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3762 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3764 // We have to output the whole command if it has an option
3765 // because LyX doesn't support this yet, see bug #8214,
3766 // only if there is a single option specifying a variant, we can handle it.
3768 string langopts = p.getOpt();
3769 // check if the option contains a variant, if yes, extract it
3770 string::size_type pos_var = langopts.find("variant");
3771 string::size_type i = langopts.find(',');
3772 string::size_type k = langopts.find('=', pos_var);
3773 if (pos_var != string::npos && i == string::npos) {
3775 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3776 lang = preamble.polyglossia2lyx(variant);
3777 parse_text_attributes(p, os, FLAG_ITEM, outer,
3779 context.font.language, lang);
3781 output_ert_inset(os, t.asInput() + langopts, context);
3783 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3784 parse_text_attributes(p, os, FLAG_ITEM, outer,
3786 context.font.language, lang);
3790 else if (t.cs() == "inputencoding") {
3791 // nothing to write here
3792 string const enc = subst(p.verbatim_item(), "\n", " ");
3793 p.setEncoding(enc, Encoding::inputenc);
3796 else if ((where = is_known(t.cs(), known_special_chars))) {
3797 context.check_layout(os);
3798 os << known_coded_special_chars[where - known_special_chars];
3799 skip_spaces_braces(p);
3802 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3803 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3804 context.check_layout(os);
3805 os << "\\SpecialChar \\" << t.cs()
3806 << p.get_token().asInput() << '\n';
3809 else if (t.cs() == "textquotedbl") {
3810 context.check_layout(os);
3815 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3816 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3817 || t.cs() == "%" || t.cs() == "-") {
3818 context.check_layout(os);
3820 os << "\\SpecialChar \\-\n";
3825 else if (t.cs() == "char") {
3826 context.check_layout(os);
3827 if (p.next_token().character() == '`') {
3829 if (p.next_token().cs() == "\"") {
3834 output_ert_inset(os, "\\char`", context);
3837 output_ert_inset(os, "\\char", context);
3841 else if (t.cs() == "verb") {
3842 context.check_layout(os);
3843 // set catcodes to verbatim early, just in case.
3844 p.setCatcodes(VERBATIM_CATCODES);
3845 string delim = p.get_token().asInput();
3846 Parser::Arg arg = p.verbatimStuff(delim);
3848 output_ert_inset(os, "\\verb" + delim
3849 + arg.second + delim, context);
3851 cerr << "invalid \\verb command. Skipping" << endl;
3854 // Problem: \= creates a tabstop inside the tabbing environment
3855 // and else an accent. In the latter case we really would want
3856 // \={o} instead of \= o.
3857 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3858 output_ert_inset(os, t.asInput(), context);
3860 else if (t.cs() == "\\") {
3861 context.check_layout(os);
3863 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3864 else if (p.next_token().asInput() == "*") {
3866 // getOpt() eats the following space if there
3867 // is no optional argument, but that is OK
3868 // here since it has no effect in the output.
3869 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3872 begin_inset(os, "Newline newline");
3877 else if (t.cs() == "newline" ||
3878 (t.cs() == "linebreak" && !p.hasOpt())) {
3879 context.check_layout(os);
3880 begin_inset(os, "Newline ");
3883 skip_spaces_braces(p);
3886 else if (t.cs() == "input" || t.cs() == "include"
3887 || t.cs() == "verbatiminput") {
3888 string name = t.cs();
3889 if (t.cs() == "verbatiminput"
3890 && p.next_token().asInput() == "*")
3891 name += p.get_token().asInput();
3892 context.check_layout(os);
3893 string filename(normalize_filename(p.getArg('{', '}')));
3894 string const path = getMasterFilePath(true);
3895 // We want to preserve relative / absolute filenames,
3896 // therefore path is only used for testing
3897 if ((t.cs() == "include" || t.cs() == "input") &&
3898 !makeAbsPath(filename, path).exists()) {
3899 // The file extension is probably missing.
3900 // Now try to find it out.
3901 string const tex_name =
3902 find_file(filename, path,
3903 known_tex_extensions);
3904 if (!tex_name.empty())
3905 filename = tex_name;
3907 bool external = false;
3909 if (makeAbsPath(filename, path).exists()) {
3910 string const abstexname =
3911 makeAbsPath(filename, path).absFileName();
3912 string const absfigname =
3913 changeExtension(abstexname, ".fig");
3914 fix_child_filename(filename);
3915 string const lyxname =
3916 changeExtension(filename, ".lyx");
3917 string const abslyxname = makeAbsPath(
3918 lyxname, getParentFilePath(false)).absFileName();
3920 if (!skipChildren())
3921 external = FileName(absfigname).exists();
3922 if (t.cs() == "input" && !skipChildren()) {
3923 string const ext = getExtension(abstexname);
3925 // Combined PS/LaTeX:
3926 // x.eps, x.pstex_t (old xfig)
3927 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3928 FileName const absepsname(
3929 changeExtension(abstexname, ".eps"));
3930 FileName const abspstexname(
3931 changeExtension(abstexname, ".pstex"));
3932 bool const xfigeps =
3933 (absepsname.exists() ||
3934 abspstexname.exists()) &&
3937 // Combined PDF/LaTeX:
3938 // x.pdf, x.pdftex_t (old xfig)
3939 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3940 FileName const abspdfname(
3941 changeExtension(abstexname, ".pdf"));
3942 bool const xfigpdf =
3943 abspdfname.exists() &&
3944 (ext == "pdftex_t" || ext == "pdf_t");
3948 // Combined PS/PDF/LaTeX:
3949 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3950 string const absbase2(
3951 removeExtension(abstexname) + "_pspdftex");
3952 FileName const abseps2name(
3953 addExtension(absbase2, ".eps"));
3954 FileName const abspdf2name(
3955 addExtension(absbase2, ".pdf"));
3956 bool const xfigboth =
3957 abspdf2name.exists() &&
3958 abseps2name.exists() && ext == "pspdftex";
3960 xfig = xfigpdf || xfigeps || xfigboth;
3961 external = external && xfig;
3964 outname = changeExtension(filename, ".fig");
3965 FileName abssrc(changeExtension(abstexname, ".fig"));
3966 copy_file(abssrc, outname);
3968 // Don't try to convert, the result
3969 // would be full of ERT.
3971 FileName abssrc(abstexname);
3972 copy_file(abssrc, outname);
3973 } else if (t.cs() != "verbatiminput" &&
3975 tex2lyx(abstexname, FileName(abslyxname),
3978 // no need to call copy_file
3979 // tex2lyx creates the file
3982 FileName abssrc(abstexname);
3983 copy_file(abssrc, outname);
3986 cerr << "Warning: Could not find included file '"
3987 << filename << "'." << endl;
3991 begin_inset(os, "External\n");
3992 os << "\ttemplate XFig\n"
3993 << "\tfilename " << outname << '\n';
3994 registerExternalTemplatePackages("XFig");
3996 begin_command_inset(os, "include", name);
3997 outname = subst(outname, "\"", "\\\"");
3998 os << "preview false\n"
3999 "filename \"" << outname << "\"\n";
4000 if (t.cs() == "verbatiminput")
4001 preamble.registerAutomaticallyLoadedPackage("verbatim");
4006 else if (t.cs() == "bibliographystyle") {
4007 // store new bibliographystyle
4008 bibliographystyle = p.verbatim_item();
4009 // If any other command than \bibliography, \addcontentsline
4010 // and \nocite{*} follows, we need to output the style
4011 // (because it might be used by that command).
4012 // Otherwise, it will automatically be output by LyX.
4015 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4016 if (t2.cat() == catBegin)
4018 if (t2.cat() != catEscape)
4020 if (t2.cs() == "nocite") {
4021 if (p.getArg('{', '}') == "*")
4023 } else if (t2.cs() == "bibliography")
4025 else if (t2.cs() == "phantomsection") {
4029 else if (t2.cs() == "addcontentsline") {
4030 // get the 3 arguments of \addcontentsline
4033 contentslineContent = p.getArg('{', '}');
4034 // if the last argument is not \refname we must output
4035 if (contentslineContent == "\\refname")
4042 output_ert_inset(os,
4043 "\\bibliographystyle{" + bibliographystyle + '}',
4048 else if (t.cs() == "phantomsection") {
4049 // we only support this if it occurs between
4050 // \bibliographystyle and \bibliography
4051 if (bibliographystyle.empty())
4052 output_ert_inset(os, "\\phantomsection", context);
4055 else if (t.cs() == "addcontentsline") {
4056 context.check_layout(os);
4057 // get the 3 arguments of \addcontentsline
4058 string const one = p.getArg('{', '}');
4059 string const two = p.getArg('{', '}');
4060 string const three = p.getArg('{', '}');
4061 // only if it is a \refname, we support if for the bibtex inset
4062 if (contentslineContent != "\\refname") {
4063 output_ert_inset(os,
4064 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4069 else if (t.cs() == "bibliography") {
4070 context.check_layout(os);
4072 begin_command_inset(os, "bibtex", "bibtex");
4073 if (!btprint.empty()) {
4074 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4075 // clear the string because the next BibTeX inset can be without the
4076 // \nocite{*} option
4079 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4080 // Do we have addcontentsline?
4081 if (contentslineContent == "\\refname") {
4082 BibOpts = "bibtotoc";
4083 // clear string because next BibTeX inset can be without addcontentsline
4084 contentslineContent.clear();
4086 // Do we have a bibliographystyle set?
4087 if (!bibliographystyle.empty()) {
4088 if (BibOpts.empty())
4089 BibOpts = bibliographystyle;
4091 BibOpts = BibOpts + ',' + bibliographystyle;
4092 // clear it because each bibtex entry has its style
4093 // and we need an empty string to handle \phantomsection
4094 bibliographystyle.clear();
4096 os << "options " << '"' << BibOpts << '"' << "\n";
4100 else if (t.cs() == "parbox") {
4101 // Test whether this is an outer box of a shaded box
4103 // swallow arguments
4104 while (p.hasOpt()) {
4106 p.skip_spaces(true);
4109 p.skip_spaces(true);
4111 if (p.next_token().cat() == catBegin)
4113 p.skip_spaces(true);
4114 Token to = p.get_token();
4115 bool shaded = false;
4116 if (to.asInput() == "\\begin") {
4117 p.skip_spaces(true);
4118 if (p.getArg('{', '}') == "shaded")
4123 parse_outer_box(p, os, FLAG_ITEM, outer,
4124 context, "parbox", "shaded");
4126 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4130 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4131 t.cs() == "shadowbox" || t.cs() == "doublebox")
4132 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4134 else if (t.cs() == "framebox") {
4135 if (p.next_token().character() == '(') {
4136 //the syntax is: \framebox(x,y)[position]{content}
4137 string arg = t.asInput();
4138 arg += p.getFullParentheseArg();
4139 arg += p.getFullOpt();
4140 eat_whitespace(p, os, context, false);
4141 output_ert_inset(os, arg + '{', context);
4142 parse_text(p, os, FLAG_ITEM, outer, context);
4143 output_ert_inset(os, "}", context);
4145 string special = p.getFullOpt();
4146 special += p.getOpt();
4147 // LyX does not yet support \framebox without any option
4148 if (!special.empty())
4149 parse_outer_box(p, os, FLAG_ITEM, outer,
4150 context, t.cs(), special);
4152 eat_whitespace(p, os, context, false);
4153 output_ert_inset(os, "\\framebox{", context);
4154 parse_text(p, os, FLAG_ITEM, outer, context);
4155 output_ert_inset(os, "}", context);
4160 //\makebox() is part of the picture environment and different from \makebox{}
4161 //\makebox{} will be parsed by parse_box
4162 else if (t.cs() == "makebox") {
4163 if (p.next_token().character() == '(') {
4164 //the syntax is: \makebox(x,y)[position]{content}
4165 string arg = t.asInput();
4166 arg += p.getFullParentheseArg();
4167 arg += p.getFullOpt();
4168 eat_whitespace(p, os, context, false);
4169 output_ert_inset(os, arg + '{', context);
4170 parse_text(p, os, FLAG_ITEM, outer, context);
4171 output_ert_inset(os, "}", context);
4173 //the syntax is: \makebox[width][position]{content}
4174 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4178 else if (t.cs() == "smallskip" ||
4179 t.cs() == "medskip" ||
4180 t.cs() == "bigskip" ||
4181 t.cs() == "vfill") {
4182 context.check_layout(os);
4183 begin_inset(os, "VSpace ");
4186 skip_spaces_braces(p);
4189 else if ((where = is_known(t.cs(), known_spaces))) {
4190 context.check_layout(os);
4191 begin_inset(os, "space ");
4192 os << '\\' << known_coded_spaces[where - known_spaces]
4195 // LaTeX swallows whitespace after all spaces except
4196 // "\\,". We have to do that here, too, because LyX
4197 // adds "{}" which would make the spaces significant.
4199 eat_whitespace(p, os, context, false);
4200 // LyX adds "{}" after all spaces except "\\ " and
4201 // "\\,", so we have to remove "{}".
4202 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4203 // remove the braces after "\\,", too.
4208 else if (t.cs() == "newpage" ||
4209 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4210 t.cs() == "clearpage" ||
4211 t.cs() == "cleardoublepage") {
4212 context.check_layout(os);
4213 begin_inset(os, "Newpage ");
4216 skip_spaces_braces(p);
4219 else if (t.cs() == "DeclareRobustCommand" ||
4220 t.cs() == "DeclareRobustCommandx" ||
4221 t.cs() == "newcommand" ||
4222 t.cs() == "newcommandx" ||
4223 t.cs() == "providecommand" ||
4224 t.cs() == "providecommandx" ||
4225 t.cs() == "renewcommand" ||
4226 t.cs() == "renewcommandx") {
4227 // DeclareRobustCommand, DeclareRobustCommandx,
4228 // providecommand and providecommandx could be handled
4229 // by parse_command(), but we need to call
4230 // add_known_command() here.
4231 string name = t.asInput();
4232 if (p.next_token().asInput() == "*") {
4233 // Starred form. Eat '*'
4237 string const command = p.verbatim_item();
4238 string const opt1 = p.getFullOpt();
4239 string const opt2 = p.getFullOpt();
4240 add_known_command(command, opt1, !opt2.empty());
4241 string const ert = name + '{' + command + '}' +
4243 '{' + p.verbatim_item() + '}';
4245 if (t.cs() == "DeclareRobustCommand" ||
4246 t.cs() == "DeclareRobustCommandx" ||
4247 t.cs() == "providecommand" ||
4248 t.cs() == "providecommandx" ||
4249 name[name.length()-1] == '*')
4250 output_ert_inset(os, ert, context);
4252 context.check_layout(os);
4253 begin_inset(os, "FormulaMacro");
4259 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4260 // let could be handled by parse_command(),
4261 // but we need to call add_known_command() here.
4262 string ert = t.asInput();
4265 if (p.next_token().cat() == catBegin) {
4266 name = p.verbatim_item();
4267 ert += '{' + name + '}';
4269 name = p.verbatim_item();
4274 if (p.next_token().cat() == catBegin) {
4275 command = p.verbatim_item();
4276 ert += '{' + command + '}';
4278 command = p.verbatim_item();
4281 // If command is known, make name known too, to parse
4282 // its arguments correctly. For this reason we also
4283 // have commands in syntax.default that are hardcoded.
4284 CommandMap::iterator it = known_commands.find(command);
4285 if (it != known_commands.end())
4286 known_commands[t.asInput()] = it->second;
4287 output_ert_inset(os, ert, context);
4290 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4291 bool starred = false;
4292 if (p.next_token().asInput() == "*") {
4296 string name = t.asInput();
4297 string const length = p.verbatim_item();
4300 bool valid = splitLatexLength(length, valstring, unit);
4301 bool known_hspace = false;
4302 bool known_vspace = false;
4303 bool known_unit = false;
4306 istringstream iss(valstring);
4309 if (t.cs()[0] == 'h') {
4310 if (unit == "\\fill") {
4315 known_hspace = true;
4318 if (unit == "\\smallskipamount") {
4320 known_vspace = true;
4321 } else if (unit == "\\medskipamount") {
4323 known_vspace = true;
4324 } else if (unit == "\\bigskipamount") {
4326 known_vspace = true;
4327 } else if (unit == "\\fill") {
4329 known_vspace = true;
4333 if (!known_hspace && !known_vspace) {
4334 switch (unitFromString(unit)) {
4355 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4356 // Literal horizontal length or known variable
4357 context.check_layout(os);
4358 begin_inset(os, "space ");
4366 if (known_unit && !known_hspace)
4368 << translate_len(length);
4370 } else if (known_unit || known_vspace) {
4371 // Literal vertical length or known variable
4372 context.check_layout(os);
4373 begin_inset(os, "VSpace ");
4381 // LyX can't handle other length variables in Inset VSpace/space
4386 output_ert_inset(os, name + '{' + unit + '}', context);
4387 else if (value == -1.0)
4388 output_ert_inset(os, name + "{-" + unit + '}', context);
4390 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4392 output_ert_inset(os, name + '{' + length + '}', context);
4396 // The single '=' is meant here.
4397 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4399 context.check_layout(os);
4400 begin_inset(os, "Flex ");
4401 os << to_utf8(newinsetlayout->name()) << '\n'
4402 << "status collapsed\n";
4403 if (newinsetlayout->isPassThru()) {
4404 // set catcodes to verbatim early, just in case.
4405 p.setCatcodes(VERBATIM_CATCODES);
4406 string delim = p.get_token().asInput();
4408 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4409 //FIXME: handle error condition
4410 string const arg = p.verbatimStuff("}").second;
4411 Context newcontext(true, context.textclass);
4412 if (newinsetlayout->forcePlainLayout())
4413 newcontext.layout = &context.textclass.plainLayout();
4414 output_ert(os, arg, newcontext);
4417 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4421 else if (t.cs() == "includepdf") {
4423 string const arg = p.getArg('[', ']');
4424 map<string, string> opts;
4425 vector<string> keys;
4426 split_map(arg, opts, keys);
4427 string name = normalize_filename(p.verbatim_item());
4428 string const path = getMasterFilePath(true);
4429 // We want to preserve relative / absolute filenames,
4430 // therefore path is only used for testing
4431 if (!makeAbsPath(name, path).exists()) {
4432 // The file extension is probably missing.
4433 // Now try to find it out.
4434 char const * const pdfpages_format[] = {"pdf", 0};
4435 string const pdftex_name =
4436 find_file(name, path, pdfpages_format);
4437 if (!pdftex_name.empty()) {
4442 FileName const absname = makeAbsPath(name, path);
4443 if (absname.exists())
4445 fix_child_filename(name);
4446 copy_file(absname, name);
4448 cerr << "Warning: Could not find file '"
4449 << name << "'." << endl;
4451 context.check_layout(os);
4452 begin_inset(os, "External\n\ttemplate ");
4453 os << "PDFPages\n\tfilename "
4455 // parse the options
4456 if (opts.find("pages") != opts.end())
4457 os << "\textra LaTeX \"pages="
4458 << opts["pages"] << "\"\n";
4459 if (opts.find("angle") != opts.end())
4460 os << "\trotateAngle "
4461 << opts["angle"] << '\n';
4462 if (opts.find("origin") != opts.end()) {
4464 string const opt = opts["origin"];
4465 if (opt == "tl") ss << "topleft";
4466 if (opt == "bl") ss << "bottomleft";
4467 if (opt == "Bl") ss << "baselineleft";
4468 if (opt == "c") ss << "center";
4469 if (opt == "tc") ss << "topcenter";
4470 if (opt == "bc") ss << "bottomcenter";
4471 if (opt == "Bc") ss << "baselinecenter";
4472 if (opt == "tr") ss << "topright";
4473 if (opt == "br") ss << "bottomright";
4474 if (opt == "Br") ss << "baselineright";
4475 if (!ss.str().empty())
4476 os << "\trotateOrigin " << ss.str() << '\n';
4478 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4480 if (opts.find("width") != opts.end())
4482 << translate_len(opts["width"]) << '\n';
4483 if (opts.find("height") != opts.end())
4485 << translate_len(opts["height"]) << '\n';
4486 if (opts.find("keepaspectratio") != opts.end())
4487 os << "\tkeepAspectRatio\n";
4489 context.check_layout(os);
4490 registerExternalTemplatePackages("PDFPages");
4493 else if (t.cs() == "loadgame") {
4495 string name = normalize_filename(p.verbatim_item());
4496 string const path = getMasterFilePath(true);
4497 // We want to preserve relative / absolute filenames,
4498 // therefore path is only used for testing
4499 if (!makeAbsPath(name, path).exists()) {
4500 // The file extension is probably missing.
4501 // Now try to find it out.
4502 char const * const lyxskak_format[] = {"fen", 0};
4503 string const lyxskak_name =
4504 find_file(name, path, lyxskak_format);
4505 if (!lyxskak_name.empty())
4506 name = lyxskak_name;
4508 FileName const absname = makeAbsPath(name, path);
4509 if (absname.exists())
4511 fix_child_filename(name);
4512 copy_file(absname, name);
4514 cerr << "Warning: Could not find file '"
4515 << name << "'." << endl;
4516 context.check_layout(os);
4517 begin_inset(os, "External\n\ttemplate ");
4518 os << "ChessDiagram\n\tfilename "
4521 context.check_layout(os);
4522 // after a \loadgame follows a \showboard
4523 if (p.get_token().asInput() == "showboard")
4525 registerExternalTemplatePackages("ChessDiagram");
4529 // try to see whether the string is in unicodesymbols
4530 // Only use text mode commands, since we are in text mode here,
4531 // and math commands may be invalid (bug 6797)
4532 string name = t.asInput();
4533 // handle the dingbats and Cyrillic
4534 if (name == "\\ding" || name == "\\textcyr")
4535 name = name + '{' + p.getArg('{', '}') + '}';
4536 // handle the ifsym characters
4537 else if (name == "\\textifsymbol") {
4538 string const optif = p.getFullOpt();
4539 string const argif = p.getArg('{', '}');
4540 name = name + optif + '{' + argif + '}';
4542 // handle the \ascii characters
4543 // the case of \ascii within braces, as LyX outputs it, is already
4544 // handled for t.cat() == catBegin
4545 else if (name == "\\ascii") {
4546 // the code is "\asci\xxx"
4547 name = "{" + name + p.get_token().asInput() + "}";
4550 // handle some TIPA special characters
4551 else if (preamble.isPackageUsed("tipa")) {
4552 if (name == "\\textglobfall") {
4555 } else if (name == "\\s") {
4556 // fromLaTeXCommand() does not yet
4557 // recognize tipa short cuts
4558 name = "\\textsyllabic";
4559 } else if (name == "\\=" &&
4560 p.next_token().asInput() == "*") {
4561 // fromLaTeXCommand() does not yet
4562 // recognize tipa short cuts
4565 } else if (name == "\\textdoublevertline") {
4566 // FIXME: This is not correct,
4567 // \textvertline is higher than \textbardbl
4568 name = "\\textbardbl";
4570 } else if (name == "\\!" ) {
4571 if (p.next_token().asInput() == "b") {
4572 p.get_token(); // eat 'b'
4575 } else if (p.next_token().asInput() == "d") {
4579 } else if (p.next_token().asInput() == "g") {
4583 } else if (p.next_token().asInput() == "G") {
4585 name = "\\texthtscg";
4587 } else if (p.next_token().asInput() == "j") {
4589 name = "\\texthtbardotlessj";
4591 } else if (p.next_token().asInput() == "o") {
4593 name = "\\textbullseye";
4596 } else if (name == "\\*" ) {
4597 if (p.next_token().asInput() == "k") {
4599 name = "\\textturnk";
4601 } else if (p.next_token().asInput() == "r") {
4602 p.get_token(); // eat 'b'
4603 name = "\\textturnr";
4605 } else if (p.next_token().asInput() == "t") {
4607 name = "\\textturnt";
4609 } else if (p.next_token().asInput() == "w") {
4611 name = "\\textturnw";
4616 if ((name.size() == 2 &&
4617 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4618 p.next_token().asInput() != "*") ||
4619 is_known(name.substr(1), known_tipa_marks)) {
4620 // name is a command that corresponds to a
4621 // combining character in unicodesymbols.
4622 // Append the argument, fromLaTeXCommand()
4623 // will either convert it to a single
4624 // character or a combining sequence.
4625 name += '{' + p.verbatim_item() + '}';
4627 // now get the character from unicodesymbols
4631 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4632 Encodings::TEXT_CMD, termination, rem, &req);
4634 context.check_layout(os);
4637 output_ert_inset(os, to_utf8(rem), context);
4639 skip_spaces_braces(p);
4640 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4641 preamble.registerAutomaticallyLoadedPackage(*it);
4643 //cerr << "#: " << t << " mode: " << mode << endl;
4644 // heuristic: read up to next non-nested space
4646 string s = t.asInput();
4647 string z = p.verbatim_item();
4648 while (p.good() && z != " " && !z.empty()) {
4649 //cerr << "read: " << z << endl;
4651 z = p.verbatim_item();
4653 cerr << "found ERT: " << s << endl;
4654 output_ert_inset(os, s + ' ', context);
4657 if (t.asInput() == name &&
4658 p.next_token().asInput() == "*") {
4659 // Starred commands like \vspace*{}
4660 p.get_token(); // Eat '*'
4663 if (!parse_command(name, p, os, outer, context))
4664 output_ert_inset(os, name, context);
4668 if (flags & FLAG_LEAVE) {
4669 flags &= ~FLAG_LEAVE;
4676 string guessLanguage(Parser & p, string const & lang)
4678 typedef std::map<std::string, size_t> LangMap;
4679 // map from language names to number of characters
4682 for (char const * const * i = supported_CJK_languages; *i; i++)
4683 used[string(*i)] = 0;
4686 Token const t = p.get_token();
4687 // comments are not counted for any language
4688 if (t.cat() == catComment)
4690 // commands are not counted as well, but we need to detect
4691 // \begin{CJK} and switch encoding if needed
4692 if (t.cat() == catEscape) {
4693 if (t.cs() == "inputencoding") {
4694 string const enc = subst(p.verbatim_item(), "\n", " ");
4695 p.setEncoding(enc, Encoding::inputenc);
4698 if (t.cs() != "begin")
4701 // Non-CJK content is counted for lang.
4702 // We do not care about the real language here:
4703 // If we have more non-CJK contents than CJK contents,
4704 // we simply use the language that was specified as
4705 // babel main language.
4706 used[lang] += t.asInput().length();
4709 // Now we are starting an environment
4711 string const name = p.getArg('{', '}');
4712 if (name != "CJK") {
4716 // It is a CJK environment
4718 /* name = */ p.getArg('{', '}');
4719 string const encoding = p.getArg('{', '}');
4720 /* mapping = */ p.getArg('{', '}');
4721 string const encoding_old = p.getEncoding();
4722 char const * const * const where =
4723 is_known(encoding, supported_CJK_encodings);
4725 p.setEncoding(encoding, Encoding::CJK);
4727 p.setEncoding("UTF-8");
4728 string const text = p.ertEnvironment("CJK");
4729 p.setEncoding(encoding_old);
4732 // ignore contents in unknown CJK encoding
4735 // the language of the text
4737 supported_CJK_languages[where - supported_CJK_encodings];
4738 used[cjk] += text.length();
4740 LangMap::const_iterator use = used.begin();
4741 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4742 if (it->second > use->second)