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") {
940 width_special = "none";
944 if (!outer_type.empty()) {
945 if (outer_flags & FLAG_END)
946 ss << "\\begin{" << outer_type << '}';
948 ss << '\\' << outer_type << '{';
949 if (!special.empty())
953 if (!inner_type.empty()) {
954 if (inner_type != "shaded") {
955 if (inner_flags & FLAG_END)
956 ss << "\\begin{" << inner_type << '}';
958 ss << '\\' << inner_type;
960 if (!position.empty())
961 ss << '[' << position << ']';
962 if (!latex_height.empty())
963 ss << '[' << latex_height << ']';
964 if (!inner_pos.empty())
965 ss << '[' << inner_pos << ']';
966 ss << '{' << latex_width << '}';
967 if (!(inner_flags & FLAG_END))
970 if (inner_type == "shaded")
971 ss << "\\begin{shaded}";
972 output_ert_inset(os, ss.str(), parent_context);
973 if (!inner_type.empty()) {
974 parse_text(p, os, inner_flags, outer, parent_context);
975 if (inner_flags & FLAG_END)
976 output_ert_inset(os, "\\end{" + inner_type + '}',
979 output_ert_inset(os, "}", parent_context);
981 if (!outer_type.empty()) {
982 // If we already read the inner box we have to pop
984 if (!inner_type.empty() && (inner_flags & FLAG_END))
985 active_environments.pop_back();
987 // Ensure that the end of the outer box is parsed correctly:
988 // The opening brace has been eaten by parse_outer_box()
989 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
990 outer_flags &= ~FLAG_ITEM;
991 outer_flags |= FLAG_BRACE_LAST;
993 parse_text(p, os, outer_flags, outer, parent_context);
994 if (outer_flags & FLAG_END)
995 output_ert_inset(os, "\\end{" + outer_type + '}',
998 output_ert_inset(os, "}", parent_context);
1001 // LyX does not like empty positions, so we have
1002 // to set them to the LaTeX default values here.
1003 if (position.empty())
1005 if (inner_pos.empty())
1006 inner_pos = position;
1007 parent_context.check_layout(os);
1008 begin_inset(os, "Box ");
1009 if (outer_type == "framed")
1011 else if (outer_type == "framebox" || outer_type == "fbox")
1013 else if (outer_type == "shadowbox")
1014 os << "Shadowbox\n";
1015 else if ((outer_type == "shaded" && inner_type.empty()) ||
1016 (outer_type == "minipage" && inner_type == "shaded") ||
1017 (outer_type == "parbox" && inner_type == "shaded")) {
1019 preamble.registerAutomaticallyLoadedPackage("color");
1020 } else if (outer_type == "doublebox")
1021 os << "Doublebox\n";
1022 else if (outer_type.empty() || outer_type == "mbox")
1023 os << "Frameless\n";
1025 os << outer_type << '\n';
1026 os << "position \"" << position << "\"\n";
1027 os << "hor_pos \"" << hor_pos << "\"\n";
1028 if (outer_type == "mbox")
1029 os << "has_inner_box 1\n";
1031 os << "has_inner_box " << !inner_type.empty() << "\n";
1032 os << "inner_pos \"" << inner_pos << "\"\n";
1033 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1035 if (outer_type == "mbox")
1036 os << "use_makebox 1\n";
1038 os << "use_makebox " << (inner_type == "makebox") << '\n';
1039 if (outer_type == "fbox" || outer_type == "mbox")
1040 os << "width \"\"\n";
1042 os << "width \"" << width_value << width_unit << "\"\n";
1043 os << "special \"" << width_special << "\"\n";
1044 os << "height \"" << height_value << height_unit << "\"\n";
1045 os << "height_special \"" << height_special << "\"\n";
1046 os << "status open\n\n";
1048 // Unfortunately we can't use parse_text_in_inset:
1049 // InsetBox::forcePlainLayout() is hard coded and does not
1050 // use the inset layout. Apart from that do we call parse_text
1051 // up to two times, but need only one check_end_layout.
1052 bool const forcePlainLayout =
1053 (!inner_type.empty() || inner_type == "makebox") &&
1054 outer_type != "shaded" && outer_type != "framed";
1055 Context context(true, parent_context.textclass);
1056 if (forcePlainLayout)
1057 context.layout = &context.textclass.plainLayout();
1059 context.font = parent_context.font;
1061 // If we have no inner box the contents will be read with the outer box
1062 if (!inner_type.empty())
1063 parse_text(p, os, inner_flags, outer, context);
1065 // Ensure that the end of the outer box is parsed correctly:
1066 // The opening brace has been eaten by parse_outer_box()
1067 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1068 outer_flags &= ~FLAG_ITEM;
1069 outer_flags |= FLAG_BRACE_LAST;
1072 // Find end of outer box, output contents if inner_type is
1073 // empty and output possible comments
1074 if (!outer_type.empty()) {
1075 // If we already read the inner box we have to pop
1077 if (!inner_type.empty() && (inner_flags & FLAG_END))
1078 active_environments.pop_back();
1079 // This does not output anything but comments if
1080 // inner_type is not empty (see use_ert)
1081 parse_text(p, os, outer_flags, outer, context);
1084 context.check_end_layout(os);
1086 #ifdef PRESERVE_LAYOUT
1087 // LyX puts a % after the end of the minipage
1088 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1090 //output_ert_inset(os, "%dummy", parent_context);
1093 parent_context.new_paragraph(os);
1095 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1096 //output_ert_inset(os, "%dummy", parent_context);
1099 // We add a protected space if something real follows
1100 if (p.good() && p.next_token().cat() != catComment) {
1101 begin_inset(os, "space ~\n");
1110 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1111 Context & parent_context, string const & outer_type,
1112 string const & special)
1114 eat_whitespace(p, os, parent_context, false);
1115 if (flags & FLAG_ITEM) {
1117 if (p.next_token().cat() == catBegin)
1120 cerr << "Warning: Ignoring missing '{' after \\"
1121 << outer_type << '.' << endl;
1122 eat_whitespace(p, os, parent_context, false);
1125 unsigned int inner_flags = 0;
1127 if (outer_type == "minipage" || outer_type == "parbox") {
1128 p.skip_spaces(true);
1129 while (p.hasOpt()) {
1131 p.skip_spaces(true);
1134 p.skip_spaces(true);
1135 if (outer_type == "parbox") {
1137 if (p.next_token().cat() == catBegin)
1139 p.skip_spaces(true);
1142 if (outer_type == "shaded" || outer_type == "fbox"
1143 || outer_type == "mbox") {
1144 // These boxes never have an inner box
1146 } else if (p.next_token().asInput() == "\\parbox") {
1147 inner = p.get_token().cs();
1148 inner_flags = FLAG_ITEM;
1149 } else if (p.next_token().asInput() == "\\begin") {
1150 // Is this a minipage or shaded box?
1153 inner = p.getArg('{', '}');
1155 if (inner == "minipage" || inner == "shaded")
1156 inner_flags = FLAG_END;
1161 if (inner_flags == FLAG_END) {
1162 if (inner != "shaded")
1166 eat_whitespace(p, os, parent_context, false);
1168 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1169 outer_type, special, inner);
1171 if (inner_flags == FLAG_ITEM) {
1173 eat_whitespace(p, os, parent_context, false);
1175 parse_box(p, os, flags, inner_flags, outer, parent_context,
1176 outer_type, special, inner);
1181 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1183 parent_context.check_layout(os);
1184 begin_inset(os, "listings\n");
1186 string arg = p.verbatimOption();
1187 os << "lstparams " << '"' << arg << '"' << '\n';
1188 if (arg.find("\\color") != string::npos)
1189 preamble.registerAutomaticallyLoadedPackage("color");
1192 os << "inline true\n";
1194 os << "inline false\n";
1195 os << "status collapsed\n";
1196 Context context(true, parent_context.textclass);
1197 context.layout = &parent_context.textclass.plainLayout();
1200 // set catcodes to verbatim early, just in case.
1201 p.setCatcodes(VERBATIM_CATCODES);
1202 string delim = p.get_token().asInput();
1203 //FIXME: handler error condition
1204 s = p.verbatimStuff(delim).second;
1205 // context.new_paragraph(os);
1207 s = p.verbatimEnvironment("lstlisting");
1208 output_ert(os, s, context);
1213 /// parse an unknown environment
1214 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1215 unsigned flags, bool outer,
1216 Context & parent_context)
1218 if (name == "tabbing")
1219 // We need to remember that we have to handle '\=' specially
1220 flags |= FLAG_TABBING;
1222 // We need to translate font changes and paragraphs inside the
1223 // environment to ERT if we have a non standard font.
1224 // Otherwise things like
1225 // \large\begin{foo}\huge bar\end{foo}
1227 bool const specialfont =
1228 (parent_context.font != parent_context.normalfont);
1229 bool const new_layout_allowed = parent_context.new_layout_allowed;
1231 parent_context.new_layout_allowed = false;
1232 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1233 parse_text_snippet(p, os, flags, outer, parent_context);
1234 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1236 parent_context.new_layout_allowed = new_layout_allowed;
1240 void parse_environment(Parser & p, ostream & os, bool outer,
1241 string & last_env, Context & parent_context)
1243 Layout const * newlayout;
1244 InsetLayout const * newinsetlayout = 0;
1245 string const name = p.getArg('{', '}');
1246 const bool is_starred = suffixIs(name, '*');
1247 string const unstarred_name = rtrim(name, "*");
1248 active_environments.push_back(name);
1250 if (is_math_env(name)) {
1251 parent_context.check_layout(os);
1252 begin_inset(os, "Formula ");
1253 os << "\\begin{" << name << "}";
1254 parse_math(p, os, FLAG_END, MATH_MODE);
1255 os << "\\end{" << name << "}";
1257 if (is_display_math_env(name)) {
1258 // Prevent the conversion of a line break to a space
1259 // (bug 7668). This does not change the output, but
1260 // looks ugly in LyX.
1261 eat_whitespace(p, os, parent_context, false);
1265 else if (is_known(name, preamble.polyglossia_languages)) {
1266 // We must begin a new paragraph if not already done
1267 if (! parent_context.atParagraphStart()) {
1268 parent_context.check_end_layout(os);
1269 parent_context.new_paragraph(os);
1271 // save the language in the context so that it is
1272 // handled by parse_text
1273 parent_context.font.language = preamble.polyglossia2lyx(name);
1274 parse_text(p, os, FLAG_END, outer, parent_context);
1275 // Just in case the environment is empty
1276 parent_context.extra_stuff.erase();
1277 // We must begin a new paragraph to reset the language
1278 parent_context.new_paragraph(os);
1282 else if (unstarred_name == "tabular" || name == "longtable") {
1283 eat_whitespace(p, os, parent_context, false);
1284 string width = "0pt";
1285 if (name == "tabular*") {
1286 width = lyx::translate_len(p.getArg('{', '}'));
1287 eat_whitespace(p, os, parent_context, false);
1289 parent_context.check_layout(os);
1290 begin_inset(os, "Tabular ");
1291 handle_tabular(p, os, name, width, parent_context);
1296 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1297 eat_whitespace(p, os, parent_context, false);
1298 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1299 eat_whitespace(p, os, parent_context, false);
1300 parent_context.check_layout(os);
1301 begin_inset(os, "Float " + unstarred_name + "\n");
1302 // store the float type for subfloats
1303 // subfloats only work with figures and tables
1304 if (unstarred_name == "figure")
1305 float_type = unstarred_name;
1306 else if (unstarred_name == "table")
1307 float_type = unstarred_name;
1311 os << "placement " << opt << '\n';
1312 if (contains(opt, "H"))
1313 preamble.registerAutomaticallyLoadedPackage("float");
1315 Floating const & fl = parent_context.textclass.floats()
1316 .getType(unstarred_name);
1317 if (!fl.floattype().empty() && fl.usesFloatPkg())
1318 preamble.registerAutomaticallyLoadedPackage("float");
1321 os << "wide " << convert<string>(is_starred)
1322 << "\nsideways false"
1323 << "\nstatus open\n\n";
1324 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1326 // We don't need really a new paragraph, but
1327 // we must make sure that the next item gets a \begin_layout.
1328 parent_context.new_paragraph(os);
1330 // the float is parsed thus delete the type
1334 else if (unstarred_name == "sidewaysfigure"
1335 || unstarred_name == "sidewaystable") {
1336 eat_whitespace(p, os, parent_context, false);
1337 parent_context.check_layout(os);
1338 if (unstarred_name == "sidewaysfigure")
1339 begin_inset(os, "Float figure\n");
1341 begin_inset(os, "Float table\n");
1342 os << "wide " << convert<string>(is_starred)
1343 << "\nsideways true"
1344 << "\nstatus open\n\n";
1345 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1347 // We don't need really a new paragraph, but
1348 // we must make sure that the next item gets a \begin_layout.
1349 parent_context.new_paragraph(os);
1351 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1354 else if (name == "wrapfigure" || name == "wraptable") {
1355 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1356 eat_whitespace(p, os, parent_context, false);
1357 parent_context.check_layout(os);
1360 string overhang = "0col%";
1363 lines = p.getArg('[', ']');
1364 string const placement = p.getArg('{', '}');
1366 overhang = p.getArg('[', ']');
1367 string const width = p.getArg('{', '}');
1369 if (name == "wrapfigure")
1370 begin_inset(os, "Wrap figure\n");
1372 begin_inset(os, "Wrap table\n");
1373 os << "lines " << lines
1374 << "\nplacement " << placement
1375 << "\noverhang " << lyx::translate_len(overhang)
1376 << "\nwidth " << lyx::translate_len(width)
1377 << "\nstatus open\n\n";
1378 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1380 // We don't need really a new paragraph, but
1381 // we must make sure that the next item gets a \begin_layout.
1382 parent_context.new_paragraph(os);
1384 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1387 else if (name == "minipage") {
1388 eat_whitespace(p, os, parent_context, false);
1389 // Test whether this is an outer box of a shaded box
1391 // swallow arguments
1392 while (p.hasOpt()) {
1394 p.skip_spaces(true);
1397 p.skip_spaces(true);
1398 Token t = p.get_token();
1399 bool shaded = false;
1400 if (t.asInput() == "\\begin") {
1401 p.skip_spaces(true);
1402 if (p.getArg('{', '}') == "shaded")
1407 parse_outer_box(p, os, FLAG_END, outer,
1408 parent_context, name, "shaded");
1410 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1415 else if (name == "comment") {
1416 eat_whitespace(p, os, parent_context, false);
1417 parent_context.check_layout(os);
1418 begin_inset(os, "Note Comment\n");
1419 os << "status open\n";
1420 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1423 skip_braces(p); // eat {} that might by set by LyX behind comments
1424 preamble.registerAutomaticallyLoadedPackage("verbatim");
1427 else if (name == "verbatim") {
1428 // FIXME: this should go in the generic code that
1429 // handles environments defined in layout file that
1430 // have "PassThru 1". However, the code over there is
1431 // already too complicated for my taste.
1432 parent_context.new_paragraph(os);
1433 Context context(true, parent_context.textclass,
1434 &parent_context.textclass[from_ascii("Verbatim")]);
1435 string s = p.verbatimEnvironment("verbatim");
1436 output_ert(os, s, context);
1440 else if (name == "IPA") {
1441 eat_whitespace(p, os, parent_context, false);
1442 parent_context.check_layout(os);
1443 begin_inset(os, "IPA\n");
1444 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1447 preamble.registerAutomaticallyLoadedPackage("tipa");
1448 preamble.registerAutomaticallyLoadedPackage("tipx");
1451 else if (name == "CJK") {
1452 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1453 // It is impossible to decide if a CJK environment was in its own paragraph or within
1454 // a line. We therefore always assume a paragraph since the latter is a rare case.
1455 eat_whitespace(p, os, parent_context, false);
1456 parent_context.check_end_layout(os);
1457 // store the encoding to be able to reset it
1458 string const encoding_old = p.getEncoding();
1459 string const encoding = p.getArg('{', '}');
1460 // FIXME: For some reason JIS does not work. Although the text
1461 // in tests/CJK.tex is identical with the SJIS version if you
1462 // convert both snippets using the recode command line utility,
1463 // the resulting .lyx file contains some extra characters if
1464 // you set buggy_encoding to false for JIS.
1465 bool const buggy_encoding = encoding == "JIS";
1466 if (!buggy_encoding)
1467 p.setEncoding(encoding, Encoding::CJK);
1469 // FIXME: This will read garbage, since the data is not encoded in utf8.
1470 p.setEncoding("UTF-8");
1472 // LyX only supports the same mapping for all CJK
1473 // environments, so we might need to output everything as ERT
1474 string const mapping = trim(p.getArg('{', '}'));
1475 char const * const * const where =
1476 is_known(encoding, supported_CJK_encodings);
1477 if (!buggy_encoding && !preamble.fontCJKSet())
1478 preamble.fontCJK(mapping);
1479 bool knownMapping = mapping == preamble.fontCJK();
1480 if (buggy_encoding || !knownMapping || !where) {
1481 parent_context.check_layout(os);
1482 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1484 // we must parse the content as verbatim because e.g. JIS can contain
1485 // normally invalid characters
1486 // FIXME: This works only for the most simple cases.
1487 // Since TeX control characters are not parsed,
1488 // things like comments are completely wrong.
1489 string const s = p.plainEnvironment("CJK");
1490 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1492 output_ert_inset(os, "\\", parent_context);
1493 else if (*it == '$')
1494 output_ert_inset(os, "$", parent_context);
1495 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1500 output_ert_inset(os, "\\end{" + name + "}",
1504 supported_CJK_languages[where - supported_CJK_encodings];
1505 // store the language because we must reset it at the end
1506 string const lang_old = parent_context.font.language;
1507 parent_context.font.language = lang;
1508 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1509 parent_context.font.language = lang_old;
1510 parent_context.new_paragraph(os);
1512 p.setEncoding(encoding_old);
1516 else if (name == "lyxgreyedout") {
1517 eat_whitespace(p, os, parent_context, false);
1518 parent_context.check_layout(os);
1519 begin_inset(os, "Note Greyedout\n");
1520 os << "status open\n";
1521 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1524 if (!preamble.notefontcolor().empty())
1525 preamble.registerAutomaticallyLoadedPackage("color");
1528 else if (name == "framed" || name == "shaded") {
1529 eat_whitespace(p, os, parent_context, false);
1530 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1534 else if (name == "lstlisting") {
1535 eat_whitespace(p, os, parent_context, false);
1536 parse_listings(p, os, parent_context, false);
1540 else if (!parent_context.new_layout_allowed)
1541 parse_unknown_environment(p, name, os, FLAG_END, outer,
1544 // Alignment and spacing settings
1545 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1546 // therefore are totally broken!
1547 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1548 // they are commands not environments. They are furthermore switches that
1549 // can be ended by another switches, but also by commands like \footnote or
1550 // \parbox. So the only safe way is to leave them untouched.
1551 else if (name == "center" || name == "centering" ||
1552 name == "flushleft" || name == "flushright" ||
1553 name == "singlespace" || name == "onehalfspace" ||
1554 name == "doublespace" || name == "spacing") {
1555 eat_whitespace(p, os, parent_context, false);
1556 // We must begin a new paragraph if not already done
1557 if (! parent_context.atParagraphStart()) {
1558 parent_context.check_end_layout(os);
1559 parent_context.new_paragraph(os);
1561 if (name == "flushleft")
1562 parent_context.add_extra_stuff("\\align left\n");
1563 else if (name == "flushright")
1564 parent_context.add_extra_stuff("\\align right\n");
1565 else if (name == "center" || name == "centering")
1566 parent_context.add_extra_stuff("\\align center\n");
1567 else if (name == "singlespace")
1568 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1569 else if (name == "onehalfspace") {
1570 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1571 preamble.registerAutomaticallyLoadedPackage("setspace");
1572 } else if (name == "doublespace") {
1573 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1574 preamble.registerAutomaticallyLoadedPackage("setspace");
1575 } else if (name == "spacing") {
1576 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1577 preamble.registerAutomaticallyLoadedPackage("setspace");
1579 parse_text(p, os, FLAG_END, outer, parent_context);
1580 // Just in case the environment is empty
1581 parent_context.extra_stuff.erase();
1582 // We must begin a new paragraph to reset the alignment
1583 parent_context.new_paragraph(os);
1587 // The single '=' is meant here.
1588 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1589 eat_whitespace(p, os, parent_context, false);
1590 Context context(true, parent_context.textclass, newlayout,
1591 parent_context.layout, parent_context.font);
1592 if (parent_context.deeper_paragraph) {
1593 // We are beginning a nested environment after a
1594 // deeper paragraph inside the outer list environment.
1595 // Therefore we don't need to output a "begin deeper".
1596 context.need_end_deeper = true;
1598 parent_context.check_end_layout(os);
1599 if (last_env == name) {
1600 // we need to output a separator since LyX would export
1601 // the two environments as one otherwise (bug 5716)
1602 docstring const sep = from_ascii("--Separator--");
1603 TeX2LyXDocClass const & textclass(parent_context.textclass);
1604 if (textclass.hasLayout(sep)) {
1605 Context newcontext(parent_context);
1606 newcontext.layout = &(textclass[sep]);
1607 newcontext.check_layout(os);
1608 newcontext.check_end_layout(os);
1610 parent_context.check_layout(os);
1611 begin_inset(os, "Note Note\n");
1612 os << "status closed\n";
1613 Context newcontext(true, textclass,
1614 &(textclass.defaultLayout()));
1615 newcontext.check_layout(os);
1616 newcontext.check_end_layout(os);
1618 parent_context.check_end_layout(os);
1621 switch (context.layout->latextype) {
1622 case LATEX_LIST_ENVIRONMENT:
1623 context.add_par_extra_stuff("\\labelwidthstring "
1624 + p.verbatim_item() + '\n');
1627 case LATEX_BIB_ENVIRONMENT:
1628 p.verbatim_item(); // swallow next arg
1634 context.check_deeper(os);
1635 // handle known optional and required arguments
1636 // FIXME: Since format 446, layouts do not require anymore all optional
1637 // arguments before the required ones. Needs to be implemented!
1638 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1639 // It is impossible to place anything after the environment name,
1640 // but before the first \\item.
1641 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1642 bool need_layout = true;
1644 while (optargs < context.layout->optArgs()) {
1645 eat_whitespace(p, os, context, false);
1646 if (p.next_token().cat() == catEscape ||
1647 p.next_token().character() != '[')
1649 p.get_token(); // eat '['
1651 context.check_layout(os);
1652 need_layout = false;
1654 // FIXME: Just a workaround. InsetArgument::updateBuffer
1655 // will compute a proper ID for all "999" Arguments
1656 // (which is also what lyx2lyx produces).
1657 // However, tex2lyx should be able to output proper IDs
1659 begin_inset(os, "Argument 999\n");
1660 os << "status collapsed\n\n";
1661 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1663 eat_whitespace(p, os, context, false);
1667 while (reqargs < context.layout->requiredArgs()) {
1668 eat_whitespace(p, os, context, false);
1669 if (p.next_token().cat() != catBegin)
1671 p.get_token(); // eat '{'
1673 context.check_layout(os);
1674 need_layout = false;
1676 // FIXME: Just a workaround. InsetArgument::updateBuffer
1677 // will compute a proper ID for all "999" Arguments
1678 // (which is also what lyx2lyx produces).
1679 // However, tex2lyx should be able to output proper IDs
1681 begin_inset(os, "Argument 999\n");
1682 os << "status collapsed\n\n";
1683 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1685 eat_whitespace(p, os, context, false);
1689 parse_text(p, os, FLAG_END, outer, context);
1690 context.check_end_layout(os);
1691 if (parent_context.deeper_paragraph) {
1692 // We must suppress the "end deeper" because we
1693 // suppressed the "begin deeper" above.
1694 context.need_end_deeper = false;
1696 context.check_end_deeper(os);
1697 parent_context.new_paragraph(os);
1699 if (!preamble.titleLayoutFound())
1700 preamble.titleLayoutFound(newlayout->intitle);
1701 set<string> const & req = newlayout->requires();
1702 set<string>::const_iterator it = req.begin();
1703 set<string>::const_iterator en = req.end();
1704 for (; it != en; ++it)
1705 preamble.registerAutomaticallyLoadedPackage(*it);
1708 // The single '=' is meant here.
1709 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1710 eat_whitespace(p, os, parent_context, false);
1711 parent_context.check_layout(os);
1712 begin_inset(os, "Flex ");
1713 os << to_utf8(newinsetlayout->name()) << '\n'
1714 << "status collapsed\n";
1715 if (newinsetlayout->isPassThru()) {
1716 string const arg = p.verbatimEnvironment(name);
1717 Context context(true, parent_context.textclass,
1718 &parent_context.textclass.plainLayout(),
1719 parent_context.layout);
1720 output_ert(os, arg, parent_context);
1722 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1726 else if (name == "appendix") {
1727 // This is no good latex style, but it works and is used in some documents...
1728 eat_whitespace(p, os, parent_context, false);
1729 parent_context.check_end_layout(os);
1730 Context context(true, parent_context.textclass, parent_context.layout,
1731 parent_context.layout, parent_context.font);
1732 context.check_layout(os);
1733 os << "\\start_of_appendix\n";
1734 parse_text(p, os, FLAG_END, outer, context);
1735 context.check_end_layout(os);
1739 else if (known_environments.find(name) != known_environments.end()) {
1740 vector<ArgumentType> arguments = known_environments[name];
1741 // The last "argument" denotes wether we may translate the
1742 // environment contents to LyX
1743 // The default required if no argument is given makes us
1744 // compatible with the reLyXre environment.
1745 ArgumentType contents = arguments.empty() ?
1748 if (!arguments.empty())
1749 arguments.pop_back();
1750 // See comment in parse_unknown_environment()
1751 bool const specialfont =
1752 (parent_context.font != parent_context.normalfont);
1753 bool const new_layout_allowed =
1754 parent_context.new_layout_allowed;
1756 parent_context.new_layout_allowed = false;
1757 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1758 outer, parent_context);
1759 if (contents == verbatim)
1760 output_ert_inset(os, p.ertEnvironment(name),
1763 parse_text_snippet(p, os, FLAG_END, outer,
1765 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1767 parent_context.new_layout_allowed = new_layout_allowed;
1771 parse_unknown_environment(p, name, os, FLAG_END, outer,
1775 active_environments.pop_back();
1779 /// parses a comment and outputs it to \p os.
1780 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1782 LASSERT(t.cat() == catComment, return);
1783 if (!t.cs().empty()) {
1784 context.check_layout(os);
1785 output_ert_inset(os, '%' + t.cs(), context);
1786 if (p.next_token().cat() == catNewline) {
1787 // A newline after a comment line starts a new
1789 if (context.new_layout_allowed) {
1790 if(!context.atParagraphStart())
1791 // Only start a new paragraph if not already
1792 // done (we might get called recursively)
1793 context.new_paragraph(os);
1795 output_ert_inset(os, "\n", context);
1796 eat_whitespace(p, os, context, true);
1799 // "%\n" combination
1806 * Reads spaces and comments until the first non-space, non-comment token.
1807 * New paragraphs (double newlines or \\par) are handled like simple spaces
1808 * if \p eatParagraph is true.
1809 * Spaces are skipped, but comments are written to \p os.
1811 void eat_whitespace(Parser & p, ostream & os, Context & context,
1815 Token const & t = p.get_token();
1816 if (t.cat() == catComment)
1817 parse_comment(p, os, t, context);
1818 else if ((! eatParagraph && p.isParagraph()) ||
1819 (t.cat() != catSpace && t.cat() != catNewline)) {
1828 * Set a font attribute, parse text and reset the font attribute.
1829 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1830 * \param currentvalue Current value of the attribute. Is set to the new
1831 * value during parsing.
1832 * \param newvalue New value of the attribute
1834 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1835 Context & context, string const & attribute,
1836 string & currentvalue, string const & newvalue)
1838 context.check_layout(os);
1839 string const oldvalue = currentvalue;
1840 currentvalue = newvalue;
1841 os << '\n' << attribute << ' ' << newvalue << "\n";
1842 parse_text_snippet(p, os, flags, outer, context);
1843 context.check_layout(os);
1844 os << '\n' << attribute << ' ' << oldvalue << "\n";
1845 currentvalue = oldvalue;
1849 /// get the arguments of a natbib or jurabib citation command
1850 void get_cite_arguments(Parser & p, bool natbibOrder,
1851 string & before, string & after)
1853 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1855 // text before the citation
1857 // text after the citation
1858 after = p.getFullOpt();
1860 if (!after.empty()) {
1861 before = p.getFullOpt();
1862 if (natbibOrder && !before.empty())
1863 swap(before, after);
1868 /// Convert filenames with TeX macros and/or quotes to something LyX
1870 string const normalize_filename(string const & name)
1875 Token const & t = p.get_token();
1876 if (t.cat() != catEscape)
1878 else if (t.cs() == "lyxdot") {
1879 // This is used by LyX for simple dots in relative
1883 } else if (t.cs() == "space") {
1886 } else if (t.cs() == "string") {
1887 // Convert \string" to " and \string~ to ~
1888 Token const & n = p.next_token();
1889 if (n.asInput() != "\"" && n.asInput() != "~")
1894 // Strip quotes. This is a bit complicated (see latex_path()).
1895 string full = os.str();
1896 if (!full.empty() && full[0] == '"') {
1897 string base = removeExtension(full);
1898 string ext = getExtension(full);
1899 if (!base.empty() && base[base.length()-1] == '"')
1902 return addExtension(trim(base, "\""), ext);
1903 if (full[full.length()-1] == '"')
1906 return trim(full, "\"");
1912 /// Convert \p name from TeX convention (relative to master file) to LyX
1913 /// convention (relative to .lyx file) if it is relative
1914 void fix_child_filename(string & name)
1916 string const absMasterTeX = getMasterFilePath(true);
1917 bool const isabs = FileName::isAbsolute(name);
1918 // convert from "relative to .tex master" to absolute original path
1920 name = makeAbsPath(name, absMasterTeX).absFileName();
1921 bool copyfile = copyFiles();
1922 string const absParentLyX = getParentFilePath(false);
1925 // convert from absolute original path to "relative to master file"
1926 string const rel = to_utf8(makeRelPath(from_utf8(name),
1927 from_utf8(absMasterTeX)));
1928 // re-interpret "relative to .tex file" as "relative to .lyx file"
1929 // (is different if the master .lyx file resides in a
1930 // different path than the master .tex file)
1931 string const absMasterLyX = getMasterFilePath(false);
1932 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1933 // Do not copy if the new path is impossible to create. Example:
1934 // absMasterTeX = "/foo/bar/"
1935 // absMasterLyX = "/bar/"
1936 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1937 if (contains(name, "/../"))
1944 // convert from absolute original path to
1945 // "relative to .lyx file"
1946 name = to_utf8(makeRelPath(from_utf8(abs),
1947 from_utf8(absParentLyX)));
1951 // convert from absolute original path to "relative to .lyx file"
1952 name = to_utf8(makeRelPath(from_utf8(name),
1953 from_utf8(absParentLyX)));
1958 void copy_file(FileName const & src, string dstname)
1962 string const absParent = getParentFilePath(false);
1964 if (FileName::isAbsolute(dstname))
1965 dst = FileName(dstname);
1967 dst = makeAbsPath(dstname, absParent);
1968 string const absMaster = getMasterFilePath(false);
1969 FileName const srcpath = src.onlyPath();
1970 FileName const dstpath = dst.onlyPath();
1971 if (equivalent(srcpath, dstpath))
1973 if (!dstpath.isDirectory()) {
1974 if (!dstpath.createPath()) {
1975 cerr << "Warning: Could not create directory for file `"
1976 << dst.absFileName() << "´." << endl;
1980 if (dst.isReadableFile()) {
1981 if (overwriteFiles())
1982 cerr << "Warning: Overwriting existing file `"
1983 << dst.absFileName() << "´." << endl;
1985 cerr << "Warning: Not overwriting existing file `"
1986 << dst.absFileName() << "´." << endl;
1990 if (!src.copyTo(dst))
1991 cerr << "Warning: Could not copy file `" << src.absFileName()
1992 << "´ to `" << dst.absFileName() << "´." << endl;
1996 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1997 bool parse_noweb(Parser & p, ostream & os, Context & context)
1999 // check whether a chunk is possible here.
2000 if (!context.new_layout_allowed ||
2001 !context.textclass.hasLayout(from_ascii("Chunk"))) {
2007 // read the parameters
2008 Parser::Arg stuff = p.verbatimStuff(">>=", false);
2013 string chunk = "<<" + stuff.second + ">>="
2014 + p.verbatimStuff("\n").second + '\n';
2016 stuff = p.verbatimStuff("\n@");
2021 chunk += stuff.second + "\n@";
2022 string post_chunk = p.verbatimStuff("\n").second + '\n';
2023 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2027 chunk += post_chunk;
2029 context.new_paragraph(os);
2030 Context newcontext(true, context.textclass,
2031 &context.textclass[from_ascii("Chunk")]);
2032 output_ert(os, chunk, newcontext);
2039 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2040 bool is_macro(Parser & p)
2042 Token first = p.curr_token();
2043 if (first.cat() != catEscape || !p.good())
2045 if (first.cs() == "def")
2047 if (first.cs() != "global" && first.cs() != "long")
2049 Token second = p.get_token();
2051 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2052 second.cat() == catNewline || second.cat() == catComment)) {
2053 second = p.get_token();
2056 bool secondvalid = second.cat() == catEscape;
2058 bool thirdvalid = false;
2059 if (p.good() && first.cs() == "global" && secondvalid &&
2060 second.cs() == "long") {
2061 third = p.get_token();
2063 while (p.good() && !p.isParagraph() &&
2064 (third.cat() == catSpace ||
2065 third.cat() == catNewline ||
2066 third.cat() == catComment)) {
2067 third = p.get_token();
2070 thirdvalid = third.cat() == catEscape;
2072 for (int i = 0; i < pos; ++i)
2077 return (first.cs() == "global" || first.cs() == "long") &&
2078 second.cs() == "def";
2079 return first.cs() == "global" && second.cs() == "long" &&
2080 third.cs() == "def";
2084 /// Parse a macro definition (assumes that is_macro() returned true)
2085 void parse_macro(Parser & p, ostream & os, Context & context)
2087 context.check_layout(os);
2088 Token first = p.curr_token();
2091 string command = first.asInput();
2092 if (first.cs() != "def") {
2094 eat_whitespace(p, os, context, false);
2095 second = p.curr_token();
2096 command += second.asInput();
2097 if (second.cs() != "def") {
2099 eat_whitespace(p, os, context, false);
2100 third = p.curr_token();
2101 command += third.asInput();
2104 eat_whitespace(p, os, context, false);
2105 string const name = p.get_token().cs();
2106 eat_whitespace(p, os, context, false);
2112 while (p.next_token().cat() != catBegin) {
2113 if (p.next_token().cat() == catParameter) {
2118 // followed by number?
2119 if (p.next_token().cat() == catOther) {
2120 string s = p.get_token().asInput();
2122 // number = current arity + 1?
2123 if (s.size() == 1 && s[0] == arity + '0' + 1)
2128 paramtext += p.get_token().cs();
2130 paramtext += p.get_token().cs();
2135 // only output simple (i.e. compatible) macro as FormulaMacros
2136 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2138 context.check_layout(os);
2139 begin_inset(os, "FormulaMacro");
2140 os << "\n\\def" << ert;
2143 output_ert_inset(os, command + ert, context);
2147 void registerExternalTemplatePackages(string const & name)
2149 external::TemplateManager const & etm = external::TemplateManager::get();
2150 external::Template const * const et = etm.getTemplateByName(name);
2153 external::Template::Formats::const_iterator cit = et->formats.end();
2155 cit = et->formats.find("PDFLaTeX");
2156 if (cit == et->formats.end())
2157 // If the template has not specified a PDFLaTeX output,
2158 // we try the LaTeX format.
2159 cit = et->formats.find("LaTeX");
2160 if (cit == et->formats.end())
2162 vector<string>::const_iterator qit = cit->second.requirements.begin();
2163 vector<string>::const_iterator qend = cit->second.requirements.end();
2164 for (; qit != qend; ++qit)
2165 preamble.registerAutomaticallyLoadedPackage(*qit);
2168 } // anonymous namespace
2171 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2174 Layout const * newlayout = 0;
2175 InsetLayout const * newinsetlayout = 0;
2176 char const * const * where = 0;
2177 // Store the latest bibliographystyle, addcontentslineContent and
2178 // nocite{*} option (needed for bibtex inset)
2180 string contentslineContent;
2181 string bibliographystyle = "default";
2182 bool const use_natbib = isProvided("natbib");
2183 bool const use_jurabib = isProvided("jurabib");
2186 Token const & t = p.get_token();
2188 // it is impossible to determine the correct encoding for non-CJK Japanese.
2189 // Therefore write a note at the beginning of the document
2190 if (is_nonCJKJapanese) {
2191 context.check_layout(os);
2192 begin_inset(os, "Note Note\n");
2193 os << "status open\n\\begin_layout Plain Layout\n"
2194 << "\\series bold\n"
2195 << "Important information:\n"
2196 << "\\end_layout\n\n"
2197 << "\\begin_layout Plain Layout\n"
2198 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2199 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2200 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2201 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2202 << " and specify the encoding using the -e command-line switch.\n"
2203 << " In addition, you might want to double check that the desired output encoding\n"
2204 << " is correctly selected in Document > Settings > Language.\n"
2205 << "\\end_layout\n";
2207 is_nonCJKJapanese = false;
2211 debugToken(cerr, t, flags);
2214 if (flags & FLAG_ITEM) {
2215 if (t.cat() == catSpace)
2218 flags &= ~FLAG_ITEM;
2219 if (t.cat() == catBegin) {
2220 // skip the brace and collect everything to the next matching
2222 flags |= FLAG_BRACE_LAST;
2226 // handle only this single token, leave the loop if done
2227 flags |= FLAG_LEAVE;
2230 if (t.cat() != catEscape && t.character() == ']' &&
2231 (flags & FLAG_BRACK_LAST))
2233 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2236 // If there is anything between \end{env} and \begin{env} we
2237 // don't need to output a separator.
2238 if (t.cat() != catSpace && t.cat() != catNewline &&
2239 t.asInput() != "\\begin")
2245 if (t.cat() == catMath) {
2246 // we are inside some text mode thingy, so opening new math is allowed
2247 context.check_layout(os);
2248 begin_inset(os, "Formula ");
2249 Token const & n = p.get_token();
2250 bool const display(n.cat() == catMath && outer);
2252 // TeX's $$...$$ syntax for displayed math
2254 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2256 p.get_token(); // skip the second '$' token
2258 // simple $...$ stuff
2261 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2266 // Prevent the conversion of a line break to a
2267 // space (bug 7668). This does not change the
2268 // output, but looks ugly in LyX.
2269 eat_whitespace(p, os, context, false);
2273 else if (t.cat() == catSuper || t.cat() == catSub)
2274 cerr << "catcode " << t << " illegal in text mode\n";
2276 // Basic support for english quotes. This should be
2277 // extended to other quotes, but is not so easy (a
2278 // left english quote is the same as a right german
2280 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2281 context.check_layout(os);
2282 begin_inset(os, "Quotes ");
2288 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2289 context.check_layout(os);
2290 begin_inset(os, "Quotes ");
2297 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2298 context.check_layout(os);
2299 begin_inset(os, "Quotes ");
2306 else if (t.asInput() == "<"
2307 && p.next_token().asInput() == "<") {
2308 bool has_noweb = false;
2312 has_noweb = parse_noweb(p, os, context);
2318 context.check_layout(os);
2319 begin_inset(os, "Quotes ");
2320 //FIXME: this is a right danish quote;
2321 // why not a left french quote?
2329 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2330 check_space(p, os, context);
2332 else if (t.character() == '[' && noweb_mode &&
2333 p.next_token().character() == '[') {
2334 // These can contain underscores
2336 string const s = p.getFullOpt() + ']';
2337 if (p.next_token().character() == ']')
2340 cerr << "Warning: Inserting missing ']' in '"
2341 << s << "'." << endl;
2342 output_ert_inset(os, s, context);
2345 else if (t.cat() == catLetter) {
2346 context.check_layout(os);
2347 // Workaround for bug 4752.
2348 // FIXME: This whole code block needs to be removed
2349 // when the bug is fixed and tex2lyx produces
2350 // the updated file format.
2351 // The replacement algorithm in LyX is so stupid that
2352 // it even translates a phrase if it is part of a word.
2353 bool handled = false;
2354 for (int const * l = known_phrase_lengths; *l; ++l) {
2355 string phrase = t.cs();
2356 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2357 phrase += p.get_token().cs();
2358 if (is_known(phrase, known_coded_phrases)) {
2359 output_ert_inset(os, phrase, context);
2363 for (size_t i = 1; i < phrase.length(); ++i)
2371 else if (t.cat() == catOther ||
2372 t.cat() == catAlign ||
2373 t.cat() == catParameter) {
2374 // This translates "&" to "\\&" which may be wrong...
2375 context.check_layout(os);
2379 else if (p.isParagraph()) {
2380 if (context.new_layout_allowed)
2381 context.new_paragraph(os);
2383 output_ert_inset(os, "\\par ", context);
2384 eat_whitespace(p, os, context, true);
2387 else if (t.cat() == catActive) {
2388 context.check_layout(os);
2389 if (t.character() == '~') {
2390 if (context.layout->free_spacing)
2393 begin_inset(os, "space ~\n");
2400 else if (t.cat() == catBegin) {
2401 Token const next = p.next_token();
2402 Token const end = p.next_next_token();
2403 if (next.cat() == catEnd) {
2405 Token const prev = p.prev_token();
2407 if (p.next_token().character() == '`' ||
2408 (prev.character() == '-' &&
2409 p.next_token().character() == '-'))
2410 ; // ignore it in {}`` or -{}-
2412 output_ert_inset(os, "{}", context);
2413 } else if (next.cat() == catEscape &&
2414 is_known(next.cs(), known_quotes) &&
2415 end.cat() == catEnd) {
2416 // Something like {\textquoteright} (e.g.
2417 // from writer2latex). LyX writes
2418 // \textquoteright{}, so we may skip the
2419 // braces here for better readability.
2420 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2422 } else if (p.next_token().asInput() == "\\ascii") {
2423 // handle the \ascii characters
2424 // (the case without braces is handled later)
2425 // the code is "{\ascii\xxx}"
2426 p.get_token(); // eat \ascii
2427 string name2 = p.get_token().asInput();
2428 p.get_token(); // eat the final '}'
2429 string const name = "{\\ascii" + name2 + "}";
2433 // get the character from unicodesymbols
2434 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2435 Encodings::TEXT_CMD, termination, rem, &req);
2437 context.check_layout(os);
2440 output_ert_inset(os,
2441 to_utf8(rem), context);
2442 for (set<string>::const_iterator it = req.begin();
2443 it != req.end(); ++it)
2444 preamble.registerAutomaticallyLoadedPackage(*it);
2446 // we did not find a non-ert version
2447 output_ert_inset(os, name, context);
2449 context.check_layout(os);
2450 // special handling of font attribute changes
2451 Token const prev = p.prev_token();
2452 TeXFont const oldFont = context.font;
2453 if (next.character() == '[' ||
2454 next.character() == ']' ||
2455 next.character() == '*') {
2457 if (p.next_token().cat() == catEnd) {
2462 output_ert_inset(os, "{", context);
2463 parse_text_snippet(p, os,
2466 output_ert_inset(os, "}", context);
2468 } else if (! context.new_layout_allowed) {
2469 output_ert_inset(os, "{", context);
2470 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2472 output_ert_inset(os, "}", context);
2473 } else if (is_known(next.cs(), known_sizes)) {
2474 // next will change the size, so we must
2476 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2478 if (!context.atParagraphStart())
2480 << context.font.size << "\n";
2481 } else if (is_known(next.cs(), known_font_families)) {
2482 // next will change the font family, so we
2483 // must reset it here
2484 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2486 if (!context.atParagraphStart())
2488 << context.font.family << "\n";
2489 } else if (is_known(next.cs(), known_font_series)) {
2490 // next will change the font series, so we
2491 // must reset it here
2492 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2494 if (!context.atParagraphStart())
2496 << context.font.series << "\n";
2497 } else if (is_known(next.cs(), known_font_shapes)) {
2498 // next will change the font shape, so we
2499 // must reset it here
2500 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2502 if (!context.atParagraphStart())
2504 << context.font.shape << "\n";
2505 } else if (is_known(next.cs(), known_old_font_families) ||
2506 is_known(next.cs(), known_old_font_series) ||
2507 is_known(next.cs(), known_old_font_shapes)) {
2508 // next will change the font family, series
2509 // and shape, so we must reset it here
2510 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2512 if (!context.atParagraphStart())
2514 << context.font.family
2516 << context.font.series
2518 << context.font.shape << "\n";
2520 output_ert_inset(os, "{", context);
2521 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2523 output_ert_inset(os, "}", context);
2528 else if (t.cat() == catEnd) {
2529 if (flags & FLAG_BRACE_LAST) {
2532 cerr << "stray '}' in text\n";
2533 output_ert_inset(os, "}", context);
2536 else if (t.cat() == catComment)
2537 parse_comment(p, os, t, context);
2540 // control sequences
2543 else if (t.cs() == "(" || t.cs() == "[") {
2544 bool const simple = t.cs() == "(";
2545 context.check_layout(os);
2546 begin_inset(os, "Formula");
2547 os << " \\" << t.cs();
2548 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2549 os << '\\' << (simple ? ')' : ']');
2552 // Prevent the conversion of a line break to a
2553 // space (bug 7668). This does not change the
2554 // output, but looks ugly in LyX.
2555 eat_whitespace(p, os, context, false);
2559 else if (t.cs() == "begin")
2560 parse_environment(p, os, outer, last_env,
2563 else if (t.cs() == "end") {
2564 if (flags & FLAG_END) {
2565 // eat environment name
2566 string const name = p.getArg('{', '}');
2567 if (name != active_environment())
2568 cerr << "\\end{" + name + "} does not match \\begin{"
2569 + active_environment() + "}\n";
2572 p.error("found 'end' unexpectedly");
2575 else if (t.cs() == "item") {
2577 bool const optarg = p.hasOpt();
2579 // FIXME: This swallows comments, but we cannot use
2580 // eat_whitespace() since we must not output
2581 // anything before the item.
2582 p.skip_spaces(true);
2583 s = p.verbatimOption();
2585 p.skip_spaces(false);
2587 context.check_layout(os);
2588 if (context.has_item) {
2589 // An item in an unknown list-like environment
2590 // FIXME: Do this in check_layout()!
2591 context.has_item = false;
2593 output_ert_inset(os, "\\item", context);
2595 output_ert_inset(os, "\\item ", context);
2598 if (context.layout->labeltype != LABEL_MANUAL) {
2599 // LyX does not support \item[\mybullet]
2600 // in itemize environments
2602 os << parse_text_snippet(p2,
2603 FLAG_BRACK_LAST, outer, context);
2604 } else if (!s.empty()) {
2605 // LyX adds braces around the argument,
2606 // so we need to remove them here.
2607 if (s.size() > 2 && s[0] == '{' &&
2608 s[s.size()-1] == '}')
2609 s = s.substr(1, s.size()-2);
2610 // If the argument contains a space we
2611 // must put it into ERT: Otherwise LyX
2612 // would misinterpret the space as
2613 // item delimiter (bug 7663)
2614 if (contains(s, ' ')) {
2615 output_ert_inset(os, s, context);
2618 os << parse_text_snippet(p2,
2622 // The space is needed to separate the
2623 // item from the rest of the sentence.
2625 eat_whitespace(p, os, context, false);
2630 else if (t.cs() == "bibitem") {
2632 context.check_layout(os);
2633 eat_whitespace(p, os, context, false);
2634 string label = convert_command_inset_arg(p.verbatimOption());
2635 string key = convert_command_inset_arg(p.verbatim_item());
2636 if (contains(label, '\\') || contains(key, '\\')) {
2637 // LyX can't handle LaTeX commands in labels or keys
2638 output_ert_inset(os, t.asInput() + '[' + label +
2639 "]{" + p.verbatim_item() + '}',
2642 begin_command_inset(os, "bibitem", "bibitem");
2643 os << "label \"" << label << "\"\n"
2644 "key \"" << key << "\"\n";
2649 else if (is_macro(p)) {
2650 // catch the case of \def\inputGnumericTable
2652 if (t.cs() == "def") {
2653 Token second = p.next_token();
2654 if (second.cs() == "inputGnumericTable") {
2658 Token third = p.get_token();
2660 if (third.cs() == "input") {
2664 string name = normalize_filename(p.verbatim_item());
2665 string const path = getMasterFilePath(true);
2666 // We want to preserve relative / absolute filenames,
2667 // therefore path is only used for testing
2668 // The file extension is in every case ".tex".
2669 // So we need to remove this extension and check for
2670 // the original one.
2671 name = removeExtension(name);
2672 if (!makeAbsPath(name, path).exists()) {
2673 char const * const Gnumeric_formats[] = {"gnumeric",
2675 string const Gnumeric_name =
2676 find_file(name, path, Gnumeric_formats);
2677 if (!Gnumeric_name.empty())
2678 name = Gnumeric_name;
2680 FileName const absname = makeAbsPath(name, path);
2681 if (absname.exists()) {
2682 fix_child_filename(name);
2683 copy_file(absname, name);
2685 cerr << "Warning: Could not find file '"
2686 << name << "'." << endl;
2687 context.check_layout(os);
2688 begin_inset(os, "External\n\ttemplate ");
2689 os << "GnumericSpreadsheet\n\tfilename "
2692 context.check_layout(os);
2694 // register the packages that are automatically loaded
2695 // by the Gnumeric template
2696 registerExternalTemplatePackages("GnumericSpreadsheet");
2701 parse_macro(p, os, context);
2704 else if (t.cs() == "noindent") {
2706 context.add_par_extra_stuff("\\noindent\n");
2709 else if (t.cs() == "appendix") {
2710 context.add_par_extra_stuff("\\start_of_appendix\n");
2711 // We need to start a new paragraph. Otherwise the
2712 // appendix in 'bla\appendix\chapter{' would start
2714 context.new_paragraph(os);
2715 // We need to make sure that the paragraph is
2716 // generated even if it is empty. Otherwise the
2717 // appendix in '\par\appendix\par\chapter{' would
2719 context.check_layout(os);
2720 // FIXME: This is a hack to prevent paragraph
2721 // deletion if it is empty. Handle this better!
2722 output_ert_inset(os,
2723 "%dummy comment inserted by tex2lyx to "
2724 "ensure that this paragraph is not empty",
2726 // Both measures above may generate an additional
2727 // empty paragraph, but that does not hurt, because
2728 // whitespace does not matter here.
2729 eat_whitespace(p, os, context, true);
2732 // Must catch empty dates before findLayout is called below
2733 else if (t.cs() == "date") {
2734 eat_whitespace(p, os, context, false);
2736 string const date = p.verbatim_item();
2739 preamble.suppressDate(true);
2742 preamble.suppressDate(false);
2743 if (context.new_layout_allowed &&
2744 (newlayout = findLayout(context.textclass,
2747 output_command_layout(os, p, outer,
2748 context, newlayout);
2749 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2750 if (!preamble.titleLayoutFound())
2751 preamble.titleLayoutFound(newlayout->intitle);
2752 set<string> const & req = newlayout->requires();
2753 set<string>::const_iterator it = req.begin();
2754 set<string>::const_iterator en = req.end();
2755 for (; it != en; ++it)
2756 preamble.registerAutomaticallyLoadedPackage(*it);
2758 output_ert_inset(os,
2759 "\\date{" + p.verbatim_item() + '}',
2764 // Starred section headings
2765 // Must attempt to parse "Section*" before "Section".
2766 else if ((p.next_token().asInput() == "*") &&
2767 context.new_layout_allowed &&
2768 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2771 output_command_layout(os, p, outer, context, newlayout);
2773 if (!preamble.titleLayoutFound())
2774 preamble.titleLayoutFound(newlayout->intitle);
2775 set<string> const & req = newlayout->requires();
2776 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2777 preamble.registerAutomaticallyLoadedPackage(*it);
2780 // Section headings and the like
2781 else if (context.new_layout_allowed &&
2782 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2784 output_command_layout(os, p, outer, context, newlayout);
2786 if (!preamble.titleLayoutFound())
2787 preamble.titleLayoutFound(newlayout->intitle);
2788 set<string> const & req = newlayout->requires();
2789 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2790 preamble.registerAutomaticallyLoadedPackage(*it);
2793 else if (t.cs() == "caption") {
2794 bool starred = false;
2795 if (p.next_token().asInput() == "*") {
2800 context.check_layout(os);
2803 begin_inset(os, "Caption LongTableNoNumber\n");
2805 begin_inset(os, "Caption Standard\n");
2806 Context newcontext(true, context.textclass, 0, 0, context.font);
2807 newcontext.check_layout(os);
2808 // FIXME InsetArgument is now properly implemented in InsetLayout
2809 // (for captions, but also for others)
2810 if (p.next_token().cat() != catEscape &&
2811 p.next_token().character() == '[') {
2812 p.get_token(); // eat '['
2813 begin_inset(os, "Argument 1\n");
2814 os << "status collapsed\n";
2815 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2817 eat_whitespace(p, os, context, false);
2819 parse_text(p, os, FLAG_ITEM, outer, context);
2820 context.check_end_layout(os);
2821 // We don't need really a new paragraph, but
2822 // we must make sure that the next item gets a \begin_layout.
2823 context.new_paragraph(os);
2826 newcontext.check_end_layout(os);
2829 else if (t.cs() == "subfloat") {
2830 // the syntax is \subfloat[caption]{content}
2831 // if it is a table of figure depends on the surrounding float
2832 bool has_caption = false;
2834 // do nothing if there is no outer float
2835 if (!float_type.empty()) {
2836 context.check_layout(os);
2838 begin_inset(os, "Float " + float_type + "\n");
2840 << "\nsideways false"
2841 << "\nstatus collapsed\n\n";
2844 if (p.next_token().cat() != catEscape &&
2845 p.next_token().character() == '[') {
2846 p.get_token(); // eat '['
2847 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2851 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2852 // the caption comes always as the last
2854 // we must make sure that the caption gets a \begin_layout
2855 os << "\n\\begin_layout Plain Layout";
2857 begin_inset(os, "Caption Standard\n");
2858 Context newcontext(true, context.textclass,
2859 0, 0, context.font);
2860 newcontext.check_layout(os);
2861 os << caption << "\n";
2862 newcontext.check_end_layout(os);
2863 // We don't need really a new paragraph, but
2864 // we must make sure that the next item gets a \begin_layout.
2865 //newcontext.new_paragraph(os);
2869 // We don't need really a new paragraph, but
2870 // we must make sure that the next item gets a \begin_layout.
2872 context.new_paragraph(os);
2875 context.check_end_layout(os);
2876 // close the layout we opened
2878 os << "\n\\end_layout\n";
2880 // if the float type is not supported or there is no surrounding float
2883 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2884 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2885 "]{" + p.verbatim_item() + '}', context);
2887 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2891 else if (t.cs() == "includegraphics") {
2892 bool const clip = p.next_token().asInput() == "*";
2895 string const arg = p.getArg('[', ']');
2896 map<string, string> opts;
2897 vector<string> keys;
2898 split_map(arg, opts, keys);
2900 opts["clip"] = string();
2901 string name = normalize_filename(p.verbatim_item());
2903 string const path = getMasterFilePath(true);
2904 // We want to preserve relative / absolute filenames,
2905 // therefore path is only used for testing
2906 if (!makeAbsPath(name, path).exists()) {
2907 // The file extension is probably missing.
2908 // Now try to find it out.
2909 string const dvips_name =
2910 find_file(name, path,
2911 known_dvips_graphics_formats);
2912 string const pdftex_name =
2913 find_file(name, path,
2914 known_pdftex_graphics_formats);
2915 if (!dvips_name.empty()) {
2916 if (!pdftex_name.empty()) {
2917 cerr << "This file contains the "
2919 "\"\\includegraphics{"
2921 "However, files\n\""
2922 << dvips_name << "\" and\n\""
2923 << pdftex_name << "\"\n"
2924 "both exist, so I had to make a "
2925 "choice and took the first one.\n"
2926 "Please move the unwanted one "
2927 "someplace else and try again\n"
2928 "if my choice was wrong."
2932 } else if (!pdftex_name.empty()) {
2938 FileName const absname = makeAbsPath(name, path);
2939 if (absname.exists()) {
2940 fix_child_filename(name);
2941 copy_file(absname, name);
2943 cerr << "Warning: Could not find graphics file '"
2944 << name << "'." << endl;
2946 context.check_layout(os);
2947 begin_inset(os, "Graphics ");
2948 os << "\n\tfilename " << name << '\n';
2949 if (opts.find("width") != opts.end())
2951 << translate_len(opts["width"]) << '\n';
2952 if (opts.find("height") != opts.end())
2954 << translate_len(opts["height"]) << '\n';
2955 if (opts.find("scale") != opts.end()) {
2956 istringstream iss(opts["scale"]);
2960 os << "\tscale " << val << '\n';
2962 if (opts.find("angle") != opts.end()) {
2963 os << "\trotateAngle "
2964 << opts["angle"] << '\n';
2965 vector<string>::const_iterator a =
2966 find(keys.begin(), keys.end(), "angle");
2967 vector<string>::const_iterator s =
2968 find(keys.begin(), keys.end(), "width");
2969 if (s == keys.end())
2970 s = find(keys.begin(), keys.end(), "height");
2971 if (s == keys.end())
2972 s = find(keys.begin(), keys.end(), "scale");
2973 if (s != keys.end() && distance(s, a) > 0)
2974 os << "\tscaleBeforeRotation\n";
2976 if (opts.find("origin") != opts.end()) {
2978 string const opt = opts["origin"];
2979 if (opt.find('l') != string::npos) ss << "left";
2980 if (opt.find('r') != string::npos) ss << "right";
2981 if (opt.find('c') != string::npos) ss << "center";
2982 if (opt.find('t') != string::npos) ss << "Top";
2983 if (opt.find('b') != string::npos) ss << "Bottom";
2984 if (opt.find('B') != string::npos) ss << "Baseline";
2985 if (!ss.str().empty())
2986 os << "\trotateOrigin " << ss.str() << '\n';
2988 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2990 if (opts.find("keepaspectratio") != opts.end())
2991 os << "\tkeepAspectRatio\n";
2992 if (opts.find("clip") != opts.end())
2994 if (opts.find("draft") != opts.end())
2996 if (opts.find("bb") != opts.end())
2997 os << "\tBoundingBox "
2998 << opts["bb"] << '\n';
2999 int numberOfbbOptions = 0;
3000 if (opts.find("bbllx") != opts.end())
3001 numberOfbbOptions++;
3002 if (opts.find("bblly") != opts.end())
3003 numberOfbbOptions++;
3004 if (opts.find("bburx") != opts.end())
3005 numberOfbbOptions++;
3006 if (opts.find("bbury") != opts.end())
3007 numberOfbbOptions++;
3008 if (numberOfbbOptions == 4)
3009 os << "\tBoundingBox "
3010 << opts["bbllx"] << " " << opts["bblly"] << " "
3011 << opts["bburx"] << " " << opts["bbury"] << '\n';
3012 else if (numberOfbbOptions > 0)
3013 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3014 numberOfbbOptions = 0;
3015 if (opts.find("natwidth") != opts.end())
3016 numberOfbbOptions++;
3017 if (opts.find("natheight") != opts.end())
3018 numberOfbbOptions++;
3019 if (numberOfbbOptions == 2)
3020 os << "\tBoundingBox 0bp 0bp "
3021 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3022 else if (numberOfbbOptions > 0)
3023 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3024 ostringstream special;
3025 if (opts.find("hiresbb") != opts.end())
3026 special << "hiresbb,";
3027 if (opts.find("trim") != opts.end())
3029 if (opts.find("viewport") != opts.end())
3030 special << "viewport=" << opts["viewport"] << ',';
3031 if (opts.find("totalheight") != opts.end())
3032 special << "totalheight=" << opts["totalheight"] << ',';
3033 if (opts.find("type") != opts.end())
3034 special << "type=" << opts["type"] << ',';
3035 if (opts.find("ext") != opts.end())
3036 special << "ext=" << opts["ext"] << ',';
3037 if (opts.find("read") != opts.end())
3038 special << "read=" << opts["read"] << ',';
3039 if (opts.find("command") != opts.end())
3040 special << "command=" << opts["command"] << ',';
3041 string s_special = special.str();
3042 if (!s_special.empty()) {
3043 // We had special arguments. Remove the trailing ','.
3044 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3046 // TODO: Handle the unknown settings better.
3047 // Warn about invalid options.
3048 // Check whether some option was given twice.
3050 preamble.registerAutomaticallyLoadedPackage("graphicx");
3053 else if (t.cs() == "footnote" ||
3054 (t.cs() == "thanks" && context.layout->intitle)) {
3056 context.check_layout(os);
3057 begin_inset(os, "Foot\n");
3058 os << "status collapsed\n\n";
3059 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3063 else if (t.cs() == "marginpar") {
3065 context.check_layout(os);
3066 begin_inset(os, "Marginal\n");
3067 os << "status collapsed\n\n";
3068 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3072 else if (t.cs() == "lstinline") {
3074 parse_listings(p, os, context, true);
3077 else if (t.cs() == "ensuremath") {
3079 context.check_layout(os);
3080 string const s = p.verbatim_item();
3081 //FIXME: this never triggers in UTF8
3082 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3085 output_ert_inset(os, "\\ensuremath{" + s + "}",
3089 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3090 if (preamble.titleLayoutFound()) {
3092 skip_spaces_braces(p);
3094 output_ert_inset(os, t.asInput(), context);
3097 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3098 context.check_layout(os);
3099 begin_command_inset(os, "toc", t.cs());
3101 skip_spaces_braces(p);
3102 if (t.cs() == "lstlistoflistings")
3103 preamble.registerAutomaticallyLoadedPackage("listings");
3106 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3107 context.check_layout(os);
3108 if (t.cs() == "listoffigures")
3109 begin_inset(os, "FloatList figure\n");
3111 begin_inset(os, "FloatList table\n");
3113 skip_spaces_braces(p);
3116 else if (t.cs() == "listof") {
3117 p.skip_spaces(true);
3118 string const name = p.get_token().cs();
3119 if (context.textclass.floats().typeExist(name)) {
3120 context.check_layout(os);
3121 begin_inset(os, "FloatList ");
3124 p.get_token(); // swallow second arg
3126 output_ert_inset(os, "\\listof{" + name + "}", context);
3129 else if ((where = is_known(t.cs(), known_text_font_families)))
3130 parse_text_attributes(p, os, FLAG_ITEM, outer,
3131 context, "\\family", context.font.family,
3132 known_coded_font_families[where - known_text_font_families]);
3134 else if ((where = is_known(t.cs(), known_text_font_series)))
3135 parse_text_attributes(p, os, FLAG_ITEM, outer,
3136 context, "\\series", context.font.series,
3137 known_coded_font_series[where - known_text_font_series]);
3139 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3140 parse_text_attributes(p, os, FLAG_ITEM, outer,
3141 context, "\\shape", context.font.shape,
3142 known_coded_font_shapes[where - known_text_font_shapes]);
3144 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3145 context.check_layout(os);
3146 TeXFont oldFont = context.font;
3147 context.font.init();
3148 context.font.size = oldFont.size;
3149 os << "\n\\family " << context.font.family << "\n";
3150 os << "\n\\series " << context.font.series << "\n";
3151 os << "\n\\shape " << context.font.shape << "\n";
3152 if (t.cs() == "textnormal") {
3153 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3154 output_font_change(os, context.font, oldFont);
3155 context.font = oldFont;
3157 eat_whitespace(p, os, context, false);
3160 else if (t.cs() == "textcolor") {
3161 // scheme is \textcolor{color name}{text}
3162 string const color = p.verbatim_item();
3163 // we only support the predefined colors of the color package
3164 if (color == "black" || color == "blue" || color == "cyan"
3165 || color == "green" || color == "magenta" || color == "red"
3166 || color == "white" || color == "yellow") {
3167 context.check_layout(os);
3168 os << "\n\\color " << color << "\n";
3169 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3170 context.check_layout(os);
3171 os << "\n\\color inherit\n";
3172 preamble.registerAutomaticallyLoadedPackage("color");
3174 // for custom defined colors
3175 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3178 else if (t.cs() == "underbar" || t.cs() == "uline") {
3179 // \underbar is not 100% correct (LyX outputs \uline
3180 // of ulem.sty). The difference is that \ulem allows
3181 // line breaks, and \underbar does not.
3182 // Do NOT handle \underline.
3183 // \underbar cuts through y, g, q, p etc.,
3184 // \underline does not.
3185 context.check_layout(os);
3186 os << "\n\\bar under\n";
3187 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3188 context.check_layout(os);
3189 os << "\n\\bar default\n";
3190 preamble.registerAutomaticallyLoadedPackage("ulem");
3193 else if (t.cs() == "sout") {
3194 context.check_layout(os);
3195 os << "\n\\strikeout on\n";
3196 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3197 context.check_layout(os);
3198 os << "\n\\strikeout default\n";
3199 preamble.registerAutomaticallyLoadedPackage("ulem");
3202 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3203 t.cs() == "emph" || t.cs() == "noun") {
3204 context.check_layout(os);
3205 os << "\n\\" << t.cs() << " on\n";
3206 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3207 context.check_layout(os);
3208 os << "\n\\" << t.cs() << " default\n";
3209 if (t.cs() == "uuline" || t.cs() == "uwave")
3210 preamble.registerAutomaticallyLoadedPackage("ulem");
3213 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3214 context.check_layout(os);
3215 string name = p.getArg('{', '}');
3216 string localtime = p.getArg('{', '}');
3217 preamble.registerAuthor(name);
3218 Author const & author = preamble.getAuthor(name);
3219 // from_asctime_utc() will fail if LyX decides to output the
3220 // time in the text language.
3221 time_t ptime = from_asctime_utc(localtime);
3222 if (ptime == static_cast<time_t>(-1)) {
3223 cerr << "Warning: Could not parse time `" << localtime
3224 << "´ for change tracking, using current time instead.\n";
3225 ptime = current_time();
3227 if (t.cs() == "lyxadded")
3228 os << "\n\\change_inserted ";
3230 os << "\n\\change_deleted ";
3231 os << author.bufferId() << ' ' << ptime << '\n';
3232 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3233 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3234 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3235 LaTeXPackages::isAvailable("xcolor");
3236 // No need to test for luatex, since luatex comes in
3237 // two flavours (dvi and pdf), like latex, and those
3238 // are detected by pdflatex.
3239 if (pdflatex || xetex) {
3241 preamble.registerAutomaticallyLoadedPackage("ulem");
3242 preamble.registerAutomaticallyLoadedPackage("xcolor");
3243 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3247 preamble.registerAutomaticallyLoadedPackage("dvipost");
3248 } else if (xcolorulem) {
3249 preamble.registerAutomaticallyLoadedPackage("ulem");
3250 preamble.registerAutomaticallyLoadedPackage("xcolor");
3255 else if (t.cs() == "textipa") {
3256 context.check_layout(os);
3257 begin_inset(os, "IPA\n");
3258 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3260 preamble.registerAutomaticallyLoadedPackage("tipa");
3261 preamble.registerAutomaticallyLoadedPackage("tipx");
3264 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3265 context.check_layout(os);
3266 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3267 os << "status open\n";
3268 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3273 else if (t.cs() == "textvertline") {
3274 // FIXME: This is not correct, \textvertline is higher than |
3280 else if (t.cs() == "tone" ) {
3281 context.check_layout(os);
3282 // register the tone package
3283 preamble.registerAutomaticallyLoadedPackage("tone");
3284 string content = trimSpaceAndEol(p.verbatim_item());
3285 string command = t.asInput() + "{" + content + "}";
3286 // some tones can be detected by unicodesymbols, some need special code
3287 if (is_known(content, known_tones)) {
3288 os << "\\IPAChar " << command << "\n";
3291 // try to see whether the string is in unicodesymbols
3295 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3296 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3297 termination, rem, &req);
3301 output_ert_inset(os, to_utf8(rem), context);
3302 for (set<string>::const_iterator it = req.begin();
3303 it != req.end(); ++it)
3304 preamble.registerAutomaticallyLoadedPackage(*it);
3306 // we did not find a non-ert version
3307 output_ert_inset(os, command, context);
3310 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3311 t.cs() == "vphantom") {
3312 context.check_layout(os);
3313 if (t.cs() == "phantom")
3314 begin_inset(os, "Phantom Phantom\n");
3315 if (t.cs() == "hphantom")
3316 begin_inset(os, "Phantom HPhantom\n");
3317 if (t.cs() == "vphantom")
3318 begin_inset(os, "Phantom VPhantom\n");
3319 os << "status open\n";
3320 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3325 else if (t.cs() == "href") {
3326 context.check_layout(os);
3327 string target = convert_command_inset_arg(p.verbatim_item());
3328 string name = convert_command_inset_arg(p.verbatim_item());
3330 size_t i = target.find(':');
3331 if (i != string::npos) {
3332 type = target.substr(0, i + 1);
3333 if (type == "mailto:" || type == "file:")
3334 target = target.substr(i + 1);
3335 // handle the case that name is equal to target, except of "http://"
3336 else if (target.substr(i + 3) == name && type == "http:")
3339 begin_command_inset(os, "href", "href");
3341 os << "name \"" << name << "\"\n";
3342 os << "target \"" << target << "\"\n";
3343 if (type == "mailto:" || type == "file:")
3344 os << "type \"" << type << "\"\n";
3346 skip_spaces_braces(p);
3349 else if (t.cs() == "lyxline") {
3350 // swallow size argument (it is not used anyway)
3352 if (!context.atParagraphStart()) {
3353 // so our line is in the middle of a paragraph
3354 // we need to add a new line, lest this line
3355 // follow the other content on that line and
3356 // run off the side of the page
3357 // FIXME: This may create an empty paragraph,
3358 // but without that it would not be
3359 // possible to set noindent below.
3360 // Fortunately LaTeX does not care
3361 // about the empty paragraph.
3362 context.new_paragraph(os);
3364 if (preamble.indentParagraphs()) {
3365 // we need to unindent, lest the line be too long
3366 context.add_par_extra_stuff("\\noindent\n");
3368 context.check_layout(os);
3369 begin_command_inset(os, "line", "rule");
3370 os << "offset \"0.5ex\"\n"
3371 "width \"100line%\"\n"
3376 else if (t.cs() == "rule") {
3377 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3378 string const width = p.getArg('{', '}');
3379 string const thickness = p.getArg('{', '}');
3380 context.check_layout(os);
3381 begin_command_inset(os, "line", "rule");
3382 if (!offset.empty())
3383 os << "offset \"" << translate_len(offset) << "\"\n";
3384 os << "width \"" << translate_len(width) << "\"\n"
3385 "height \"" << translate_len(thickness) << "\"\n";
3389 else if (is_known(t.cs(), known_phrases) ||
3390 (t.cs() == "protect" &&
3391 p.next_token().cat() == catEscape &&
3392 is_known(p.next_token().cs(), known_phrases))) {
3393 // LyX sometimes puts a \protect in front, so we have to ignore it
3394 // FIXME: This needs to be changed when bug 4752 is fixed.
3396 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3398 context.check_layout(os);
3399 os << known_coded_phrases[where - known_phrases];
3400 skip_spaces_braces(p);
3403 // handle refstyle first to catch \eqref which can also occur
3404 // without refstyle. Only recognize these commands if
3405 // refstyle.sty was found in the preamble (otherwise \eqref
3406 // and user defined ref commands could be misdetected).
3407 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3408 preamble.refstyle()) {
3409 context.check_layout(os);
3410 begin_command_inset(os, "ref", "formatted");
3411 os << "reference \"";
3412 os << known_refstyle_prefixes[where - known_refstyle_commands]
3414 os << convert_command_inset_arg(p.verbatim_item())
3417 preamble.registerAutomaticallyLoadedPackage("refstyle");
3420 // if refstyle is used, we must not convert \prettyref to a
3421 // formatted reference, since that would result in a refstyle command.
3422 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3423 (t.cs() != "prettyref" || !preamble.refstyle())) {
3424 string const opt = p.getOpt();
3426 context.check_layout(os);
3427 begin_command_inset(os, "ref",
3428 known_coded_ref_commands[where - known_ref_commands]);
3429 os << "reference \""
3430 << convert_command_inset_arg(p.verbatim_item())
3433 if (t.cs() == "vref" || t.cs() == "vpageref")
3434 preamble.registerAutomaticallyLoadedPackage("varioref");
3435 else if (t.cs() == "prettyref")
3436 preamble.registerAutomaticallyLoadedPackage("prettyref");
3438 // LyX does not yet support optional arguments of ref commands
3439 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3440 p.verbatim_item() + '}', context);
3444 else if (use_natbib &&
3445 is_known(t.cs(), known_natbib_commands) &&
3446 ((t.cs() != "citefullauthor" &&
3447 t.cs() != "citeyear" &&
3448 t.cs() != "citeyearpar") ||
3449 p.next_token().asInput() != "*")) {
3450 context.check_layout(os);
3451 string command = t.cs();
3452 if (p.next_token().asInput() == "*") {
3456 if (command == "citefullauthor")
3457 // alternative name for "\\citeauthor*"
3458 command = "citeauthor*";
3460 // text before the citation
3462 // text after the citation
3464 get_cite_arguments(p, true, before, after);
3466 if (command == "cite") {
3467 // \cite without optional argument means
3468 // \citet, \cite with at least one optional
3469 // argument means \citep.
3470 if (before.empty() && after.empty())
3475 if (before.empty() && after == "[]")
3476 // avoid \citet[]{a}
3478 else if (before == "[]" && after == "[]") {
3479 // avoid \citet[][]{a}
3483 // remove the brackets around after and before
3484 if (!after.empty()) {
3486 after.erase(after.length() - 1, 1);
3487 after = convert_command_inset_arg(after);
3489 if (!before.empty()) {
3491 before.erase(before.length() - 1, 1);
3492 before = convert_command_inset_arg(before);
3494 begin_command_inset(os, "citation", command);
3495 os << "after " << '"' << after << '"' << "\n";
3496 os << "before " << '"' << before << '"' << "\n";
3498 << convert_command_inset_arg(p.verbatim_item())
3501 // Need to set the cite engine if natbib is loaded by
3502 // the document class directly
3503 if (preamble.citeEngine() == "basic")
3504 preamble.citeEngine("natbib");
3507 else if (use_jurabib &&
3508 is_known(t.cs(), known_jurabib_commands) &&
3509 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3510 context.check_layout(os);
3511 string command = t.cs();
3512 if (p.next_token().asInput() == "*") {
3516 char argumentOrder = '\0';
3517 vector<string> const options =
3518 preamble.getPackageOptions("jurabib");
3519 if (find(options.begin(), options.end(),
3520 "natbiborder") != options.end())
3521 argumentOrder = 'n';
3522 else if (find(options.begin(), options.end(),
3523 "jurabiborder") != options.end())
3524 argumentOrder = 'j';
3526 // text before the citation
3528 // text after the citation
3530 get_cite_arguments(p, argumentOrder != 'j', before, after);
3532 string const citation = p.verbatim_item();
3533 if (!before.empty() && argumentOrder == '\0') {
3534 cerr << "Warning: Assuming argument order "
3535 "of jurabib version 0.6 for\n'"
3536 << command << before << after << '{'
3537 << citation << "}'.\n"
3538 "Add 'jurabiborder' to the jurabib "
3539 "package options if you used an\n"
3540 "earlier jurabib version." << endl;
3542 if (!after.empty()) {
3544 after.erase(after.length() - 1, 1);
3546 if (!before.empty()) {
3548 before.erase(before.length() - 1, 1);
3550 begin_command_inset(os, "citation", command);
3551 os << "after " << '"' << after << '"' << "\n";
3552 os << "before " << '"' << before << '"' << "\n";
3553 os << "key " << '"' << citation << '"' << "\n";
3555 // Need to set the cite engine if jurabib is loaded by
3556 // the document class directly
3557 if (preamble.citeEngine() == "basic")
3558 preamble.citeEngine("jurabib");
3561 else if (t.cs() == "cite"
3562 || t.cs() == "nocite") {
3563 context.check_layout(os);
3564 string after = convert_command_inset_arg(p.getArg('[', ']'));
3565 string key = convert_command_inset_arg(p.verbatim_item());
3566 // store the case that it is "\nocite{*}" to use it later for
3569 begin_command_inset(os, "citation", t.cs());
3570 os << "after " << '"' << after << '"' << "\n";
3571 os << "key " << '"' << key << '"' << "\n";
3573 } else if (t.cs() == "nocite")
3577 else if (t.cs() == "index" ||
3578 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3579 context.check_layout(os);
3580 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3581 p.getArg('[', ']') : "";
3582 string const kind = arg.empty() ? "idx" : arg;
3583 begin_inset(os, "Index ");
3584 os << kind << "\nstatus collapsed\n";
3585 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3588 preamble.registerAutomaticallyLoadedPackage("splitidx");
3591 else if (t.cs() == "nomenclature") {
3592 context.check_layout(os);
3593 begin_command_inset(os, "nomenclature", "nomenclature");
3594 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3595 if (!prefix.empty())
3596 os << "prefix " << '"' << prefix << '"' << "\n";
3597 os << "symbol " << '"'
3598 << convert_command_inset_arg(p.verbatim_item());
3599 os << "\"\ndescription \""
3600 << convert_command_inset_arg(p.verbatim_item())
3603 preamble.registerAutomaticallyLoadedPackage("nomencl");
3606 else if (t.cs() == "label") {
3607 context.check_layout(os);
3608 begin_command_inset(os, "label", "label");
3610 << convert_command_inset_arg(p.verbatim_item())
3615 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3616 context.check_layout(os);
3617 string commandname = t.cs();
3619 if (p.next_token().asInput() == "*") {
3624 begin_command_inset(os, "index_print", commandname);
3625 string const indexname = p.getArg('[', ']');
3627 if (indexname.empty())
3628 os << "type \"idx\"\n";
3630 os << "type \"" << indexname << "\"\n";
3633 skip_spaces_braces(p);
3634 preamble.registerAutomaticallyLoadedPackage("makeidx");
3635 if (preamble.use_indices() == "true")
3636 preamble.registerAutomaticallyLoadedPackage("splitidx");
3639 else if (t.cs() == "printnomenclature") {
3641 string width_type = "";
3642 context.check_layout(os);
3643 begin_command_inset(os, "nomencl_print", "printnomenclature");
3644 // case of a custom width
3646 width = p.getArg('[', ']');
3647 width = translate_len(width);
3648 width_type = "custom";
3650 // case of no custom width
3651 // the case of no custom width but the width set
3652 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3653 // because the user could have set anything, not only the width
3654 // of the longest label (which would be width_type = "auto")
3655 string label = convert_command_inset_arg(p.getArg('{', '}'));
3656 if (label.empty() && width_type.empty())
3657 width_type = "none";
3658 os << "set_width \"" << width_type << "\"\n";
3659 if (width_type == "custom")
3660 os << "width \"" << width << '\"';
3662 skip_spaces_braces(p);
3663 preamble.registerAutomaticallyLoadedPackage("nomencl");
3666 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3667 context.check_layout(os);
3668 begin_inset(os, "script ");
3669 os << t.cs().substr(4) << '\n';
3670 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3672 if (t.cs() == "textsubscript")
3673 preamble.registerAutomaticallyLoadedPackage("subscript");
3676 else if ((where = is_known(t.cs(), known_quotes))) {
3677 context.check_layout(os);
3678 begin_inset(os, "Quotes ");
3679 os << known_coded_quotes[where - known_quotes];
3681 // LyX adds {} after the quote, so we have to eat
3682 // spaces here if there are any before a possible
3684 eat_whitespace(p, os, context, false);
3688 else if ((where = is_known(t.cs(), known_sizes)) &&
3689 context.new_layout_allowed) {
3690 context.check_layout(os);
3691 TeXFont const oldFont = context.font;
3692 context.font.size = known_coded_sizes[where - known_sizes];
3693 output_font_change(os, oldFont, context.font);
3694 eat_whitespace(p, os, context, false);
3697 else if ((where = is_known(t.cs(), known_font_families)) &&
3698 context.new_layout_allowed) {
3699 context.check_layout(os);
3700 TeXFont const oldFont = context.font;
3701 context.font.family =
3702 known_coded_font_families[where - known_font_families];
3703 output_font_change(os, oldFont, context.font);
3704 eat_whitespace(p, os, context, false);
3707 else if ((where = is_known(t.cs(), known_font_series)) &&
3708 context.new_layout_allowed) {
3709 context.check_layout(os);
3710 TeXFont const oldFont = context.font;
3711 context.font.series =
3712 known_coded_font_series[where - known_font_series];
3713 output_font_change(os, oldFont, context.font);
3714 eat_whitespace(p, os, context, false);
3717 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3718 context.new_layout_allowed) {
3719 context.check_layout(os);
3720 TeXFont const oldFont = context.font;
3721 context.font.shape =
3722 known_coded_font_shapes[where - known_font_shapes];
3723 output_font_change(os, oldFont, context.font);
3724 eat_whitespace(p, os, context, false);
3726 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3727 context.new_layout_allowed) {
3728 context.check_layout(os);
3729 TeXFont const oldFont = context.font;
3730 context.font.init();
3731 context.font.size = oldFont.size;
3732 context.font.family =
3733 known_coded_font_families[where - known_old_font_families];
3734 output_font_change(os, oldFont, context.font);
3735 eat_whitespace(p, os, context, false);
3738 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3739 context.new_layout_allowed) {
3740 context.check_layout(os);
3741 TeXFont const oldFont = context.font;
3742 context.font.init();
3743 context.font.size = oldFont.size;
3744 context.font.series =
3745 known_coded_font_series[where - known_old_font_series];
3746 output_font_change(os, oldFont, context.font);
3747 eat_whitespace(p, os, context, false);
3750 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3751 context.new_layout_allowed) {
3752 context.check_layout(os);
3753 TeXFont const oldFont = context.font;
3754 context.font.init();
3755 context.font.size = oldFont.size;
3756 context.font.shape =
3757 known_coded_font_shapes[where - known_old_font_shapes];
3758 output_font_change(os, oldFont, context.font);
3759 eat_whitespace(p, os, context, false);
3762 else if (t.cs() == "selectlanguage") {
3763 context.check_layout(os);
3764 // save the language for the case that a
3765 // \foreignlanguage is used
3766 context.font.language = babel2lyx(p.verbatim_item());
3767 os << "\n\\lang " << context.font.language << "\n";
3770 else if (t.cs() == "foreignlanguage") {
3771 string const lang = babel2lyx(p.verbatim_item());
3772 parse_text_attributes(p, os, FLAG_ITEM, outer,
3774 context.font.language, lang);
3777 else if (prefixIs(t.cs(), "text")
3778 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3779 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3781 // We have to output the whole command if it has an option
3782 // because LyX doesn't support this yet, see bug #8214,
3783 // only if there is a single option specifying a variant, we can handle it.
3785 string langopts = p.getOpt();
3786 // check if the option contains a variant, if yes, extract it
3787 string::size_type pos_var = langopts.find("variant");
3788 string::size_type i = langopts.find(',');
3789 string::size_type k = langopts.find('=', pos_var);
3790 if (pos_var != string::npos && i == string::npos) {
3792 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3793 lang = preamble.polyglossia2lyx(variant);
3794 parse_text_attributes(p, os, FLAG_ITEM, outer,
3796 context.font.language, lang);
3798 output_ert_inset(os, t.asInput() + langopts, context);
3800 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3801 parse_text_attributes(p, os, FLAG_ITEM, outer,
3803 context.font.language, lang);
3807 else if (t.cs() == "inputencoding") {
3808 // nothing to write here
3809 string const enc = subst(p.verbatim_item(), "\n", " ");
3810 p.setEncoding(enc, Encoding::inputenc);
3813 else if ((where = is_known(t.cs(), known_special_chars))) {
3814 context.check_layout(os);
3815 os << known_coded_special_chars[where - known_special_chars];
3816 skip_spaces_braces(p);
3819 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3820 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3821 context.check_layout(os);
3822 os << "\\SpecialChar \\" << t.cs()
3823 << p.get_token().asInput() << '\n';
3826 else if (t.cs() == "textquotedbl") {
3827 context.check_layout(os);
3832 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3833 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3834 || t.cs() == "%" || t.cs() == "-") {
3835 context.check_layout(os);
3837 os << "\\SpecialChar \\-\n";
3842 else if (t.cs() == "char") {
3843 context.check_layout(os);
3844 if (p.next_token().character() == '`') {
3846 if (p.next_token().cs() == "\"") {
3851 output_ert_inset(os, "\\char`", context);
3854 output_ert_inset(os, "\\char", context);
3858 else if (t.cs() == "verb") {
3859 context.check_layout(os);
3860 // set catcodes to verbatim early, just in case.
3861 p.setCatcodes(VERBATIM_CATCODES);
3862 string delim = p.get_token().asInput();
3863 Parser::Arg arg = p.verbatimStuff(delim);
3865 output_ert_inset(os, "\\verb" + delim
3866 + arg.second + delim, context);
3868 cerr << "invalid \\verb command. Skipping" << endl;
3871 // Problem: \= creates a tabstop inside the tabbing environment
3872 // and else an accent. In the latter case we really would want
3873 // \={o} instead of \= o.
3874 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3875 output_ert_inset(os, t.asInput(), context);
3877 else if (t.cs() == "\\") {
3878 context.check_layout(os);
3880 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3881 else if (p.next_token().asInput() == "*") {
3883 // getOpt() eats the following space if there
3884 // is no optional argument, but that is OK
3885 // here since it has no effect in the output.
3886 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3889 begin_inset(os, "Newline newline");
3894 else if (t.cs() == "newline" ||
3895 (t.cs() == "linebreak" && !p.hasOpt())) {
3896 context.check_layout(os);
3897 begin_inset(os, "Newline ");
3900 skip_spaces_braces(p);
3903 else if (t.cs() == "input" || t.cs() == "include"
3904 || t.cs() == "verbatiminput") {
3905 string name = t.cs();
3906 if (t.cs() == "verbatiminput"
3907 && p.next_token().asInput() == "*")
3908 name += p.get_token().asInput();
3909 context.check_layout(os);
3910 string filename(normalize_filename(p.getArg('{', '}')));
3911 string const path = getMasterFilePath(true);
3912 // We want to preserve relative / absolute filenames,
3913 // therefore path is only used for testing
3914 if ((t.cs() == "include" || t.cs() == "input") &&
3915 !makeAbsPath(filename, path).exists()) {
3916 // The file extension is probably missing.
3917 // Now try to find it out.
3918 string const tex_name =
3919 find_file(filename, path,
3920 known_tex_extensions);
3921 if (!tex_name.empty())
3922 filename = tex_name;
3924 bool external = false;
3926 if (makeAbsPath(filename, path).exists()) {
3927 string const abstexname =
3928 makeAbsPath(filename, path).absFileName();
3929 string const absfigname =
3930 changeExtension(abstexname, ".fig");
3931 fix_child_filename(filename);
3932 string const lyxname = changeExtension(filename,
3933 roundtripMode() ? ".lyx.lyx" : ".lyx");
3934 string const abslyxname = makeAbsPath(
3935 lyxname, getParentFilePath(false)).absFileName();
3937 if (!skipChildren())
3938 external = FileName(absfigname).exists();
3939 if (t.cs() == "input" && !skipChildren()) {
3940 string const ext = getExtension(abstexname);
3942 // Combined PS/LaTeX:
3943 // x.eps, x.pstex_t (old xfig)
3944 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3945 FileName const absepsname(
3946 changeExtension(abstexname, ".eps"));
3947 FileName const abspstexname(
3948 changeExtension(abstexname, ".pstex"));
3949 bool const xfigeps =
3950 (absepsname.exists() ||
3951 abspstexname.exists()) &&
3954 // Combined PDF/LaTeX:
3955 // x.pdf, x.pdftex_t (old xfig)
3956 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3957 FileName const abspdfname(
3958 changeExtension(abstexname, ".pdf"));
3959 bool const xfigpdf =
3960 abspdfname.exists() &&
3961 (ext == "pdftex_t" || ext == "pdf_t");
3965 // Combined PS/PDF/LaTeX:
3966 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3967 string const absbase2(
3968 removeExtension(abstexname) + "_pspdftex");
3969 FileName const abseps2name(
3970 addExtension(absbase2, ".eps"));
3971 FileName const abspdf2name(
3972 addExtension(absbase2, ".pdf"));
3973 bool const xfigboth =
3974 abspdf2name.exists() &&
3975 abseps2name.exists() && ext == "pspdftex";
3977 xfig = xfigpdf || xfigeps || xfigboth;
3978 external = external && xfig;
3981 outname = changeExtension(filename, ".fig");
3982 FileName abssrc(changeExtension(abstexname, ".fig"));
3983 copy_file(abssrc, outname);
3985 // Don't try to convert, the result
3986 // would be full of ERT.
3988 FileName abssrc(abstexname);
3989 copy_file(abssrc, outname);
3990 } else if (t.cs() != "verbatiminput" &&
3992 tex2lyx(abstexname, FileName(abslyxname),
3995 // no need to call copy_file
3996 // tex2lyx creates the file
3999 FileName abssrc(abstexname);
4000 copy_file(abssrc, outname);
4003 cerr << "Warning: Could not find included file '"
4004 << filename << "'." << endl;
4008 begin_inset(os, "External\n");
4009 os << "\ttemplate XFig\n"
4010 << "\tfilename " << outname << '\n';
4011 registerExternalTemplatePackages("XFig");
4013 begin_command_inset(os, "include", name);
4014 outname = subst(outname, "\"", "\\\"");
4015 os << "preview false\n"
4016 "filename \"" << outname << "\"\n";
4017 if (t.cs() == "verbatiminput")
4018 preamble.registerAutomaticallyLoadedPackage("verbatim");
4023 else if (t.cs() == "bibliographystyle") {
4024 // store new bibliographystyle
4025 bibliographystyle = p.verbatim_item();
4026 // If any other command than \bibliography, \addcontentsline
4027 // and \nocite{*} follows, we need to output the style
4028 // (because it might be used by that command).
4029 // Otherwise, it will automatically be output by LyX.
4032 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4033 if (t2.cat() == catBegin)
4035 if (t2.cat() != catEscape)
4037 if (t2.cs() == "nocite") {
4038 if (p.getArg('{', '}') == "*")
4040 } else if (t2.cs() == "bibliography")
4042 else if (t2.cs() == "phantomsection") {
4046 else if (t2.cs() == "addcontentsline") {
4047 // get the 3 arguments of \addcontentsline
4050 contentslineContent = p.getArg('{', '}');
4051 // if the last argument is not \refname we must output
4052 if (contentslineContent == "\\refname")
4059 output_ert_inset(os,
4060 "\\bibliographystyle{" + bibliographystyle + '}',
4065 else if (t.cs() == "phantomsection") {
4066 // we only support this if it occurs between
4067 // \bibliographystyle and \bibliography
4068 if (bibliographystyle.empty())
4069 output_ert_inset(os, "\\phantomsection", context);
4072 else if (t.cs() == "addcontentsline") {
4073 context.check_layout(os);
4074 // get the 3 arguments of \addcontentsline
4075 string const one = p.getArg('{', '}');
4076 string const two = p.getArg('{', '}');
4077 string const three = p.getArg('{', '}');
4078 // only if it is a \refname, we support if for the bibtex inset
4079 if (contentslineContent != "\\refname") {
4080 output_ert_inset(os,
4081 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4086 else if (t.cs() == "bibliography") {
4087 context.check_layout(os);
4089 begin_command_inset(os, "bibtex", "bibtex");
4090 if (!btprint.empty()) {
4091 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4092 // clear the string because the next BibTeX inset can be without the
4093 // \nocite{*} option
4096 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4097 // Do we have addcontentsline?
4098 if (contentslineContent == "\\refname") {
4099 BibOpts = "bibtotoc";
4100 // clear string because next BibTeX inset can be without addcontentsline
4101 contentslineContent.clear();
4103 // Do we have a bibliographystyle set?
4104 if (!bibliographystyle.empty()) {
4105 if (BibOpts.empty())
4106 BibOpts = bibliographystyle;
4108 BibOpts = BibOpts + ',' + bibliographystyle;
4109 // clear it because each bibtex entry has its style
4110 // and we need an empty string to handle \phantomsection
4111 bibliographystyle.clear();
4113 os << "options " << '"' << BibOpts << '"' << "\n";
4117 else if (t.cs() == "parbox") {
4118 // Test whether this is an outer box of a shaded box
4120 // swallow arguments
4121 while (p.hasOpt()) {
4123 p.skip_spaces(true);
4126 p.skip_spaces(true);
4128 if (p.next_token().cat() == catBegin)
4130 p.skip_spaces(true);
4131 Token to = p.get_token();
4132 bool shaded = false;
4133 if (to.asInput() == "\\begin") {
4134 p.skip_spaces(true);
4135 if (p.getArg('{', '}') == "shaded")
4140 parse_outer_box(p, os, FLAG_ITEM, outer,
4141 context, "parbox", "shaded");
4143 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4147 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4148 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4149 t.cs() == "shadowbox" || t.cs() == "doublebox")
4150 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4152 else if (t.cs() == "framebox") {
4153 if (p.next_token().character() == '(') {
4154 //the syntax is: \framebox(x,y)[position]{content}
4155 string arg = t.asInput();
4156 arg += p.getFullParentheseArg();
4157 arg += p.getFullOpt();
4158 eat_whitespace(p, os, context, false);
4159 output_ert_inset(os, arg + '{', context);
4160 parse_text(p, os, FLAG_ITEM, outer, context);
4161 output_ert_inset(os, "}", context);
4163 //the syntax is: \framebox[width][position]{content}
4164 string special = p.getFullOpt();
4165 special += p.getOpt();
4166 parse_outer_box(p, os, FLAG_ITEM, outer,
4167 context, t.cs(), special);
4171 //\makebox() is part of the picture environment and different from \makebox{}
4172 //\makebox{} will be parsed by parse_box
4173 else if (t.cs() == "makebox") {
4174 if (p.next_token().character() == '(') {
4175 //the syntax is: \makebox(x,y)[position]{content}
4176 string arg = t.asInput();
4177 arg += p.getFullParentheseArg();
4178 arg += p.getFullOpt();
4179 eat_whitespace(p, os, context, false);
4180 output_ert_inset(os, arg + '{', context);
4181 parse_text(p, os, FLAG_ITEM, outer, context);
4182 output_ert_inset(os, "}", context);
4184 //the syntax is: \makebox[width][position]{content}
4185 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4189 else if (t.cs() == "smallskip" ||
4190 t.cs() == "medskip" ||
4191 t.cs() == "bigskip" ||
4192 t.cs() == "vfill") {
4193 context.check_layout(os);
4194 begin_inset(os, "VSpace ");
4197 skip_spaces_braces(p);
4200 else if ((where = is_known(t.cs(), known_spaces))) {
4201 context.check_layout(os);
4202 begin_inset(os, "space ");
4203 os << '\\' << known_coded_spaces[where - known_spaces]
4206 // LaTeX swallows whitespace after all spaces except
4207 // "\\,". We have to do that here, too, because LyX
4208 // adds "{}" which would make the spaces significant.
4210 eat_whitespace(p, os, context, false);
4211 // LyX adds "{}" after all spaces except "\\ " and
4212 // "\\,", so we have to remove "{}".
4213 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4214 // remove the braces after "\\,", too.
4219 else if (t.cs() == "newpage" ||
4220 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4221 t.cs() == "clearpage" ||
4222 t.cs() == "cleardoublepage") {
4223 context.check_layout(os);
4224 begin_inset(os, "Newpage ");
4227 skip_spaces_braces(p);
4230 else if (t.cs() == "DeclareRobustCommand" ||
4231 t.cs() == "DeclareRobustCommandx" ||
4232 t.cs() == "newcommand" ||
4233 t.cs() == "newcommandx" ||
4234 t.cs() == "providecommand" ||
4235 t.cs() == "providecommandx" ||
4236 t.cs() == "renewcommand" ||
4237 t.cs() == "renewcommandx") {
4238 // DeclareRobustCommand, DeclareRobustCommandx,
4239 // providecommand and providecommandx could be handled
4240 // by parse_command(), but we need to call
4241 // add_known_command() here.
4242 string name = t.asInput();
4243 if (p.next_token().asInput() == "*") {
4244 // Starred form. Eat '*'
4248 string const command = p.verbatim_item();
4249 string const opt1 = p.getFullOpt();
4250 string const opt2 = p.getFullOpt();
4251 add_known_command(command, opt1, !opt2.empty());
4252 string const ert = name + '{' + command + '}' +
4254 '{' + p.verbatim_item() + '}';
4256 if (t.cs() == "DeclareRobustCommand" ||
4257 t.cs() == "DeclareRobustCommandx" ||
4258 t.cs() == "providecommand" ||
4259 t.cs() == "providecommandx" ||
4260 name[name.length()-1] == '*')
4261 output_ert_inset(os, ert, context);
4263 context.check_layout(os);
4264 begin_inset(os, "FormulaMacro");
4270 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4271 // let could be handled by parse_command(),
4272 // but we need to call add_known_command() here.
4273 string ert = t.asInput();
4276 if (p.next_token().cat() == catBegin) {
4277 name = p.verbatim_item();
4278 ert += '{' + name + '}';
4280 name = p.verbatim_item();
4285 if (p.next_token().cat() == catBegin) {
4286 command = p.verbatim_item();
4287 ert += '{' + command + '}';
4289 command = p.verbatim_item();
4292 // If command is known, make name known too, to parse
4293 // its arguments correctly. For this reason we also
4294 // have commands in syntax.default that are hardcoded.
4295 CommandMap::iterator it = known_commands.find(command);
4296 if (it != known_commands.end())
4297 known_commands[t.asInput()] = it->second;
4298 output_ert_inset(os, ert, context);
4301 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4302 bool starred = false;
4303 if (p.next_token().asInput() == "*") {
4307 string name = t.asInput();
4308 string const length = p.verbatim_item();
4311 bool valid = splitLatexLength(length, valstring, unit);
4312 bool known_hspace = false;
4313 bool known_vspace = false;
4314 bool known_unit = false;
4317 istringstream iss(valstring);
4320 if (t.cs()[0] == 'h') {
4321 if (unit == "\\fill") {
4326 known_hspace = true;
4329 if (unit == "\\smallskipamount") {
4331 known_vspace = true;
4332 } else if (unit == "\\medskipamount") {
4334 known_vspace = true;
4335 } else if (unit == "\\bigskipamount") {
4337 known_vspace = true;
4338 } else if (unit == "\\fill") {
4340 known_vspace = true;
4344 if (!known_hspace && !known_vspace) {
4345 switch (unitFromString(unit)) {
4366 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4367 // Literal horizontal length or known variable
4368 context.check_layout(os);
4369 begin_inset(os, "space ");
4377 if (known_unit && !known_hspace)
4379 << translate_len(length);
4381 } else if (known_unit || known_vspace) {
4382 // Literal vertical length or known variable
4383 context.check_layout(os);
4384 begin_inset(os, "VSpace ");
4392 // LyX can't handle other length variables in Inset VSpace/space
4397 output_ert_inset(os, name + '{' + unit + '}', context);
4398 else if (value == -1.0)
4399 output_ert_inset(os, name + "{-" + unit + '}', context);
4401 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4403 output_ert_inset(os, name + '{' + length + '}', context);
4407 // The single '=' is meant here.
4408 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4410 context.check_layout(os);
4411 begin_inset(os, "Flex ");
4412 os << to_utf8(newinsetlayout->name()) << '\n'
4413 << "status collapsed\n";
4414 if (newinsetlayout->isPassThru()) {
4415 // set catcodes to verbatim early, just in case.
4416 p.setCatcodes(VERBATIM_CATCODES);
4417 string delim = p.get_token().asInput();
4419 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4420 //FIXME: handle error condition
4421 string const arg = p.verbatimStuff("}").second;
4422 Context newcontext(true, context.textclass);
4423 if (newinsetlayout->forcePlainLayout())
4424 newcontext.layout = &context.textclass.plainLayout();
4425 output_ert(os, arg, newcontext);
4428 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4432 else if (t.cs() == "includepdf") {
4434 string const arg = p.getArg('[', ']');
4435 map<string, string> opts;
4436 vector<string> keys;
4437 split_map(arg, opts, keys);
4438 string name = normalize_filename(p.verbatim_item());
4439 string const path = getMasterFilePath(true);
4440 // We want to preserve relative / absolute filenames,
4441 // therefore path is only used for testing
4442 if (!makeAbsPath(name, path).exists()) {
4443 // The file extension is probably missing.
4444 // Now try to find it out.
4445 char const * const pdfpages_format[] = {"pdf", 0};
4446 string const pdftex_name =
4447 find_file(name, path, pdfpages_format);
4448 if (!pdftex_name.empty()) {
4453 FileName const absname = makeAbsPath(name, path);
4454 if (absname.exists())
4456 fix_child_filename(name);
4457 copy_file(absname, name);
4459 cerr << "Warning: Could not find file '"
4460 << name << "'." << endl;
4462 context.check_layout(os);
4463 begin_inset(os, "External\n\ttemplate ");
4464 os << "PDFPages\n\tfilename "
4466 // parse the options
4467 if (opts.find("pages") != opts.end())
4468 os << "\textra LaTeX \"pages="
4469 << opts["pages"] << "\"\n";
4470 if (opts.find("angle") != opts.end())
4471 os << "\trotateAngle "
4472 << opts["angle"] << '\n';
4473 if (opts.find("origin") != opts.end()) {
4475 string const opt = opts["origin"];
4476 if (opt == "tl") ss << "topleft";
4477 if (opt == "bl") ss << "bottomleft";
4478 if (opt == "Bl") ss << "baselineleft";
4479 if (opt == "c") ss << "center";
4480 if (opt == "tc") ss << "topcenter";
4481 if (opt == "bc") ss << "bottomcenter";
4482 if (opt == "Bc") ss << "baselinecenter";
4483 if (opt == "tr") ss << "topright";
4484 if (opt == "br") ss << "bottomright";
4485 if (opt == "Br") ss << "baselineright";
4486 if (!ss.str().empty())
4487 os << "\trotateOrigin " << ss.str() << '\n';
4489 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4491 if (opts.find("width") != opts.end())
4493 << translate_len(opts["width"]) << '\n';
4494 if (opts.find("height") != opts.end())
4496 << translate_len(opts["height"]) << '\n';
4497 if (opts.find("keepaspectratio") != opts.end())
4498 os << "\tkeepAspectRatio\n";
4500 context.check_layout(os);
4501 registerExternalTemplatePackages("PDFPages");
4504 else if (t.cs() == "loadgame") {
4506 string name = normalize_filename(p.verbatim_item());
4507 string const path = getMasterFilePath(true);
4508 // We want to preserve relative / absolute filenames,
4509 // therefore path is only used for testing
4510 if (!makeAbsPath(name, path).exists()) {
4511 // The file extension is probably missing.
4512 // Now try to find it out.
4513 char const * const lyxskak_format[] = {"fen", 0};
4514 string const lyxskak_name =
4515 find_file(name, path, lyxskak_format);
4516 if (!lyxskak_name.empty())
4517 name = lyxskak_name;
4519 FileName const absname = makeAbsPath(name, path);
4520 if (absname.exists())
4522 fix_child_filename(name);
4523 copy_file(absname, name);
4525 cerr << "Warning: Could not find file '"
4526 << name << "'." << endl;
4527 context.check_layout(os);
4528 begin_inset(os, "External\n\ttemplate ");
4529 os << "ChessDiagram\n\tfilename "
4532 context.check_layout(os);
4533 // after a \loadgame follows a \showboard
4534 if (p.get_token().asInput() == "showboard")
4536 registerExternalTemplatePackages("ChessDiagram");
4540 // try to see whether the string is in unicodesymbols
4541 // Only use text mode commands, since we are in text mode here,
4542 // and math commands may be invalid (bug 6797)
4543 string name = t.asInput();
4544 // handle the dingbats and Cyrillic
4545 if (name == "\\ding" || name == "\\textcyr")
4546 name = name + '{' + p.getArg('{', '}') + '}';
4547 // handle the ifsym characters
4548 else if (name == "\\textifsymbol") {
4549 string const optif = p.getFullOpt();
4550 string const argif = p.getArg('{', '}');
4551 name = name + optif + '{' + argif + '}';
4553 // handle the \ascii characters
4554 // the case of \ascii within braces, as LyX outputs it, is already
4555 // handled for t.cat() == catBegin
4556 else if (name == "\\ascii") {
4557 // the code is "\asci\xxx"
4558 name = "{" + name + p.get_token().asInput() + "}";
4561 // handle some TIPA special characters
4562 else if (preamble.isPackageUsed("tipa")) {
4563 if (name == "\\textglobfall") {
4566 } else if (name == "\\s") {
4567 // fromLaTeXCommand() does not yet
4568 // recognize tipa short cuts
4569 name = "\\textsyllabic";
4570 } else if (name == "\\=" &&
4571 p.next_token().asInput() == "*") {
4572 // fromLaTeXCommand() does not yet
4573 // recognize tipa short cuts
4576 } else if (name == "\\textdoublevertline") {
4577 // FIXME: This is not correct,
4578 // \textvertline is higher than \textbardbl
4579 name = "\\textbardbl";
4581 } else if (name == "\\!" ) {
4582 if (p.next_token().asInput() == "b") {
4583 p.get_token(); // eat 'b'
4586 } else if (p.next_token().asInput() == "d") {
4590 } else if (p.next_token().asInput() == "g") {
4594 } else if (p.next_token().asInput() == "G") {
4596 name = "\\texthtscg";
4598 } else if (p.next_token().asInput() == "j") {
4600 name = "\\texthtbardotlessj";
4602 } else if (p.next_token().asInput() == "o") {
4604 name = "\\textbullseye";
4607 } else if (name == "\\*" ) {
4608 if (p.next_token().asInput() == "k") {
4610 name = "\\textturnk";
4612 } else if (p.next_token().asInput() == "r") {
4613 p.get_token(); // eat 'b'
4614 name = "\\textturnr";
4616 } else if (p.next_token().asInput() == "t") {
4618 name = "\\textturnt";
4620 } else if (p.next_token().asInput() == "w") {
4622 name = "\\textturnw";
4627 if ((name.size() == 2 &&
4628 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4629 p.next_token().asInput() != "*") ||
4630 is_known(name.substr(1), known_tipa_marks)) {
4631 // name is a command that corresponds to a
4632 // combining character in unicodesymbols.
4633 // Append the argument, fromLaTeXCommand()
4634 // will either convert it to a single
4635 // character or a combining sequence.
4636 name += '{' + p.verbatim_item() + '}';
4638 // now get the character from unicodesymbols
4642 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4643 Encodings::TEXT_CMD, termination, rem, &req);
4645 context.check_layout(os);
4648 output_ert_inset(os, to_utf8(rem), context);
4650 skip_spaces_braces(p);
4651 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4652 preamble.registerAutomaticallyLoadedPackage(*it);
4654 //cerr << "#: " << t << " mode: " << mode << endl;
4655 // heuristic: read up to next non-nested space
4657 string s = t.asInput();
4658 string z = p.verbatim_item();
4659 while (p.good() && z != " " && !z.empty()) {
4660 //cerr << "read: " << z << endl;
4662 z = p.verbatim_item();
4664 cerr << "found ERT: " << s << endl;
4665 output_ert_inset(os, s + ' ', context);
4668 if (t.asInput() == name &&
4669 p.next_token().asInput() == "*") {
4670 // Starred commands like \vspace*{}
4671 p.get_token(); // Eat '*'
4674 if (!parse_command(name, p, os, outer, context))
4675 output_ert_inset(os, name, context);
4679 if (flags & FLAG_LEAVE) {
4680 flags &= ~FLAG_LEAVE;
4687 string guessLanguage(Parser & p, string const & lang)
4689 typedef std::map<std::string, size_t> LangMap;
4690 // map from language names to number of characters
4693 for (char const * const * i = supported_CJK_languages; *i; i++)
4694 used[string(*i)] = 0;
4697 Token const t = p.get_token();
4698 // comments are not counted for any language
4699 if (t.cat() == catComment)
4701 // commands are not counted as well, but we need to detect
4702 // \begin{CJK} and switch encoding if needed
4703 if (t.cat() == catEscape) {
4704 if (t.cs() == "inputencoding") {
4705 string const enc = subst(p.verbatim_item(), "\n", " ");
4706 p.setEncoding(enc, Encoding::inputenc);
4709 if (t.cs() != "begin")
4712 // Non-CJK content is counted for lang.
4713 // We do not care about the real language here:
4714 // If we have more non-CJK contents than CJK contents,
4715 // we simply use the language that was specified as
4716 // babel main language.
4717 used[lang] += t.asInput().length();
4720 // Now we are starting an environment
4722 string const name = p.getArg('{', '}');
4723 if (name != "CJK") {
4727 // It is a CJK environment
4729 /* name = */ p.getArg('{', '}');
4730 string const encoding = p.getArg('{', '}');
4731 /* mapping = */ p.getArg('{', '}');
4732 string const encoding_old = p.getEncoding();
4733 char const * const * const where =
4734 is_known(encoding, supported_CJK_encodings);
4736 p.setEncoding(encoding, Encoding::CJK);
4738 p.setEncoding("UTF-8");
4739 string const text = p.ertEnvironment("CJK");
4740 p.setEncoding(encoding_old);
4743 // ignore contents in unknown CJK encoding
4746 // the language of the text
4748 supported_CJK_languages[where - supported_CJK_encodings];
4749 used[cjk] += text.length();
4751 LangMap::const_iterator use = used.begin();
4752 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4753 if (it->second > use->second)