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") {
938 outer_type == "fbox";
939 width_value = "-999";
941 width_special = "none";
945 if (!outer_type.empty()) {
946 if (outer_flags & FLAG_END)
947 ss << "\\begin{" << outer_type << '}';
949 ss << '\\' << outer_type << '{';
950 if (!special.empty())
954 if (!inner_type.empty()) {
955 if (inner_type != "shaded") {
956 if (inner_flags & FLAG_END)
957 ss << "\\begin{" << inner_type << '}';
959 ss << '\\' << inner_type;
961 if (!position.empty())
962 ss << '[' << position << ']';
963 if (!latex_height.empty())
964 ss << '[' << latex_height << ']';
965 if (!inner_pos.empty())
966 ss << '[' << inner_pos << ']';
967 ss << '{' << latex_width << '}';
968 if (!(inner_flags & FLAG_END))
971 if (inner_type == "shaded")
972 ss << "\\begin{shaded}";
973 output_ert_inset(os, ss.str(), parent_context);
974 if (!inner_type.empty()) {
975 parse_text(p, os, inner_flags, outer, parent_context);
976 if (inner_flags & FLAG_END)
977 output_ert_inset(os, "\\end{" + inner_type + '}',
980 output_ert_inset(os, "}", parent_context);
982 if (!outer_type.empty()) {
983 // If we already read the inner box we have to pop
985 if (!inner_type.empty() && (inner_flags & FLAG_END))
986 active_environments.pop_back();
988 // Ensure that the end of the outer box is parsed correctly:
989 // The opening brace has been eaten by parse_outer_box()
990 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
991 outer_flags &= ~FLAG_ITEM;
992 outer_flags |= FLAG_BRACE_LAST;
994 parse_text(p, os, outer_flags, outer, parent_context);
995 if (outer_flags & FLAG_END)
996 output_ert_inset(os, "\\end{" + outer_type + '}',
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" || outer_type == "fbox")
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() || outer_type == "mbox")
1024 os << "Frameless\n";
1026 os << outer_type << '\n';
1027 os << "position \"" << position << "\"\n";
1028 os << "hor_pos \"" << hor_pos << "\"\n";
1029 if (outer_type == "mbox")
1030 os << "has_inner_box 1\n";
1032 os << "has_inner_box " << !inner_type.empty() << "\n";
1033 os << "inner_pos \"" << inner_pos << "\"\n";
1034 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1036 if (outer_type == "mbox")
1037 os << "use_makebox 1\n";
1039 os << "use_makebox " << (inner_type == "makebox") << '\n';
1040 if (outer_type == "fbox" || outer_type == "mbox")
1041 os << "width \"-999col%\"\n";
1043 os << "width \"" << width_value << width_unit << "\"\n";
1044 os << "special \"" << width_special << "\"\n";
1045 os << "height \"" << height_value << height_unit << "\"\n";
1046 os << "height_special \"" << height_special << "\"\n";
1047 os << "status open\n\n";
1049 // Unfortunately we can't use parse_text_in_inset:
1050 // InsetBox::forcePlainLayout() is hard coded and does not
1051 // use the inset layout. Apart from that do we call parse_text
1052 // up to two times, but need only one check_end_layout.
1053 bool const forcePlainLayout =
1054 (!inner_type.empty() || inner_type == "makebox") &&
1055 outer_type != "shaded" && outer_type != "framed";
1056 Context context(true, parent_context.textclass);
1057 if (forcePlainLayout)
1058 context.layout = &context.textclass.plainLayout();
1060 context.font = parent_context.font;
1062 // If we have no inner box the contents will be read with the outer box
1063 if (!inner_type.empty())
1064 parse_text(p, os, inner_flags, outer, context);
1066 // Ensure that the end of the outer box is parsed correctly:
1067 // The opening brace has been eaten by parse_outer_box()
1068 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1069 outer_flags &= ~FLAG_ITEM;
1070 outer_flags |= FLAG_BRACE_LAST;
1073 // Find end of outer box, output contents if inner_type is
1074 // empty and output possible comments
1075 if (!outer_type.empty()) {
1076 // If we already read the inner box we have to pop
1078 if (!inner_type.empty() && (inner_flags & FLAG_END))
1079 active_environments.pop_back();
1080 // This does not output anything but comments if
1081 // inner_type is not empty (see use_ert)
1082 parse_text(p, os, outer_flags, outer, context);
1085 context.check_end_layout(os);
1087 #ifdef PRESERVE_LAYOUT
1088 // LyX puts a % after the end of the minipage
1089 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1091 //output_ert_inset(os, "%dummy", parent_context);
1094 parent_context.new_paragraph(os);
1096 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1097 //output_ert_inset(os, "%dummy", parent_context);
1100 // We add a protected space if something real follows
1101 if (p.good() && p.next_token().cat() != catComment) {
1102 begin_inset(os, "space ~\n");
1111 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1112 Context & parent_context, string const & outer_type,
1113 string const & special)
1115 eat_whitespace(p, os, parent_context, false);
1116 if (flags & FLAG_ITEM) {
1118 if (p.next_token().cat() == catBegin)
1121 cerr << "Warning: Ignoring missing '{' after \\"
1122 << outer_type << '.' << endl;
1123 eat_whitespace(p, os, parent_context, false);
1126 unsigned int inner_flags = 0;
1128 if (outer_type == "minipage" || outer_type == "parbox") {
1129 p.skip_spaces(true);
1130 while (p.hasOpt()) {
1132 p.skip_spaces(true);
1135 p.skip_spaces(true);
1136 if (outer_type == "parbox") {
1138 if (p.next_token().cat() == catBegin)
1140 p.skip_spaces(true);
1143 if (outer_type == "shaded" || outer_type == "fbox"
1144 || outer_type == "mbox") {
1145 // These boxes never have an inner box
1147 } else if (p.next_token().asInput() == "\\parbox") {
1148 inner = p.get_token().cs();
1149 inner_flags = FLAG_ITEM;
1150 } else if (p.next_token().asInput() == "\\begin") {
1151 // Is this a minipage or shaded box?
1154 inner = p.getArg('{', '}');
1156 if (inner == "minipage" || inner == "shaded")
1157 inner_flags = FLAG_END;
1162 if (inner_flags == FLAG_END) {
1163 if (inner != "shaded")
1167 eat_whitespace(p, os, parent_context, false);
1169 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1170 outer_type, special, inner);
1172 if (inner_flags == FLAG_ITEM) {
1174 eat_whitespace(p, os, parent_context, false);
1176 parse_box(p, os, flags, inner_flags, outer, parent_context,
1177 outer_type, special, inner);
1182 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1184 parent_context.check_layout(os);
1185 begin_inset(os, "listings\n");
1187 string arg = p.verbatimOption();
1188 os << "lstparams " << '"' << arg << '"' << '\n';
1189 if (arg.find("\\color") != string::npos)
1190 preamble.registerAutomaticallyLoadedPackage("color");
1193 os << "inline true\n";
1195 os << "inline false\n";
1196 os << "status collapsed\n";
1197 Context context(true, parent_context.textclass);
1198 context.layout = &parent_context.textclass.plainLayout();
1201 // set catcodes to verbatim early, just in case.
1202 p.setCatcodes(VERBATIM_CATCODES);
1203 string delim = p.get_token().asInput();
1204 //FIXME: handler error condition
1205 s = p.verbatimStuff(delim).second;
1206 // context.new_paragraph(os);
1208 s = p.verbatimEnvironment("lstlisting");
1209 output_ert(os, s, context);
1214 /// parse an unknown environment
1215 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1216 unsigned flags, bool outer,
1217 Context & parent_context)
1219 if (name == "tabbing")
1220 // We need to remember that we have to handle '\=' specially
1221 flags |= FLAG_TABBING;
1223 // We need to translate font changes and paragraphs inside the
1224 // environment to ERT if we have a non standard font.
1225 // Otherwise things like
1226 // \large\begin{foo}\huge bar\end{foo}
1228 bool const specialfont =
1229 (parent_context.font != parent_context.normalfont);
1230 bool const new_layout_allowed = parent_context.new_layout_allowed;
1232 parent_context.new_layout_allowed = false;
1233 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1234 parse_text_snippet(p, os, flags, outer, parent_context);
1235 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1237 parent_context.new_layout_allowed = new_layout_allowed;
1241 void parse_environment(Parser & p, ostream & os, bool outer,
1242 string & last_env, Context & parent_context)
1244 Layout const * newlayout;
1245 InsetLayout const * newinsetlayout = 0;
1246 string const name = p.getArg('{', '}');
1247 const bool is_starred = suffixIs(name, '*');
1248 string const unstarred_name = rtrim(name, "*");
1249 active_environments.push_back(name);
1251 if (is_math_env(name)) {
1252 parent_context.check_layout(os);
1253 begin_inset(os, "Formula ");
1254 os << "\\begin{" << name << "}";
1255 parse_math(p, os, FLAG_END, MATH_MODE);
1256 os << "\\end{" << name << "}";
1258 if (is_display_math_env(name)) {
1259 // Prevent the conversion of a line break to a space
1260 // (bug 7668). This does not change the output, but
1261 // looks ugly in LyX.
1262 eat_whitespace(p, os, parent_context, false);
1266 else if (is_known(name, preamble.polyglossia_languages)) {
1267 // We must begin a new paragraph if not already done
1268 if (! parent_context.atParagraphStart()) {
1269 parent_context.check_end_layout(os);
1270 parent_context.new_paragraph(os);
1272 // save the language in the context so that it is
1273 // handled by parse_text
1274 parent_context.font.language = preamble.polyglossia2lyx(name);
1275 parse_text(p, os, FLAG_END, outer, parent_context);
1276 // Just in case the environment is empty
1277 parent_context.extra_stuff.erase();
1278 // We must begin a new paragraph to reset the language
1279 parent_context.new_paragraph(os);
1283 else if (unstarred_name == "tabular" || name == "longtable") {
1284 eat_whitespace(p, os, parent_context, false);
1285 string width = "0pt";
1286 if (name == "tabular*") {
1287 width = lyx::translate_len(p.getArg('{', '}'));
1288 eat_whitespace(p, os, parent_context, false);
1290 parent_context.check_layout(os);
1291 begin_inset(os, "Tabular ");
1292 handle_tabular(p, os, name, width, parent_context);
1297 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1298 eat_whitespace(p, os, parent_context, false);
1299 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1300 eat_whitespace(p, os, parent_context, false);
1301 parent_context.check_layout(os);
1302 begin_inset(os, "Float " + unstarred_name + "\n");
1303 // store the float type for subfloats
1304 // subfloats only work with figures and tables
1305 if (unstarred_name == "figure")
1306 float_type = unstarred_name;
1307 else if (unstarred_name == "table")
1308 float_type = unstarred_name;
1312 os << "placement " << opt << '\n';
1313 if (contains(opt, "H"))
1314 preamble.registerAutomaticallyLoadedPackage("float");
1316 Floating const & fl = parent_context.textclass.floats()
1317 .getType(unstarred_name);
1318 if (!fl.floattype().empty() && fl.usesFloatPkg())
1319 preamble.registerAutomaticallyLoadedPackage("float");
1322 os << "wide " << convert<string>(is_starred)
1323 << "\nsideways false"
1324 << "\nstatus open\n\n";
1325 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1327 // We don't need really a new paragraph, but
1328 // we must make sure that the next item gets a \begin_layout.
1329 parent_context.new_paragraph(os);
1331 // the float is parsed thus delete the type
1335 else if (unstarred_name == "sidewaysfigure"
1336 || unstarred_name == "sidewaystable") {
1337 eat_whitespace(p, os, parent_context, false);
1338 parent_context.check_layout(os);
1339 if (unstarred_name == "sidewaysfigure")
1340 begin_inset(os, "Float figure\n");
1342 begin_inset(os, "Float table\n");
1343 os << "wide " << convert<string>(is_starred)
1344 << "\nsideways true"
1345 << "\nstatus open\n\n";
1346 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1348 // We don't need really a new paragraph, but
1349 // we must make sure that the next item gets a \begin_layout.
1350 parent_context.new_paragraph(os);
1352 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1355 else if (name == "wrapfigure" || name == "wraptable") {
1356 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1357 eat_whitespace(p, os, parent_context, false);
1358 parent_context.check_layout(os);
1361 string overhang = "0col%";
1364 lines = p.getArg('[', ']');
1365 string const placement = p.getArg('{', '}');
1367 overhang = p.getArg('[', ']');
1368 string const width = p.getArg('{', '}');
1370 if (name == "wrapfigure")
1371 begin_inset(os, "Wrap figure\n");
1373 begin_inset(os, "Wrap table\n");
1374 os << "lines " << lines
1375 << "\nplacement " << placement
1376 << "\noverhang " << lyx::translate_len(overhang)
1377 << "\nwidth " << lyx::translate_len(width)
1378 << "\nstatus open\n\n";
1379 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1381 // We don't need really a new paragraph, but
1382 // we must make sure that the next item gets a \begin_layout.
1383 parent_context.new_paragraph(os);
1385 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1388 else if (name == "minipage") {
1389 eat_whitespace(p, os, parent_context, false);
1390 // Test whether this is an outer box of a shaded box
1392 // swallow arguments
1393 while (p.hasOpt()) {
1395 p.skip_spaces(true);
1398 p.skip_spaces(true);
1399 Token t = p.get_token();
1400 bool shaded = false;
1401 if (t.asInput() == "\\begin") {
1402 p.skip_spaces(true);
1403 if (p.getArg('{', '}') == "shaded")
1408 parse_outer_box(p, os, FLAG_END, outer,
1409 parent_context, name, "shaded");
1411 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1416 else if (name == "comment") {
1417 eat_whitespace(p, os, parent_context, false);
1418 parent_context.check_layout(os);
1419 begin_inset(os, "Note Comment\n");
1420 os << "status open\n";
1421 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1424 skip_braces(p); // eat {} that might by set by LyX behind comments
1425 preamble.registerAutomaticallyLoadedPackage("verbatim");
1428 else if (name == "verbatim") {
1429 // FIXME: this should go in the generic code that
1430 // handles environments defined in layout file that
1431 // have "PassThru 1". However, the code over there is
1432 // already too complicated for my taste.
1433 parent_context.new_paragraph(os);
1434 Context context(true, parent_context.textclass,
1435 &parent_context.textclass[from_ascii("Verbatim")]);
1436 string s = p.verbatimEnvironment("verbatim");
1437 output_ert(os, s, context);
1441 else if (name == "IPA") {
1442 eat_whitespace(p, os, parent_context, false);
1443 parent_context.check_layout(os);
1444 begin_inset(os, "IPA\n");
1445 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1448 preamble.registerAutomaticallyLoadedPackage("tipa");
1449 preamble.registerAutomaticallyLoadedPackage("tipx");
1452 else if (name == "CJK") {
1453 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1454 // It is impossible to decide if a CJK environment was in its own paragraph or within
1455 // a line. We therefore always assume a paragraph since the latter is a rare case.
1456 eat_whitespace(p, os, parent_context, false);
1457 parent_context.check_end_layout(os);
1458 // store the encoding to be able to reset it
1459 string const encoding_old = p.getEncoding();
1460 string const encoding = p.getArg('{', '}');
1461 // FIXME: For some reason JIS does not work. Although the text
1462 // in tests/CJK.tex is identical with the SJIS version if you
1463 // convert both snippets using the recode command line utility,
1464 // the resulting .lyx file contains some extra characters if
1465 // you set buggy_encoding to false for JIS.
1466 bool const buggy_encoding = encoding == "JIS";
1467 if (!buggy_encoding)
1468 p.setEncoding(encoding, Encoding::CJK);
1470 // FIXME: This will read garbage, since the data is not encoded in utf8.
1471 p.setEncoding("UTF-8");
1473 // LyX only supports the same mapping for all CJK
1474 // environments, so we might need to output everything as ERT
1475 string const mapping = trim(p.getArg('{', '}'));
1476 char const * const * const where =
1477 is_known(encoding, supported_CJK_encodings);
1478 if (!buggy_encoding && !preamble.fontCJKSet())
1479 preamble.fontCJK(mapping);
1480 bool knownMapping = mapping == preamble.fontCJK();
1481 if (buggy_encoding || !knownMapping || !where) {
1482 parent_context.check_layout(os);
1483 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1485 // we must parse the content as verbatim because e.g. JIS can contain
1486 // normally invalid characters
1487 // FIXME: This works only for the most simple cases.
1488 // Since TeX control characters are not parsed,
1489 // things like comments are completely wrong.
1490 string const s = p.plainEnvironment("CJK");
1491 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1493 output_ert_inset(os, "\\", parent_context);
1494 else if (*it == '$')
1495 output_ert_inset(os, "$", parent_context);
1496 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1501 output_ert_inset(os, "\\end{" + name + "}",
1505 supported_CJK_languages[where - supported_CJK_encodings];
1506 // store the language because we must reset it at the end
1507 string const lang_old = parent_context.font.language;
1508 parent_context.font.language = lang;
1509 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1510 parent_context.font.language = lang_old;
1511 parent_context.new_paragraph(os);
1513 p.setEncoding(encoding_old);
1517 else if (name == "lyxgreyedout") {
1518 eat_whitespace(p, os, parent_context, false);
1519 parent_context.check_layout(os);
1520 begin_inset(os, "Note Greyedout\n");
1521 os << "status open\n";
1522 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1525 if (!preamble.notefontcolor().empty())
1526 preamble.registerAutomaticallyLoadedPackage("color");
1529 else if (name == "framed" || name == "shaded") {
1530 eat_whitespace(p, os, parent_context, false);
1531 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1535 else if (name == "lstlisting") {
1536 eat_whitespace(p, os, parent_context, false);
1537 parse_listings(p, os, parent_context, false);
1541 else if (!parent_context.new_layout_allowed)
1542 parse_unknown_environment(p, name, os, FLAG_END, outer,
1545 // Alignment and spacing settings
1546 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1547 // therefore are totally broken!
1548 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1549 // they are commands not environments. They are furthermore switches that
1550 // can be ended by another switches, but also by commands like \footnote or
1551 // \parbox. So the only safe way is to leave them untouched.
1552 else if (name == "center" || name == "centering" ||
1553 name == "flushleft" || name == "flushright" ||
1554 name == "singlespace" || name == "onehalfspace" ||
1555 name == "doublespace" || name == "spacing") {
1556 eat_whitespace(p, os, parent_context, false);
1557 // We must begin a new paragraph if not already done
1558 if (! parent_context.atParagraphStart()) {
1559 parent_context.check_end_layout(os);
1560 parent_context.new_paragraph(os);
1562 if (name == "flushleft")
1563 parent_context.add_extra_stuff("\\align left\n");
1564 else if (name == "flushright")
1565 parent_context.add_extra_stuff("\\align right\n");
1566 else if (name == "center" || name == "centering")
1567 parent_context.add_extra_stuff("\\align center\n");
1568 else if (name == "singlespace")
1569 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1570 else if (name == "onehalfspace") {
1571 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1572 preamble.registerAutomaticallyLoadedPackage("setspace");
1573 } else if (name == "doublespace") {
1574 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1575 preamble.registerAutomaticallyLoadedPackage("setspace");
1576 } else if (name == "spacing") {
1577 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1578 preamble.registerAutomaticallyLoadedPackage("setspace");
1580 parse_text(p, os, FLAG_END, outer, parent_context);
1581 // Just in case the environment is empty
1582 parent_context.extra_stuff.erase();
1583 // We must begin a new paragraph to reset the alignment
1584 parent_context.new_paragraph(os);
1588 // The single '=' is meant here.
1589 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1590 eat_whitespace(p, os, parent_context, false);
1591 Context context(true, parent_context.textclass, newlayout,
1592 parent_context.layout, parent_context.font);
1593 if (parent_context.deeper_paragraph) {
1594 // We are beginning a nested environment after a
1595 // deeper paragraph inside the outer list environment.
1596 // Therefore we don't need to output a "begin deeper".
1597 context.need_end_deeper = true;
1599 parent_context.check_end_layout(os);
1600 if (last_env == name) {
1601 // we need to output a separator since LyX would export
1602 // the two environments as one otherwise (bug 5716)
1603 docstring const sep = from_ascii("--Separator--");
1604 TeX2LyXDocClass const & textclass(parent_context.textclass);
1605 if (textclass.hasLayout(sep)) {
1606 Context newcontext(parent_context);
1607 newcontext.layout = &(textclass[sep]);
1608 newcontext.check_layout(os);
1609 newcontext.check_end_layout(os);
1611 parent_context.check_layout(os);
1612 begin_inset(os, "Note Note\n");
1613 os << "status closed\n";
1614 Context newcontext(true, textclass,
1615 &(textclass.defaultLayout()));
1616 newcontext.check_layout(os);
1617 newcontext.check_end_layout(os);
1619 parent_context.check_end_layout(os);
1622 switch (context.layout->latextype) {
1623 case LATEX_LIST_ENVIRONMENT:
1624 context.add_par_extra_stuff("\\labelwidthstring "
1625 + p.verbatim_item() + '\n');
1628 case LATEX_BIB_ENVIRONMENT:
1629 p.verbatim_item(); // swallow next arg
1635 context.check_deeper(os);
1636 // handle known optional and required arguments
1637 // FIXME: Since format 446, layouts do not require anymore all optional
1638 // arguments before the required ones. Needs to be implemented!
1639 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1640 // It is impossible to place anything after the environment name,
1641 // but before the first \\item.
1642 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1643 bool need_layout = true;
1645 while (optargs < context.layout->optArgs()) {
1646 eat_whitespace(p, os, context, false);
1647 if (p.next_token().cat() == catEscape ||
1648 p.next_token().character() != '[')
1650 p.get_token(); // eat '['
1652 context.check_layout(os);
1653 need_layout = false;
1655 // FIXME: Just a workaround. InsetArgument::updateBuffer
1656 // will compute a proper ID for all "999" Arguments
1657 // (which is also what lyx2lyx produces).
1658 // However, tex2lyx should be able to output proper IDs
1660 begin_inset(os, "Argument 999\n");
1661 os << "status collapsed\n\n";
1662 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1664 eat_whitespace(p, os, context, false);
1668 while (reqargs < context.layout->requiredArgs()) {
1669 eat_whitespace(p, os, context, false);
1670 if (p.next_token().cat() != catBegin)
1672 p.get_token(); // eat '{'
1674 context.check_layout(os);
1675 need_layout = false;
1677 // FIXME: Just a workaround. InsetArgument::updateBuffer
1678 // will compute a proper ID for all "999" Arguments
1679 // (which is also what lyx2lyx produces).
1680 // However, tex2lyx should be able to output proper IDs
1682 begin_inset(os, "Argument 999\n");
1683 os << "status collapsed\n\n";
1684 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1686 eat_whitespace(p, os, context, false);
1690 parse_text(p, os, FLAG_END, outer, context);
1691 context.check_end_layout(os);
1692 if (parent_context.deeper_paragraph) {
1693 // We must suppress the "end deeper" because we
1694 // suppressed the "begin deeper" above.
1695 context.need_end_deeper = false;
1697 context.check_end_deeper(os);
1698 parent_context.new_paragraph(os);
1700 if (!preamble.titleLayoutFound())
1701 preamble.titleLayoutFound(newlayout->intitle);
1702 set<string> const & req = newlayout->requires();
1703 set<string>::const_iterator it = req.begin();
1704 set<string>::const_iterator en = req.end();
1705 for (; it != en; ++it)
1706 preamble.registerAutomaticallyLoadedPackage(*it);
1709 // The single '=' is meant here.
1710 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1711 eat_whitespace(p, os, parent_context, false);
1712 parent_context.check_layout(os);
1713 begin_inset(os, "Flex ");
1714 os << to_utf8(newinsetlayout->name()) << '\n'
1715 << "status collapsed\n";
1716 if (newinsetlayout->isPassThru()) {
1717 string const arg = p.verbatimEnvironment(name);
1718 Context context(true, parent_context.textclass,
1719 &parent_context.textclass.plainLayout(),
1720 parent_context.layout);
1721 output_ert(os, arg, parent_context);
1723 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1727 else if (name == "appendix") {
1728 // This is no good latex style, but it works and is used in some documents...
1729 eat_whitespace(p, os, parent_context, false);
1730 parent_context.check_end_layout(os);
1731 Context context(true, parent_context.textclass, parent_context.layout,
1732 parent_context.layout, parent_context.font);
1733 context.check_layout(os);
1734 os << "\\start_of_appendix\n";
1735 parse_text(p, os, FLAG_END, outer, context);
1736 context.check_end_layout(os);
1740 else if (known_environments.find(name) != known_environments.end()) {
1741 vector<ArgumentType> arguments = known_environments[name];
1742 // The last "argument" denotes wether we may translate the
1743 // environment contents to LyX
1744 // The default required if no argument is given makes us
1745 // compatible with the reLyXre environment.
1746 ArgumentType contents = arguments.empty() ?
1749 if (!arguments.empty())
1750 arguments.pop_back();
1751 // See comment in parse_unknown_environment()
1752 bool const specialfont =
1753 (parent_context.font != parent_context.normalfont);
1754 bool const new_layout_allowed =
1755 parent_context.new_layout_allowed;
1757 parent_context.new_layout_allowed = false;
1758 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1759 outer, parent_context);
1760 if (contents == verbatim)
1761 output_ert_inset(os, p.ertEnvironment(name),
1764 parse_text_snippet(p, os, FLAG_END, outer,
1766 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1768 parent_context.new_layout_allowed = new_layout_allowed;
1772 parse_unknown_environment(p, name, os, FLAG_END, outer,
1776 active_environments.pop_back();
1780 /// parses a comment and outputs it to \p os.
1781 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1783 LASSERT(t.cat() == catComment, return);
1784 if (!t.cs().empty()) {
1785 context.check_layout(os);
1786 output_ert_inset(os, '%' + t.cs(), context);
1787 if (p.next_token().cat() == catNewline) {
1788 // A newline after a comment line starts a new
1790 if (context.new_layout_allowed) {
1791 if(!context.atParagraphStart())
1792 // Only start a new paragraph if not already
1793 // done (we might get called recursively)
1794 context.new_paragraph(os);
1796 output_ert_inset(os, "\n", context);
1797 eat_whitespace(p, os, context, true);
1800 // "%\n" combination
1807 * Reads spaces and comments until the first non-space, non-comment token.
1808 * New paragraphs (double newlines or \\par) are handled like simple spaces
1809 * if \p eatParagraph is true.
1810 * Spaces are skipped, but comments are written to \p os.
1812 void eat_whitespace(Parser & p, ostream & os, Context & context,
1816 Token const & t = p.get_token();
1817 if (t.cat() == catComment)
1818 parse_comment(p, os, t, context);
1819 else if ((! eatParagraph && p.isParagraph()) ||
1820 (t.cat() != catSpace && t.cat() != catNewline)) {
1829 * Set a font attribute, parse text and reset the font attribute.
1830 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1831 * \param currentvalue Current value of the attribute. Is set to the new
1832 * value during parsing.
1833 * \param newvalue New value of the attribute
1835 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1836 Context & context, string const & attribute,
1837 string & currentvalue, string const & newvalue)
1839 context.check_layout(os);
1840 string const oldvalue = currentvalue;
1841 currentvalue = newvalue;
1842 os << '\n' << attribute << ' ' << newvalue << "\n";
1843 parse_text_snippet(p, os, flags, outer, context);
1844 context.check_layout(os);
1845 os << '\n' << attribute << ' ' << oldvalue << "\n";
1846 currentvalue = oldvalue;
1850 /// get the arguments of a natbib or jurabib citation command
1851 void get_cite_arguments(Parser & p, bool natbibOrder,
1852 string & before, string & after)
1854 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1856 // text before the citation
1858 // text after the citation
1859 after = p.getFullOpt();
1861 if (!after.empty()) {
1862 before = p.getFullOpt();
1863 if (natbibOrder && !before.empty())
1864 swap(before, after);
1869 /// Convert filenames with TeX macros and/or quotes to something LyX
1871 string const normalize_filename(string const & name)
1876 Token const & t = p.get_token();
1877 if (t.cat() != catEscape)
1879 else if (t.cs() == "lyxdot") {
1880 // This is used by LyX for simple dots in relative
1884 } else if (t.cs() == "space") {
1887 } else if (t.cs() == "string") {
1888 // Convert \string" to " and \string~ to ~
1889 Token const & n = p.next_token();
1890 if (n.asInput() != "\"" && n.asInput() != "~")
1895 // Strip quotes. This is a bit complicated (see latex_path()).
1896 string full = os.str();
1897 if (!full.empty() && full[0] == '"') {
1898 string base = removeExtension(full);
1899 string ext = getExtension(full);
1900 if (!base.empty() && base[base.length()-1] == '"')
1903 return addExtension(trim(base, "\""), ext);
1904 if (full[full.length()-1] == '"')
1907 return trim(full, "\"");
1913 /// Convert \p name from TeX convention (relative to master file) to LyX
1914 /// convention (relative to .lyx file) if it is relative
1915 void fix_child_filename(string & name)
1917 string const absMasterTeX = getMasterFilePath(true);
1918 bool const isabs = FileName::isAbsolute(name);
1919 // convert from "relative to .tex master" to absolute original path
1921 name = makeAbsPath(name, absMasterTeX).absFileName();
1922 bool copyfile = copyFiles();
1923 string const absParentLyX = getParentFilePath(false);
1926 // convert from absolute original path to "relative to master file"
1927 string const rel = to_utf8(makeRelPath(from_utf8(name),
1928 from_utf8(absMasterTeX)));
1929 // re-interpret "relative to .tex file" as "relative to .lyx file"
1930 // (is different if the master .lyx file resides in a
1931 // different path than the master .tex file)
1932 string const absMasterLyX = getMasterFilePath(false);
1933 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1934 // Do not copy if the new path is impossible to create. Example:
1935 // absMasterTeX = "/foo/bar/"
1936 // absMasterLyX = "/bar/"
1937 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1938 if (contains(name, "/../"))
1945 // convert from absolute original path to
1946 // "relative to .lyx file"
1947 name = to_utf8(makeRelPath(from_utf8(abs),
1948 from_utf8(absParentLyX)));
1952 // convert from absolute original path to "relative to .lyx file"
1953 name = to_utf8(makeRelPath(from_utf8(name),
1954 from_utf8(absParentLyX)));
1959 void copy_file(FileName const & src, string dstname)
1963 string const absParent = getParentFilePath(false);
1965 if (FileName::isAbsolute(dstname))
1966 dst = FileName(dstname);
1968 dst = makeAbsPath(dstname, absParent);
1969 string const absMaster = getMasterFilePath(false);
1970 FileName const srcpath = src.onlyPath();
1971 FileName const dstpath = dst.onlyPath();
1972 if (equivalent(srcpath, dstpath))
1974 if (!dstpath.isDirectory()) {
1975 if (!dstpath.createPath()) {
1976 cerr << "Warning: Could not create directory for file `"
1977 << dst.absFileName() << "´." << endl;
1981 if (dst.isReadableFile()) {
1982 if (overwriteFiles())
1983 cerr << "Warning: Overwriting existing file `"
1984 << dst.absFileName() << "´." << endl;
1986 cerr << "Warning: Not overwriting existing file `"
1987 << dst.absFileName() << "´." << endl;
1991 if (!src.copyTo(dst))
1992 cerr << "Warning: Could not copy file `" << src.absFileName()
1993 << "´ to `" << dst.absFileName() << "´." << endl;
1997 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1998 bool parse_noweb(Parser & p, ostream & os, Context & context)
2000 // check whether a chunk is possible here.
2001 if (!context.new_layout_allowed ||
2002 !context.textclass.hasLayout(from_ascii("Chunk"))) {
2008 // read the parameters
2009 Parser::Arg stuff = p.verbatimStuff(">>=", false);
2014 string chunk = "<<" + stuff.second + ">>="
2015 + p.verbatimStuff("\n").second + '\n';
2017 stuff = p.verbatimStuff("\n@");
2022 chunk += stuff.second + "\n@";
2023 string post_chunk = p.verbatimStuff("\n").second + '\n';
2024 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2028 chunk += post_chunk;
2030 context.new_paragraph(os);
2031 Context newcontext(true, context.textclass,
2032 &context.textclass[from_ascii("Chunk")]);
2033 output_ert(os, chunk, newcontext);
2040 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2041 bool is_macro(Parser & p)
2043 Token first = p.curr_token();
2044 if (first.cat() != catEscape || !p.good())
2046 if (first.cs() == "def")
2048 if (first.cs() != "global" && first.cs() != "long")
2050 Token second = p.get_token();
2052 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2053 second.cat() == catNewline || second.cat() == catComment)) {
2054 second = p.get_token();
2057 bool secondvalid = second.cat() == catEscape;
2059 bool thirdvalid = false;
2060 if (p.good() && first.cs() == "global" && secondvalid &&
2061 second.cs() == "long") {
2062 third = p.get_token();
2064 while (p.good() && !p.isParagraph() &&
2065 (third.cat() == catSpace ||
2066 third.cat() == catNewline ||
2067 third.cat() == catComment)) {
2068 third = p.get_token();
2071 thirdvalid = third.cat() == catEscape;
2073 for (int i = 0; i < pos; ++i)
2078 return (first.cs() == "global" || first.cs() == "long") &&
2079 second.cs() == "def";
2080 return first.cs() == "global" && second.cs() == "long" &&
2081 third.cs() == "def";
2085 /// Parse a macro definition (assumes that is_macro() returned true)
2086 void parse_macro(Parser & p, ostream & os, Context & context)
2088 context.check_layout(os);
2089 Token first = p.curr_token();
2092 string command = first.asInput();
2093 if (first.cs() != "def") {
2095 eat_whitespace(p, os, context, false);
2096 second = p.curr_token();
2097 command += second.asInput();
2098 if (second.cs() != "def") {
2100 eat_whitespace(p, os, context, false);
2101 third = p.curr_token();
2102 command += third.asInput();
2105 eat_whitespace(p, os, context, false);
2106 string const name = p.get_token().cs();
2107 eat_whitespace(p, os, context, false);
2113 while (p.next_token().cat() != catBegin) {
2114 if (p.next_token().cat() == catParameter) {
2119 // followed by number?
2120 if (p.next_token().cat() == catOther) {
2121 string s = p.get_token().asInput();
2123 // number = current arity + 1?
2124 if (s.size() == 1 && s[0] == arity + '0' + 1)
2129 paramtext += p.get_token().cs();
2131 paramtext += p.get_token().cs();
2136 // only output simple (i.e. compatible) macro as FormulaMacros
2137 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2139 context.check_layout(os);
2140 begin_inset(os, "FormulaMacro");
2141 os << "\n\\def" << ert;
2144 output_ert_inset(os, command + ert, context);
2148 void registerExternalTemplatePackages(string const & name)
2150 external::TemplateManager const & etm = external::TemplateManager::get();
2151 external::Template const * const et = etm.getTemplateByName(name);
2154 external::Template::Formats::const_iterator cit = et->formats.end();
2156 cit = et->formats.find("PDFLaTeX");
2157 if (cit == et->formats.end())
2158 // If the template has not specified a PDFLaTeX output,
2159 // we try the LaTeX format.
2160 cit = et->formats.find("LaTeX");
2161 if (cit == et->formats.end())
2163 vector<string>::const_iterator qit = cit->second.requirements.begin();
2164 vector<string>::const_iterator qend = cit->second.requirements.end();
2165 for (; qit != qend; ++qit)
2166 preamble.registerAutomaticallyLoadedPackage(*qit);
2169 } // anonymous namespace
2172 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2175 Layout const * newlayout = 0;
2176 InsetLayout const * newinsetlayout = 0;
2177 char const * const * where = 0;
2178 // Store the latest bibliographystyle, addcontentslineContent and
2179 // nocite{*} option (needed for bibtex inset)
2181 string contentslineContent;
2182 string bibliographystyle = "default";
2183 bool const use_natbib = isProvided("natbib");
2184 bool const use_jurabib = isProvided("jurabib");
2187 Token const & t = p.get_token();
2189 // it is impossible to determine the correct encoding for non-CJK Japanese.
2190 // Therefore write a note at the beginning of the document
2191 if (is_nonCJKJapanese) {
2192 context.check_layout(os);
2193 begin_inset(os, "Note Note\n");
2194 os << "status open\n\\begin_layout Plain Layout\n"
2195 << "\\series bold\n"
2196 << "Important information:\n"
2197 << "\\end_layout\n\n"
2198 << "\\begin_layout Plain Layout\n"
2199 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2200 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2201 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2202 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2203 << " and specify the encoding using the -e command-line switch.\n"
2204 << " In addition, you might want to double check that the desired output encoding\n"
2205 << " is correctly selected in Document > Settings > Language.\n"
2206 << "\\end_layout\n";
2208 is_nonCJKJapanese = false;
2212 debugToken(cerr, t, flags);
2215 if (flags & FLAG_ITEM) {
2216 if (t.cat() == catSpace)
2219 flags &= ~FLAG_ITEM;
2220 if (t.cat() == catBegin) {
2221 // skip the brace and collect everything to the next matching
2223 flags |= FLAG_BRACE_LAST;
2227 // handle only this single token, leave the loop if done
2228 flags |= FLAG_LEAVE;
2231 if (t.cat() != catEscape && t.character() == ']' &&
2232 (flags & FLAG_BRACK_LAST))
2234 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2237 // If there is anything between \end{env} and \begin{env} we
2238 // don't need to output a separator.
2239 if (t.cat() != catSpace && t.cat() != catNewline &&
2240 t.asInput() != "\\begin")
2246 if (t.cat() == catMath) {
2247 // we are inside some text mode thingy, so opening new math is allowed
2248 context.check_layout(os);
2249 begin_inset(os, "Formula ");
2250 Token const & n = p.get_token();
2251 bool const display(n.cat() == catMath && outer);
2253 // TeX's $$...$$ syntax for displayed math
2255 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2257 p.get_token(); // skip the second '$' token
2259 // simple $...$ stuff
2262 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2267 // Prevent the conversion of a line break to a
2268 // space (bug 7668). This does not change the
2269 // output, but looks ugly in LyX.
2270 eat_whitespace(p, os, context, false);
2274 else if (t.cat() == catSuper || t.cat() == catSub)
2275 cerr << "catcode " << t << " illegal in text mode\n";
2277 // Basic support for english quotes. This should be
2278 // extended to other quotes, but is not so easy (a
2279 // left english quote is the same as a right german
2281 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2282 context.check_layout(os);
2283 begin_inset(os, "Quotes ");
2289 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2290 context.check_layout(os);
2291 begin_inset(os, "Quotes ");
2298 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2299 context.check_layout(os);
2300 begin_inset(os, "Quotes ");
2307 else if (t.asInput() == "<"
2308 && p.next_token().asInput() == "<") {
2309 bool has_noweb = false;
2313 has_noweb = parse_noweb(p, os, context);
2319 context.check_layout(os);
2320 begin_inset(os, "Quotes ");
2321 //FIXME: this is a right danish quote;
2322 // why not a left french quote?
2330 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2331 check_space(p, os, context);
2333 else if (t.character() == '[' && noweb_mode &&
2334 p.next_token().character() == '[') {
2335 // These can contain underscores
2337 string const s = p.getFullOpt() + ']';
2338 if (p.next_token().character() == ']')
2341 cerr << "Warning: Inserting missing ']' in '"
2342 << s << "'." << endl;
2343 output_ert_inset(os, s, context);
2346 else if (t.cat() == catLetter) {
2347 context.check_layout(os);
2348 // Workaround for bug 4752.
2349 // FIXME: This whole code block needs to be removed
2350 // when the bug is fixed and tex2lyx produces
2351 // the updated file format.
2352 // The replacement algorithm in LyX is so stupid that
2353 // it even translates a phrase if it is part of a word.
2354 bool handled = false;
2355 for (int const * l = known_phrase_lengths; *l; ++l) {
2356 string phrase = t.cs();
2357 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2358 phrase += p.get_token().cs();
2359 if (is_known(phrase, known_coded_phrases)) {
2360 output_ert_inset(os, phrase, context);
2364 for (size_t i = 1; i < phrase.length(); ++i)
2372 else if (t.cat() == catOther ||
2373 t.cat() == catAlign ||
2374 t.cat() == catParameter) {
2375 // This translates "&" to "\\&" which may be wrong...
2376 context.check_layout(os);
2380 else if (p.isParagraph()) {
2381 if (context.new_layout_allowed)
2382 context.new_paragraph(os);
2384 output_ert_inset(os, "\\par ", context);
2385 eat_whitespace(p, os, context, true);
2388 else if (t.cat() == catActive) {
2389 context.check_layout(os);
2390 if (t.character() == '~') {
2391 if (context.layout->free_spacing)
2394 begin_inset(os, "space ~\n");
2401 else if (t.cat() == catBegin) {
2402 Token const next = p.next_token();
2403 Token const end = p.next_next_token();
2404 if (next.cat() == catEnd) {
2406 Token const prev = p.prev_token();
2408 if (p.next_token().character() == '`' ||
2409 (prev.character() == '-' &&
2410 p.next_token().character() == '-'))
2411 ; // ignore it in {}`` or -{}-
2413 output_ert_inset(os, "{}", context);
2414 } else if (next.cat() == catEscape &&
2415 is_known(next.cs(), known_quotes) &&
2416 end.cat() == catEnd) {
2417 // Something like {\textquoteright} (e.g.
2418 // from writer2latex). LyX writes
2419 // \textquoteright{}, so we may skip the
2420 // braces here for better readability.
2421 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2423 } else if (p.next_token().asInput() == "\\ascii") {
2424 // handle the \ascii characters
2425 // (the case without braces is handled later)
2426 // the code is "{\ascii\xxx}"
2427 p.get_token(); // eat \ascii
2428 string name2 = p.get_token().asInput();
2429 p.get_token(); // eat the final '}'
2430 string const name = "{\\ascii" + name2 + "}";
2434 // get the character from unicodesymbols
2435 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2436 Encodings::TEXT_CMD, termination, rem, &req);
2438 context.check_layout(os);
2441 output_ert_inset(os,
2442 to_utf8(rem), context);
2443 for (set<string>::const_iterator it = req.begin();
2444 it != req.end(); ++it)
2445 preamble.registerAutomaticallyLoadedPackage(*it);
2447 // we did not find a non-ert version
2448 output_ert_inset(os, name, context);
2450 context.check_layout(os);
2451 // special handling of font attribute changes
2452 Token const prev = p.prev_token();
2453 TeXFont const oldFont = context.font;
2454 if (next.character() == '[' ||
2455 next.character() == ']' ||
2456 next.character() == '*') {
2458 if (p.next_token().cat() == catEnd) {
2463 output_ert_inset(os, "{", context);
2464 parse_text_snippet(p, os,
2467 output_ert_inset(os, "}", context);
2469 } else if (! context.new_layout_allowed) {
2470 output_ert_inset(os, "{", context);
2471 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2473 output_ert_inset(os, "}", context);
2474 } else if (is_known(next.cs(), known_sizes)) {
2475 // next will change the size, so we must
2477 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2479 if (!context.atParagraphStart())
2481 << context.font.size << "\n";
2482 } else if (is_known(next.cs(), known_font_families)) {
2483 // next will change the font family, so we
2484 // must reset it here
2485 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2487 if (!context.atParagraphStart())
2489 << context.font.family << "\n";
2490 } else if (is_known(next.cs(), known_font_series)) {
2491 // next will change the font series, so we
2492 // must reset it here
2493 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2495 if (!context.atParagraphStart())
2497 << context.font.series << "\n";
2498 } else if (is_known(next.cs(), known_font_shapes)) {
2499 // next will change the font shape, so we
2500 // must reset it here
2501 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2503 if (!context.atParagraphStart())
2505 << context.font.shape << "\n";
2506 } else if (is_known(next.cs(), known_old_font_families) ||
2507 is_known(next.cs(), known_old_font_series) ||
2508 is_known(next.cs(), known_old_font_shapes)) {
2509 // next will change the font family, series
2510 // and shape, so we must reset it here
2511 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2513 if (!context.atParagraphStart())
2515 << context.font.family
2517 << context.font.series
2519 << context.font.shape << "\n";
2521 output_ert_inset(os, "{", context);
2522 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2524 output_ert_inset(os, "}", context);
2529 else if (t.cat() == catEnd) {
2530 if (flags & FLAG_BRACE_LAST) {
2533 cerr << "stray '}' in text\n";
2534 output_ert_inset(os, "}", context);
2537 else if (t.cat() == catComment)
2538 parse_comment(p, os, t, context);
2541 // control sequences
2544 else if (t.cs() == "(" || t.cs() == "[") {
2545 bool const simple = t.cs() == "(";
2546 context.check_layout(os);
2547 begin_inset(os, "Formula");
2548 os << " \\" << t.cs();
2549 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2550 os << '\\' << (simple ? ')' : ']');
2553 // Prevent the conversion of a line break to a
2554 // space (bug 7668). This does not change the
2555 // output, but looks ugly in LyX.
2556 eat_whitespace(p, os, context, false);
2560 else if (t.cs() == "begin")
2561 parse_environment(p, os, outer, last_env,
2564 else if (t.cs() == "end") {
2565 if (flags & FLAG_END) {
2566 // eat environment name
2567 string const name = p.getArg('{', '}');
2568 if (name != active_environment())
2569 cerr << "\\end{" + name + "} does not match \\begin{"
2570 + active_environment() + "}\n";
2573 p.error("found 'end' unexpectedly");
2576 else if (t.cs() == "item") {
2578 bool const optarg = p.hasOpt();
2580 // FIXME: This swallows comments, but we cannot use
2581 // eat_whitespace() since we must not output
2582 // anything before the item.
2583 p.skip_spaces(true);
2584 s = p.verbatimOption();
2586 p.skip_spaces(false);
2588 context.check_layout(os);
2589 if (context.has_item) {
2590 // An item in an unknown list-like environment
2591 // FIXME: Do this in check_layout()!
2592 context.has_item = false;
2594 output_ert_inset(os, "\\item", context);
2596 output_ert_inset(os, "\\item ", context);
2599 if (context.layout->labeltype != LABEL_MANUAL) {
2600 // LyX does not support \item[\mybullet]
2601 // in itemize environments
2603 os << parse_text_snippet(p2,
2604 FLAG_BRACK_LAST, outer, context);
2605 } else if (!s.empty()) {
2606 // LyX adds braces around the argument,
2607 // so we need to remove them here.
2608 if (s.size() > 2 && s[0] == '{' &&
2609 s[s.size()-1] == '}')
2610 s = s.substr(1, s.size()-2);
2611 // If the argument contains a space we
2612 // must put it into ERT: Otherwise LyX
2613 // would misinterpret the space as
2614 // item delimiter (bug 7663)
2615 if (contains(s, ' ')) {
2616 output_ert_inset(os, s, context);
2619 os << parse_text_snippet(p2,
2623 // The space is needed to separate the
2624 // item from the rest of the sentence.
2626 eat_whitespace(p, os, context, false);
2631 else if (t.cs() == "bibitem") {
2633 context.check_layout(os);
2634 eat_whitespace(p, os, context, false);
2635 string label = convert_command_inset_arg(p.verbatimOption());
2636 string key = convert_command_inset_arg(p.verbatim_item());
2637 if (contains(label, '\\') || contains(key, '\\')) {
2638 // LyX can't handle LaTeX commands in labels or keys
2639 output_ert_inset(os, t.asInput() + '[' + label +
2640 "]{" + p.verbatim_item() + '}',
2643 begin_command_inset(os, "bibitem", "bibitem");
2644 os << "label \"" << label << "\"\n"
2645 "key \"" << key << "\"\n";
2650 else if (is_macro(p)) {
2651 // catch the case of \def\inputGnumericTable
2653 if (t.cs() == "def") {
2654 Token second = p.next_token();
2655 if (second.cs() == "inputGnumericTable") {
2659 Token third = p.get_token();
2661 if (third.cs() == "input") {
2665 string name = normalize_filename(p.verbatim_item());
2666 string const path = getMasterFilePath(true);
2667 // We want to preserve relative / absolute filenames,
2668 // therefore path is only used for testing
2669 // The file extension is in every case ".tex".
2670 // So we need to remove this extension and check for
2671 // the original one.
2672 name = removeExtension(name);
2673 if (!makeAbsPath(name, path).exists()) {
2674 char const * const Gnumeric_formats[] = {"gnumeric",
2676 string const Gnumeric_name =
2677 find_file(name, path, Gnumeric_formats);
2678 if (!Gnumeric_name.empty())
2679 name = Gnumeric_name;
2681 FileName const absname = makeAbsPath(name, path);
2682 if (absname.exists()) {
2683 fix_child_filename(name);
2684 copy_file(absname, name);
2686 cerr << "Warning: Could not find file '"
2687 << name << "'." << endl;
2688 context.check_layout(os);
2689 begin_inset(os, "External\n\ttemplate ");
2690 os << "GnumericSpreadsheet\n\tfilename "
2693 context.check_layout(os);
2695 // register the packages that are automatically loaded
2696 // by the Gnumeric template
2697 registerExternalTemplatePackages("GnumericSpreadsheet");
2702 parse_macro(p, os, context);
2705 else if (t.cs() == "noindent") {
2707 context.add_par_extra_stuff("\\noindent\n");
2710 else if (t.cs() == "appendix") {
2711 context.add_par_extra_stuff("\\start_of_appendix\n");
2712 // We need to start a new paragraph. Otherwise the
2713 // appendix in 'bla\appendix\chapter{' would start
2715 context.new_paragraph(os);
2716 // We need to make sure that the paragraph is
2717 // generated even if it is empty. Otherwise the
2718 // appendix in '\par\appendix\par\chapter{' would
2720 context.check_layout(os);
2721 // FIXME: This is a hack to prevent paragraph
2722 // deletion if it is empty. Handle this better!
2723 output_ert_inset(os,
2724 "%dummy comment inserted by tex2lyx to "
2725 "ensure that this paragraph is not empty",
2727 // Both measures above may generate an additional
2728 // empty paragraph, but that does not hurt, because
2729 // whitespace does not matter here.
2730 eat_whitespace(p, os, context, true);
2733 // Must catch empty dates before findLayout is called below
2734 else if (t.cs() == "date") {
2735 eat_whitespace(p, os, context, false);
2737 string const date = p.verbatim_item();
2740 preamble.suppressDate(true);
2743 preamble.suppressDate(false);
2744 if (context.new_layout_allowed &&
2745 (newlayout = findLayout(context.textclass,
2748 output_command_layout(os, p, outer,
2749 context, newlayout);
2750 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2751 if (!preamble.titleLayoutFound())
2752 preamble.titleLayoutFound(newlayout->intitle);
2753 set<string> const & req = newlayout->requires();
2754 set<string>::const_iterator it = req.begin();
2755 set<string>::const_iterator en = req.end();
2756 for (; it != en; ++it)
2757 preamble.registerAutomaticallyLoadedPackage(*it);
2759 output_ert_inset(os,
2760 "\\date{" + p.verbatim_item() + '}',
2765 // Starred section headings
2766 // Must attempt to parse "Section*" before "Section".
2767 else if ((p.next_token().asInput() == "*") &&
2768 context.new_layout_allowed &&
2769 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2772 output_command_layout(os, p, outer, context, newlayout);
2774 if (!preamble.titleLayoutFound())
2775 preamble.titleLayoutFound(newlayout->intitle);
2776 set<string> const & req = newlayout->requires();
2777 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2778 preamble.registerAutomaticallyLoadedPackage(*it);
2781 // Section headings and the like
2782 else if (context.new_layout_allowed &&
2783 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2785 output_command_layout(os, p, outer, context, newlayout);
2787 if (!preamble.titleLayoutFound())
2788 preamble.titleLayoutFound(newlayout->intitle);
2789 set<string> const & req = newlayout->requires();
2790 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2791 preamble.registerAutomaticallyLoadedPackage(*it);
2794 else if (t.cs() == "caption") {
2796 context.check_layout(os);
2798 begin_inset(os, "Caption Standard\n");
2799 Context newcontext(true, context.textclass, 0, 0, context.font);
2800 newcontext.check_layout(os);
2801 // FIXME InsetArgument is now properly implemented in InsetLayout
2802 // (for captions, but also for others)
2803 if (p.next_token().cat() != catEscape &&
2804 p.next_token().character() == '[') {
2805 p.get_token(); // eat '['
2806 begin_inset(os, "Argument 1\n");
2807 os << "status collapsed\n";
2808 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2810 eat_whitespace(p, os, context, false);
2812 parse_text(p, os, FLAG_ITEM, outer, context);
2813 context.check_end_layout(os);
2814 // We don't need really a new paragraph, but
2815 // we must make sure that the next item gets a \begin_layout.
2816 context.new_paragraph(os);
2819 newcontext.check_end_layout(os);
2822 else if (t.cs() == "subfloat") {
2823 // the syntax is \subfloat[caption]{content}
2824 // if it is a table of figure depends on the surrounding float
2825 bool has_caption = false;
2827 // do nothing if there is no outer float
2828 if (!float_type.empty()) {
2829 context.check_layout(os);
2831 begin_inset(os, "Float " + float_type + "\n");
2833 << "\nsideways false"
2834 << "\nstatus collapsed\n\n";
2837 if (p.next_token().cat() != catEscape &&
2838 p.next_token().character() == '[') {
2839 p.get_token(); // eat '['
2840 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2844 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2845 // the caption comes always as the last
2847 // we must make sure that the caption gets a \begin_layout
2848 os << "\n\\begin_layout Plain Layout";
2850 begin_inset(os, "Caption Standard\n");
2851 Context newcontext(true, context.textclass,
2852 0, 0, context.font);
2853 newcontext.check_layout(os);
2854 os << caption << "\n";
2855 newcontext.check_end_layout(os);
2856 // We don't need really a new paragraph, but
2857 // we must make sure that the next item gets a \begin_layout.
2858 //newcontext.new_paragraph(os);
2862 // We don't need really a new paragraph, but
2863 // we must make sure that the next item gets a \begin_layout.
2865 context.new_paragraph(os);
2868 context.check_end_layout(os);
2869 // close the layout we opened
2871 os << "\n\\end_layout\n";
2873 // if the float type is not supported or there is no surrounding float
2876 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2877 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2878 "]{" + p.verbatim_item() + '}', context);
2880 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2884 else if (t.cs() == "includegraphics") {
2885 bool const clip = p.next_token().asInput() == "*";
2888 string const arg = p.getArg('[', ']');
2889 map<string, string> opts;
2890 vector<string> keys;
2891 split_map(arg, opts, keys);
2893 opts["clip"] = string();
2894 string name = normalize_filename(p.verbatim_item());
2896 string const path = getMasterFilePath(true);
2897 // We want to preserve relative / absolute filenames,
2898 // therefore path is only used for testing
2899 if (!makeAbsPath(name, path).exists()) {
2900 // The file extension is probably missing.
2901 // Now try to find it out.
2902 string const dvips_name =
2903 find_file(name, path,
2904 known_dvips_graphics_formats);
2905 string const pdftex_name =
2906 find_file(name, path,
2907 known_pdftex_graphics_formats);
2908 if (!dvips_name.empty()) {
2909 if (!pdftex_name.empty()) {
2910 cerr << "This file contains the "
2912 "\"\\includegraphics{"
2914 "However, files\n\""
2915 << dvips_name << "\" and\n\""
2916 << pdftex_name << "\"\n"
2917 "both exist, so I had to make a "
2918 "choice and took the first one.\n"
2919 "Please move the unwanted one "
2920 "someplace else and try again\n"
2921 "if my choice was wrong."
2925 } else if (!pdftex_name.empty()) {
2931 FileName const absname = makeAbsPath(name, path);
2932 if (absname.exists()) {
2933 fix_child_filename(name);
2934 copy_file(absname, name);
2936 cerr << "Warning: Could not find graphics file '"
2937 << name << "'." << endl;
2939 context.check_layout(os);
2940 begin_inset(os, "Graphics ");
2941 os << "\n\tfilename " << name << '\n';
2942 if (opts.find("width") != opts.end())
2944 << translate_len(opts["width"]) << '\n';
2945 if (opts.find("height") != opts.end())
2947 << translate_len(opts["height"]) << '\n';
2948 if (opts.find("scale") != opts.end()) {
2949 istringstream iss(opts["scale"]);
2953 os << "\tscale " << val << '\n';
2955 if (opts.find("angle") != opts.end()) {
2956 os << "\trotateAngle "
2957 << opts["angle"] << '\n';
2958 vector<string>::const_iterator a =
2959 find(keys.begin(), keys.end(), "angle");
2960 vector<string>::const_iterator s =
2961 find(keys.begin(), keys.end(), "width");
2962 if (s == keys.end())
2963 s = find(keys.begin(), keys.end(), "height");
2964 if (s == keys.end())
2965 s = find(keys.begin(), keys.end(), "scale");
2966 if (s != keys.end() && distance(s, a) > 0)
2967 os << "\tscaleBeforeRotation\n";
2969 if (opts.find("origin") != opts.end()) {
2971 string const opt = opts["origin"];
2972 if (opt.find('l') != string::npos) ss << "left";
2973 if (opt.find('r') != string::npos) ss << "right";
2974 if (opt.find('c') != string::npos) ss << "center";
2975 if (opt.find('t') != string::npos) ss << "Top";
2976 if (opt.find('b') != string::npos) ss << "Bottom";
2977 if (opt.find('B') != string::npos) ss << "Baseline";
2978 if (!ss.str().empty())
2979 os << "\trotateOrigin " << ss.str() << '\n';
2981 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2983 if (opts.find("keepaspectratio") != opts.end())
2984 os << "\tkeepAspectRatio\n";
2985 if (opts.find("clip") != opts.end())
2987 if (opts.find("draft") != opts.end())
2989 if (opts.find("bb") != opts.end())
2990 os << "\tBoundingBox "
2991 << opts["bb"] << '\n';
2992 int numberOfbbOptions = 0;
2993 if (opts.find("bbllx") != opts.end())
2994 numberOfbbOptions++;
2995 if (opts.find("bblly") != opts.end())
2996 numberOfbbOptions++;
2997 if (opts.find("bburx") != opts.end())
2998 numberOfbbOptions++;
2999 if (opts.find("bbury") != opts.end())
3000 numberOfbbOptions++;
3001 if (numberOfbbOptions == 4)
3002 os << "\tBoundingBox "
3003 << opts["bbllx"] << " " << opts["bblly"] << " "
3004 << opts["bburx"] << " " << opts["bbury"] << '\n';
3005 else if (numberOfbbOptions > 0)
3006 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3007 numberOfbbOptions = 0;
3008 if (opts.find("natwidth") != opts.end())
3009 numberOfbbOptions++;
3010 if (opts.find("natheight") != opts.end())
3011 numberOfbbOptions++;
3012 if (numberOfbbOptions == 2)
3013 os << "\tBoundingBox 0bp 0bp "
3014 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3015 else if (numberOfbbOptions > 0)
3016 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3017 ostringstream special;
3018 if (opts.find("hiresbb") != opts.end())
3019 special << "hiresbb,";
3020 if (opts.find("trim") != opts.end())
3022 if (opts.find("viewport") != opts.end())
3023 special << "viewport=" << opts["viewport"] << ',';
3024 if (opts.find("totalheight") != opts.end())
3025 special << "totalheight=" << opts["totalheight"] << ',';
3026 if (opts.find("type") != opts.end())
3027 special << "type=" << opts["type"] << ',';
3028 if (opts.find("ext") != opts.end())
3029 special << "ext=" << opts["ext"] << ',';
3030 if (opts.find("read") != opts.end())
3031 special << "read=" << opts["read"] << ',';
3032 if (opts.find("command") != opts.end())
3033 special << "command=" << opts["command"] << ',';
3034 string s_special = special.str();
3035 if (!s_special.empty()) {
3036 // We had special arguments. Remove the trailing ','.
3037 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3039 // TODO: Handle the unknown settings better.
3040 // Warn about invalid options.
3041 // Check whether some option was given twice.
3043 preamble.registerAutomaticallyLoadedPackage("graphicx");
3046 else if (t.cs() == "footnote" ||
3047 (t.cs() == "thanks" && context.layout->intitle)) {
3049 context.check_layout(os);
3050 begin_inset(os, "Foot\n");
3051 os << "status collapsed\n\n";
3052 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3056 else if (t.cs() == "marginpar") {
3058 context.check_layout(os);
3059 begin_inset(os, "Marginal\n");
3060 os << "status collapsed\n\n";
3061 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3065 else if (t.cs() == "lstinline") {
3067 parse_listings(p, os, context, true);
3070 else if (t.cs() == "ensuremath") {
3072 context.check_layout(os);
3073 string const s = p.verbatim_item();
3074 //FIXME: this never triggers in UTF8
3075 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3078 output_ert_inset(os, "\\ensuremath{" + s + "}",
3082 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3083 if (preamble.titleLayoutFound()) {
3085 skip_spaces_braces(p);
3087 output_ert_inset(os, t.asInput(), context);
3090 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3091 context.check_layout(os);
3092 begin_command_inset(os, "toc", t.cs());
3094 skip_spaces_braces(p);
3095 if (t.cs() == "lstlistoflistings")
3096 preamble.registerAutomaticallyLoadedPackage("listings");
3099 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3100 context.check_layout(os);
3101 if (t.cs() == "listoffigures")
3102 begin_inset(os, "FloatList figure\n");
3104 begin_inset(os, "FloatList table\n");
3106 skip_spaces_braces(p);
3109 else if (t.cs() == "listof") {
3110 p.skip_spaces(true);
3111 string const name = p.get_token().cs();
3112 if (context.textclass.floats().typeExist(name)) {
3113 context.check_layout(os);
3114 begin_inset(os, "FloatList ");
3117 p.get_token(); // swallow second arg
3119 output_ert_inset(os, "\\listof{" + name + "}", context);
3122 else if ((where = is_known(t.cs(), known_text_font_families)))
3123 parse_text_attributes(p, os, FLAG_ITEM, outer,
3124 context, "\\family", context.font.family,
3125 known_coded_font_families[where - known_text_font_families]);
3127 else if ((where = is_known(t.cs(), known_text_font_series)))
3128 parse_text_attributes(p, os, FLAG_ITEM, outer,
3129 context, "\\series", context.font.series,
3130 known_coded_font_series[where - known_text_font_series]);
3132 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3133 parse_text_attributes(p, os, FLAG_ITEM, outer,
3134 context, "\\shape", context.font.shape,
3135 known_coded_font_shapes[where - known_text_font_shapes]);
3137 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3138 context.check_layout(os);
3139 TeXFont oldFont = context.font;
3140 context.font.init();
3141 context.font.size = oldFont.size;
3142 os << "\n\\family " << context.font.family << "\n";
3143 os << "\n\\series " << context.font.series << "\n";
3144 os << "\n\\shape " << context.font.shape << "\n";
3145 if (t.cs() == "textnormal") {
3146 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3147 output_font_change(os, context.font, oldFont);
3148 context.font = oldFont;
3150 eat_whitespace(p, os, context, false);
3153 else if (t.cs() == "textcolor") {
3154 // scheme is \textcolor{color name}{text}
3155 string const color = p.verbatim_item();
3156 // we only support the predefined colors of the color package
3157 if (color == "black" || color == "blue" || color == "cyan"
3158 || color == "green" || color == "magenta" || color == "red"
3159 || color == "white" || color == "yellow") {
3160 context.check_layout(os);
3161 os << "\n\\color " << color << "\n";
3162 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3163 context.check_layout(os);
3164 os << "\n\\color inherit\n";
3165 preamble.registerAutomaticallyLoadedPackage("color");
3167 // for custom defined colors
3168 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3171 else if (t.cs() == "underbar" || t.cs() == "uline") {
3172 // \underbar is not 100% correct (LyX outputs \uline
3173 // of ulem.sty). The difference is that \ulem allows
3174 // line breaks, and \underbar does not.
3175 // Do NOT handle \underline.
3176 // \underbar cuts through y, g, q, p etc.,
3177 // \underline does not.
3178 context.check_layout(os);
3179 os << "\n\\bar under\n";
3180 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3181 context.check_layout(os);
3182 os << "\n\\bar default\n";
3183 preamble.registerAutomaticallyLoadedPackage("ulem");
3186 else if (t.cs() == "sout") {
3187 context.check_layout(os);
3188 os << "\n\\strikeout on\n";
3189 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3190 context.check_layout(os);
3191 os << "\n\\strikeout default\n";
3192 preamble.registerAutomaticallyLoadedPackage("ulem");
3195 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3196 t.cs() == "emph" || t.cs() == "noun") {
3197 context.check_layout(os);
3198 os << "\n\\" << t.cs() << " on\n";
3199 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3200 context.check_layout(os);
3201 os << "\n\\" << t.cs() << " default\n";
3202 if (t.cs() == "uuline" || t.cs() == "uwave")
3203 preamble.registerAutomaticallyLoadedPackage("ulem");
3206 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3207 context.check_layout(os);
3208 string name = p.getArg('{', '}');
3209 string localtime = p.getArg('{', '}');
3210 preamble.registerAuthor(name);
3211 Author const & author = preamble.getAuthor(name);
3212 // from_asctime_utc() will fail if LyX decides to output the
3213 // time in the text language.
3214 time_t ptime = from_asctime_utc(localtime);
3215 if (ptime == static_cast<time_t>(-1)) {
3216 cerr << "Warning: Could not parse time `" << localtime
3217 << "´ for change tracking, using current time instead.\n";
3218 ptime = current_time();
3220 if (t.cs() == "lyxadded")
3221 os << "\n\\change_inserted ";
3223 os << "\n\\change_deleted ";
3224 os << author.bufferId() << ' ' << ptime << '\n';
3225 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3226 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3227 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3228 LaTeXPackages::isAvailable("xcolor");
3229 // No need to test for luatex, since luatex comes in
3230 // two flavours (dvi and pdf), like latex, and those
3231 // are detected by pdflatex.
3232 if (pdflatex || xetex) {
3234 preamble.registerAutomaticallyLoadedPackage("ulem");
3235 preamble.registerAutomaticallyLoadedPackage("xcolor");
3236 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3240 preamble.registerAutomaticallyLoadedPackage("dvipost");
3241 } else if (xcolorulem) {
3242 preamble.registerAutomaticallyLoadedPackage("ulem");
3243 preamble.registerAutomaticallyLoadedPackage("xcolor");
3248 else if (t.cs() == "textipa") {
3249 context.check_layout(os);
3250 begin_inset(os, "IPA\n");
3251 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3253 preamble.registerAutomaticallyLoadedPackage("tipa");
3254 preamble.registerAutomaticallyLoadedPackage("tipx");
3257 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3258 context.check_layout(os);
3259 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3260 os << "status open\n";
3261 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3266 else if (t.cs() == "textvertline") {
3267 // FIXME: This is not correct, \textvertline is higher than |
3273 else if (t.cs() == "tone" ) {
3274 context.check_layout(os);
3275 // register the tone package
3276 preamble.registerAutomaticallyLoadedPackage("tone");
3277 string content = trimSpaceAndEol(p.verbatim_item());
3278 string command = t.asInput() + "{" + content + "}";
3279 // some tones can be detected by unicodesymbols, some need special code
3280 if (is_known(content, known_tones)) {
3281 os << "\\IPAChar " << command << "\n";
3284 // try to see whether the string is in unicodesymbols
3288 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3289 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3290 termination, rem, &req);
3294 output_ert_inset(os, to_utf8(rem), context);
3295 for (set<string>::const_iterator it = req.begin();
3296 it != req.end(); ++it)
3297 preamble.registerAutomaticallyLoadedPackage(*it);
3299 // we did not find a non-ert version
3300 output_ert_inset(os, command, context);
3303 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3304 t.cs() == "vphantom") {
3305 context.check_layout(os);
3306 if (t.cs() == "phantom")
3307 begin_inset(os, "Phantom Phantom\n");
3308 if (t.cs() == "hphantom")
3309 begin_inset(os, "Phantom HPhantom\n");
3310 if (t.cs() == "vphantom")
3311 begin_inset(os, "Phantom VPhantom\n");
3312 os << "status open\n";
3313 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3318 else if (t.cs() == "href") {
3319 context.check_layout(os);
3320 string target = convert_command_inset_arg(p.verbatim_item());
3321 string name = convert_command_inset_arg(p.verbatim_item());
3323 size_t i = target.find(':');
3324 if (i != string::npos) {
3325 type = target.substr(0, i + 1);
3326 if (type == "mailto:" || type == "file:")
3327 target = target.substr(i + 1);
3328 // handle the case that name is equal to target, except of "http://"
3329 else if (target.substr(i + 3) == name && type == "http:")
3332 begin_command_inset(os, "href", "href");
3334 os << "name \"" << name << "\"\n";
3335 os << "target \"" << target << "\"\n";
3336 if (type == "mailto:" || type == "file:")
3337 os << "type \"" << type << "\"\n";
3339 skip_spaces_braces(p);
3342 else if (t.cs() == "lyxline") {
3343 // swallow size argument (it is not used anyway)
3345 if (!context.atParagraphStart()) {
3346 // so our line is in the middle of a paragraph
3347 // we need to add a new line, lest this line
3348 // follow the other content on that line and
3349 // run off the side of the page
3350 // FIXME: This may create an empty paragraph,
3351 // but without that it would not be
3352 // possible to set noindent below.
3353 // Fortunately LaTeX does not care
3354 // about the empty paragraph.
3355 context.new_paragraph(os);
3357 if (preamble.indentParagraphs()) {
3358 // we need to unindent, lest the line be too long
3359 context.add_par_extra_stuff("\\noindent\n");
3361 context.check_layout(os);
3362 begin_command_inset(os, "line", "rule");
3363 os << "offset \"0.5ex\"\n"
3364 "width \"100line%\"\n"
3369 else if (t.cs() == "rule") {
3370 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3371 string const width = p.getArg('{', '}');
3372 string const thickness = p.getArg('{', '}');
3373 context.check_layout(os);
3374 begin_command_inset(os, "line", "rule");
3375 if (!offset.empty())
3376 os << "offset \"" << translate_len(offset) << "\"\n";
3377 os << "width \"" << translate_len(width) << "\"\n"
3378 "height \"" << translate_len(thickness) << "\"\n";
3382 else if (is_known(t.cs(), known_phrases) ||
3383 (t.cs() == "protect" &&
3384 p.next_token().cat() == catEscape &&
3385 is_known(p.next_token().cs(), known_phrases))) {
3386 // LyX sometimes puts a \protect in front, so we have to ignore it
3387 // FIXME: This needs to be changed when bug 4752 is fixed.
3389 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3391 context.check_layout(os);
3392 os << known_coded_phrases[where - known_phrases];
3393 skip_spaces_braces(p);
3396 // handle refstyle first to catch \eqref which can also occur
3397 // without refstyle. Only recognize these commands if
3398 // refstyle.sty was found in the preamble (otherwise \eqref
3399 // and user defined ref commands could be misdetected).
3400 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3401 preamble.refstyle()) {
3402 context.check_layout(os);
3403 begin_command_inset(os, "ref", "formatted");
3404 os << "reference \"";
3405 os << known_refstyle_prefixes[where - known_refstyle_commands]
3407 os << convert_command_inset_arg(p.verbatim_item())
3410 preamble.registerAutomaticallyLoadedPackage("refstyle");
3413 // if refstyle is used, we must not convert \prettyref to a
3414 // formatted reference, since that would result in a refstyle command.
3415 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3416 (t.cs() != "prettyref" || !preamble.refstyle())) {
3417 string const opt = p.getOpt();
3419 context.check_layout(os);
3420 begin_command_inset(os, "ref",
3421 known_coded_ref_commands[where - known_ref_commands]);
3422 os << "reference \""
3423 << convert_command_inset_arg(p.verbatim_item())
3426 if (t.cs() == "vref" || t.cs() == "vpageref")
3427 preamble.registerAutomaticallyLoadedPackage("varioref");
3428 else if (t.cs() == "prettyref")
3429 preamble.registerAutomaticallyLoadedPackage("prettyref");
3431 // LyX does not yet support optional arguments of ref commands
3432 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3433 p.verbatim_item() + '}', context);
3437 else if (use_natbib &&
3438 is_known(t.cs(), known_natbib_commands) &&
3439 ((t.cs() != "citefullauthor" &&
3440 t.cs() != "citeyear" &&
3441 t.cs() != "citeyearpar") ||
3442 p.next_token().asInput() != "*")) {
3443 context.check_layout(os);
3444 string command = t.cs();
3445 if (p.next_token().asInput() == "*") {
3449 if (command == "citefullauthor")
3450 // alternative name for "\\citeauthor*"
3451 command = "citeauthor*";
3453 // text before the citation
3455 // text after the citation
3457 get_cite_arguments(p, true, before, after);
3459 if (command == "cite") {
3460 // \cite without optional argument means
3461 // \citet, \cite with at least one optional
3462 // argument means \citep.
3463 if (before.empty() && after.empty())
3468 if (before.empty() && after == "[]")
3469 // avoid \citet[]{a}
3471 else if (before == "[]" && after == "[]") {
3472 // avoid \citet[][]{a}
3476 // remove the brackets around after and before
3477 if (!after.empty()) {
3479 after.erase(after.length() - 1, 1);
3480 after = convert_command_inset_arg(after);
3482 if (!before.empty()) {
3484 before.erase(before.length() - 1, 1);
3485 before = convert_command_inset_arg(before);
3487 begin_command_inset(os, "citation", command);
3488 os << "after " << '"' << after << '"' << "\n";
3489 os << "before " << '"' << before << '"' << "\n";
3491 << convert_command_inset_arg(p.verbatim_item())
3494 // Need to set the cite engine if natbib is loaded by
3495 // the document class directly
3496 if (preamble.citeEngine() == "basic")
3497 preamble.citeEngine("natbib");
3500 else if (use_jurabib &&
3501 is_known(t.cs(), known_jurabib_commands) &&
3502 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3503 context.check_layout(os);
3504 string command = t.cs();
3505 if (p.next_token().asInput() == "*") {
3509 char argumentOrder = '\0';
3510 vector<string> const options =
3511 preamble.getPackageOptions("jurabib");
3512 if (find(options.begin(), options.end(),
3513 "natbiborder") != options.end())
3514 argumentOrder = 'n';
3515 else if (find(options.begin(), options.end(),
3516 "jurabiborder") != options.end())
3517 argumentOrder = 'j';
3519 // text before the citation
3521 // text after the citation
3523 get_cite_arguments(p, argumentOrder != 'j', before, after);
3525 string const citation = p.verbatim_item();
3526 if (!before.empty() && argumentOrder == '\0') {
3527 cerr << "Warning: Assuming argument order "
3528 "of jurabib version 0.6 for\n'"
3529 << command << before << after << '{'
3530 << citation << "}'.\n"
3531 "Add 'jurabiborder' to the jurabib "
3532 "package options if you used an\n"
3533 "earlier jurabib version." << endl;
3535 if (!after.empty()) {
3537 after.erase(after.length() - 1, 1);
3539 if (!before.empty()) {
3541 before.erase(before.length() - 1, 1);
3543 begin_command_inset(os, "citation", command);
3544 os << "after " << '"' << after << '"' << "\n";
3545 os << "before " << '"' << before << '"' << "\n";
3546 os << "key " << '"' << citation << '"' << "\n";
3548 // Need to set the cite engine if jurabib is loaded by
3549 // the document class directly
3550 if (preamble.citeEngine() == "basic")
3551 preamble.citeEngine("jurabib");
3554 else if (t.cs() == "cite"
3555 || t.cs() == "nocite") {
3556 context.check_layout(os);
3557 string after = convert_command_inset_arg(p.getArg('[', ']'));
3558 string key = convert_command_inset_arg(p.verbatim_item());
3559 // store the case that it is "\nocite{*}" to use it later for
3562 begin_command_inset(os, "citation", t.cs());
3563 os << "after " << '"' << after << '"' << "\n";
3564 os << "key " << '"' << key << '"' << "\n";
3566 } else if (t.cs() == "nocite")
3570 else if (t.cs() == "index" ||
3571 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3572 context.check_layout(os);
3573 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3574 p.getArg('[', ']') : "";
3575 string const kind = arg.empty() ? "idx" : arg;
3576 begin_inset(os, "Index ");
3577 os << kind << "\nstatus collapsed\n";
3578 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3581 preamble.registerAutomaticallyLoadedPackage("splitidx");
3584 else if (t.cs() == "nomenclature") {
3585 context.check_layout(os);
3586 begin_command_inset(os, "nomenclature", "nomenclature");
3587 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3588 if (!prefix.empty())
3589 os << "prefix " << '"' << prefix << '"' << "\n";
3590 os << "symbol " << '"'
3591 << convert_command_inset_arg(p.verbatim_item());
3592 os << "\"\ndescription \""
3593 << convert_command_inset_arg(p.verbatim_item())
3596 preamble.registerAutomaticallyLoadedPackage("nomencl");
3599 else if (t.cs() == "label") {
3600 context.check_layout(os);
3601 begin_command_inset(os, "label", "label");
3603 << convert_command_inset_arg(p.verbatim_item())
3608 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3609 context.check_layout(os);
3610 string commandname = t.cs();
3612 if (p.next_token().asInput() == "*") {
3617 begin_command_inset(os, "index_print", commandname);
3618 string const indexname = p.getArg('[', ']');
3620 if (indexname.empty())
3621 os << "type \"idx\"\n";
3623 os << "type \"" << indexname << "\"\n";
3626 skip_spaces_braces(p);
3627 preamble.registerAutomaticallyLoadedPackage("makeidx");
3628 if (preamble.use_indices() == "true")
3629 preamble.registerAutomaticallyLoadedPackage("splitidx");
3632 else if (t.cs() == "printnomenclature") {
3634 string width_type = "";
3635 context.check_layout(os);
3636 begin_command_inset(os, "nomencl_print", "printnomenclature");
3637 // case of a custom width
3639 width = p.getArg('[', ']');
3640 width = translate_len(width);
3641 width_type = "custom";
3643 // case of no custom width
3644 // the case of no custom width but the width set
3645 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3646 // because the user could have set anything, not only the width
3647 // of the longest label (which would be width_type = "auto")
3648 string label = convert_command_inset_arg(p.getArg('{', '}'));
3649 if (label.empty() && width_type.empty())
3650 width_type = "none";
3651 os << "set_width \"" << width_type << "\"\n";
3652 if (width_type == "custom")
3653 os << "width \"" << width << '\"';
3655 skip_spaces_braces(p);
3656 preamble.registerAutomaticallyLoadedPackage("nomencl");
3659 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3660 context.check_layout(os);
3661 begin_inset(os, "script ");
3662 os << t.cs().substr(4) << '\n';
3663 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3665 if (t.cs() == "textsubscript")
3666 preamble.registerAutomaticallyLoadedPackage("subscript");
3669 else if ((where = is_known(t.cs(), known_quotes))) {
3670 context.check_layout(os);
3671 begin_inset(os, "Quotes ");
3672 os << known_coded_quotes[where - known_quotes];
3674 // LyX adds {} after the quote, so we have to eat
3675 // spaces here if there are any before a possible
3677 eat_whitespace(p, os, context, false);
3681 else if ((where = is_known(t.cs(), known_sizes)) &&
3682 context.new_layout_allowed) {
3683 context.check_layout(os);
3684 TeXFont const oldFont = context.font;
3685 context.font.size = known_coded_sizes[where - known_sizes];
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_families)) &&
3691 context.new_layout_allowed) {
3692 context.check_layout(os);
3693 TeXFont const oldFont = context.font;
3694 context.font.family =
3695 known_coded_font_families[where - known_font_families];
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_series)) &&
3701 context.new_layout_allowed) {
3702 context.check_layout(os);
3703 TeXFont const oldFont = context.font;
3704 context.font.series =
3705 known_coded_font_series[where - known_font_series];
3706 output_font_change(os, oldFont, context.font);
3707 eat_whitespace(p, os, context, false);
3710 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3711 context.new_layout_allowed) {
3712 context.check_layout(os);
3713 TeXFont const oldFont = context.font;
3714 context.font.shape =
3715 known_coded_font_shapes[where - known_font_shapes];
3716 output_font_change(os, oldFont, context.font);
3717 eat_whitespace(p, os, context, false);
3719 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3720 context.new_layout_allowed) {
3721 context.check_layout(os);
3722 TeXFont const oldFont = context.font;
3723 context.font.init();
3724 context.font.size = oldFont.size;
3725 context.font.family =
3726 known_coded_font_families[where - known_old_font_families];
3727 output_font_change(os, oldFont, context.font);
3728 eat_whitespace(p, os, context, false);
3731 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3732 context.new_layout_allowed) {
3733 context.check_layout(os);
3734 TeXFont const oldFont = context.font;
3735 context.font.init();
3736 context.font.size = oldFont.size;
3737 context.font.series =
3738 known_coded_font_series[where - known_old_font_series];
3739 output_font_change(os, oldFont, context.font);
3740 eat_whitespace(p, os, context, false);
3743 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3744 context.new_layout_allowed) {
3745 context.check_layout(os);
3746 TeXFont const oldFont = context.font;
3747 context.font.init();
3748 context.font.size = oldFont.size;
3749 context.font.shape =
3750 known_coded_font_shapes[where - known_old_font_shapes];
3751 output_font_change(os, oldFont, context.font);
3752 eat_whitespace(p, os, context, false);
3755 else if (t.cs() == "selectlanguage") {
3756 context.check_layout(os);
3757 // save the language for the case that a
3758 // \foreignlanguage is used
3759 context.font.language = babel2lyx(p.verbatim_item());
3760 os << "\n\\lang " << context.font.language << "\n";
3763 else if (t.cs() == "foreignlanguage") {
3764 string const lang = babel2lyx(p.verbatim_item());
3765 parse_text_attributes(p, os, FLAG_ITEM, outer,
3767 context.font.language, lang);
3770 else if (prefixIs(t.cs(), "text")
3771 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3772 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3774 // We have to output the whole command if it has an option
3775 // because LyX doesn't support this yet, see bug #8214,
3776 // only if there is a single option specifying a variant, we can handle it.
3778 string langopts = p.getOpt();
3779 // check if the option contains a variant, if yes, extract it
3780 string::size_type pos_var = langopts.find("variant");
3781 string::size_type i = langopts.find(',');
3782 string::size_type k = langopts.find('=', pos_var);
3783 if (pos_var != string::npos && i == string::npos) {
3785 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3786 lang = preamble.polyglossia2lyx(variant);
3787 parse_text_attributes(p, os, FLAG_ITEM, outer,
3789 context.font.language, lang);
3791 output_ert_inset(os, t.asInput() + langopts, context);
3793 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3794 parse_text_attributes(p, os, FLAG_ITEM, outer,
3796 context.font.language, lang);
3800 else if (t.cs() == "inputencoding") {
3801 // nothing to write here
3802 string const enc = subst(p.verbatim_item(), "\n", " ");
3803 p.setEncoding(enc, Encoding::inputenc);
3806 else if ((where = is_known(t.cs(), known_special_chars))) {
3807 context.check_layout(os);
3808 os << known_coded_special_chars[where - known_special_chars];
3809 skip_spaces_braces(p);
3812 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3813 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3814 context.check_layout(os);
3815 os << "\\SpecialChar \\" << t.cs()
3816 << p.get_token().asInput() << '\n';
3819 else if (t.cs() == "textquotedbl") {
3820 context.check_layout(os);
3825 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3826 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3827 || t.cs() == "%" || t.cs() == "-") {
3828 context.check_layout(os);
3830 os << "\\SpecialChar \\-\n";
3835 else if (t.cs() == "char") {
3836 context.check_layout(os);
3837 if (p.next_token().character() == '`') {
3839 if (p.next_token().cs() == "\"") {
3844 output_ert_inset(os, "\\char`", context);
3847 output_ert_inset(os, "\\char", context);
3851 else if (t.cs() == "verb") {
3852 context.check_layout(os);
3853 // set catcodes to verbatim early, just in case.
3854 p.setCatcodes(VERBATIM_CATCODES);
3855 string delim = p.get_token().asInput();
3856 Parser::Arg arg = p.verbatimStuff(delim);
3858 output_ert_inset(os, "\\verb" + delim
3859 + arg.second + delim, context);
3861 cerr << "invalid \\verb command. Skipping" << endl;
3864 // Problem: \= creates a tabstop inside the tabbing environment
3865 // and else an accent. In the latter case we really would want
3866 // \={o} instead of \= o.
3867 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3868 output_ert_inset(os, t.asInput(), context);
3870 else if (t.cs() == "\\") {
3871 context.check_layout(os);
3873 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3874 else if (p.next_token().asInput() == "*") {
3876 // getOpt() eats the following space if there
3877 // is no optional argument, but that is OK
3878 // here since it has no effect in the output.
3879 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3882 begin_inset(os, "Newline newline");
3887 else if (t.cs() == "newline" ||
3888 (t.cs() == "linebreak" && !p.hasOpt())) {
3889 context.check_layout(os);
3890 begin_inset(os, "Newline ");
3893 skip_spaces_braces(p);
3896 else if (t.cs() == "input" || t.cs() == "include"
3897 || t.cs() == "verbatiminput") {
3898 string name = t.cs();
3899 if (t.cs() == "verbatiminput"
3900 && p.next_token().asInput() == "*")
3901 name += p.get_token().asInput();
3902 context.check_layout(os);
3903 string filename(normalize_filename(p.getArg('{', '}')));
3904 string const path = getMasterFilePath(true);
3905 // We want to preserve relative / absolute filenames,
3906 // therefore path is only used for testing
3907 if ((t.cs() == "include" || t.cs() == "input") &&
3908 !makeAbsPath(filename, path).exists()) {
3909 // The file extension is probably missing.
3910 // Now try to find it out.
3911 string const tex_name =
3912 find_file(filename, path,
3913 known_tex_extensions);
3914 if (!tex_name.empty())
3915 filename = tex_name;
3917 bool external = false;
3919 if (makeAbsPath(filename, path).exists()) {
3920 string const abstexname =
3921 makeAbsPath(filename, path).absFileName();
3922 string const absfigname =
3923 changeExtension(abstexname, ".fig");
3924 fix_child_filename(filename);
3925 string const lyxname =
3926 changeExtension(filename, ".lyx");
3927 string const abslyxname = makeAbsPath(
3928 lyxname, getParentFilePath(false)).absFileName();
3930 if (!skipChildren())
3931 external = FileName(absfigname).exists();
3932 if (t.cs() == "input" && !skipChildren()) {
3933 string const ext = getExtension(abstexname);
3935 // Combined PS/LaTeX:
3936 // x.eps, x.pstex_t (old xfig)
3937 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3938 FileName const absepsname(
3939 changeExtension(abstexname, ".eps"));
3940 FileName const abspstexname(
3941 changeExtension(abstexname, ".pstex"));
3942 bool const xfigeps =
3943 (absepsname.exists() ||
3944 abspstexname.exists()) &&
3947 // Combined PDF/LaTeX:
3948 // x.pdf, x.pdftex_t (old xfig)
3949 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3950 FileName const abspdfname(
3951 changeExtension(abstexname, ".pdf"));
3952 bool const xfigpdf =
3953 abspdfname.exists() &&
3954 (ext == "pdftex_t" || ext == "pdf_t");
3958 // Combined PS/PDF/LaTeX:
3959 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3960 string const absbase2(
3961 removeExtension(abstexname) + "_pspdftex");
3962 FileName const abseps2name(
3963 addExtension(absbase2, ".eps"));
3964 FileName const abspdf2name(
3965 addExtension(absbase2, ".pdf"));
3966 bool const xfigboth =
3967 abspdf2name.exists() &&
3968 abseps2name.exists() && ext == "pspdftex";
3970 xfig = xfigpdf || xfigeps || xfigboth;
3971 external = external && xfig;
3974 outname = changeExtension(filename, ".fig");
3975 FileName abssrc(changeExtension(abstexname, ".fig"));
3976 copy_file(abssrc, outname);
3978 // Don't try to convert, the result
3979 // would be full of ERT.
3981 FileName abssrc(abstexname);
3982 copy_file(abssrc, outname);
3983 } else if (t.cs() != "verbatiminput" &&
3985 tex2lyx(abstexname, FileName(abslyxname),
3988 // no need to call copy_file
3989 // tex2lyx creates the file
3992 FileName abssrc(abstexname);
3993 copy_file(abssrc, outname);
3996 cerr << "Warning: Could not find included file '"
3997 << filename << "'." << endl;
4001 begin_inset(os, "External\n");
4002 os << "\ttemplate XFig\n"
4003 << "\tfilename " << outname << '\n';
4004 registerExternalTemplatePackages("XFig");
4006 begin_command_inset(os, "include", name);
4007 outname = subst(outname, "\"", "\\\"");
4008 os << "preview false\n"
4009 "filename \"" << outname << "\"\n";
4010 if (t.cs() == "verbatiminput")
4011 preamble.registerAutomaticallyLoadedPackage("verbatim");
4016 else if (t.cs() == "bibliographystyle") {
4017 // store new bibliographystyle
4018 bibliographystyle = p.verbatim_item();
4019 // If any other command than \bibliography, \addcontentsline
4020 // and \nocite{*} follows, we need to output the style
4021 // (because it might be used by that command).
4022 // Otherwise, it will automatically be output by LyX.
4025 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4026 if (t2.cat() == catBegin)
4028 if (t2.cat() != catEscape)
4030 if (t2.cs() == "nocite") {
4031 if (p.getArg('{', '}') == "*")
4033 } else if (t2.cs() == "bibliography")
4035 else if (t2.cs() == "phantomsection") {
4039 else if (t2.cs() == "addcontentsline") {
4040 // get the 3 arguments of \addcontentsline
4043 contentslineContent = p.getArg('{', '}');
4044 // if the last argument is not \refname we must output
4045 if (contentslineContent == "\\refname")
4052 output_ert_inset(os,
4053 "\\bibliographystyle{" + bibliographystyle + '}',
4058 else if (t.cs() == "phantomsection") {
4059 // we only support this if it occurs between
4060 // \bibliographystyle and \bibliography
4061 if (bibliographystyle.empty())
4062 output_ert_inset(os, "\\phantomsection", context);
4065 else if (t.cs() == "addcontentsline") {
4066 context.check_layout(os);
4067 // get the 3 arguments of \addcontentsline
4068 string const one = p.getArg('{', '}');
4069 string const two = p.getArg('{', '}');
4070 string const three = p.getArg('{', '}');
4071 // only if it is a \refname, we support if for the bibtex inset
4072 if (contentslineContent != "\\refname") {
4073 output_ert_inset(os,
4074 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4079 else if (t.cs() == "bibliography") {
4080 context.check_layout(os);
4082 begin_command_inset(os, "bibtex", "bibtex");
4083 if (!btprint.empty()) {
4084 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4085 // clear the string because the next BibTeX inset can be without the
4086 // \nocite{*} option
4089 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4090 // Do we have addcontentsline?
4091 if (contentslineContent == "\\refname") {
4092 BibOpts = "bibtotoc";
4093 // clear string because next BibTeX inset can be without addcontentsline
4094 contentslineContent.clear();
4096 // Do we have a bibliographystyle set?
4097 if (!bibliographystyle.empty()) {
4098 if (BibOpts.empty())
4099 BibOpts = bibliographystyle;
4101 BibOpts = BibOpts + ',' + bibliographystyle;
4102 // clear it because each bibtex entry has its style
4103 // and we need an empty string to handle \phantomsection
4104 bibliographystyle.clear();
4106 os << "options " << '"' << BibOpts << '"' << "\n";
4110 else if (t.cs() == "parbox") {
4111 // Test whether this is an outer box of a shaded box
4113 // swallow arguments
4114 while (p.hasOpt()) {
4116 p.skip_spaces(true);
4119 p.skip_spaces(true);
4121 if (p.next_token().cat() == catBegin)
4123 p.skip_spaces(true);
4124 Token to = p.get_token();
4125 bool shaded = false;
4126 if (to.asInput() == "\\begin") {
4127 p.skip_spaces(true);
4128 if (p.getArg('{', '}') == "shaded")
4133 parse_outer_box(p, os, FLAG_ITEM, outer,
4134 context, "parbox", "shaded");
4136 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4140 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4141 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4142 t.cs() == "shadowbox" || t.cs() == "doublebox")
4143 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4145 else if (t.cs() == "framebox") {
4146 if (p.next_token().character() == '(') {
4147 //the syntax is: \framebox(x,y)[position]{content}
4148 string arg = t.asInput();
4149 arg += p.getFullParentheseArg();
4150 arg += p.getFullOpt();
4151 eat_whitespace(p, os, context, false);
4152 output_ert_inset(os, arg + '{', context);
4153 parse_text(p, os, FLAG_ITEM, outer, context);
4154 output_ert_inset(os, "}", context);
4156 //the syntax is: \framebox[width][position]{content}
4157 string special = p.getFullOpt();
4158 special += p.getOpt();
4159 parse_outer_box(p, os, FLAG_ITEM, outer,
4160 context, t.cs(), special);
4164 //\makebox() is part of the picture environment and different from \makebox{}
4165 //\makebox{} will be parsed by parse_box
4166 else if (t.cs() == "makebox") {
4167 if (p.next_token().character() == '(') {
4168 //the syntax is: \makebox(x,y)[position]{content}
4169 string arg = t.asInput();
4170 arg += p.getFullParentheseArg();
4171 arg += p.getFullOpt();
4172 eat_whitespace(p, os, context, false);
4173 output_ert_inset(os, arg + '{', context);
4174 parse_text(p, os, FLAG_ITEM, outer, context);
4175 output_ert_inset(os, "}", context);
4177 //the syntax is: \makebox[width][position]{content}
4178 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4182 else if (t.cs() == "smallskip" ||
4183 t.cs() == "medskip" ||
4184 t.cs() == "bigskip" ||
4185 t.cs() == "vfill") {
4186 context.check_layout(os);
4187 begin_inset(os, "VSpace ");
4190 skip_spaces_braces(p);
4193 else if ((where = is_known(t.cs(), known_spaces))) {
4194 context.check_layout(os);
4195 begin_inset(os, "space ");
4196 os << '\\' << known_coded_spaces[where - known_spaces]
4199 // LaTeX swallows whitespace after all spaces except
4200 // "\\,". We have to do that here, too, because LyX
4201 // adds "{}" which would make the spaces significant.
4203 eat_whitespace(p, os, context, false);
4204 // LyX adds "{}" after all spaces except "\\ " and
4205 // "\\,", so we have to remove "{}".
4206 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4207 // remove the braces after "\\,", too.
4212 else if (t.cs() == "newpage" ||
4213 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4214 t.cs() == "clearpage" ||
4215 t.cs() == "cleardoublepage") {
4216 context.check_layout(os);
4217 begin_inset(os, "Newpage ");
4220 skip_spaces_braces(p);
4223 else if (t.cs() == "DeclareRobustCommand" ||
4224 t.cs() == "DeclareRobustCommandx" ||
4225 t.cs() == "newcommand" ||
4226 t.cs() == "newcommandx" ||
4227 t.cs() == "providecommand" ||
4228 t.cs() == "providecommandx" ||
4229 t.cs() == "renewcommand" ||
4230 t.cs() == "renewcommandx") {
4231 // DeclareRobustCommand, DeclareRobustCommandx,
4232 // providecommand and providecommandx could be handled
4233 // by parse_command(), but we need to call
4234 // add_known_command() here.
4235 string name = t.asInput();
4236 if (p.next_token().asInput() == "*") {
4237 // Starred form. Eat '*'
4241 string const command = p.verbatim_item();
4242 string const opt1 = p.getFullOpt();
4243 string const opt2 = p.getFullOpt();
4244 add_known_command(command, opt1, !opt2.empty());
4245 string const ert = name + '{' + command + '}' +
4247 '{' + p.verbatim_item() + '}';
4249 if (t.cs() == "DeclareRobustCommand" ||
4250 t.cs() == "DeclareRobustCommandx" ||
4251 t.cs() == "providecommand" ||
4252 t.cs() == "providecommandx" ||
4253 name[name.length()-1] == '*')
4254 output_ert_inset(os, ert, context);
4256 context.check_layout(os);
4257 begin_inset(os, "FormulaMacro");
4263 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4264 // let could be handled by parse_command(),
4265 // but we need to call add_known_command() here.
4266 string ert = t.asInput();
4269 if (p.next_token().cat() == catBegin) {
4270 name = p.verbatim_item();
4271 ert += '{' + name + '}';
4273 name = p.verbatim_item();
4278 if (p.next_token().cat() == catBegin) {
4279 command = p.verbatim_item();
4280 ert += '{' + command + '}';
4282 command = p.verbatim_item();
4285 // If command is known, make name known too, to parse
4286 // its arguments correctly. For this reason we also
4287 // have commands in syntax.default that are hardcoded.
4288 CommandMap::iterator it = known_commands.find(command);
4289 if (it != known_commands.end())
4290 known_commands[t.asInput()] = it->second;
4291 output_ert_inset(os, ert, context);
4294 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4295 bool starred = false;
4296 if (p.next_token().asInput() == "*") {
4300 string name = t.asInput();
4301 string const length = p.verbatim_item();
4304 bool valid = splitLatexLength(length, valstring, unit);
4305 bool known_hspace = false;
4306 bool known_vspace = false;
4307 bool known_unit = false;
4310 istringstream iss(valstring);
4313 if (t.cs()[0] == 'h') {
4314 if (unit == "\\fill") {
4319 known_hspace = true;
4322 if (unit == "\\smallskipamount") {
4324 known_vspace = true;
4325 } else if (unit == "\\medskipamount") {
4327 known_vspace = true;
4328 } else if (unit == "\\bigskipamount") {
4330 known_vspace = true;
4331 } else if (unit == "\\fill") {
4333 known_vspace = true;
4337 if (!known_hspace && !known_vspace) {
4338 switch (unitFromString(unit)) {
4359 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4360 // Literal horizontal length or known variable
4361 context.check_layout(os);
4362 begin_inset(os, "space ");
4370 if (known_unit && !known_hspace)
4372 << translate_len(length);
4374 } else if (known_unit || known_vspace) {
4375 // Literal vertical length or known variable
4376 context.check_layout(os);
4377 begin_inset(os, "VSpace ");
4385 // LyX can't handle other length variables in Inset VSpace/space
4390 output_ert_inset(os, name + '{' + unit + '}', context);
4391 else if (value == -1.0)
4392 output_ert_inset(os, name + "{-" + unit + '}', context);
4394 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4396 output_ert_inset(os, name + '{' + length + '}', context);
4400 // The single '=' is meant here.
4401 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4403 context.check_layout(os);
4404 begin_inset(os, "Flex ");
4405 os << to_utf8(newinsetlayout->name()) << '\n'
4406 << "status collapsed\n";
4407 if (newinsetlayout->isPassThru()) {
4408 // set catcodes to verbatim early, just in case.
4409 p.setCatcodes(VERBATIM_CATCODES);
4410 string delim = p.get_token().asInput();
4412 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4413 //FIXME: handle error condition
4414 string const arg = p.verbatimStuff("}").second;
4415 Context newcontext(true, context.textclass);
4416 if (newinsetlayout->forcePlainLayout())
4417 newcontext.layout = &context.textclass.plainLayout();
4418 output_ert(os, arg, newcontext);
4421 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4425 else if (t.cs() == "includepdf") {
4427 string const arg = p.getArg('[', ']');
4428 map<string, string> opts;
4429 vector<string> keys;
4430 split_map(arg, opts, keys);
4431 string name = normalize_filename(p.verbatim_item());
4432 string const path = getMasterFilePath(true);
4433 // We want to preserve relative / absolute filenames,
4434 // therefore path is only used for testing
4435 if (!makeAbsPath(name, path).exists()) {
4436 // The file extension is probably missing.
4437 // Now try to find it out.
4438 char const * const pdfpages_format[] = {"pdf", 0};
4439 string const pdftex_name =
4440 find_file(name, path, pdfpages_format);
4441 if (!pdftex_name.empty()) {
4446 FileName const absname = makeAbsPath(name, path);
4447 if (absname.exists())
4449 fix_child_filename(name);
4450 copy_file(absname, name);
4452 cerr << "Warning: Could not find file '"
4453 << name << "'." << endl;
4455 context.check_layout(os);
4456 begin_inset(os, "External\n\ttemplate ");
4457 os << "PDFPages\n\tfilename "
4459 // parse the options
4460 if (opts.find("pages") != opts.end())
4461 os << "\textra LaTeX \"pages="
4462 << opts["pages"] << "\"\n";
4463 if (opts.find("angle") != opts.end())
4464 os << "\trotateAngle "
4465 << opts["angle"] << '\n';
4466 if (opts.find("origin") != opts.end()) {
4468 string const opt = opts["origin"];
4469 if (opt == "tl") ss << "topleft";
4470 if (opt == "bl") ss << "bottomleft";
4471 if (opt == "Bl") ss << "baselineleft";
4472 if (opt == "c") ss << "center";
4473 if (opt == "tc") ss << "topcenter";
4474 if (opt == "bc") ss << "bottomcenter";
4475 if (opt == "Bc") ss << "baselinecenter";
4476 if (opt == "tr") ss << "topright";
4477 if (opt == "br") ss << "bottomright";
4478 if (opt == "Br") ss << "baselineright";
4479 if (!ss.str().empty())
4480 os << "\trotateOrigin " << ss.str() << '\n';
4482 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4484 if (opts.find("width") != opts.end())
4486 << translate_len(opts["width"]) << '\n';
4487 if (opts.find("height") != opts.end())
4489 << translate_len(opts["height"]) << '\n';
4490 if (opts.find("keepaspectratio") != opts.end())
4491 os << "\tkeepAspectRatio\n";
4493 context.check_layout(os);
4494 registerExternalTemplatePackages("PDFPages");
4497 else if (t.cs() == "loadgame") {
4499 string name = normalize_filename(p.verbatim_item());
4500 string const path = getMasterFilePath(true);
4501 // We want to preserve relative / absolute filenames,
4502 // therefore path is only used for testing
4503 if (!makeAbsPath(name, path).exists()) {
4504 // The file extension is probably missing.
4505 // Now try to find it out.
4506 char const * const lyxskak_format[] = {"fen", 0};
4507 string const lyxskak_name =
4508 find_file(name, path, lyxskak_format);
4509 if (!lyxskak_name.empty())
4510 name = lyxskak_name;
4512 FileName const absname = makeAbsPath(name, path);
4513 if (absname.exists())
4515 fix_child_filename(name);
4516 copy_file(absname, name);
4518 cerr << "Warning: Could not find file '"
4519 << name << "'." << endl;
4520 context.check_layout(os);
4521 begin_inset(os, "External\n\ttemplate ");
4522 os << "ChessDiagram\n\tfilename "
4525 context.check_layout(os);
4526 // after a \loadgame follows a \showboard
4527 if (p.get_token().asInput() == "showboard")
4529 registerExternalTemplatePackages("ChessDiagram");
4533 // try to see whether the string is in unicodesymbols
4534 // Only use text mode commands, since we are in text mode here,
4535 // and math commands may be invalid (bug 6797)
4536 string name = t.asInput();
4537 // handle the dingbats and Cyrillic
4538 if (name == "\\ding" || name == "\\textcyr")
4539 name = name + '{' + p.getArg('{', '}') + '}';
4540 // handle the ifsym characters
4541 else if (name == "\\textifsymbol") {
4542 string const optif = p.getFullOpt();
4543 string const argif = p.getArg('{', '}');
4544 name = name + optif + '{' + argif + '}';
4546 // handle the \ascii characters
4547 // the case of \ascii within braces, as LyX outputs it, is already
4548 // handled for t.cat() == catBegin
4549 else if (name == "\\ascii") {
4550 // the code is "\asci\xxx"
4551 name = "{" + name + p.get_token().asInput() + "}";
4554 // handle some TIPA special characters
4555 else if (preamble.isPackageUsed("tipa")) {
4556 if (name == "\\textglobfall") {
4559 } else if (name == "\\s") {
4560 // fromLaTeXCommand() does not yet
4561 // recognize tipa short cuts
4562 name = "\\textsyllabic";
4563 } else if (name == "\\=" &&
4564 p.next_token().asInput() == "*") {
4565 // fromLaTeXCommand() does not yet
4566 // recognize tipa short cuts
4569 } else if (name == "\\textdoublevertline") {
4570 // FIXME: This is not correct,
4571 // \textvertline is higher than \textbardbl
4572 name = "\\textbardbl";
4574 } else if (name == "\\!" ) {
4575 if (p.next_token().asInput() == "b") {
4576 p.get_token(); // eat 'b'
4579 } else if (p.next_token().asInput() == "d") {
4583 } else if (p.next_token().asInput() == "g") {
4587 } else if (p.next_token().asInput() == "G") {
4589 name = "\\texthtscg";
4591 } else if (p.next_token().asInput() == "j") {
4593 name = "\\texthtbardotlessj";
4595 } else if (p.next_token().asInput() == "o") {
4597 name = "\\textbullseye";
4600 } else if (name == "\\*" ) {
4601 if (p.next_token().asInput() == "k") {
4603 name = "\\textturnk";
4605 } else if (p.next_token().asInput() == "r") {
4606 p.get_token(); // eat 'b'
4607 name = "\\textturnr";
4609 } else if (p.next_token().asInput() == "t") {
4611 name = "\\textturnt";
4613 } else if (p.next_token().asInput() == "w") {
4615 name = "\\textturnw";
4620 if ((name.size() == 2 &&
4621 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4622 p.next_token().asInput() != "*") ||
4623 is_known(name.substr(1), known_tipa_marks)) {
4624 // name is a command that corresponds to a
4625 // combining character in unicodesymbols.
4626 // Append the argument, fromLaTeXCommand()
4627 // will either convert it to a single
4628 // character or a combining sequence.
4629 name += '{' + p.verbatim_item() + '}';
4631 // now get the character from unicodesymbols
4635 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4636 Encodings::TEXT_CMD, termination, rem, &req);
4638 context.check_layout(os);
4641 output_ert_inset(os, to_utf8(rem), context);
4643 skip_spaces_braces(p);
4644 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4645 preamble.registerAutomaticallyLoadedPackage(*it);
4647 //cerr << "#: " << t << " mode: " << mode << endl;
4648 // heuristic: read up to next non-nested space
4650 string s = t.asInput();
4651 string z = p.verbatim_item();
4652 while (p.good() && z != " " && !z.empty()) {
4653 //cerr << "read: " << z << endl;
4655 z = p.verbatim_item();
4657 cerr << "found ERT: " << s << endl;
4658 output_ert_inset(os, s + ' ', context);
4661 if (t.asInput() == name &&
4662 p.next_token().asInput() == "*") {
4663 // Starred commands like \vspace*{}
4664 p.get_token(); // Eat '*'
4667 if (!parse_command(name, p, os, outer, context))
4668 output_ert_inset(os, name, context);
4672 if (flags & FLAG_LEAVE) {
4673 flags &= ~FLAG_LEAVE;
4680 string guessLanguage(Parser & p, string const & lang)
4682 typedef std::map<std::string, size_t> LangMap;
4683 // map from language names to number of characters
4686 for (char const * const * i = supported_CJK_languages; *i; i++)
4687 used[string(*i)] = 0;
4690 Token const t = p.get_token();
4691 // comments are not counted for any language
4692 if (t.cat() == catComment)
4694 // commands are not counted as well, but we need to detect
4695 // \begin{CJK} and switch encoding if needed
4696 if (t.cat() == catEscape) {
4697 if (t.cs() == "inputencoding") {
4698 string const enc = subst(p.verbatim_item(), "\n", " ");
4699 p.setEncoding(enc, Encoding::inputenc);
4702 if (t.cs() != "begin")
4705 // Non-CJK content is counted for lang.
4706 // We do not care about the real language here:
4707 // If we have more non-CJK contents than CJK contents,
4708 // we simply use the language that was specified as
4709 // babel main language.
4710 used[lang] += t.asInput().length();
4713 // Now we are starting an environment
4715 string const name = p.getArg('{', '}');
4716 if (name != "CJK") {
4720 // It is a CJK environment
4722 /* name = */ p.getArg('{', '}');
4723 string const encoding = p.getArg('{', '}');
4724 /* mapping = */ p.getArg('{', '}');
4725 string const encoding_old = p.getEncoding();
4726 char const * const * const where =
4727 is_known(encoding, supported_CJK_encodings);
4729 p.setEncoding(encoding, Encoding::CJK);
4731 p.setEncoding("UTF-8");
4732 string const text = p.ertEnvironment("CJK");
4733 p.setEncoding(encoding_old);
4736 // ignore contents in unknown CJK encoding
4739 // the language of the text
4741 supported_CJK_languages[where - supported_CJK_encodings];
4742 used[cjk] += text.length();
4744 LangMap::const_iterator use = used.begin();
4745 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4746 if (it->second > use->second)