2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49 Context const & context, InsetLayout const * layout)
51 bool const forcePlainLayout =
52 layout ? layout->forcePlainLayout() : false;
53 Context newcontext(true, context.textclass);
55 newcontext.layout = &context.textclass.plainLayout();
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context const & context, string const & name)
68 InsetLayout const * layout = 0;
69 DocumentClass::InsetLayouts::const_iterator it =
70 context.textclass.insetLayouts().find(from_ascii(name));
71 if (it != context.textclass.insetLayouts().end())
72 layout = &(it->second);
73 parse_text_in_inset(p, os, flags, outer, context, layout);
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context newcontext(context);
81 // Don't inherit the paragraph-level extra stuff
82 newcontext.par_extra_stuff.clear();
83 parse_text(p, os, flags, outer, newcontext);
84 // Make sure that we don't create invalid .lyx files
85 context.need_layout = newcontext.need_layout;
86 context.need_end_layout = newcontext.need_end_layout;
91 * Thin wrapper around parse_text_snippet() using a string.
93 * We completely ignore \c context.need_layout and \c context.need_end_layout,
94 * because our return value is not used directly (otherwise the stream version
95 * of parse_text_snippet() could be used). That means that the caller needs
96 * to do layout management manually.
97 * This is intended to parse text that does not create any layout changes.
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
102 Context newcontext(context);
103 newcontext.need_layout = false;
104 newcontext.need_end_layout = false;
105 newcontext.new_layout_allowed = false;
106 // Avoid warning by Context::~Context()
107 newcontext.par_extra_stuff.clear();
109 parse_text_snippet(p, os, flags, outer, newcontext);
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115 "vpageref", "prettyref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "eqref", 0 };
120 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
121 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
122 "secref", "subref", "tabref", "thmref", 0 };
124 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
125 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
126 "sec", "sub", "tab", "thm", 0 };
130 * supported CJK encodings
131 * JIS does not work with LyX's encoding conversion
133 const char * const supported_CJK_encodings[] = {
134 "EUC-JP", "KS", "GB", "UTF8",
135 "Bg5", /*"JIS",*/ "SJIS", 0};
138 * the same as supported_CJK_encodings with their corresponding LyX language name
139 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
141 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
142 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
143 * please keep this in sync with supported_CJK_encodings line by line!
145 const char * const supported_CJK_languages[] = {
146 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
147 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
151 * The starred forms are also known except for "citefullauthor",
152 * "citeyear" and "citeyearpar".
154 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
155 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
156 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
160 * No starred form other than "cite*" known.
162 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
163 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
164 // jurabib commands not (yet) supported by LyX:
166 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
167 // "footciteauthor", "footciteyear", "footciteyearpar",
168 "citefield", "citetitle", 0 };
170 /// LaTeX names for quotes
171 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
172 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
173 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
174 "guilsinglleft", "frq", "guilsinglright", 0};
176 /// the same as known_quotes with .lyx names
177 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
178 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
179 "gld", "grd", "gls", "ers", "fls",
180 "fls", "frs", "frs", 0};
182 /// LaTeX names for font sizes
183 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
184 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
186 /// the same as known_sizes with .lyx names
187 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
188 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
190 /// LaTeX 2.09 names for font families
191 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
193 /// LaTeX names for font families
194 char const * const known_font_families[] = { "rmfamily", "sffamily",
197 /// LaTeX names for font family changing commands
198 char const * const known_text_font_families[] = { "textrm", "textsf",
201 /// The same as known_old_font_families, known_font_families and
202 /// known_text_font_families with .lyx names
203 char const * const known_coded_font_families[] = { "roman", "sans",
206 /// LaTeX 2.09 names for font series
207 char const * const known_old_font_series[] = { "bf", 0};
209 /// LaTeX names for font series
210 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
212 /// LaTeX names for font series changing commands
213 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
215 /// The same as known_old_font_series, known_font_series and
216 /// known_text_font_series with .lyx names
217 char const * const known_coded_font_series[] = { "bold", "medium", 0};
219 /// LaTeX 2.09 names for font shapes
220 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
222 /// LaTeX names for font shapes
223 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
226 /// LaTeX names for font shape changing commands
227 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
230 /// The same as known_old_font_shapes, known_font_shapes and
231 /// known_text_font_shapes with .lyx names
232 char const * const known_coded_font_shapes[] = { "italic", "slanted",
233 "smallcaps", "up", 0};
235 /// Known special characters which need skip_spaces_braces() afterwards
236 char const * const known_special_chars[] = {"ldots", "lyxarrow",
237 "textcompwordmark", "slash", 0};
239 /// the same as known_special_chars with .lyx names
240 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
241 "textcompwordmark{}", "slash{}", 0};
244 * Graphics file extensions known by the dvips driver of the graphics package.
245 * These extensions are used to complete the filename of an included
246 * graphics file if it does not contain an extension.
247 * The order must be the same that latex uses to find a file, because we
248 * will use the first extension that matches.
249 * This is only an approximation for the common cases. If we would want to
250 * do it right in all cases, we would need to know which graphics driver is
251 * used and know the extensions of every driver of the graphics package.
253 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
254 "ps.gz", "eps.Z", "ps.Z", 0};
257 * Graphics file extensions known by the pdftex driver of the graphics package.
258 * \sa known_dvips_graphics_formats
260 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
264 * Known file extensions for TeX files as used by \\include.
266 char const * const known_tex_extensions[] = {"tex", 0};
268 /// spaces known by InsetSpace
269 char const * const known_spaces[] = { " ", "space", ",",
270 "thinspace", "quad", "qquad", "enspace", "enskip",
271 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
272 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
273 "upbracefill", "downbracefill", 0};
275 /// the same as known_spaces with .lyx names
276 char const * const known_coded_spaces[] = { "space{}", "space{}",
277 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
278 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
279 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
280 "upbracefill{}", "downbracefill{}", 0};
282 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
283 /// them in ERT. "LaTeXe" must come before "LaTeX"!
284 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
285 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
286 int const known_phrase_lengths[] = {3, 5, 7, 0};
288 /// known TIPA combining diacritical marks
289 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
290 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
291 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
292 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
293 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
294 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
297 /// TIPA tones that need special handling
298 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
300 // string to store the float type to be able to determine the type of subfloats
301 string float_type = "";
304 /// splits "x=z, y=b" into a map and an ordered keyword vector
305 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
310 keys.resize(v.size());
311 for (size_t i = 0; i < v.size(); ++i) {
312 size_t const pos = v[i].find('=');
313 string const index = trimSpaceAndEol(v[i].substr(0, pos));
314 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
322 * Split a LaTeX length into value and unit.
323 * The latter can be a real unit like "pt", or a latex length variable
324 * like "\textwidth". The unit may contain additional stuff like glue
325 * lengths, but we don't care, because such lengths are ERT anyway.
326 * \returns true if \p value and \p unit are valid.
328 bool splitLatexLength(string const & len, string & value, string & unit)
332 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
333 //'4,5' is a valid LaTeX length number. Change it to '4.5'
334 string const length = subst(len, ',', '.');
335 if (i == string::npos)
338 if (len[0] == '\\') {
339 // We had something like \textwidth without a factor
345 value = trimSpaceAndEol(string(length, 0, i));
349 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
350 if (contains(len, '\\'))
351 unit = trimSpaceAndEol(string(len, i));
353 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
358 /// A simple function to translate a latex length to something LyX can
359 /// understand. Not perfect, but rather best-effort.
360 bool translate_len(string const & length, string & valstring, string & unit)
362 if (!splitLatexLength(length, valstring, unit))
364 // LyX uses percent values
366 istringstream iss(valstring);
371 string const percentval = oss.str();
373 if (unit.empty() || unit[0] != '\\')
375 string::size_type const i = unit.find(' ');
376 string const endlen = (i == string::npos) ? string() : string(unit, i);
377 if (unit == "\\textwidth") {
378 valstring = percentval;
379 unit = "text%" + endlen;
380 } else if (unit == "\\columnwidth") {
381 valstring = percentval;
382 unit = "col%" + endlen;
383 } else if (unit == "\\paperwidth") {
384 valstring = percentval;
385 unit = "page%" + endlen;
386 } else if (unit == "\\linewidth") {
387 valstring = percentval;
388 unit = "line%" + endlen;
389 } else if (unit == "\\paperheight") {
390 valstring = percentval;
391 unit = "pheight%" + endlen;
392 } else if (unit == "\\textheight") {
393 valstring = percentval;
394 unit = "theight%" + endlen;
402 string translate_len(string const & length)
406 if (translate_len(length, value, unit))
408 // If the input is invalid, return what we have.
416 * Translates a LaTeX length into \p value, \p unit and
417 * \p special parts suitable for a box inset.
418 * The difference from translate_len() is that a box inset knows about
419 * some special "units" that are stored in \p special.
421 void translate_box_len(string const & length, string & value, string & unit, string & special)
423 if (translate_len(length, value, unit)) {
424 if (unit == "\\height" || unit == "\\depth" ||
425 unit == "\\totalheight" || unit == "\\width") {
426 special = unit.substr(1);
427 // The unit is not used, but LyX requires a dummy setting
440 * Find a file with basename \p name in path \p path and an extension
443 string find_file(string const & name, string const & path,
444 char const * const * extensions)
446 for (char const * const * what = extensions; *what; ++what) {
447 string const trial = addExtension(name, *what);
448 if (makeAbsPath(trial, path).exists())
455 void begin_inset(ostream & os, string const & name)
457 os << "\n\\begin_inset " << name;
461 void begin_command_inset(ostream & os, string const & name,
462 string const & latexname)
464 begin_inset(os, "CommandInset ");
465 os << name << "\nLatexCommand " << latexname << '\n';
469 void end_inset(ostream & os)
471 os << "\n\\end_inset\n\n";
475 bool skip_braces(Parser & p)
477 if (p.next_token().cat() != catBegin)
480 if (p.next_token().cat() == catEnd) {
489 /// replace LaTeX commands in \p s from the unicodesymbols file with their
491 docstring convert_unicodesymbols(docstring s)
494 for (size_t i = 0; i < s.size();) {
503 docstring parsed = encodings.fromLaTeXCommand(s,
504 Encodings::TEXT_CMD, termination, rem, &req);
505 set<string>::const_iterator it = req.begin();
506 set<string>::const_iterator en = req.end();
507 for (; it != en; ++it)
508 preamble.registerAutomaticallyLoadedPackage(*it);
511 if (s.empty() || s[0] != '\\')
520 /// try to convert \p s to a valid InsetCommand argument
521 string convert_command_inset_arg(string s)
524 // since we don't know the input encoding we can't use from_utf8
525 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
526 // LyX cannot handle newlines in a latex command
527 return subst(s, "\n", " ");
531 void output_ert(ostream & os, string const & s, Context & context)
533 context.check_layout(os);
534 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
536 os << "\n\\backslash\n";
537 else if (*it == '\n') {
538 context.new_paragraph(os);
539 context.check_layout(os);
543 context.check_end_layout(os);
547 void output_ert_inset(ostream & os, string const & s, Context & context)
549 // We must have a valid layout before outputting the ERT inset.
550 context.check_layout(os);
551 Context newcontext(true, context.textclass);
552 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
553 if (layout.forcePlainLayout())
554 newcontext.layout = &context.textclass.plainLayout();
555 begin_inset(os, "ERT");
556 os << "\nstatus collapsed\n";
557 output_ert(os, s, newcontext);
562 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
564 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
567 if (checkModule(name, command))
568 return findLayoutWithoutModule(textclass, name, command);
573 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
575 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
578 if (checkModule(name, command))
579 return findInsetLayoutWithoutModule(textclass, name, command);
584 void eat_whitespace(Parser &, ostream &, Context &, bool);
588 * Skips whitespace and braces.
589 * This should be called after a command has been parsed that is not put into
590 * ERT, and where LyX adds "{}" if needed.
592 void skip_spaces_braces(Parser & p, bool keepws = false)
594 /* The following four examples produce the same typeset output and
595 should be handled by this function:
603 // Unfortunately we need to skip comments, too.
604 // We can't use eat_whitespace since writing them after the {}
605 // results in different output in some cases.
606 bool const skipped_spaces = p.skip_spaces(true);
607 bool const skipped_braces = skip_braces(p);
608 if (keepws && skipped_spaces && !skipped_braces)
609 // put back the space (it is better handled by check_space)
610 p.unskip_spaces(true);
614 void output_command_layout(ostream & os, Parser & p, bool outer,
615 Context & parent_context,
616 Layout const * newlayout)
618 TeXFont const oldFont = parent_context.font;
619 // save the current font size
620 string const size = oldFont.size;
621 // reset the font size to default, because the font size switches
622 // don't affect section headings and the like
623 parent_context.font.size = Context::normalfont.size;
624 // we only need to write the font change if we have an open layout
625 if (!parent_context.atParagraphStart())
626 output_font_change(os, oldFont, parent_context.font);
627 parent_context.check_end_layout(os);
628 Context context(true, parent_context.textclass, newlayout,
629 parent_context.layout, parent_context.font);
630 if (parent_context.deeper_paragraph) {
631 // We are beginning a nested environment after a
632 // deeper paragraph inside the outer list environment.
633 // Therefore we don't need to output a "begin deeper".
634 context.need_end_deeper = true;
636 context.check_deeper(os);
637 context.check_layout(os);
638 // FIXME: Adjust to format 446!
639 // Since format 446, layouts do not require anymore all optional
640 // arguments before the required ones. Needs to be implemented!
642 while (optargs < context.layout->optArgs()) {
643 eat_whitespace(p, os, context, false);
644 if (p.next_token().cat() == catEscape ||
645 p.next_token().character() != '[')
647 p.get_token(); // eat '['
648 // FIXME: Just a workaround. InsetArgument::updateBuffer
649 // will compute a proper ID for all "999" Arguments
650 // (which is also what lyx2lyx produces).
651 // However, tex2lyx should be able to output proper IDs
653 begin_inset(os, "Argument 999\n");
654 os << "status collapsed\n\n";
655 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
657 eat_whitespace(p, os, context, false);
661 while (reqargs < context.layout->requiredArgs()) {
662 eat_whitespace(p, os, context, false);
663 if (p.next_token().cat() != catBegin)
665 p.get_token(); // eat '{'
666 // FIXME: Just a workaround. InsetArgument::updateBuffer
667 // will compute a proper ID for all "999" Arguments
668 // (which is also what lyx2lyx produces).
669 // However, tex2lyx should be able to output proper IDs
671 begin_inset(os, "Argument 999\n");
672 os << "status collapsed\n\n";
673 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
675 eat_whitespace(p, os, context, false);
678 parse_text(p, os, FLAG_ITEM, outer, context);
679 context.check_end_layout(os);
680 if (parent_context.deeper_paragraph) {
681 // We must suppress the "end deeper" because we
682 // suppressed the "begin deeper" above.
683 context.need_end_deeper = false;
685 context.check_end_deeper(os);
686 // We don't need really a new paragraph, but
687 // we must make sure that the next item gets a \begin_layout.
688 parent_context.new_paragraph(os);
689 // Set the font size to the original value. No need to output it here
690 // (Context::begin_layout() will do that if needed)
691 parent_context.font.size = size;
696 * Output a space if necessary.
697 * This function gets called for every whitespace token.
699 * We have three cases here:
700 * 1. A space must be suppressed. Example: The lyxcode case below
701 * 2. A space may be suppressed. Example: Spaces before "\par"
702 * 3. A space must not be suppressed. Example: A space between two words
704 * We currently handle only 1. and 3 and from 2. only the case of
705 * spaces before newlines as a side effect.
707 * 2. could be used to suppress as many spaces as possible. This has two effects:
708 * - Reimporting LyX generated LaTeX files changes almost no whitespace
709 * - Superflous whitespace from non LyX generated LaTeX files is removed.
710 * The drawback is that the logic inside the function becomes
711 * complicated, and that is the reason why it is not implemented.
713 void check_space(Parser & p, ostream & os, Context & context)
715 Token const next = p.next_token();
716 Token const curr = p.curr_token();
717 // A space before a single newline and vice versa must be ignored
718 // LyX emits a newline before \end{lyxcode}.
719 // This newline must be ignored,
720 // otherwise LyX will add an additional protected space.
721 if (next.cat() == catSpace ||
722 next.cat() == catNewline ||
723 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
726 context.check_layout(os);
732 * Parse all arguments of \p command
734 void parse_arguments(string const & command,
735 vector<ArgumentType> const & template_arguments,
736 Parser & p, ostream & os, bool outer, Context & context)
738 string ert = command;
739 size_t no_arguments = template_arguments.size();
740 for (size_t i = 0; i < no_arguments; ++i) {
741 switch (template_arguments[i]) {
744 // This argument contains regular LaTeX
745 output_ert_inset(os, ert + '{', context);
746 eat_whitespace(p, os, context, false);
747 if (template_arguments[i] == required)
748 parse_text(p, os, FLAG_ITEM, outer, context);
750 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
754 // This argument consists only of a single item.
755 // The presence of '{' or not must be preserved.
757 if (p.next_token().cat() == catBegin)
758 ert += '{' + p.verbatim_item() + '}';
760 ert += p.verbatim_item();
764 // This argument may contain special characters
765 ert += '{' + p.verbatim_item() + '}';
769 // true because we must not eat whitespace
770 // if an optional arg follows we must not strip the
771 // brackets from this one
772 if (i < no_arguments - 1 &&
773 template_arguments[i+1] == optional)
774 ert += p.getFullOpt(true);
776 ert += p.getOpt(true);
780 output_ert_inset(os, ert, context);
785 * Check whether \p command is a known command. If yes,
786 * handle the command with all arguments.
787 * \return true if the command was parsed, false otherwise.
789 bool parse_command(string const & command, Parser & p, ostream & os,
790 bool outer, Context & context)
792 if (known_commands.find(command) != known_commands.end()) {
793 parse_arguments(command, known_commands[command], p, os,
801 /// Parses a minipage or parbox
802 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
803 unsigned inner_flags, bool outer, Context & parent_context,
804 string const & outer_type, string const & special,
805 string const & inner_type)
809 string hor_pos = "c";
810 // We need to set the height to the LaTeX default of 1\\totalheight
811 // for the case when no height argument is given
812 string height_value = "1";
813 string height_unit = "in";
814 string height_special = "totalheight";
819 string width_special = "none";
820 if (!inner_type.empty() && p.hasOpt()) {
821 if (inner_type != "makebox")
822 position = p.getArg('[', ']');
824 latex_width = p.getArg('[', ']');
825 translate_box_len(latex_width, width_value, width_unit, width_special);
828 if (position != "t" && position != "c" && position != "b") {
829 cerr << "invalid position " << position << " for "
830 << inner_type << endl;
834 if (inner_type != "makebox") {
835 latex_height = p.getArg('[', ']');
836 translate_box_len(latex_height, height_value, height_unit, height_special);
838 string const opt = p.getArg('[', ']');
841 if (hor_pos != "l" && hor_pos != "c" &&
842 hor_pos != "r" && hor_pos != "s") {
843 cerr << "invalid hor_pos " << hor_pos
844 << " for " << inner_type << endl;
851 inner_pos = p.getArg('[', ']');
852 if (inner_pos != "c" && inner_pos != "t" &&
853 inner_pos != "b" && inner_pos != "s") {
854 cerr << "invalid inner_pos "
855 << inner_pos << " for "
856 << inner_type << endl;
857 inner_pos = position;
862 if (inner_type.empty()) {
863 if (special.empty() && outer_type != "framebox")
864 latex_width = "1\\columnwidth";
867 latex_width = p2.getArg('[', ']');
868 string const opt = p2.getArg('[', ']');
871 if (hor_pos != "l" && hor_pos != "c" &&
872 hor_pos != "r" && hor_pos != "s") {
873 cerr << "invalid hor_pos " << hor_pos
874 << " for " << outer_type << endl;
879 } else if (inner_type != "makebox")
880 latex_width = p.verbatim_item();
881 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
882 // as this is LyX's standard for such cases (except for makebox)
883 // \framebox is more special and handled below
884 if (latex_width.empty() && inner_type != "makebox"
885 && outer_type != "framebox")
886 latex_width = "1\\columnwidth";
888 translate_len(latex_width, width_value, width_unit);
890 bool shadedparbox = false;
891 if (inner_type == "shaded") {
892 eat_whitespace(p, os, parent_context, false);
893 if (outer_type == "parbox") {
895 if (p.next_token().cat() == catBegin)
897 eat_whitespace(p, os, parent_context, false);
903 // If we already read the inner box we have to push the inner env
904 if (!outer_type.empty() && !inner_type.empty() &&
905 (inner_flags & FLAG_END))
906 active_environments.push_back(inner_type);
907 // LyX can't handle length variables
908 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
909 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
910 // Look whether there is some content after the end of the
911 // inner box, but before the end of the outer box.
912 // If yes, we need to output ERT.
914 if (inner_flags & FLAG_END)
915 p.ertEnvironment(inner_type);
919 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
920 if ((outer_env && p.next_token().asInput() != "\\end") ||
921 (!outer_env && p.next_token().cat() != catEnd)) {
922 // something is between the end of the inner box and
923 // the end of the outer box, so we need to use ERT.
928 // if only \makebox{content} was used we can set its width to 1\width
929 // because this identic and also identic to \mbox
930 // this doesn't work for \framebox{content}, thus we have to use ERT for this
931 if (latex_width.empty() && inner_type == "makebox") {
934 width_special = "width";
935 } else if (latex_width.empty() && outer_type == "framebox") {
940 if (!outer_type.empty()) {
941 if (outer_flags & FLAG_END)
942 ss << "\\begin{" << outer_type << '}';
944 ss << '\\' << outer_type << '{';
945 if (!special.empty())
949 if (!inner_type.empty()) {
950 if (inner_type != "shaded") {
951 if (inner_flags & FLAG_END)
952 ss << "\\begin{" << inner_type << '}';
954 ss << '\\' << inner_type;
956 if (!position.empty())
957 ss << '[' << position << ']';
958 if (!latex_height.empty())
959 ss << '[' << latex_height << ']';
960 if (!inner_pos.empty())
961 ss << '[' << inner_pos << ']';
962 ss << '{' << latex_width << '}';
963 if (!(inner_flags & FLAG_END))
966 if (inner_type == "shaded")
967 ss << "\\begin{shaded}";
968 output_ert_inset(os, ss.str(), parent_context);
969 if (!inner_type.empty()) {
970 parse_text(p, os, inner_flags, outer, parent_context);
971 if (inner_flags & FLAG_END)
972 output_ert_inset(os, "\\end{" + inner_type + '}',
975 output_ert_inset(os, "}", parent_context);
977 if (!outer_type.empty()) {
978 // If we already read the inner box we have to pop
980 if (!inner_type.empty() && (inner_flags & FLAG_END))
981 active_environments.pop_back();
983 // Ensure that the end of the outer box is parsed correctly:
984 // The opening brace has been eaten by parse_outer_box()
985 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
986 outer_flags &= ~FLAG_ITEM;
987 outer_flags |= FLAG_BRACE_LAST;
989 parse_text(p, os, outer_flags, outer, parent_context);
990 if (outer_flags & FLAG_END)
991 output_ert_inset(os, "\\end{" + outer_type + '}',
993 else if (inner_type.empty() && outer_type == "framebox")
994 // in this case it is already closed later
997 output_ert_inset(os, "}", parent_context);
1000 // LyX does not like empty positions, so we have
1001 // to set them to the LaTeX default values here.
1002 if (position.empty())
1004 if (inner_pos.empty())
1005 inner_pos = position;
1006 parent_context.check_layout(os);
1007 begin_inset(os, "Box ");
1008 if (outer_type == "framed")
1010 else if (outer_type == "framebox")
1012 else if (outer_type == "shadowbox")
1013 os << "Shadowbox\n";
1014 else if ((outer_type == "shaded" && inner_type.empty()) ||
1015 (outer_type == "minipage" && inner_type == "shaded") ||
1016 (outer_type == "parbox" && inner_type == "shaded")) {
1018 preamble.registerAutomaticallyLoadedPackage("color");
1019 } else if (outer_type == "doublebox")
1020 os << "Doublebox\n";
1021 else if (outer_type.empty())
1022 os << "Frameless\n";
1024 os << outer_type << '\n';
1025 os << "position \"" << position << "\"\n";
1026 os << "hor_pos \"" << hor_pos << "\"\n";
1027 os << "has_inner_box " << !inner_type.empty() << "\n";
1028 os << "inner_pos \"" << inner_pos << "\"\n";
1029 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1031 os << "use_makebox " << (inner_type == "makebox") << '\n';
1032 os << "width \"" << width_value << width_unit << "\"\n";
1033 os << "special \"" << width_special << "\"\n";
1034 os << "height \"" << height_value << height_unit << "\"\n";
1035 os << "height_special \"" << height_special << "\"\n";
1036 os << "status open\n\n";
1038 // Unfortunately we can't use parse_text_in_inset:
1039 // InsetBox::forcePlainLayout() is hard coded and does not
1040 // use the inset layout. Apart from that do we call parse_text
1041 // up to two times, but need only one check_end_layout.
1042 bool const forcePlainLayout =
1043 (!inner_type.empty() || inner_type == "makebox") &&
1044 outer_type != "shaded" && outer_type != "framed";
1045 Context context(true, parent_context.textclass);
1046 if (forcePlainLayout)
1047 context.layout = &context.textclass.plainLayout();
1049 context.font = parent_context.font;
1051 // If we have no inner box the contents will be read with the outer box
1052 if (!inner_type.empty())
1053 parse_text(p, os, inner_flags, outer, context);
1055 // Ensure that the end of the outer box is parsed correctly:
1056 // The opening brace has been eaten by parse_outer_box()
1057 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1058 outer_flags &= ~FLAG_ITEM;
1059 outer_flags |= FLAG_BRACE_LAST;
1062 // Find end of outer box, output contents if inner_type is
1063 // empty and output possible comments
1064 if (!outer_type.empty()) {
1065 // If we already read the inner box we have to pop
1067 if (!inner_type.empty() && (inner_flags & FLAG_END))
1068 active_environments.pop_back();
1069 // This does not output anything but comments if
1070 // inner_type is not empty (see use_ert)
1071 parse_text(p, os, outer_flags, outer, context);
1074 context.check_end_layout(os);
1076 #ifdef PRESERVE_LAYOUT
1077 // LyX puts a % after the end of the minipage
1078 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1080 //output_ert_inset(os, "%dummy", parent_context);
1083 parent_context.new_paragraph(os);
1085 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1086 //output_ert_inset(os, "%dummy", parent_context);
1089 // We add a protected space if something real follows
1090 if (p.good() && p.next_token().cat() != catComment) {
1091 begin_inset(os, "space ~\n");
1100 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1101 Context & parent_context, string const & outer_type,
1102 string const & special)
1104 eat_whitespace(p, os, parent_context, false);
1105 if (flags & FLAG_ITEM) {
1107 if (p.next_token().cat() == catBegin)
1110 cerr << "Warning: Ignoring missing '{' after \\"
1111 << outer_type << '.' << endl;
1112 eat_whitespace(p, os, parent_context, false);
1115 unsigned int inner_flags = 0;
1117 if (outer_type == "minipage" || outer_type == "parbox") {
1118 p.skip_spaces(true);
1119 while (p.hasOpt()) {
1121 p.skip_spaces(true);
1124 p.skip_spaces(true);
1125 if (outer_type == "parbox") {
1127 if (p.next_token().cat() == catBegin)
1129 p.skip_spaces(true);
1132 if (outer_type == "shaded") {
1133 // These boxes never have an inner box
1135 } else if (p.next_token().asInput() == "\\parbox") {
1136 inner = p.get_token().cs();
1137 inner_flags = FLAG_ITEM;
1138 } else if (p.next_token().asInput() == "\\begin") {
1139 // Is this a minipage or shaded box?
1142 inner = p.getArg('{', '}');
1144 if (inner == "minipage" || inner == "shaded")
1145 inner_flags = FLAG_END;
1150 if (inner_flags == FLAG_END) {
1151 if (inner != "shaded")
1155 eat_whitespace(p, os, parent_context, false);
1157 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1158 outer_type, special, inner);
1160 if (inner_flags == FLAG_ITEM) {
1162 eat_whitespace(p, os, parent_context, false);
1164 parse_box(p, os, flags, inner_flags, outer, parent_context,
1165 outer_type, special, inner);
1170 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1172 parent_context.check_layout(os);
1173 begin_inset(os, "listings\n");
1175 string arg = p.verbatimOption();
1176 os << "lstparams " << '"' << arg << '"' << '\n';
1177 if (arg.find("\\color") != string::npos)
1178 preamble.registerAutomaticallyLoadedPackage("color");
1181 os << "inline true\n";
1183 os << "inline false\n";
1184 os << "status collapsed\n";
1185 Context context(true, parent_context.textclass);
1186 context.layout = &parent_context.textclass.plainLayout();
1189 // set catcodes to verbatim early, just in case.
1190 p.setCatcodes(VERBATIM_CATCODES);
1191 string delim = p.get_token().asInput();
1192 s = p.verbatimStuff(delim);
1193 // context.new_paragraph(os);
1195 s = p.verbatimEnvironment("lstlisting");
1196 output_ert(os, s, context);
1201 /// parse an unknown environment
1202 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1203 unsigned flags, bool outer,
1204 Context & parent_context)
1206 if (name == "tabbing")
1207 // We need to remember that we have to handle '\=' specially
1208 flags |= FLAG_TABBING;
1210 // We need to translate font changes and paragraphs inside the
1211 // environment to ERT if we have a non standard font.
1212 // Otherwise things like
1213 // \large\begin{foo}\huge bar\end{foo}
1215 bool const specialfont =
1216 (parent_context.font != parent_context.normalfont);
1217 bool const new_layout_allowed = parent_context.new_layout_allowed;
1219 parent_context.new_layout_allowed = false;
1220 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1221 parse_text_snippet(p, os, flags, outer, parent_context);
1222 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1224 parent_context.new_layout_allowed = new_layout_allowed;
1228 void parse_environment(Parser & p, ostream & os, bool outer,
1229 string & last_env, Context & parent_context)
1231 Layout const * newlayout;
1232 InsetLayout const * newinsetlayout = 0;
1233 string const name = p.getArg('{', '}');
1234 const bool is_starred = suffixIs(name, '*');
1235 string const unstarred_name = rtrim(name, "*");
1236 active_environments.push_back(name);
1238 if (is_math_env(name)) {
1239 parent_context.check_layout(os);
1240 begin_inset(os, "Formula ");
1241 os << "\\begin{" << name << "}";
1242 parse_math(p, os, FLAG_END, MATH_MODE);
1243 os << "\\end{" << name << "}";
1245 if (is_display_math_env(name)) {
1246 // Prevent the conversion of a line break to a space
1247 // (bug 7668). This does not change the output, but
1248 // looks ugly in LyX.
1249 eat_whitespace(p, os, parent_context, false);
1253 else if (is_known(name, preamble.polyglossia_languages)) {
1254 // We must begin a new paragraph if not already done
1255 if (! parent_context.atParagraphStart()) {
1256 parent_context.check_end_layout(os);
1257 parent_context.new_paragraph(os);
1259 // save the language in the context so that it is
1260 // handled by parse_text
1261 parent_context.font.language = preamble.polyglossia2lyx(name);
1262 parse_text(p, os, FLAG_END, outer, parent_context);
1263 // Just in case the environment is empty
1264 parent_context.extra_stuff.erase();
1265 // We must begin a new paragraph to reset the language
1266 parent_context.new_paragraph(os);
1270 else if (unstarred_name == "tabular" || name == "longtable") {
1271 eat_whitespace(p, os, parent_context, false);
1272 string width = "0pt";
1273 if (name == "tabular*") {
1274 width = lyx::translate_len(p.getArg('{', '}'));
1275 eat_whitespace(p, os, parent_context, false);
1277 parent_context.check_layout(os);
1278 begin_inset(os, "Tabular ");
1279 handle_tabular(p, os, name, width, parent_context);
1284 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1285 eat_whitespace(p, os, parent_context, false);
1286 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1287 eat_whitespace(p, os, parent_context, false);
1288 parent_context.check_layout(os);
1289 begin_inset(os, "Float " + unstarred_name + "\n");
1290 // store the float type for subfloats
1291 // subfloats only work with figures and tables
1292 if (unstarred_name == "figure")
1293 float_type = unstarred_name;
1294 else if (unstarred_name == "table")
1295 float_type = unstarred_name;
1299 os << "placement " << opt << '\n';
1300 if (contains(opt, "H"))
1301 preamble.registerAutomaticallyLoadedPackage("float");
1303 Floating const & fl = parent_context.textclass.floats()
1304 .getType(unstarred_name);
1305 if (!fl.floattype().empty() && fl.usesFloatPkg())
1306 preamble.registerAutomaticallyLoadedPackage("float");
1309 os << "wide " << convert<string>(is_starred)
1310 << "\nsideways false"
1311 << "\nstatus open\n\n";
1312 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1314 // We don't need really a new paragraph, but
1315 // we must make sure that the next item gets a \begin_layout.
1316 parent_context.new_paragraph(os);
1318 // the float is parsed thus delete the type
1322 else if (unstarred_name == "sidewaysfigure"
1323 || unstarred_name == "sidewaystable") {
1324 eat_whitespace(p, os, parent_context, false);
1325 parent_context.check_layout(os);
1326 if (unstarred_name == "sidewaysfigure")
1327 begin_inset(os, "Float figure\n");
1329 begin_inset(os, "Float table\n");
1330 os << "wide " << convert<string>(is_starred)
1331 << "\nsideways true"
1332 << "\nstatus open\n\n";
1333 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1335 // We don't need really a new paragraph, but
1336 // we must make sure that the next item gets a \begin_layout.
1337 parent_context.new_paragraph(os);
1339 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1342 else if (name == "wrapfigure" || name == "wraptable") {
1343 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1344 eat_whitespace(p, os, parent_context, false);
1345 parent_context.check_layout(os);
1348 string overhang = "0col%";
1351 lines = p.getArg('[', ']');
1352 string const placement = p.getArg('{', '}');
1354 overhang = p.getArg('[', ']');
1355 string const width = p.getArg('{', '}');
1357 if (name == "wrapfigure")
1358 begin_inset(os, "Wrap figure\n");
1360 begin_inset(os, "Wrap table\n");
1361 os << "lines " << lines
1362 << "\nplacement " << placement
1363 << "\noverhang " << lyx::translate_len(overhang)
1364 << "\nwidth " << lyx::translate_len(width)
1365 << "\nstatus open\n\n";
1366 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1368 // We don't need really a new paragraph, but
1369 // we must make sure that the next item gets a \begin_layout.
1370 parent_context.new_paragraph(os);
1372 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1375 else if (name == "minipage") {
1376 eat_whitespace(p, os, parent_context, false);
1377 // Test whether this is an outer box of a shaded box
1379 // swallow arguments
1380 while (p.hasOpt()) {
1382 p.skip_spaces(true);
1385 p.skip_spaces(true);
1386 Token t = p.get_token();
1387 bool shaded = false;
1388 if (t.asInput() == "\\begin") {
1389 p.skip_spaces(true);
1390 if (p.getArg('{', '}') == "shaded")
1395 parse_outer_box(p, os, FLAG_END, outer,
1396 parent_context, name, "shaded");
1398 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1403 else if (name == "comment") {
1404 eat_whitespace(p, os, parent_context, false);
1405 parent_context.check_layout(os);
1406 begin_inset(os, "Note Comment\n");
1407 os << "status open\n";
1408 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1411 skip_braces(p); // eat {} that might by set by LyX behind comments
1412 preamble.registerAutomaticallyLoadedPackage("verbatim");
1415 else if (name == "verbatim") {
1416 // FIXME: this should go in the generic code that
1417 // handles environments defined in layout file that
1418 // have "PassThru 1". However, the code over there is
1419 // already too complicated for my taste.
1420 parent_context.new_paragraph(os);
1421 Context context(true, parent_context.textclass,
1422 &parent_context.textclass[from_ascii("Verbatim")]);
1423 string s = p.verbatimEnvironment("verbatim");
1424 output_ert(os, s, context);
1428 else if (name == "IPA") {
1429 eat_whitespace(p, os, parent_context, false);
1430 parent_context.check_layout(os);
1431 begin_inset(os, "IPA\n");
1432 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1435 preamble.registerAutomaticallyLoadedPackage("tipa");
1436 preamble.registerAutomaticallyLoadedPackage("tipx");
1439 else if (name == "CJK") {
1440 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1441 // It is impossible to decide if a CJK environment was in its own paragraph or within
1442 // a line. We therefore always assume a paragraph since the latter is a rare case.
1443 eat_whitespace(p, os, parent_context, false);
1444 parent_context.check_end_layout(os);
1445 // store the encoding to be able to reset it
1446 string const encoding_old = p.getEncoding();
1447 string const encoding = p.getArg('{', '}');
1448 // FIXME: For some reason JIS does not work. Although the text
1449 // in tests/CJK.tex is identical with the SJIS version if you
1450 // convert both snippets using the recode command line utility,
1451 // the resulting .lyx file contains some extra characters if
1452 // you set buggy_encoding to false for JIS.
1453 bool const buggy_encoding = encoding == "JIS";
1454 if (!buggy_encoding)
1455 p.setEncoding(encoding, Encoding::CJK);
1457 // FIXME: This will read garbage, since the data is not encoded in utf8.
1458 p.setEncoding("UTF-8");
1460 // LyX only supports the same mapping for all CJK
1461 // environments, so we might need to output everything as ERT
1462 string const mapping = trim(p.getArg('{', '}'));
1463 char const * const * const where =
1464 is_known(encoding, supported_CJK_encodings);
1465 if (!buggy_encoding && !preamble.fontCJKSet())
1466 preamble.fontCJK(mapping);
1467 bool knownMapping = mapping == preamble.fontCJK();
1468 if (buggy_encoding || !knownMapping || !where) {
1469 parent_context.check_layout(os);
1470 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1472 // we must parse the content as verbatim because e.g. JIS can contain
1473 // normally invalid characters
1474 // FIXME: This works only for the most simple cases.
1475 // Since TeX control characters are not parsed,
1476 // things like comments are completely wrong.
1477 string const s = p.plainEnvironment("CJK");
1478 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1480 output_ert_inset(os, "\\", parent_context);
1481 else if (*it == '$')
1482 output_ert_inset(os, "$", parent_context);
1486 output_ert_inset(os, "\\end{" + name + "}",
1490 supported_CJK_languages[where - supported_CJK_encodings];
1491 // store the language because we must reset it at the end
1492 string const lang_old = parent_context.font.language;
1493 parent_context.font.language = lang;
1494 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1495 parent_context.font.language = lang_old;
1496 parent_context.new_paragraph(os);
1498 p.setEncoding(encoding_old);
1502 else if (name == "lyxgreyedout") {
1503 eat_whitespace(p, os, parent_context, false);
1504 parent_context.check_layout(os);
1505 begin_inset(os, "Note Greyedout\n");
1506 os << "status open\n";
1507 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1510 if (!preamble.notefontcolor().empty())
1511 preamble.registerAutomaticallyLoadedPackage("color");
1514 else if (name == "framed" || name == "shaded") {
1515 eat_whitespace(p, os, parent_context, false);
1516 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1520 else if (name == "lstlisting") {
1521 eat_whitespace(p, os, parent_context, false);
1522 parse_listings(p, os, parent_context, false);
1526 else if (!parent_context.new_layout_allowed)
1527 parse_unknown_environment(p, name, os, FLAG_END, outer,
1530 // Alignment and spacing settings
1531 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1532 // therefore are totally broken!
1533 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1534 // they are commands not environments. They are furthermore switches that
1535 // can be ended by another switches, but also by commands like \footnote or
1536 // \parbox. So the only safe way is to leave them untouched.
1537 else if (name == "center" || name == "centering" ||
1538 name == "flushleft" || name == "flushright" ||
1539 name == "singlespace" || name == "onehalfspace" ||
1540 name == "doublespace" || name == "spacing") {
1541 eat_whitespace(p, os, parent_context, false);
1542 // We must begin a new paragraph if not already done
1543 if (! parent_context.atParagraphStart()) {
1544 parent_context.check_end_layout(os);
1545 parent_context.new_paragraph(os);
1547 if (name == "flushleft")
1548 parent_context.add_extra_stuff("\\align left\n");
1549 else if (name == "flushright")
1550 parent_context.add_extra_stuff("\\align right\n");
1551 else if (name == "center" || name == "centering")
1552 parent_context.add_extra_stuff("\\align center\n");
1553 else if (name == "singlespace")
1554 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1555 else if (name == "onehalfspace") {
1556 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1557 preamble.registerAutomaticallyLoadedPackage("setspace");
1558 } else if (name == "doublespace") {
1559 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1560 preamble.registerAutomaticallyLoadedPackage("setspace");
1561 } else if (name == "spacing") {
1562 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1563 preamble.registerAutomaticallyLoadedPackage("setspace");
1565 parse_text(p, os, FLAG_END, outer, parent_context);
1566 // Just in case the environment is empty
1567 parent_context.extra_stuff.erase();
1568 // We must begin a new paragraph to reset the alignment
1569 parent_context.new_paragraph(os);
1573 // The single '=' is meant here.
1574 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1575 eat_whitespace(p, os, parent_context, false);
1576 Context context(true, parent_context.textclass, newlayout,
1577 parent_context.layout, parent_context.font);
1578 if (parent_context.deeper_paragraph) {
1579 // We are beginning a nested environment after a
1580 // deeper paragraph inside the outer list environment.
1581 // Therefore we don't need to output a "begin deeper".
1582 context.need_end_deeper = true;
1584 parent_context.check_end_layout(os);
1585 if (last_env == name) {
1586 // we need to output a separator since LyX would export
1587 // the two environments as one otherwise (bug 5716)
1588 docstring const sep = from_ascii("--Separator--");
1589 TeX2LyXDocClass const & textclass(parent_context.textclass);
1590 if (textclass.hasLayout(sep)) {
1591 Context newcontext(parent_context);
1592 newcontext.layout = &(textclass[sep]);
1593 newcontext.check_layout(os);
1594 newcontext.check_end_layout(os);
1596 parent_context.check_layout(os);
1597 begin_inset(os, "Note Note\n");
1598 os << "status closed\n";
1599 Context newcontext(true, textclass,
1600 &(textclass.defaultLayout()));
1601 newcontext.check_layout(os);
1602 newcontext.check_end_layout(os);
1604 parent_context.check_end_layout(os);
1607 switch (context.layout->latextype) {
1608 case LATEX_LIST_ENVIRONMENT:
1609 context.add_par_extra_stuff("\\labelwidthstring "
1610 + p.verbatim_item() + '\n');
1613 case LATEX_BIB_ENVIRONMENT:
1614 p.verbatim_item(); // swallow next arg
1620 context.check_deeper(os);
1621 // handle known optional and required arguments
1622 // FIXME: Since format 446, layouts do not require anymore all optional
1623 // arguments before the required ones. Needs to be implemented!
1624 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1625 // It is impossible to place anything after the environment name,
1626 // but before the first \\item.
1627 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1628 bool need_layout = true;
1630 while (optargs < context.layout->optArgs()) {
1631 eat_whitespace(p, os, context, false);
1632 if (p.next_token().cat() == catEscape ||
1633 p.next_token().character() != '[')
1635 p.get_token(); // eat '['
1637 context.check_layout(os);
1638 need_layout = false;
1640 // FIXME: Just a workaround. InsetArgument::updateBuffer
1641 // will compute a proper ID for all "999" Arguments
1642 // (which is also what lyx2lyx produces).
1643 // However, tex2lyx should be able to output proper IDs
1645 begin_inset(os, "Argument 999\n");
1646 os << "status collapsed\n\n";
1647 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1649 eat_whitespace(p, os, context, false);
1653 while (reqargs < context.layout->requiredArgs()) {
1654 eat_whitespace(p, os, context, false);
1655 if (p.next_token().cat() != catBegin)
1657 p.get_token(); // eat '{'
1659 context.check_layout(os);
1660 need_layout = false;
1662 // FIXME: Just a workaround. InsetArgument::updateBuffer
1663 // will compute a proper ID for all "999" Arguments
1664 // (which is also what lyx2lyx produces).
1665 // However, tex2lyx should be able to output proper IDs
1667 begin_inset(os, "Argument 999\n");
1668 os << "status collapsed\n\n";
1669 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1671 eat_whitespace(p, os, context, false);
1675 parse_text(p, os, FLAG_END, outer, context);
1676 context.check_end_layout(os);
1677 if (parent_context.deeper_paragraph) {
1678 // We must suppress the "end deeper" because we
1679 // suppressed the "begin deeper" above.
1680 context.need_end_deeper = false;
1682 context.check_end_deeper(os);
1683 parent_context.new_paragraph(os);
1685 if (!preamble.titleLayoutFound())
1686 preamble.titleLayoutFound(newlayout->intitle);
1687 set<string> const & req = newlayout->requires();
1688 set<string>::const_iterator it = req.begin();
1689 set<string>::const_iterator en = req.end();
1690 for (; it != en; ++it)
1691 preamble.registerAutomaticallyLoadedPackage(*it);
1694 // The single '=' is meant here.
1695 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1696 eat_whitespace(p, os, parent_context, false);
1697 parent_context.check_layout(os);
1698 begin_inset(os, "Flex ");
1699 os << to_utf8(newinsetlayout->name()) << '\n'
1700 << "status collapsed\n";
1701 if (newinsetlayout->isPassThru()) {
1702 string const arg = p.verbatimEnvironment(name);
1703 Context context(true, parent_context.textclass,
1704 &parent_context.textclass.plainLayout(),
1705 parent_context.layout);
1706 output_ert(os, arg, parent_context);
1708 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1712 else if (name == "appendix") {
1713 // This is no good latex style, but it works and is used in some documents...
1714 eat_whitespace(p, os, parent_context, false);
1715 parent_context.check_end_layout(os);
1716 Context context(true, parent_context.textclass, parent_context.layout,
1717 parent_context.layout, parent_context.font);
1718 context.check_layout(os);
1719 os << "\\start_of_appendix\n";
1720 parse_text(p, os, FLAG_END, outer, context);
1721 context.check_end_layout(os);
1725 else if (known_environments.find(name) != known_environments.end()) {
1726 vector<ArgumentType> arguments = known_environments[name];
1727 // The last "argument" denotes wether we may translate the
1728 // environment contents to LyX
1729 // The default required if no argument is given makes us
1730 // compatible with the reLyXre environment.
1731 ArgumentType contents = arguments.empty() ?
1734 if (!arguments.empty())
1735 arguments.pop_back();
1736 // See comment in parse_unknown_environment()
1737 bool const specialfont =
1738 (parent_context.font != parent_context.normalfont);
1739 bool const new_layout_allowed =
1740 parent_context.new_layout_allowed;
1742 parent_context.new_layout_allowed = false;
1743 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1744 outer, parent_context);
1745 if (contents == verbatim)
1746 output_ert_inset(os, p.ertEnvironment(name),
1749 parse_text_snippet(p, os, FLAG_END, outer,
1751 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1753 parent_context.new_layout_allowed = new_layout_allowed;
1757 parse_unknown_environment(p, name, os, FLAG_END, outer,
1761 active_environments.pop_back();
1765 /// parses a comment and outputs it to \p os.
1766 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1768 LASSERT(t.cat() == catComment, return);
1769 if (!t.cs().empty()) {
1770 context.check_layout(os);
1771 output_ert_inset(os, '%' + t.cs(), context);
1772 if (p.next_token().cat() == catNewline) {
1773 // A newline after a comment line starts a new
1775 if (context.new_layout_allowed) {
1776 if(!context.atParagraphStart())
1777 // Only start a new paragraph if not already
1778 // done (we might get called recursively)
1779 context.new_paragraph(os);
1781 output_ert_inset(os, "\n", context);
1782 eat_whitespace(p, os, context, true);
1785 // "%\n" combination
1792 * Reads spaces and comments until the first non-space, non-comment token.
1793 * New paragraphs (double newlines or \\par) are handled like simple spaces
1794 * if \p eatParagraph is true.
1795 * Spaces are skipped, but comments are written to \p os.
1797 void eat_whitespace(Parser & p, ostream & os, Context & context,
1801 Token const & t = p.get_token();
1802 if (t.cat() == catComment)
1803 parse_comment(p, os, t, context);
1804 else if ((! eatParagraph && p.isParagraph()) ||
1805 (t.cat() != catSpace && t.cat() != catNewline)) {
1814 * Set a font attribute, parse text and reset the font attribute.
1815 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1816 * \param currentvalue Current value of the attribute. Is set to the new
1817 * value during parsing.
1818 * \param newvalue New value of the attribute
1820 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1821 Context & context, string const & attribute,
1822 string & currentvalue, string const & newvalue)
1824 context.check_layout(os);
1825 string const oldvalue = currentvalue;
1826 currentvalue = newvalue;
1827 os << '\n' << attribute << ' ' << newvalue << "\n";
1828 parse_text_snippet(p, os, flags, outer, context);
1829 context.check_layout(os);
1830 os << '\n' << attribute << ' ' << oldvalue << "\n";
1831 currentvalue = oldvalue;
1835 /// get the arguments of a natbib or jurabib citation command
1836 void get_cite_arguments(Parser & p, bool natbibOrder,
1837 string & before, string & after)
1839 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1841 // text before the citation
1843 // text after the citation
1844 after = p.getFullOpt();
1846 if (!after.empty()) {
1847 before = p.getFullOpt();
1848 if (natbibOrder && !before.empty())
1849 swap(before, after);
1854 /// Convert filenames with TeX macros and/or quotes to something LyX
1856 string const normalize_filename(string const & name)
1861 Token const & t = p.get_token();
1862 if (t.cat() != catEscape)
1864 else if (t.cs() == "lyxdot") {
1865 // This is used by LyX for simple dots in relative
1869 } else if (t.cs() == "space") {
1872 } else if (t.cs() == "string") {
1873 // Convert \string" to " and \string~ to ~
1874 Token const & n = p.next_token();
1875 if (n.asInput() != "\"" && n.asInput() != "~")
1880 // Strip quotes. This is a bit complicated (see latex_path()).
1881 string full = os.str();
1882 if (!full.empty() && full[0] == '"') {
1883 string base = removeExtension(full);
1884 string ext = getExtension(full);
1885 if (!base.empty() && base[base.length()-1] == '"')
1888 return addExtension(trim(base, "\""), ext);
1889 if (full[full.length()-1] == '"')
1892 return trim(full, "\"");
1898 /// Convert \p name from TeX convention (relative to master file) to LyX
1899 /// convention (relative to .lyx file) if it is relative
1900 void fix_child_filename(string & name)
1902 string const absMasterTeX = getMasterFilePath(true);
1903 bool const isabs = FileName::isAbsolute(name);
1904 // convert from "relative to .tex master" to absolute original path
1906 name = makeAbsPath(name, absMasterTeX).absFileName();
1907 bool copyfile = copyFiles();
1908 string const absParentLyX = getParentFilePath(false);
1911 // convert from absolute original path to "relative to master file"
1912 string const rel = to_utf8(makeRelPath(from_utf8(name),
1913 from_utf8(absMasterTeX)));
1914 // re-interpret "relative to .tex file" as "relative to .lyx file"
1915 // (is different if the master .lyx file resides in a
1916 // different path than the master .tex file)
1917 string const absMasterLyX = getMasterFilePath(false);
1918 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1919 // Do not copy if the new path is impossible to create. Example:
1920 // absMasterTeX = "/foo/bar/"
1921 // absMasterLyX = "/bar/"
1922 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1923 if (contains(name, "/../"))
1930 // convert from absolute original path to
1931 // "relative to .lyx file"
1932 name = to_utf8(makeRelPath(from_utf8(abs),
1933 from_utf8(absParentLyX)));
1937 // convert from absolute original path to "relative to .lyx file"
1938 name = to_utf8(makeRelPath(from_utf8(name),
1939 from_utf8(absParentLyX)));
1944 void copy_file(FileName const & src, string dstname)
1948 string const absParent = getParentFilePath(false);
1950 if (FileName::isAbsolute(dstname))
1951 dst = FileName(dstname);
1953 dst = makeAbsPath(dstname, absParent);
1954 string const absMaster = getMasterFilePath(false);
1955 FileName const srcpath = src.onlyPath();
1956 FileName const dstpath = dst.onlyPath();
1957 if (equivalent(srcpath, dstpath))
1959 if (!dstpath.isDirectory()) {
1960 if (!dstpath.createPath()) {
1961 cerr << "Warning: Could not create directory for file `"
1962 << dst.absFileName() << "´." << endl;
1966 if (dst.isReadableFile()) {
1967 if (overwriteFiles())
1968 cerr << "Warning: Overwriting existing file `"
1969 << dst.absFileName() << "´." << endl;
1971 cerr << "Warning: Not overwriting existing file `"
1972 << dst.absFileName() << "´." << endl;
1976 if (!src.copyTo(dst))
1977 cerr << "Warning: Could not copy file `" << src.absFileName()
1978 << "´ to `" << dst.absFileName() << "´." << endl;
1982 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1983 void parse_noweb(Parser & p, ostream & os, Context & context)
1985 // assemble the rest of the keyword
1989 Token const & t = p.get_token();
1990 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1993 chunk = (p.good() && p.next_token().asInput() == "=");
1995 name += p.get_token().asInput();
1998 name += t.asInput();
2001 if (!chunk || !context.new_layout_allowed ||
2002 !context.textclass.hasLayout(from_ascii("Chunk"))) {
2003 cerr << "Warning: Could not interpret '" << name
2004 << "'. Ignoring it." << endl;
2008 // We use new_paragraph instead of check_end_layout because the stuff
2009 // following the noweb chunk needs to start with a \begin_layout.
2010 // This may create a new paragraph even if there was none in the
2011 // noweb file, but the alternative is an invalid LyX file. Since
2012 // noweb code chunks are implemented with a layout style in LyX they
2013 // always must be in an own paragraph.
2014 context.new_paragraph(os);
2015 Context newcontext(true, context.textclass,
2016 &context.textclass[from_ascii("Chunk")]);
2017 newcontext.check_layout(os);
2020 Token const & t = p.get_token();
2021 // We abuse the parser a bit, because this is no TeX syntax
2023 if (t.cat() == catEscape)
2024 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2027 Context tmp(false, context.textclass,
2028 &context.textclass[from_ascii("Chunk")]);
2029 tmp.need_end_layout = true;
2030 tmp.check_layout(oss);
2031 os << subst(t.asInput(), "\n", oss.str());
2033 // The chunk is ended by an @ at the beginning of a line.
2034 // After the @ the line may contain a comment and/or
2035 // whitespace, but nothing else.
2036 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2037 (p.next_token().cat() == catSpace ||
2038 p.next_token().cat() == catNewline ||
2039 p.next_token().cat() == catComment)) {
2040 while (p.good() && p.next_token().cat() == catSpace)
2041 os << p.get_token().asInput();
2042 if (p.next_token().cat() == catComment)
2043 // The comment includes a final '\n'
2044 os << p.get_token().asInput();
2046 if (p.next_token().cat() == catNewline)
2053 newcontext.check_end_layout(os);
2057 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2058 bool is_macro(Parser & p)
2060 Token first = p.curr_token();
2061 if (first.cat() != catEscape || !p.good())
2063 if (first.cs() == "def")
2065 if (first.cs() != "global" && first.cs() != "long")
2067 Token second = p.get_token();
2069 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2070 second.cat() == catNewline || second.cat() == catComment)) {
2071 second = p.get_token();
2074 bool secondvalid = second.cat() == catEscape;
2076 bool thirdvalid = false;
2077 if (p.good() && first.cs() == "global" && secondvalid &&
2078 second.cs() == "long") {
2079 third = p.get_token();
2081 while (p.good() && !p.isParagraph() &&
2082 (third.cat() == catSpace ||
2083 third.cat() == catNewline ||
2084 third.cat() == catComment)) {
2085 third = p.get_token();
2088 thirdvalid = third.cat() == catEscape;
2090 for (int i = 0; i < pos; ++i)
2095 return (first.cs() == "global" || first.cs() == "long") &&
2096 second.cs() == "def";
2097 return first.cs() == "global" && second.cs() == "long" &&
2098 third.cs() == "def";
2102 /// Parse a macro definition (assumes that is_macro() returned true)
2103 void parse_macro(Parser & p, ostream & os, Context & context)
2105 context.check_layout(os);
2106 Token first = p.curr_token();
2109 string command = first.asInput();
2110 if (first.cs() != "def") {
2112 eat_whitespace(p, os, context, false);
2113 second = p.curr_token();
2114 command += second.asInput();
2115 if (second.cs() != "def") {
2117 eat_whitespace(p, os, context, false);
2118 third = p.curr_token();
2119 command += third.asInput();
2122 eat_whitespace(p, os, context, false);
2123 string const name = p.get_token().cs();
2124 eat_whitespace(p, os, context, false);
2130 while (p.next_token().cat() != catBegin) {
2131 if (p.next_token().cat() == catParameter) {
2136 // followed by number?
2137 if (p.next_token().cat() == catOther) {
2138 string s = p.get_token().asInput();
2140 // number = current arity + 1?
2141 if (s.size() == 1 && s[0] == arity + '0' + 1)
2146 paramtext += p.get_token().cs();
2148 paramtext += p.get_token().cs();
2153 // only output simple (i.e. compatible) macro as FormulaMacros
2154 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2156 context.check_layout(os);
2157 begin_inset(os, "FormulaMacro");
2158 os << "\n\\def" << ert;
2161 output_ert_inset(os, command + ert, context);
2165 void registerExternalTemplatePackages(string const & name)
2167 external::TemplateManager const & etm = external::TemplateManager::get();
2168 external::Template const * const et = etm.getTemplateByName(name);
2171 external::Template::Formats::const_iterator cit = et->formats.end();
2173 cit = et->formats.find("PDFLaTeX");
2174 if (cit == et->formats.end())
2175 // If the template has not specified a PDFLaTeX output,
2176 // we try the LaTeX format.
2177 cit = et->formats.find("LaTeX");
2178 if (cit == et->formats.end())
2180 vector<string>::const_iterator qit = cit->second.requirements.begin();
2181 vector<string>::const_iterator qend = cit->second.requirements.end();
2182 for (; qit != qend; ++qit)
2183 preamble.registerAutomaticallyLoadedPackage(*qit);
2186 } // anonymous namespace
2189 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2192 Layout const * newlayout = 0;
2193 InsetLayout const * newinsetlayout = 0;
2194 char const * const * where = 0;
2195 // Store the latest bibliographystyle, addcontentslineContent and
2196 // nocite{*} option (needed for bibtex inset)
2198 string contentslineContent;
2199 string bibliographystyle = "default";
2200 bool const use_natbib = isProvided("natbib");
2201 bool const use_jurabib = isProvided("jurabib");
2204 Token const & t = p.get_token();
2206 // it is impossible to determine the correct encoding for non-CJK Japanese.
2207 // Therefore write a note at the beginning of the document
2208 if (is_nonCJKJapanese) {
2209 context.check_layout(os);
2210 begin_inset(os, "Note Note\n");
2211 os << "status open\n\\begin_layout Plain Layout\n"
2212 << "\\series bold\n"
2213 << "Important information:\n"
2214 << "\\end_layout\n\n"
2215 << "\\begin_layout Plain Layout\n"
2216 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2217 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2218 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2219 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2220 << " and specify the encoding using the -e command-line switch.\n"
2221 << " In addition, you might want to double check that the desired output encoding\n"
2222 << " is correctly selected in Document > Settings > Language.\n"
2223 << "\\end_layout\n";
2225 is_nonCJKJapanese = false;
2229 debugToken(cerr, t, flags);
2232 if (flags & FLAG_ITEM) {
2233 if (t.cat() == catSpace)
2236 flags &= ~FLAG_ITEM;
2237 if (t.cat() == catBegin) {
2238 // skip the brace and collect everything to the next matching
2240 flags |= FLAG_BRACE_LAST;
2244 // handle only this single token, leave the loop if done
2245 flags |= FLAG_LEAVE;
2248 if (t.cat() != catEscape && t.character() == ']' &&
2249 (flags & FLAG_BRACK_LAST))
2251 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2254 // If there is anything between \end{env} and \begin{env} we
2255 // don't need to output a separator.
2256 if (t.cat() != catSpace && t.cat() != catNewline &&
2257 t.asInput() != "\\begin")
2263 if (t.cat() == catMath) {
2264 // we are inside some text mode thingy, so opening new math is allowed
2265 context.check_layout(os);
2266 begin_inset(os, "Formula ");
2267 Token const & n = p.get_token();
2268 bool const display(n.cat() == catMath && outer);
2270 // TeX's $$...$$ syntax for displayed math
2272 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2274 p.get_token(); // skip the second '$' token
2276 // simple $...$ stuff
2279 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2284 // Prevent the conversion of a line break to a
2285 // space (bug 7668). This does not change the
2286 // output, but looks ugly in LyX.
2287 eat_whitespace(p, os, context, false);
2291 else if (t.cat() == catSuper || t.cat() == catSub)
2292 cerr << "catcode " << t << " illegal in text mode\n";
2294 // Basic support for english quotes. This should be
2295 // extended to other quotes, but is not so easy (a
2296 // left english quote is the same as a right german
2298 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2299 context.check_layout(os);
2300 begin_inset(os, "Quotes ");
2306 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2307 context.check_layout(os);
2308 begin_inset(os, "Quotes ");
2315 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2316 context.check_layout(os);
2317 begin_inset(os, "Quotes ");
2324 else if (t.asInput() == "<"
2325 && p.next_token().asInput() == "<" && noweb_mode) {
2327 parse_noweb(p, os, context);
2330 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2331 context.check_layout(os);
2332 begin_inset(os, "Quotes ");
2339 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2340 check_space(p, os, context);
2342 else if (t.character() == '[' && noweb_mode &&
2343 p.next_token().character() == '[') {
2344 // These can contain underscores
2346 string const s = p.getFullOpt() + ']';
2347 if (p.next_token().character() == ']')
2350 cerr << "Warning: Inserting missing ']' in '"
2351 << s << "'." << endl;
2352 output_ert_inset(os, s, context);
2355 else if (t.cat() == catLetter) {
2356 context.check_layout(os);
2357 // Workaround for bug 4752.
2358 // FIXME: This whole code block needs to be removed
2359 // when the bug is fixed and tex2lyx produces
2360 // the updated file format.
2361 // The replacement algorithm in LyX is so stupid that
2362 // it even translates a phrase if it is part of a word.
2363 bool handled = false;
2364 for (int const * l = known_phrase_lengths; *l; ++l) {
2365 string phrase = t.cs();
2366 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2367 phrase += p.get_token().cs();
2368 if (is_known(phrase, known_coded_phrases)) {
2369 output_ert_inset(os, phrase, context);
2373 for (size_t i = 1; i < phrase.length(); ++i)
2381 else if (t.cat() == catOther ||
2382 t.cat() == catAlign ||
2383 t.cat() == catParameter) {
2384 // This translates "&" to "\\&" which may be wrong...
2385 context.check_layout(os);
2389 else if (p.isParagraph()) {
2390 if (context.new_layout_allowed)
2391 context.new_paragraph(os);
2393 output_ert_inset(os, "\\par ", context);
2394 eat_whitespace(p, os, context, true);
2397 else if (t.cat() == catActive) {
2398 context.check_layout(os);
2399 if (t.character() == '~') {
2400 if (context.layout->free_spacing)
2403 begin_inset(os, "space ~\n");
2410 else if (t.cat() == catBegin) {
2411 Token const next = p.next_token();
2412 Token const end = p.next_next_token();
2413 if (next.cat() == catEnd) {
2415 Token const prev = p.prev_token();
2417 if (p.next_token().character() == '`' ||
2418 (prev.character() == '-' &&
2419 p.next_token().character() == '-'))
2420 ; // ignore it in {}`` or -{}-
2422 output_ert_inset(os, "{}", context);
2423 } else if (next.cat() == catEscape &&
2424 is_known(next.cs(), known_quotes) &&
2425 end.cat() == catEnd) {
2426 // Something like {\textquoteright} (e.g.
2427 // from writer2latex). LyX writes
2428 // \textquoteright{}, so we may skip the
2429 // braces here for better readability.
2430 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2433 context.check_layout(os);
2434 // special handling of font attribute changes
2435 Token const prev = p.prev_token();
2436 TeXFont const oldFont = context.font;
2437 if (next.character() == '[' ||
2438 next.character() == ']' ||
2439 next.character() == '*') {
2441 if (p.next_token().cat() == catEnd) {
2446 output_ert_inset(os, "{", context);
2447 parse_text_snippet(p, os,
2450 output_ert_inset(os, "}", context);
2452 } else if (! context.new_layout_allowed) {
2453 output_ert_inset(os, "{", context);
2454 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2456 output_ert_inset(os, "}", context);
2457 } else if (is_known(next.cs(), known_sizes)) {
2458 // next will change the size, so we must
2460 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2462 if (!context.atParagraphStart())
2464 << context.font.size << "\n";
2465 } else if (is_known(next.cs(), known_font_families)) {
2466 // next will change the font family, so we
2467 // must reset it here
2468 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2470 if (!context.atParagraphStart())
2472 << context.font.family << "\n";
2473 } else if (is_known(next.cs(), known_font_series)) {
2474 // next will change the font series, so we
2475 // must reset it here
2476 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2478 if (!context.atParagraphStart())
2480 << context.font.series << "\n";
2481 } else if (is_known(next.cs(), known_font_shapes)) {
2482 // next will change the font shape, so we
2483 // must reset it here
2484 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2486 if (!context.atParagraphStart())
2488 << context.font.shape << "\n";
2489 } else if (is_known(next.cs(), known_old_font_families) ||
2490 is_known(next.cs(), known_old_font_series) ||
2491 is_known(next.cs(), known_old_font_shapes)) {
2492 // next will change the font family, series
2493 // and shape, so we must reset it here
2494 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2496 if (!context.atParagraphStart())
2498 << context.font.family
2500 << context.font.series
2502 << context.font.shape << "\n";
2504 output_ert_inset(os, "{", context);
2505 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2507 output_ert_inset(os, "}", context);
2512 else if (t.cat() == catEnd) {
2513 if (flags & FLAG_BRACE_LAST) {
2516 cerr << "stray '}' in text\n";
2517 output_ert_inset(os, "}", context);
2520 else if (t.cat() == catComment)
2521 parse_comment(p, os, t, context);
2524 // control sequences
2527 else if (t.cs() == "(") {
2528 context.check_layout(os);
2529 begin_inset(os, "Formula");
2531 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2536 else if (t.cs() == "[") {
2537 context.check_layout(os);
2538 begin_inset(os, "Formula");
2540 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2543 // Prevent the conversion of a line break to a space
2544 // (bug 7668). This does not change the output, but
2545 // looks ugly in LyX.
2546 eat_whitespace(p, os, context, false);
2549 else if (t.cs() == "begin")
2550 parse_environment(p, os, outer, last_env,
2553 else if (t.cs() == "end") {
2554 if (flags & FLAG_END) {
2555 // eat environment name
2556 string const name = p.getArg('{', '}');
2557 if (name != active_environment())
2558 cerr << "\\end{" + name + "} does not match \\begin{"
2559 + active_environment() + "}\n";
2562 p.error("found 'end' unexpectedly");
2565 else if (t.cs() == "item") {
2567 bool const optarg = p.hasOpt();
2569 // FIXME: This swallows comments, but we cannot use
2570 // eat_whitespace() since we must not output
2571 // anything before the item.
2572 p.skip_spaces(true);
2573 s = p.verbatimOption();
2575 p.skip_spaces(false);
2577 context.check_layout(os);
2578 if (context.has_item) {
2579 // An item in an unknown list-like environment
2580 // FIXME: Do this in check_layout()!
2581 context.has_item = false;
2583 output_ert_inset(os, "\\item", context);
2585 output_ert_inset(os, "\\item ", context);
2588 if (context.layout->labeltype != LABEL_MANUAL) {
2589 // LyX does not support \item[\mybullet]
2590 // in itemize environments
2592 os << parse_text_snippet(p2,
2593 FLAG_BRACK_LAST, outer, context);
2594 } else if (!s.empty()) {
2595 // LyX adds braces around the argument,
2596 // so we need to remove them here.
2597 if (s.size() > 2 && s[0] == '{' &&
2598 s[s.size()-1] == '}')
2599 s = s.substr(1, s.size()-2);
2600 // If the argument contains a space we
2601 // must put it into ERT: Otherwise LyX
2602 // would misinterpret the space as
2603 // item delimiter (bug 7663)
2604 if (contains(s, ' ')) {
2605 output_ert_inset(os, s, context);
2608 os << parse_text_snippet(p2,
2612 // The space is needed to separate the
2613 // item from the rest of the sentence.
2615 eat_whitespace(p, os, context, false);
2620 else if (t.cs() == "bibitem") {
2622 context.check_layout(os);
2623 eat_whitespace(p, os, context, false);
2624 string label = convert_command_inset_arg(p.verbatimOption());
2625 string key = convert_command_inset_arg(p.verbatim_item());
2626 if (contains(label, '\\') || contains(key, '\\')) {
2627 // LyX can't handle LaTeX commands in labels or keys
2628 output_ert_inset(os, t.asInput() + '[' + label +
2629 "]{" + p.verbatim_item() + '}',
2632 begin_command_inset(os, "bibitem", "bibitem");
2633 os << "label \"" << label << "\"\n"
2634 "key \"" << key << "\"\n";
2639 else if (is_macro(p)) {
2640 // catch the case of \def\inputGnumericTable
2642 if (t.cs() == "def") {
2643 Token second = p.next_token();
2644 if (second.cs() == "inputGnumericTable") {
2648 Token third = p.get_token();
2650 if (third.cs() == "input") {
2654 string name = normalize_filename(p.verbatim_item());
2655 string const path = getMasterFilePath(true);
2656 // We want to preserve relative / absolute filenames,
2657 // therefore path is only used for testing
2658 // The file extension is in every case ".tex".
2659 // So we need to remove this extension and check for
2660 // the original one.
2661 name = removeExtension(name);
2662 if (!makeAbsPath(name, path).exists()) {
2663 char const * const Gnumeric_formats[] = {"gnumeric",
2665 string const Gnumeric_name =
2666 find_file(name, path, Gnumeric_formats);
2667 if (!Gnumeric_name.empty())
2668 name = Gnumeric_name;
2670 FileName const absname = makeAbsPath(name, path);
2671 if (absname.exists()) {
2672 fix_child_filename(name);
2673 copy_file(absname, name);
2675 cerr << "Warning: Could not find file '"
2676 << name << "'." << endl;
2677 context.check_layout(os);
2678 begin_inset(os, "External\n\ttemplate ");
2679 os << "GnumericSpreadsheet\n\tfilename "
2682 context.check_layout(os);
2684 // register the packages that are automatically loaded
2685 // by the Gnumeric template
2686 registerExternalTemplatePackages("GnumericSpreadsheet");
2691 parse_macro(p, os, context);
2694 else if (t.cs() == "noindent") {
2696 context.add_par_extra_stuff("\\noindent\n");
2699 else if (t.cs() == "appendix") {
2700 context.add_par_extra_stuff("\\start_of_appendix\n");
2701 // We need to start a new paragraph. Otherwise the
2702 // appendix in 'bla\appendix\chapter{' would start
2704 context.new_paragraph(os);
2705 // We need to make sure that the paragraph is
2706 // generated even if it is empty. Otherwise the
2707 // appendix in '\par\appendix\par\chapter{' would
2709 context.check_layout(os);
2710 // FIXME: This is a hack to prevent paragraph
2711 // deletion if it is empty. Handle this better!
2712 output_ert_inset(os,
2713 "%dummy comment inserted by tex2lyx to "
2714 "ensure that this paragraph is not empty",
2716 // Both measures above may generate an additional
2717 // empty paragraph, but that does not hurt, because
2718 // whitespace does not matter here.
2719 eat_whitespace(p, os, context, true);
2722 // Must catch empty dates before findLayout is called below
2723 else if (t.cs() == "date") {
2724 eat_whitespace(p, os, context, false);
2726 string const date = p.verbatim_item();
2729 preamble.suppressDate(true);
2732 preamble.suppressDate(false);
2733 if (context.new_layout_allowed &&
2734 (newlayout = findLayout(context.textclass,
2737 output_command_layout(os, p, outer,
2738 context, newlayout);
2739 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2740 if (!preamble.titleLayoutFound())
2741 preamble.titleLayoutFound(newlayout->intitle);
2742 set<string> const & req = newlayout->requires();
2743 set<string>::const_iterator it = req.begin();
2744 set<string>::const_iterator en = req.end();
2745 for (; it != en; ++it)
2746 preamble.registerAutomaticallyLoadedPackage(*it);
2748 output_ert_inset(os,
2749 "\\date{" + p.verbatim_item() + '}',
2754 // Starred section headings
2755 // Must attempt to parse "Section*" before "Section".
2756 else if ((p.next_token().asInput() == "*") &&
2757 context.new_layout_allowed &&
2758 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2761 output_command_layout(os, p, outer, context, newlayout);
2763 if (!preamble.titleLayoutFound())
2764 preamble.titleLayoutFound(newlayout->intitle);
2765 set<string> const & req = newlayout->requires();
2766 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2767 preamble.registerAutomaticallyLoadedPackage(*it);
2770 // Section headings and the like
2771 else if (context.new_layout_allowed &&
2772 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2774 output_command_layout(os, p, outer, context, newlayout);
2776 if (!preamble.titleLayoutFound())
2777 preamble.titleLayoutFound(newlayout->intitle);
2778 set<string> const & req = newlayout->requires();
2779 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2780 preamble.registerAutomaticallyLoadedPackage(*it);
2783 else if (t.cs() == "caption") {
2785 context.check_layout(os);
2787 begin_inset(os, "Caption Standard\n");
2788 Context newcontext(true, context.textclass, 0, 0, context.font);
2789 newcontext.check_layout(os);
2790 // FIXME InsetArgument is now properly implemented in InsetLayout
2791 // (for captions, but also for others)
2792 if (p.next_token().cat() != catEscape &&
2793 p.next_token().character() == '[') {
2794 p.get_token(); // eat '['
2795 begin_inset(os, "Argument 1\n");
2796 os << "status collapsed\n";
2797 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2799 eat_whitespace(p, os, context, false);
2801 parse_text(p, os, FLAG_ITEM, outer, context);
2802 context.check_end_layout(os);
2803 // We don't need really a new paragraph, but
2804 // we must make sure that the next item gets a \begin_layout.
2805 context.new_paragraph(os);
2808 newcontext.check_end_layout(os);
2811 else if (t.cs() == "subfloat") {
2812 // the syntax is \subfloat[caption]{content}
2813 // if it is a table of figure depends on the surrounding float
2814 bool has_caption = false;
2816 // do nothing if there is no outer float
2817 if (!float_type.empty()) {
2818 context.check_layout(os);
2820 begin_inset(os, "Float " + float_type + "\n");
2822 << "\nsideways false"
2823 << "\nstatus collapsed\n\n";
2826 if (p.next_token().cat() != catEscape &&
2827 p.next_token().character() == '[') {
2828 p.get_token(); // eat '['
2829 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2833 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2834 // the caption comes always as the last
2836 // we must make sure that the caption gets a \begin_layout
2837 os << "\n\\begin_layout Plain Layout";
2839 begin_inset(os, "Caption Standard\n");
2840 Context newcontext(true, context.textclass,
2841 0, 0, context.font);
2842 newcontext.check_layout(os);
2843 os << caption << "\n";
2844 newcontext.check_end_layout(os);
2845 // We don't need really a new paragraph, but
2846 // we must make sure that the next item gets a \begin_layout.
2847 //newcontext.new_paragraph(os);
2851 // We don't need really a new paragraph, but
2852 // we must make sure that the next item gets a \begin_layout.
2854 context.new_paragraph(os);
2857 context.check_end_layout(os);
2858 // close the layout we opened
2860 os << "\n\\end_layout\n";
2862 // if the float type is not supported or there is no surrounding float
2865 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2866 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2867 "]{" + p.verbatim_item() + '}', context);
2869 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2873 else if (t.cs() == "includegraphics") {
2874 bool const clip = p.next_token().asInput() == "*";
2877 string const arg = p.getArg('[', ']');
2878 map<string, string> opts;
2879 vector<string> keys;
2880 split_map(arg, opts, keys);
2882 opts["clip"] = string();
2883 string name = normalize_filename(p.verbatim_item());
2885 string const path = getMasterFilePath(true);
2886 // We want to preserve relative / absolute filenames,
2887 // therefore path is only used for testing
2888 if (!makeAbsPath(name, path).exists()) {
2889 // The file extension is probably missing.
2890 // Now try to find it out.
2891 string const dvips_name =
2892 find_file(name, path,
2893 known_dvips_graphics_formats);
2894 string const pdftex_name =
2895 find_file(name, path,
2896 known_pdftex_graphics_formats);
2897 if (!dvips_name.empty()) {
2898 if (!pdftex_name.empty()) {
2899 cerr << "This file contains the "
2901 "\"\\includegraphics{"
2903 "However, files\n\""
2904 << dvips_name << "\" and\n\""
2905 << pdftex_name << "\"\n"
2906 "both exist, so I had to make a "
2907 "choice and took the first one.\n"
2908 "Please move the unwanted one "
2909 "someplace else and try again\n"
2910 "if my choice was wrong."
2914 } else if (!pdftex_name.empty()) {
2920 FileName const absname = makeAbsPath(name, path);
2921 if (absname.exists()) {
2922 fix_child_filename(name);
2923 copy_file(absname, name);
2925 cerr << "Warning: Could not find graphics file '"
2926 << name << "'." << endl;
2928 context.check_layout(os);
2929 begin_inset(os, "Graphics ");
2930 os << "\n\tfilename " << name << '\n';
2931 if (opts.find("width") != opts.end())
2933 << translate_len(opts["width"]) << '\n';
2934 if (opts.find("height") != opts.end())
2936 << translate_len(opts["height"]) << '\n';
2937 if (opts.find("scale") != opts.end()) {
2938 istringstream iss(opts["scale"]);
2942 os << "\tscale " << val << '\n';
2944 if (opts.find("angle") != opts.end()) {
2945 os << "\trotateAngle "
2946 << opts["angle"] << '\n';
2947 vector<string>::const_iterator a =
2948 find(keys.begin(), keys.end(), "angle");
2949 vector<string>::const_iterator s =
2950 find(keys.begin(), keys.end(), "width");
2951 if (s == keys.end())
2952 s = find(keys.begin(), keys.end(), "height");
2953 if (s == keys.end())
2954 s = find(keys.begin(), keys.end(), "scale");
2955 if (s != keys.end() && distance(s, a) > 0)
2956 os << "\tscaleBeforeRotation\n";
2958 if (opts.find("origin") != opts.end()) {
2960 string const opt = opts["origin"];
2961 if (opt.find('l') != string::npos) ss << "left";
2962 if (opt.find('r') != string::npos) ss << "right";
2963 if (opt.find('c') != string::npos) ss << "center";
2964 if (opt.find('t') != string::npos) ss << "Top";
2965 if (opt.find('b') != string::npos) ss << "Bottom";
2966 if (opt.find('B') != string::npos) ss << "Baseline";
2967 if (!ss.str().empty())
2968 os << "\trotateOrigin " << ss.str() << '\n';
2970 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2972 if (opts.find("keepaspectratio") != opts.end())
2973 os << "\tkeepAspectRatio\n";
2974 if (opts.find("clip") != opts.end())
2976 if (opts.find("draft") != opts.end())
2978 if (opts.find("bb") != opts.end())
2979 os << "\tBoundingBox "
2980 << opts["bb"] << '\n';
2981 int numberOfbbOptions = 0;
2982 if (opts.find("bbllx") != opts.end())
2983 numberOfbbOptions++;
2984 if (opts.find("bblly") != opts.end())
2985 numberOfbbOptions++;
2986 if (opts.find("bburx") != opts.end())
2987 numberOfbbOptions++;
2988 if (opts.find("bbury") != opts.end())
2989 numberOfbbOptions++;
2990 if (numberOfbbOptions == 4)
2991 os << "\tBoundingBox "
2992 << opts["bbllx"] << " " << opts["bblly"] << " "
2993 << opts["bburx"] << " " << opts["bbury"] << '\n';
2994 else if (numberOfbbOptions > 0)
2995 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2996 numberOfbbOptions = 0;
2997 if (opts.find("natwidth") != opts.end())
2998 numberOfbbOptions++;
2999 if (opts.find("natheight") != opts.end())
3000 numberOfbbOptions++;
3001 if (numberOfbbOptions == 2)
3002 os << "\tBoundingBox 0bp 0bp "
3003 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3004 else if (numberOfbbOptions > 0)
3005 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3006 ostringstream special;
3007 if (opts.find("hiresbb") != opts.end())
3008 special << "hiresbb,";
3009 if (opts.find("trim") != opts.end())
3011 if (opts.find("viewport") != opts.end())
3012 special << "viewport=" << opts["viewport"] << ',';
3013 if (opts.find("totalheight") != opts.end())
3014 special << "totalheight=" << opts["totalheight"] << ',';
3015 if (opts.find("type") != opts.end())
3016 special << "type=" << opts["type"] << ',';
3017 if (opts.find("ext") != opts.end())
3018 special << "ext=" << opts["ext"] << ',';
3019 if (opts.find("read") != opts.end())
3020 special << "read=" << opts["read"] << ',';
3021 if (opts.find("command") != opts.end())
3022 special << "command=" << opts["command"] << ',';
3023 string s_special = special.str();
3024 if (!s_special.empty()) {
3025 // We had special arguments. Remove the trailing ','.
3026 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3028 // TODO: Handle the unknown settings better.
3029 // Warn about invalid options.
3030 // Check whether some option was given twice.
3032 preamble.registerAutomaticallyLoadedPackage("graphicx");
3035 else if (t.cs() == "footnote" ||
3036 (t.cs() == "thanks" && context.layout->intitle)) {
3038 context.check_layout(os);
3039 begin_inset(os, "Foot\n");
3040 os << "status collapsed\n\n";
3041 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3045 else if (t.cs() == "marginpar") {
3047 context.check_layout(os);
3048 begin_inset(os, "Marginal\n");
3049 os << "status collapsed\n\n";
3050 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3054 else if (t.cs() == "lstinline") {
3056 parse_listings(p, os, context, true);
3059 else if (t.cs() == "ensuremath") {
3061 context.check_layout(os);
3062 string const s = p.verbatim_item();
3063 //FIXME: this never triggers in UTF8
3064 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3067 output_ert_inset(os, "\\ensuremath{" + s + "}",
3071 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3072 if (preamble.titleLayoutFound()) {
3074 skip_spaces_braces(p);
3076 output_ert_inset(os, t.asInput(), context);
3079 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3080 context.check_layout(os);
3081 begin_command_inset(os, "toc", t.cs());
3083 skip_spaces_braces(p);
3084 if (t.cs() == "lstlistoflistings")
3085 preamble.registerAutomaticallyLoadedPackage("listings");
3088 else if (t.cs() == "listoffigures") {
3089 context.check_layout(os);
3090 begin_inset(os, "FloatList figure\n");
3092 skip_spaces_braces(p);
3095 else if (t.cs() == "listoftables") {
3096 context.check_layout(os);
3097 begin_inset(os, "FloatList table\n");
3099 skip_spaces_braces(p);
3102 else if (t.cs() == "listof") {
3103 p.skip_spaces(true);
3104 string const name = p.get_token().cs();
3105 if (context.textclass.floats().typeExist(name)) {
3106 context.check_layout(os);
3107 begin_inset(os, "FloatList ");
3110 p.get_token(); // swallow second arg
3112 output_ert_inset(os, "\\listof{" + name + "}", context);
3115 else if ((where = is_known(t.cs(), known_text_font_families)))
3116 parse_text_attributes(p, os, FLAG_ITEM, outer,
3117 context, "\\family", context.font.family,
3118 known_coded_font_families[where - known_text_font_families]);
3120 else if ((where = is_known(t.cs(), known_text_font_series)))
3121 parse_text_attributes(p, os, FLAG_ITEM, outer,
3122 context, "\\series", context.font.series,
3123 known_coded_font_series[where - known_text_font_series]);
3125 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3126 parse_text_attributes(p, os, FLAG_ITEM, outer,
3127 context, "\\shape", context.font.shape,
3128 known_coded_font_shapes[where - known_text_font_shapes]);
3130 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3131 context.check_layout(os);
3132 TeXFont oldFont = context.font;
3133 context.font.init();
3134 context.font.size = oldFont.size;
3135 os << "\n\\family " << context.font.family << "\n";
3136 os << "\n\\series " << context.font.series << "\n";
3137 os << "\n\\shape " << context.font.shape << "\n";
3138 if (t.cs() == "textnormal") {
3139 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3140 output_font_change(os, context.font, oldFont);
3141 context.font = oldFont;
3143 eat_whitespace(p, os, context, false);
3146 else if (t.cs() == "textcolor") {
3147 // scheme is \textcolor{color name}{text}
3148 string const color = p.verbatim_item();
3149 // we only support the predefined colors of the color package
3150 if (color == "black" || color == "blue" || color == "cyan"
3151 || color == "green" || color == "magenta" || color == "red"
3152 || color == "white" || color == "yellow") {
3153 context.check_layout(os);
3154 os << "\n\\color " << color << "\n";
3155 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3156 context.check_layout(os);
3157 os << "\n\\color inherit\n";
3158 preamble.registerAutomaticallyLoadedPackage("color");
3160 // for custom defined colors
3161 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3164 else if (t.cs() == "underbar" || t.cs() == "uline") {
3165 // \underbar is not 100% correct (LyX outputs \uline
3166 // of ulem.sty). The difference is that \ulem allows
3167 // line breaks, and \underbar does not.
3168 // Do NOT handle \underline.
3169 // \underbar cuts through y, g, q, p etc.,
3170 // \underline does not.
3171 context.check_layout(os);
3172 os << "\n\\bar under\n";
3173 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3174 context.check_layout(os);
3175 os << "\n\\bar default\n";
3176 preamble.registerAutomaticallyLoadedPackage("ulem");
3179 else if (t.cs() == "sout") {
3180 context.check_layout(os);
3181 os << "\n\\strikeout on\n";
3182 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3183 context.check_layout(os);
3184 os << "\n\\strikeout default\n";
3185 preamble.registerAutomaticallyLoadedPackage("ulem");
3188 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3189 t.cs() == "emph" || t.cs() == "noun") {
3190 context.check_layout(os);
3191 os << "\n\\" << t.cs() << " on\n";
3192 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3193 context.check_layout(os);
3194 os << "\n\\" << t.cs() << " default\n";
3195 if (t.cs() == "uuline" || t.cs() == "uwave")
3196 preamble.registerAutomaticallyLoadedPackage("ulem");
3199 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3200 context.check_layout(os);
3201 string name = p.getArg('{', '}');
3202 string localtime = p.getArg('{', '}');
3203 preamble.registerAuthor(name);
3204 Author const & author = preamble.getAuthor(name);
3205 // from_asctime_utc() will fail if LyX decides to output the
3206 // time in the text language.
3207 time_t ptime = from_asctime_utc(localtime);
3208 if (ptime == static_cast<time_t>(-1)) {
3209 cerr << "Warning: Could not parse time `" << localtime
3210 << "´ for change tracking, using current time instead.\n";
3211 ptime = current_time();
3213 if (t.cs() == "lyxadded")
3214 os << "\n\\change_inserted ";
3216 os << "\n\\change_deleted ";
3217 os << author.bufferId() << ' ' << ptime << '\n';
3218 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3219 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3220 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3221 LaTeXPackages::isAvailable("xcolor");
3222 // No need to test for luatex, since luatex comes in
3223 // two flavours (dvi and pdf), like latex, and those
3224 // are detected by pdflatex.
3225 if (pdflatex || xetex) {
3227 preamble.registerAutomaticallyLoadedPackage("ulem");
3228 preamble.registerAutomaticallyLoadedPackage("xcolor");
3229 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3233 preamble.registerAutomaticallyLoadedPackage("dvipost");
3234 } else if (xcolorulem) {
3235 preamble.registerAutomaticallyLoadedPackage("ulem");
3236 preamble.registerAutomaticallyLoadedPackage("xcolor");
3241 else if (t.cs() == "textipa") {
3242 context.check_layout(os);
3243 begin_inset(os, "IPA\n");
3244 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3246 preamble.registerAutomaticallyLoadedPackage("tipa");
3247 preamble.registerAutomaticallyLoadedPackage("tipx");
3250 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3251 context.check_layout(os);
3252 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3253 os << "status open\n";
3254 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3259 // the TIPA Combining diacritical marks
3260 else if (is_known(t.cs(), known_tipa_marks)) {
3261 context.check_layout(os);
3262 // try to see whether the string is in unicodesymbols
3265 string content = trimSpaceAndEol(p.verbatim_item());
3266 string command = t.asInput() + "{" + content + "}";
3268 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3269 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3270 termination, rem, &req);
3273 cerr << "When parsing " << command
3274 << ", result is " << to_utf8(s)
3275 << "+" << to_utf8(rem) << endl;
3276 os << content << to_utf8(s);
3277 // tipa is already registered because of the surrounding IPA environment
3278 // or \textipa but it does not harm to register it again if necessary
3279 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3280 preamble.registerAutomaticallyLoadedPackage(*it);
3282 // we did not find a non-ert version
3283 output_ert_inset(os, command, context);
3286 else if (t.cs() == "tone" ) {
3287 context.check_layout(os);
3288 // register the tone package
3289 preamble.registerAutomaticallyLoadedPackage("tone");
3290 string content = trimSpaceAndEol(p.verbatim_item());
3291 string command = t.asInput() + "{" + content + "}";
3292 // some tones can be detected by unicodesymbols, some need special code
3293 if (is_known(content, known_tones)) {
3294 os << "\\IPAChar " << command << "\n";
3297 // try to see whether the string is in unicodesymbols
3301 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3302 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3303 termination, rem, &req);
3306 cerr << "When parsing " << command
3307 << ", result is " << to_utf8(s)
3308 << "+" << to_utf8(rem) << endl;
3311 // we did not find a non-ert version
3312 output_ert_inset(os, command, context);
3315 else if (t.cs() == "textvertline" ) {
3316 // this TIPA character does not occur in
3317 // unicodesymbols because it is in the ASCII range
3318 context.check_layout(os);
3323 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3324 t.cs() == "vphantom") {
3325 context.check_layout(os);
3326 if (t.cs() == "phantom")
3327 begin_inset(os, "Phantom Phantom\n");
3328 if (t.cs() == "hphantom")
3329 begin_inset(os, "Phantom HPhantom\n");
3330 if (t.cs() == "vphantom")
3331 begin_inset(os, "Phantom VPhantom\n");
3332 os << "status open\n";
3333 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3338 else if (t.cs() == "href") {
3339 context.check_layout(os);
3340 string target = convert_command_inset_arg(p.verbatim_item());
3341 string name = convert_command_inset_arg(p.verbatim_item());
3343 size_t i = target.find(':');
3344 if (i != string::npos) {
3345 type = target.substr(0, i + 1);
3346 if (type == "mailto:" || type == "file:")
3347 target = target.substr(i + 1);
3348 // handle the case that name is equal to target, except of "http://"
3349 else if (target.substr(i + 3) == name && type == "http:")
3352 begin_command_inset(os, "href", "href");
3354 os << "name \"" << name << "\"\n";
3355 os << "target \"" << target << "\"\n";
3356 if (type == "mailto:" || type == "file:")
3357 os << "type \"" << type << "\"\n";
3359 skip_spaces_braces(p);
3362 else if (t.cs() == "lyxline") {
3363 // swallow size argument (it is not used anyway)
3365 if (!context.atParagraphStart()) {
3366 // so our line is in the middle of a paragraph
3367 // we need to add a new line, lest this line
3368 // follow the other content on that line and
3369 // run off the side of the page
3370 // FIXME: This may create an empty paragraph,
3371 // but without that it would not be
3372 // possible to set noindent below.
3373 // Fortunately LaTeX does not care
3374 // about the empty paragraph.
3375 context.new_paragraph(os);
3377 if (preamble.indentParagraphs()) {
3378 // we need to unindent, lest the line be too long
3379 context.add_par_extra_stuff("\\noindent\n");
3381 context.check_layout(os);
3382 begin_command_inset(os, "line", "rule");
3383 os << "offset \"0.5ex\"\n"
3384 "width \"100line%\"\n"
3389 else if (t.cs() == "rule") {
3390 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3391 string const width = p.getArg('{', '}');
3392 string const thickness = p.getArg('{', '}');
3393 context.check_layout(os);
3394 begin_command_inset(os, "line", "rule");
3395 if (!offset.empty())
3396 os << "offset \"" << translate_len(offset) << "\"\n";
3397 os << "width \"" << translate_len(width) << "\"\n"
3398 "height \"" << translate_len(thickness) << "\"\n";
3402 else if (is_known(t.cs(), known_phrases) ||
3403 (t.cs() == "protect" &&
3404 p.next_token().cat() == catEscape &&
3405 is_known(p.next_token().cs(), known_phrases))) {
3406 // LyX sometimes puts a \protect in front, so we have to ignore it
3407 // FIXME: This needs to be changed when bug 4752 is fixed.
3409 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3411 context.check_layout(os);
3412 os << known_coded_phrases[where - known_phrases];
3413 skip_spaces_braces(p);
3416 else if ((where = is_known(t.cs(), known_ref_commands))) {
3417 // \eqref can also occur if refstyle is used
3418 if (t.cs() == "eqref" && preamble.refstyle() == "1") {
3419 context.check_layout(os);
3420 begin_command_inset(os, "ref", "formatted");
3421 os << "reference \"eq:"
3422 << convert_command_inset_arg(p.verbatim_item())
3425 preamble.registerAutomaticallyLoadedPackage("refstyle");
3427 string const opt = p.getOpt();
3429 context.check_layout(os);
3430 begin_command_inset(os, "ref",
3431 known_coded_ref_commands[where - known_ref_commands]);
3432 os << "reference \""
3433 << convert_command_inset_arg(p.verbatim_item())
3436 if (t.cs() == "vref" || t.cs() == "vpageref")
3437 preamble.registerAutomaticallyLoadedPackage("varioref");
3439 // LyX does not yet support optional arguments of ref commands
3440 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3441 p.verbatim_item() + "}", context);
3446 else if ((where = is_known(t.cs(), known_refstyle_commands))) {
3447 context.check_layout(os);
3448 // \eqref can also occur if refstyle is not used
3449 // this case is already handled in the previous else if
3450 begin_command_inset(os, "ref", "formatted");
3451 os << "reference \"";
3452 os << known_refstyle_prefixes[where - known_refstyle_commands]
3454 os << convert_command_inset_arg(p.verbatim_item())
3457 preamble.registerAutomaticallyLoadedPackage("refstyle");
3460 else if (use_natbib &&
3461 is_known(t.cs(), known_natbib_commands) &&
3462 ((t.cs() != "citefullauthor" &&
3463 t.cs() != "citeyear" &&
3464 t.cs() != "citeyearpar") ||
3465 p.next_token().asInput() != "*")) {
3466 context.check_layout(os);
3467 string command = t.cs();
3468 if (p.next_token().asInput() == "*") {
3472 if (command == "citefullauthor")
3473 // alternative name for "\\citeauthor*"
3474 command = "citeauthor*";
3476 // text before the citation
3478 // text after the citation
3480 get_cite_arguments(p, true, before, after);
3482 if (command == "cite") {
3483 // \cite without optional argument means
3484 // \citet, \cite with at least one optional
3485 // argument means \citep.
3486 if (before.empty() && after.empty())
3491 if (before.empty() && after == "[]")
3492 // avoid \citet[]{a}
3494 else if (before == "[]" && after == "[]") {
3495 // avoid \citet[][]{a}
3499 // remove the brackets around after and before
3500 if (!after.empty()) {
3502 after.erase(after.length() - 1, 1);
3503 after = convert_command_inset_arg(after);
3505 if (!before.empty()) {
3507 before.erase(before.length() - 1, 1);
3508 before = convert_command_inset_arg(before);
3510 begin_command_inset(os, "citation", command);
3511 os << "after " << '"' << after << '"' << "\n";
3512 os << "before " << '"' << before << '"' << "\n";
3514 << convert_command_inset_arg(p.verbatim_item())
3517 // Need to set the cite engine if natbib is loaded by
3518 // the document class directly
3519 if (preamble.citeEngine() == "basic")
3520 preamble.citeEngine("natbib");
3523 else if (use_jurabib &&
3524 is_known(t.cs(), known_jurabib_commands) &&
3525 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3526 context.check_layout(os);
3527 string command = t.cs();
3528 if (p.next_token().asInput() == "*") {
3532 char argumentOrder = '\0';
3533 vector<string> const options =
3534 preamble.getPackageOptions("jurabib");
3535 if (find(options.begin(), options.end(),
3536 "natbiborder") != options.end())
3537 argumentOrder = 'n';
3538 else if (find(options.begin(), options.end(),
3539 "jurabiborder") != options.end())
3540 argumentOrder = 'j';
3542 // text before the citation
3544 // text after the citation
3546 get_cite_arguments(p, argumentOrder != 'j', before, after);
3548 string const citation = p.verbatim_item();
3549 if (!before.empty() && argumentOrder == '\0') {
3550 cerr << "Warning: Assuming argument order "
3551 "of jurabib version 0.6 for\n'"
3552 << command << before << after << '{'
3553 << citation << "}'.\n"
3554 "Add 'jurabiborder' to the jurabib "
3555 "package options if you used an\n"
3556 "earlier jurabib version." << endl;
3558 if (!after.empty()) {
3560 after.erase(after.length() - 1, 1);
3562 if (!before.empty()) {
3564 before.erase(before.length() - 1, 1);
3566 begin_command_inset(os, "citation", command);
3567 os << "after " << '"' << after << '"' << "\n";
3568 os << "before " << '"' << before << '"' << "\n";
3569 os << "key " << '"' << citation << '"' << "\n";
3571 // Need to set the cite engine if jurabib is loaded by
3572 // the document class directly
3573 if (preamble.citeEngine() == "basic")
3574 preamble.citeEngine("jurabib");
3577 else if (t.cs() == "cite"
3578 || t.cs() == "nocite") {
3579 context.check_layout(os);
3580 string after = convert_command_inset_arg(p.getArg('[', ']'));
3581 string key = convert_command_inset_arg(p.verbatim_item());
3582 // store the case that it is "\nocite{*}" to use it later for
3585 begin_command_inset(os, "citation", t.cs());
3586 os << "after " << '"' << after << '"' << "\n";
3587 os << "key " << '"' << key << '"' << "\n";
3589 } else if (t.cs() == "nocite")
3593 else if (t.cs() == "index" ||
3594 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3595 context.check_layout(os);
3596 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3597 p.getArg('[', ']') : "";
3598 string const kind = arg.empty() ? "idx" : arg;
3599 begin_inset(os, "Index ");
3600 os << kind << "\nstatus collapsed\n";
3601 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3604 preamble.registerAutomaticallyLoadedPackage("splitidx");
3607 else if (t.cs() == "nomenclature") {
3608 context.check_layout(os);
3609 begin_command_inset(os, "nomenclature", "nomenclature");
3610 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3611 if (!prefix.empty())
3612 os << "prefix " << '"' << prefix << '"' << "\n";
3613 os << "symbol " << '"'
3614 << convert_command_inset_arg(p.verbatim_item());
3615 os << "\"\ndescription \""
3616 << convert_command_inset_arg(p.verbatim_item())
3619 preamble.registerAutomaticallyLoadedPackage("nomencl");
3622 else if (t.cs() == "label") {
3623 context.check_layout(os);
3624 begin_command_inset(os, "label", "label");
3626 << convert_command_inset_arg(p.verbatim_item())
3631 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3632 context.check_layout(os);
3633 string commandname = t.cs();
3635 if (p.next_token().asInput() == "*") {
3640 begin_command_inset(os, "index_print", commandname);
3641 string const indexname = p.getArg('[', ']');
3643 if (indexname.empty())
3644 os << "type \"idx\"\n";
3646 os << "type \"" << indexname << "\"\n";
3649 skip_spaces_braces(p);
3650 preamble.registerAutomaticallyLoadedPackage("makeidx");
3651 if (preamble.use_indices() == "true")
3652 preamble.registerAutomaticallyLoadedPackage("splitidx");
3655 else if (t.cs() == "printnomenclature") {
3657 string width_type = "";
3658 context.check_layout(os);
3659 begin_command_inset(os, "nomencl_print", "printnomenclature");
3660 // case of a custom width
3662 width = p.getArg('[', ']');
3663 width = translate_len(width);
3664 width_type = "custom";
3666 // case of no custom width
3667 // the case of no custom width but the width set
3668 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3669 // because the user could have set anything, not only the width
3670 // of the longest label (which would be width_type = "auto")
3671 string label = convert_command_inset_arg(p.getArg('{', '}'));
3672 if (label.empty() && width_type.empty())
3673 width_type = "none";
3674 os << "set_width \"" << width_type << "\"\n";
3675 if (width_type == "custom")
3676 os << "width \"" << width << '\"';
3678 skip_spaces_braces(p);
3679 preamble.registerAutomaticallyLoadedPackage("nomencl");
3682 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3683 context.check_layout(os);
3684 begin_inset(os, "script ");
3685 os << t.cs().substr(4) << '\n';
3686 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3688 if (t.cs() == "textsubscript")
3689 preamble.registerAutomaticallyLoadedPackage("subscript");
3692 else if ((where = is_known(t.cs(), known_quotes))) {
3693 context.check_layout(os);
3694 begin_inset(os, "Quotes ");
3695 os << known_coded_quotes[where - known_quotes];
3697 // LyX adds {} after the quote, so we have to eat
3698 // spaces here if there are any before a possible
3700 eat_whitespace(p, os, context, false);
3704 else if ((where = is_known(t.cs(), known_sizes)) &&
3705 context.new_layout_allowed) {
3706 context.check_layout(os);
3707 TeXFont const oldFont = context.font;
3708 context.font.size = known_coded_sizes[where - known_sizes];
3709 output_font_change(os, oldFont, context.font);
3710 eat_whitespace(p, os, context, false);
3713 else if ((where = is_known(t.cs(), known_font_families)) &&
3714 context.new_layout_allowed) {
3715 context.check_layout(os);
3716 TeXFont const oldFont = context.font;
3717 context.font.family =
3718 known_coded_font_families[where - known_font_families];
3719 output_font_change(os, oldFont, context.font);
3720 eat_whitespace(p, os, context, false);
3723 else if ((where = is_known(t.cs(), known_font_series)) &&
3724 context.new_layout_allowed) {
3725 context.check_layout(os);
3726 TeXFont const oldFont = context.font;
3727 context.font.series =
3728 known_coded_font_series[where - known_font_series];
3729 output_font_change(os, oldFont, context.font);
3730 eat_whitespace(p, os, context, false);
3733 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3734 context.new_layout_allowed) {
3735 context.check_layout(os);
3736 TeXFont const oldFont = context.font;
3737 context.font.shape =
3738 known_coded_font_shapes[where - known_font_shapes];
3739 output_font_change(os, oldFont, context.font);
3740 eat_whitespace(p, os, context, false);
3742 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3743 context.new_layout_allowed) {
3744 context.check_layout(os);
3745 TeXFont const oldFont = context.font;
3746 context.font.init();
3747 context.font.size = oldFont.size;
3748 context.font.family =
3749 known_coded_font_families[where - known_old_font_families];
3750 output_font_change(os, oldFont, context.font);
3751 eat_whitespace(p, os, context, false);
3754 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3755 context.new_layout_allowed) {
3756 context.check_layout(os);
3757 TeXFont const oldFont = context.font;
3758 context.font.init();
3759 context.font.size = oldFont.size;
3760 context.font.series =
3761 known_coded_font_series[where - known_old_font_series];
3762 output_font_change(os, oldFont, context.font);
3763 eat_whitespace(p, os, context, false);
3766 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3767 context.new_layout_allowed) {
3768 context.check_layout(os);
3769 TeXFont const oldFont = context.font;
3770 context.font.init();
3771 context.font.size = oldFont.size;
3772 context.font.shape =
3773 known_coded_font_shapes[where - known_old_font_shapes];
3774 output_font_change(os, oldFont, context.font);
3775 eat_whitespace(p, os, context, false);
3778 else if (t.cs() == "selectlanguage") {
3779 context.check_layout(os);
3780 // save the language for the case that a
3781 // \foreignlanguage is used
3782 context.font.language = babel2lyx(p.verbatim_item());
3783 os << "\n\\lang " << context.font.language << "\n";
3786 else if (t.cs() == "foreignlanguage") {
3787 string const lang = babel2lyx(p.verbatim_item());
3788 parse_text_attributes(p, os, FLAG_ITEM, outer,
3790 context.font.language, lang);
3793 else if (prefixIs(t.cs(), "text")
3794 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3795 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3797 // We have to output the whole command if it has an option
3798 // because LyX doesn't support this yet, see bug #8214,
3799 // only if there is a single option specifying a variant, we can handle it.
3801 string langopts = p.getOpt();
3802 // check if the option contains a variant, if yes, extract it
3803 string::size_type pos_var = langopts.find("variant");
3804 string::size_type i = langopts.find(',');
3805 string::size_type k = langopts.find('=', pos_var);
3806 if (pos_var != string::npos && i == string::npos) {
3808 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3809 lang = preamble.polyglossia2lyx(variant);
3810 parse_text_attributes(p, os, FLAG_ITEM, outer,
3812 context.font.language, lang);
3814 output_ert_inset(os, t.asInput() + langopts, context);
3816 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3817 parse_text_attributes(p, os, FLAG_ITEM, outer,
3819 context.font.language, lang);
3823 else if (t.cs() == "inputencoding") {
3824 // nothing to write here
3825 string const enc = subst(p.verbatim_item(), "\n", " ");
3826 p.setEncoding(enc, Encoding::inputenc);
3829 else if ((where = is_known(t.cs(), known_special_chars))) {
3830 context.check_layout(os);
3831 os << "\\SpecialChar \\"
3832 << known_coded_special_chars[where - known_special_chars]
3834 skip_spaces_braces(p);
3837 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3838 context.check_layout(os);
3839 os << "\\SpecialChar \\nobreakdash-\n";
3843 else if (t.cs() == "textquotedbl") {
3844 context.check_layout(os);
3849 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3850 context.check_layout(os);
3851 os << "\\SpecialChar \\@.\n";
3855 else if (t.cs() == "-") {
3856 context.check_layout(os);
3857 os << "\\SpecialChar \\-\n";
3860 else if (t.cs() == "textasciitilde") {
3861 context.check_layout(os);
3863 skip_spaces_braces(p);
3866 else if (t.cs() == "textasciicircum") {
3867 context.check_layout(os);
3869 skip_spaces_braces(p);
3872 else if (t.cs() == "textbackslash") {
3873 context.check_layout(os);
3874 os << "\n\\backslash\n";
3875 skip_spaces_braces(p);
3878 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3879 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3881 context.check_layout(os);
3885 else if (t.cs() == "char") {
3886 context.check_layout(os);
3887 if (p.next_token().character() == '`') {
3889 if (p.next_token().cs() == "\"") {
3894 output_ert_inset(os, "\\char`", context);
3897 output_ert_inset(os, "\\char", context);
3901 else if (t.cs() == "verb") {
3902 context.check_layout(os);
3903 // set catcodes to verbatim early, just in case.
3904 p.setCatcodes(VERBATIM_CATCODES);
3905 string delim = p.get_token().asInput();
3906 string const arg = p.verbatimStuff(delim);
3907 output_ert_inset(os, "\\verb" + delim + arg + delim, context);
3910 // Problem: \= creates a tabstop inside the tabbing environment
3911 // and else an accent. In the latter case we really would want
3912 // \={o} instead of \= o.
3913 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3914 output_ert_inset(os, t.asInput(), context);
3916 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3917 else if (t.cs().size() == 1
3918 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3919 context.check_layout(os);
3920 // try to see whether the string is in unicodesymbols
3923 string command = t.asInput() + "{"
3924 + trimSpaceAndEol(p.verbatim_item())
3927 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3928 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3929 termination, rem, &req);
3932 cerr << "When parsing " << command
3933 << ", result is " << to_utf8(s)
3934 << "+" << to_utf8(rem) << endl;
3936 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3937 preamble.registerAutomaticallyLoadedPackage(*it);
3939 // we did not find a non-ert version
3940 output_ert_inset(os, command, context);
3943 else if (t.cs() == "\\") {
3944 context.check_layout(os);
3946 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3947 else if (p.next_token().asInput() == "*") {
3949 // getOpt() eats the following space if there
3950 // is no optional argument, but that is OK
3951 // here since it has no effect in the output.
3952 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3955 begin_inset(os, "Newline newline");
3960 else if (t.cs() == "newline" ||
3961 (t.cs() == "linebreak" && !p.hasOpt())) {
3962 context.check_layout(os);
3963 begin_inset(os, "Newline ");
3966 skip_spaces_braces(p);
3969 else if (t.cs() == "input" || t.cs() == "include"
3970 || t.cs() == "verbatiminput") {
3971 string name = t.cs();
3972 if (t.cs() == "verbatiminput"
3973 && p.next_token().asInput() == "*")
3974 name += p.get_token().asInput();
3975 context.check_layout(os);
3976 string filename(normalize_filename(p.getArg('{', '}')));
3977 string const path = getMasterFilePath(true);
3978 // We want to preserve relative / absolute filenames,
3979 // therefore path is only used for testing
3980 if ((t.cs() == "include" || t.cs() == "input") &&
3981 !makeAbsPath(filename, path).exists()) {
3982 // The file extension is probably missing.
3983 // Now try to find it out.
3984 string const tex_name =
3985 find_file(filename, path,
3986 known_tex_extensions);
3987 if (!tex_name.empty())
3988 filename = tex_name;
3990 bool external = false;
3992 if (makeAbsPath(filename, path).exists()) {
3993 string const abstexname =
3994 makeAbsPath(filename, path).absFileName();
3995 string const absfigname =
3996 changeExtension(abstexname, ".fig");
3997 fix_child_filename(filename);
3998 string const lyxname =
3999 changeExtension(filename, ".lyx");
4000 string const abslyxname = makeAbsPath(
4001 lyxname, getParentFilePath(false)).absFileName();
4003 if (!skipChildren())
4004 external = FileName(absfigname).exists();
4005 if (t.cs() == "input" && !skipChildren()) {
4006 string const ext = getExtension(abstexname);
4008 // Combined PS/LaTeX:
4009 // x.eps, x.pstex_t (old xfig)
4010 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4011 FileName const absepsname(
4012 changeExtension(abstexname, ".eps"));
4013 FileName const abspstexname(
4014 changeExtension(abstexname, ".pstex"));
4015 bool const xfigeps =
4016 (absepsname.exists() ||
4017 abspstexname.exists()) &&
4020 // Combined PDF/LaTeX:
4021 // x.pdf, x.pdftex_t (old xfig)
4022 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4023 FileName const abspdfname(
4024 changeExtension(abstexname, ".pdf"));
4025 bool const xfigpdf =
4026 abspdfname.exists() &&
4027 (ext == "pdftex_t" || ext == "pdf_t");
4031 // Combined PS/PDF/LaTeX:
4032 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4033 string const absbase2(
4034 removeExtension(abstexname) + "_pspdftex");
4035 FileName const abseps2name(
4036 addExtension(absbase2, ".eps"));
4037 FileName const abspdf2name(
4038 addExtension(absbase2, ".pdf"));
4039 bool const xfigboth =
4040 abspdf2name.exists() &&
4041 abseps2name.exists() && ext == "pspdftex";
4043 xfig = xfigpdf || xfigeps || xfigboth;
4044 external = external && xfig;
4047 outname = changeExtension(filename, ".fig");
4048 FileName abssrc(changeExtension(abstexname, ".fig"));
4049 copy_file(abssrc, outname);
4051 // Don't try to convert, the result
4052 // would be full of ERT.
4054 FileName abssrc(abstexname);
4055 copy_file(abssrc, outname);
4056 } else if (t.cs() != "verbatiminput" &&
4058 tex2lyx(abstexname, FileName(abslyxname),
4061 // no need to call copy_file
4062 // tex2lyx creates the file
4065 FileName abssrc(abstexname);
4066 copy_file(abssrc, outname);
4069 cerr << "Warning: Could not find included file '"
4070 << filename << "'." << endl;
4074 begin_inset(os, "External\n");
4075 os << "\ttemplate XFig\n"
4076 << "\tfilename " << outname << '\n';
4077 registerExternalTemplatePackages("XFig");
4079 begin_command_inset(os, "include", name);
4080 outname = subst(outname, "\"", "\\\"");
4081 os << "preview false\n"
4082 "filename \"" << outname << "\"\n";
4083 if (t.cs() == "verbatiminput")
4084 preamble.registerAutomaticallyLoadedPackage("verbatim");
4089 else if (t.cs() == "bibliographystyle") {
4090 // store new bibliographystyle
4091 bibliographystyle = p.verbatim_item();
4092 // If any other command than \bibliography, \addcontentsline
4093 // and \nocite{*} follows, we need to output the style
4094 // (because it might be used by that command).
4095 // Otherwise, it will automatically be output by LyX.
4098 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4099 if (t2.cat() == catBegin)
4101 if (t2.cat() != catEscape)
4103 if (t2.cs() == "nocite") {
4104 if (p.getArg('{', '}') == "*")
4106 } else if (t2.cs() == "bibliography")
4108 else if (t2.cs() == "phantomsection") {
4112 else if (t2.cs() == "addcontentsline") {
4113 // get the 3 arguments of \addcontentsline
4116 contentslineContent = p.getArg('{', '}');
4117 // if the last argument is not \refname we must output
4118 if (contentslineContent == "\\refname")
4125 output_ert_inset(os,
4126 "\\bibliographystyle{" + bibliographystyle + '}',
4131 else if (t.cs() == "phantomsection") {
4132 // we only support this if it occurs between
4133 // \bibliographystyle and \bibliography
4134 if (bibliographystyle.empty())
4135 output_ert_inset(os, "\\phantomsection", context);
4138 else if (t.cs() == "addcontentsline") {
4139 context.check_layout(os);
4140 // get the 3 arguments of \addcontentsline
4141 string const one = p.getArg('{', '}');
4142 string const two = p.getArg('{', '}');
4143 string const three = p.getArg('{', '}');
4144 // only if it is a \refname, we support if for the bibtex inset
4145 if (contentslineContent != "\\refname") {
4146 output_ert_inset(os,
4147 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4152 else if (t.cs() == "bibliography") {
4153 context.check_layout(os);
4155 begin_command_inset(os, "bibtex", "bibtex");
4156 if (!btprint.empty()) {
4157 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4158 // clear the string because the next BibTeX inset can be without the
4159 // \nocite{*} option
4162 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4163 // Do we have addcontentsline?
4164 if (contentslineContent == "\\refname") {
4165 BibOpts = "bibtotoc";
4166 // clear string because next BibTeX inset can be without addcontentsline
4167 contentslineContent.clear();
4169 // Do we have a bibliographystyle set?
4170 if (!bibliographystyle.empty()) {
4171 if (BibOpts.empty())
4172 BibOpts = bibliographystyle;
4174 BibOpts = BibOpts + ',' + bibliographystyle;
4175 // clear it because each bibtex entry has its style
4176 // and we need an empty string to handle \phantomsection
4177 bibliographystyle.clear();
4179 os << "options " << '"' << BibOpts << '"' << "\n";
4183 else if (t.cs() == "parbox") {
4184 // Test whether this is an outer box of a shaded box
4186 // swallow arguments
4187 while (p.hasOpt()) {
4189 p.skip_spaces(true);
4192 p.skip_spaces(true);
4194 if (p.next_token().cat() == catBegin)
4196 p.skip_spaces(true);
4197 Token to = p.get_token();
4198 bool shaded = false;
4199 if (to.asInput() == "\\begin") {
4200 p.skip_spaces(true);
4201 if (p.getArg('{', '}') == "shaded")
4206 parse_outer_box(p, os, FLAG_ITEM, outer,
4207 context, "parbox", "shaded");
4209 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4213 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4214 t.cs() == "shadowbox" || t.cs() == "doublebox")
4215 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4217 else if (t.cs() == "framebox") {
4218 if (p.next_token().character() == '(') {
4219 //the syntax is: \framebox(x,y)[position]{content}
4220 string arg = t.asInput();
4221 arg += p.getFullParentheseArg();
4222 arg += p.getFullOpt();
4223 eat_whitespace(p, os, context, false);
4224 output_ert_inset(os, arg + '{', context);
4225 parse_text(p, os, FLAG_ITEM, outer, context);
4226 output_ert_inset(os, "}", context);
4228 string special = p.getFullOpt();
4229 special += p.getOpt();
4230 // LyX does not yet support \framebox without any option
4231 if (!special.empty())
4232 parse_outer_box(p, os, FLAG_ITEM, outer,
4233 context, t.cs(), special);
4235 eat_whitespace(p, os, context, false);
4236 output_ert_inset(os, "\\framebox{", context);
4237 parse_text(p, os, FLAG_ITEM, outer, context);
4238 output_ert_inset(os, "}", context);
4243 //\makebox() is part of the picture environment and different from \makebox{}
4244 //\makebox{} will be parsed by parse_box
4245 else if (t.cs() == "makebox") {
4246 if (p.next_token().character() == '(') {
4247 //the syntax is: \makebox(x,y)[position]{content}
4248 string arg = t.asInput();
4249 arg += p.getFullParentheseArg();
4250 arg += p.getFullOpt();
4251 eat_whitespace(p, os, context, false);
4252 output_ert_inset(os, arg + '{', context);
4253 parse_text(p, os, FLAG_ITEM, outer, context);
4254 output_ert_inset(os, "}", context);
4256 //the syntax is: \makebox[width][position]{content}
4257 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4261 else if (t.cs() == "smallskip" ||
4262 t.cs() == "medskip" ||
4263 t.cs() == "bigskip" ||
4264 t.cs() == "vfill") {
4265 context.check_layout(os);
4266 begin_inset(os, "VSpace ");
4269 skip_spaces_braces(p);
4272 else if ((where = is_known(t.cs(), known_spaces))) {
4273 context.check_layout(os);
4274 begin_inset(os, "space ");
4275 os << '\\' << known_coded_spaces[where - known_spaces]
4278 // LaTeX swallows whitespace after all spaces except
4279 // "\\,". We have to do that here, too, because LyX
4280 // adds "{}" which would make the spaces significant.
4282 eat_whitespace(p, os, context, false);
4283 // LyX adds "{}" after all spaces except "\\ " and
4284 // "\\,", so we have to remove "{}".
4285 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4286 // remove the braces after "\\,", too.
4291 else if (t.cs() == "newpage" ||
4292 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4293 t.cs() == "clearpage" ||
4294 t.cs() == "cleardoublepage") {
4295 context.check_layout(os);
4296 begin_inset(os, "Newpage ");
4299 skip_spaces_braces(p);
4302 else if (t.cs() == "DeclareRobustCommand" ||
4303 t.cs() == "DeclareRobustCommandx" ||
4304 t.cs() == "newcommand" ||
4305 t.cs() == "newcommandx" ||
4306 t.cs() == "providecommand" ||
4307 t.cs() == "providecommandx" ||
4308 t.cs() == "renewcommand" ||
4309 t.cs() == "renewcommandx") {
4310 // DeclareRobustCommand, DeclareRobustCommandx,
4311 // providecommand and providecommandx could be handled
4312 // by parse_command(), but we need to call
4313 // add_known_command() here.
4314 string name = t.asInput();
4315 if (p.next_token().asInput() == "*") {
4316 // Starred form. Eat '*'
4320 string const command = p.verbatim_item();
4321 string const opt1 = p.getFullOpt();
4322 string const opt2 = p.getFullOpt();
4323 add_known_command(command, opt1, !opt2.empty());
4324 string const ert = name + '{' + command + '}' +
4326 '{' + p.verbatim_item() + '}';
4328 if (t.cs() == "DeclareRobustCommand" ||
4329 t.cs() == "DeclareRobustCommandx" ||
4330 t.cs() == "providecommand" ||
4331 t.cs() == "providecommandx" ||
4332 name[name.length()-1] == '*')
4333 output_ert_inset(os, ert, context);
4335 context.check_layout(os);
4336 begin_inset(os, "FormulaMacro");
4342 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4343 // let could be handled by parse_command(),
4344 // but we need to call add_known_command() here.
4345 string ert = t.asInput();
4348 if (p.next_token().cat() == catBegin) {
4349 name = p.verbatim_item();
4350 ert += '{' + name + '}';
4352 name = p.verbatim_item();
4357 if (p.next_token().cat() == catBegin) {
4358 command = p.verbatim_item();
4359 ert += '{' + command + '}';
4361 command = p.verbatim_item();
4364 // If command is known, make name known too, to parse
4365 // its arguments correctly. For this reason we also
4366 // have commands in syntax.default that are hardcoded.
4367 CommandMap::iterator it = known_commands.find(command);
4368 if (it != known_commands.end())
4369 known_commands[t.asInput()] = it->second;
4370 output_ert_inset(os, ert, context);
4373 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4374 bool starred = false;
4375 if (p.next_token().asInput() == "*") {
4379 string name = t.asInput();
4380 string const length = p.verbatim_item();
4383 bool valid = splitLatexLength(length, valstring, unit);
4384 bool known_hspace = false;
4385 bool known_vspace = false;
4386 bool known_unit = false;
4389 istringstream iss(valstring);
4392 if (t.cs()[0] == 'h') {
4393 if (unit == "\\fill") {
4398 known_hspace = true;
4401 if (unit == "\\smallskipamount") {
4403 known_vspace = true;
4404 } else if (unit == "\\medskipamount") {
4406 known_vspace = true;
4407 } else if (unit == "\\bigskipamount") {
4409 known_vspace = true;
4410 } else if (unit == "\\fill") {
4412 known_vspace = true;
4416 if (!known_hspace && !known_vspace) {
4417 switch (unitFromString(unit)) {
4438 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4439 // Literal horizontal length or known variable
4440 context.check_layout(os);
4441 begin_inset(os, "space ");
4449 if (known_unit && !known_hspace)
4451 << translate_len(length);
4453 } else if (known_unit || known_vspace) {
4454 // Literal vertical length or known variable
4455 context.check_layout(os);
4456 begin_inset(os, "VSpace ");
4464 // LyX can't handle other length variables in Inset VSpace/space
4469 output_ert_inset(os, name + '{' + unit + '}', context);
4470 else if (value == -1.0)
4471 output_ert_inset(os, name + "{-" + unit + '}', context);
4473 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4475 output_ert_inset(os, name + '{' + length + '}', context);
4479 // The single '=' is meant here.
4480 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4482 context.check_layout(os);
4483 begin_inset(os, "Flex ");
4484 os << to_utf8(newinsetlayout->name()) << '\n'
4485 << "status collapsed\n";
4486 if (newinsetlayout->isPassThru()) {
4487 // set catcodes to verbatim early, just in case.
4488 p.setCatcodes(VERBATIM_CATCODES);
4489 string delim = p.get_token().asInput();
4491 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4492 string const arg = p.verbatimStuff("}");
4493 Context newcontext(true, context.textclass);
4494 if (newinsetlayout->forcePlainLayout())
4495 newcontext.layout = &context.textclass.plainLayout();
4496 output_ert(os, arg, newcontext);
4499 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4503 else if (t.cs() == "includepdf") {
4505 string const arg = p.getArg('[', ']');
4506 map<string, string> opts;
4507 vector<string> keys;
4508 split_map(arg, opts, keys);
4509 string name = normalize_filename(p.verbatim_item());
4510 string const path = getMasterFilePath(true);
4511 // We want to preserve relative / absolute filenames,
4512 // therefore path is only used for testing
4513 if (!makeAbsPath(name, path).exists()) {
4514 // The file extension is probably missing.
4515 // Now try to find it out.
4516 char const * const pdfpages_format[] = {"pdf", 0};
4517 string const pdftex_name =
4518 find_file(name, path, pdfpages_format);
4519 if (!pdftex_name.empty()) {
4524 FileName const absname = makeAbsPath(name, path);
4525 if (absname.exists())
4527 fix_child_filename(name);
4528 copy_file(absname, name);
4530 cerr << "Warning: Could not find file '"
4531 << name << "'." << endl;
4533 context.check_layout(os);
4534 begin_inset(os, "External\n\ttemplate ");
4535 os << "PDFPages\n\tfilename "
4537 // parse the options
4538 if (opts.find("pages") != opts.end())
4539 os << "\textra LaTeX \"pages="
4540 << opts["pages"] << "\"\n";
4541 if (opts.find("angle") != opts.end())
4542 os << "\trotateAngle "
4543 << opts["angle"] << '\n';
4544 if (opts.find("origin") != opts.end()) {
4546 string const opt = opts["origin"];
4547 if (opt == "tl") ss << "topleft";
4548 if (opt == "bl") ss << "bottomleft";
4549 if (opt == "Bl") ss << "baselineleft";
4550 if (opt == "c") ss << "center";
4551 if (opt == "tc") ss << "topcenter";
4552 if (opt == "bc") ss << "bottomcenter";
4553 if (opt == "Bc") ss << "baselinecenter";
4554 if (opt == "tr") ss << "topright";
4555 if (opt == "br") ss << "bottomright";
4556 if (opt == "Br") ss << "baselineright";
4557 if (!ss.str().empty())
4558 os << "\trotateOrigin " << ss.str() << '\n';
4560 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4562 if (opts.find("width") != opts.end())
4564 << translate_len(opts["width"]) << '\n';
4565 if (opts.find("height") != opts.end())
4567 << translate_len(opts["height"]) << '\n';
4568 if (opts.find("keepaspectratio") != opts.end())
4569 os << "\tkeepAspectRatio\n";
4571 context.check_layout(os);
4572 registerExternalTemplatePackages("PDFPages");
4575 else if (t.cs() == "loadgame") {
4577 string name = normalize_filename(p.verbatim_item());
4578 string const path = getMasterFilePath(true);
4579 // We want to preserve relative / absolute filenames,
4580 // therefore path is only used for testing
4581 if (!makeAbsPath(name, path).exists()) {
4582 // The file extension is probably missing.
4583 // Now try to find it out.
4584 char const * const lyxskak_format[] = {"fen", 0};
4585 string const lyxskak_name =
4586 find_file(name, path, lyxskak_format);
4587 if (!lyxskak_name.empty())
4588 name = lyxskak_name;
4590 FileName const absname = makeAbsPath(name, path);
4591 if (absname.exists())
4593 fix_child_filename(name);
4594 copy_file(absname, name);
4596 cerr << "Warning: Could not find file '"
4597 << name << "'." << endl;
4598 context.check_layout(os);
4599 begin_inset(os, "External\n\ttemplate ");
4600 os << "ChessDiagram\n\tfilename "
4603 context.check_layout(os);
4604 // after a \loadgame follows a \showboard
4605 if (p.get_token().asInput() == "showboard")
4607 registerExternalTemplatePackages("ChessDiagram");
4611 // try to see whether the string is in unicodesymbols
4612 // Only use text mode commands, since we are in text mode here,
4613 // and math commands may be invalid (bug 6797)
4617 string name = t.asInput();
4618 // handle some TIPA special characters
4619 if (name == "\\textglobfall") {
4623 if (name == "\\textdoublevertline") {
4624 name = "\\textbardbl";
4627 if (name == "\\!" ) {
4628 if (p.next_token().asInput() == "b") {
4629 p.get_token(); // eat 'b'
4633 if (p.next_token().asInput() == "d") {
4638 if (p.next_token().asInput() == "g") {
4643 if (p.next_token().asInput() == "G") {
4645 name = "\\texthtscg";
4648 if (p.next_token().asInput() == "j") {
4650 name = "\\texthtbardotlessj";
4653 if (p.next_token().asInput() == "o") {
4655 name = "\\textbullseye";
4659 if (name == "\\*" ) {
4660 if (p.next_token().asInput() == "k") {
4662 name = "\\textturnk";
4665 if (p.next_token().asInput() == "r") {
4666 p.get_token(); // eat 'b'
4667 name = "\\textturnr";
4670 if (p.next_token().asInput() == "t") {
4672 name = "\\textturnt";
4675 if (p.next_token().asInput() == "w") {
4677 name = "\\textturnw";
4681 // now get the character from unicodesymbols
4682 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4683 Encodings::TEXT_CMD, termination, rem, &req);
4686 cerr << "When parsing " << t.cs()
4687 << ", result is " << to_utf8(s)
4688 << "+" << to_utf8(rem) << endl;
4689 context.check_layout(os);
4692 skip_spaces_braces(p);
4693 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4694 preamble.registerAutomaticallyLoadedPackage(*it);
4696 //cerr << "#: " << t << " mode: " << mode << endl;
4697 // heuristic: read up to next non-nested space
4699 string s = t.asInput();
4700 string z = p.verbatim_item();
4701 while (p.good() && z != " " && !z.empty()) {
4702 //cerr << "read: " << z << endl;
4704 z = p.verbatim_item();
4706 cerr << "found ERT: " << s << endl;
4707 output_ert_inset(os, s + ' ', context);
4710 string name = t.asInput();
4711 if (p.next_token().asInput() == "*") {
4712 // Starred commands like \vspace*{}
4713 p.get_token(); // Eat '*'
4716 if (!parse_command(name, p, os, outer, context))
4717 output_ert_inset(os, name, context);
4721 if (flags & FLAG_LEAVE) {
4722 flags &= ~FLAG_LEAVE;
4729 string guessLanguage(Parser & p, string const & lang)
4731 typedef std::map<std::string, size_t> LangMap;
4732 // map from language names to number of characters
4735 for (char const * const * i = supported_CJK_languages; *i; i++)
4736 used[string(*i)] = 0;
4739 Token const t = p.get_token();
4740 // comments are not counted for any language
4741 if (t.cat() == catComment)
4743 // commands are not counted as well, but we need to detect
4744 // \begin{CJK} and switch encoding if needed
4745 if (t.cat() == catEscape) {
4746 if (t.cs() == "inputencoding") {
4747 string const enc = subst(p.verbatim_item(), "\n", " ");
4748 p.setEncoding(enc, Encoding::inputenc);
4751 if (t.cs() != "begin")
4754 // Non-CJK content is counted for lang.
4755 // We do not care about the real language here:
4756 // If we have more non-CJK contents than CJK contents,
4757 // we simply use the language that was specified as
4758 // babel main language.
4759 used[lang] += t.asInput().length();
4762 // Now we are starting an environment
4764 string const name = p.getArg('{', '}');
4765 if (name != "CJK") {
4769 // It is a CJK environment
4771 /* name = */ p.getArg('{', '}');
4772 string const encoding = p.getArg('{', '}');
4773 /* mapping = */ p.getArg('{', '}');
4774 string const encoding_old = p.getEncoding();
4775 char const * const * const where =
4776 is_known(encoding, supported_CJK_encodings);
4778 p.setEncoding(encoding, Encoding::CJK);
4780 p.setEncoding("UTF-8");
4781 string const text = p.ertEnvironment("CJK");
4782 p.setEncoding(encoding_old);
4785 // ignore contents in unknown CJK encoding
4788 // the language of the text
4790 supported_CJK_languages[where - supported_CJK_encodings];
4791 used[cjk] += text.length();
4793 LangMap::const_iterator use = used.begin();
4794 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4795 if (it->second > use->second)