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", "nameref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "nameref", "eqref", 0 };
120 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
121 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
122 "secref", "subref", "tabref", "thmref", 0 };
124 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
125 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
126 "sec", "sub", "tab", "thm", 0 };
130 * supported CJK encodings
131 * JIS does not work with LyX's encoding conversion
133 const char * const supported_CJK_encodings[] = {
134 "EUC-JP", "KS", "GB", "UTF8",
135 "Bg5", /*"JIS",*/ "SJIS", 0};
138 * the same as supported_CJK_encodings with their corresponding LyX language name
139 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
141 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
142 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
143 * please keep this in sync with supported_CJK_encodings line by line!
145 const char * const supported_CJK_languages[] = {
146 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
147 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
151 * The starred forms are also known except for "citefullauthor",
152 * "citeyear" and "citeyearpar".
154 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
155 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
156 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
160 * No starred form other than "cite*" known.
162 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
163 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
164 // jurabib commands not (yet) supported by LyX:
166 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
167 // "footciteauthor", "footciteyear", "footciteyearpar",
168 "citefield", "citetitle", 0 };
170 /// LaTeX names for quotes
171 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
172 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
173 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
174 "guilsinglleft", "frq", "guilsinglright", 0};
176 /// the same as known_quotes with .lyx names
177 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
178 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
179 "gld", "grd", "gls", "ers", "fls",
180 "fls", "frs", "frs", 0};
182 /// LaTeX names for font sizes
183 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
184 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
186 /// the same as known_sizes with .lyx names
187 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
188 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
190 /// LaTeX 2.09 names for font families
191 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
193 /// LaTeX names for font families
194 char const * const known_font_families[] = { "rmfamily", "sffamily",
197 /// LaTeX names for font family changing commands
198 char const * const known_text_font_families[] = { "textrm", "textsf",
201 /// The same as known_old_font_families, known_font_families and
202 /// known_text_font_families with .lyx names
203 char const * const known_coded_font_families[] = { "roman", "sans",
206 /// LaTeX 2.09 names for font series
207 char const * const known_old_font_series[] = { "bf", 0};
209 /// LaTeX names for font series
210 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
212 /// LaTeX names for font series changing commands
213 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
215 /// The same as known_old_font_series, known_font_series and
216 /// known_text_font_series with .lyx names
217 char const * const known_coded_font_series[] = { "bold", "medium", 0};
219 /// LaTeX 2.09 names for font shapes
220 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
222 /// LaTeX names for font shapes
223 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
226 /// LaTeX names for font shape changing commands
227 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
230 /// The same as known_old_font_shapes, known_font_shapes and
231 /// known_text_font_shapes with .lyx names
232 char const * const known_coded_font_shapes[] = { "italic", "slanted",
233 "smallcaps", "up", 0};
235 /// Known special characters which need skip_spaces_braces() afterwards
236 char const * const known_special_chars[] = {"ldots",
237 "lyxarrow", "textcompwordmark",
238 "slash", "textasciitilde", "textasciicircum", "textbackslash", 0};
240 /// the same as known_special_chars with .lyx names
241 char const * const known_coded_special_chars[] = {"\\SpecialChar \\ldots{}\n",
242 "\\SpecialChar \\menuseparator\n", "\\SpecialChar \\textcompwordmark{}\n",
243 "\\SpecialChar \\slash{}\n", "~", "^", "\n\\backslash\n", 0};
246 * Graphics file extensions known by the dvips driver of the graphics package.
247 * These extensions are used to complete the filename of an included
248 * graphics file if it does not contain an extension.
249 * The order must be the same that latex uses to find a file, because we
250 * will use the first extension that matches.
251 * This is only an approximation for the common cases. If we would want to
252 * do it right in all cases, we would need to know which graphics driver is
253 * used and know the extensions of every driver of the graphics package.
255 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
256 "ps.gz", "eps.Z", "ps.Z", 0};
259 * Graphics file extensions known by the pdftex driver of the graphics package.
260 * \sa known_dvips_graphics_formats
262 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
266 * Known file extensions for TeX files as used by \\include.
268 char const * const known_tex_extensions[] = {"tex", 0};
270 /// spaces known by InsetSpace
271 char const * const known_spaces[] = { " ", "space", ",",
272 "thinspace", "quad", "qquad", "enspace", "enskip",
273 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
274 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
275 "upbracefill", "downbracefill", 0};
277 /// the same as known_spaces with .lyx names
278 char const * const known_coded_spaces[] = { "space{}", "space{}",
279 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
280 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
281 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
282 "upbracefill{}", "downbracefill{}", 0};
284 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
285 /// them in ERT. "LaTeXe" must come before "LaTeX"!
286 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
287 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
288 int const known_phrase_lengths[] = {3, 5, 7, 0};
290 /// known TIPA combining diacritical marks
291 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
292 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
293 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
294 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
295 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
296 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
299 /// TIPA tones that need special handling
300 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
302 // string to store the float type to be able to determine the type of subfloats
303 string float_type = "";
306 /// splits "x=z, y=b" into a map and an ordered keyword vector
307 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
312 keys.resize(v.size());
313 for (size_t i = 0; i < v.size(); ++i) {
314 size_t const pos = v[i].find('=');
315 string const index = trimSpaceAndEol(v[i].substr(0, pos));
316 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
324 * Split a LaTeX length into value and unit.
325 * The latter can be a real unit like "pt", or a latex length variable
326 * like "\textwidth". The unit may contain additional stuff like glue
327 * lengths, but we don't care, because such lengths are ERT anyway.
328 * \returns true if \p value and \p unit are valid.
330 bool splitLatexLength(string const & len, string & value, string & unit)
334 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
335 //'4,5' is a valid LaTeX length number. Change it to '4.5'
336 string const length = subst(len, ',', '.');
337 if (i == string::npos)
340 if (len[0] == '\\') {
341 // We had something like \textwidth without a factor
347 value = trimSpaceAndEol(string(length, 0, i));
351 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
352 if (contains(len, '\\'))
353 unit = trimSpaceAndEol(string(len, i));
355 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
360 /// A simple function to translate a latex length to something LyX can
361 /// understand. Not perfect, but rather best-effort.
362 bool translate_len(string const & length, string & valstring, string & unit)
364 if (!splitLatexLength(length, valstring, unit))
366 // LyX uses percent values
368 istringstream iss(valstring);
373 string const percentval = oss.str();
375 if (unit.empty() || unit[0] != '\\')
377 string::size_type const i = unit.find(' ');
378 string const endlen = (i == string::npos) ? string() : string(unit, i);
379 if (unit == "\\textwidth") {
380 valstring = percentval;
381 unit = "text%" + endlen;
382 } else if (unit == "\\columnwidth") {
383 valstring = percentval;
384 unit = "col%" + endlen;
385 } else if (unit == "\\paperwidth") {
386 valstring = percentval;
387 unit = "page%" + endlen;
388 } else if (unit == "\\linewidth") {
389 valstring = percentval;
390 unit = "line%" + endlen;
391 } else if (unit == "\\paperheight") {
392 valstring = percentval;
393 unit = "pheight%" + endlen;
394 } else if (unit == "\\textheight") {
395 valstring = percentval;
396 unit = "theight%" + endlen;
404 string translate_len(string const & length)
408 if (translate_len(length, value, unit))
410 // If the input is invalid, return what we have.
418 * Translates a LaTeX length into \p value, \p unit and
419 * \p special parts suitable for a box inset.
420 * The difference from translate_len() is that a box inset knows about
421 * some special "units" that are stored in \p special.
423 void translate_box_len(string const & length, string & value, string & unit, string & special)
425 if (translate_len(length, value, unit)) {
426 if (unit == "\\height" || unit == "\\depth" ||
427 unit == "\\totalheight" || unit == "\\width") {
428 special = unit.substr(1);
429 // The unit is not used, but LyX requires a dummy setting
442 * Find a file with basename \p name in path \p path and an extension
445 string find_file(string const & name, string const & path,
446 char const * const * extensions)
448 for (char const * const * what = extensions; *what; ++what) {
449 string const trial = addExtension(name, *what);
450 if (makeAbsPath(trial, path).exists())
457 void begin_inset(ostream & os, string const & name)
459 os << "\n\\begin_inset " << name;
463 void begin_command_inset(ostream & os, string const & name,
464 string const & latexname)
466 begin_inset(os, "CommandInset ");
467 os << name << "\nLatexCommand " << latexname << '\n';
471 void end_inset(ostream & os)
473 os << "\n\\end_inset\n\n";
477 bool skip_braces(Parser & p)
479 if (p.next_token().cat() != catBegin)
482 if (p.next_token().cat() == catEnd) {
491 /// replace LaTeX commands in \p s from the unicodesymbols file with their
493 docstring convert_unicodesymbols(docstring s)
496 for (size_t i = 0; i < s.size();) {
505 docstring parsed = encodings.fromLaTeXCommand(s,
506 Encodings::TEXT_CMD, termination, rem, &req);
507 set<string>::const_iterator it = req.begin();
508 set<string>::const_iterator en = req.end();
509 for (; it != en; ++it)
510 preamble.registerAutomaticallyLoadedPackage(*it);
513 if (s.empty() || s[0] != '\\')
522 /// try to convert \p s to a valid InsetCommand argument
523 string convert_command_inset_arg(string s)
526 // since we don't know the input encoding we can't use from_utf8
527 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
528 // LyX cannot handle newlines in a latex command
529 return subst(s, "\n", " ");
533 void output_ert(ostream & os, string const & s, Context & context)
535 context.check_layout(os);
536 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
538 os << "\n\\backslash\n";
539 else if (*it == '\n') {
540 context.new_paragraph(os);
541 context.check_layout(os);
545 context.check_end_layout(os);
549 void output_ert_inset(ostream & os, string const & s, Context & context)
551 // We must have a valid layout before outputting the ERT inset.
552 context.check_layout(os);
553 Context newcontext(true, context.textclass);
554 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
555 if (layout.forcePlainLayout())
556 newcontext.layout = &context.textclass.plainLayout();
557 begin_inset(os, "ERT");
558 os << "\nstatus collapsed\n";
559 output_ert(os, s, newcontext);
564 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
566 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
569 if (checkModule(name, command))
570 return findLayoutWithoutModule(textclass, name, command);
575 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
577 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
580 if (checkModule(name, command))
581 return findInsetLayoutWithoutModule(textclass, name, command);
586 void eat_whitespace(Parser &, ostream &, Context &, bool);
590 * Skips whitespace and braces.
591 * This should be called after a command has been parsed that is not put into
592 * ERT, and where LyX adds "{}" if needed.
594 void skip_spaces_braces(Parser & p, bool keepws = false)
596 /* The following four examples produce the same typeset output and
597 should be handled by this function:
605 // Unfortunately we need to skip comments, too.
606 // We can't use eat_whitespace since writing them after the {}
607 // results in different output in some cases.
608 bool const skipped_spaces = p.skip_spaces(true);
609 bool const skipped_braces = skip_braces(p);
610 if (keepws && skipped_spaces && !skipped_braces)
611 // put back the space (it is better handled by check_space)
612 p.unskip_spaces(true);
616 void output_command_layout(ostream & os, Parser & p, bool outer,
617 Context & parent_context,
618 Layout const * newlayout)
620 TeXFont const oldFont = parent_context.font;
621 // save the current font size
622 string const size = oldFont.size;
623 // reset the font size to default, because the font size switches
624 // don't affect section headings and the like
625 parent_context.font.size = Context::normalfont.size;
626 // we only need to write the font change if we have an open layout
627 if (!parent_context.atParagraphStart())
628 output_font_change(os, oldFont, parent_context.font);
629 parent_context.check_end_layout(os);
630 Context context(true, parent_context.textclass, newlayout,
631 parent_context.layout, parent_context.font);
632 if (parent_context.deeper_paragraph) {
633 // We are beginning a nested environment after a
634 // deeper paragraph inside the outer list environment.
635 // Therefore we don't need to output a "begin deeper".
636 context.need_end_deeper = true;
638 context.check_deeper(os);
639 context.check_layout(os);
640 Layout::LaTeXArgMap::const_iterator lait = context.layout->latexargs().begin();
641 Layout::LaTeXArgMap::const_iterator const laend = context.layout->latexargs().end();
642 for (; lait != laend; ++lait) {
643 eat_whitespace(p, os, context, false);
644 if (lait->second.mandatory) {
645 if (p.next_token().cat() != catBegin)
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_BRACE_LAST, outer, context);
658 if (p.next_token().cat() == catEscape ||
659 p.next_token().character() != '[')
661 p.get_token(); // eat '['
662 // FIXME: Just a workaround. InsetArgument::updateBuffer
663 // will compute a proper ID for all "999" Arguments
664 // (which is also what lyx2lyx produces).
665 // However, tex2lyx should be able to output proper IDs
667 begin_inset(os, "Argument 999\n");
668 os << "status collapsed\n\n";
669 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
672 eat_whitespace(p, os, context, false);
674 parse_text(p, os, FLAG_ITEM, outer, context);
675 context.check_end_layout(os);
676 if (parent_context.deeper_paragraph) {
677 // We must suppress the "end deeper" because we
678 // suppressed the "begin deeper" above.
679 context.need_end_deeper = false;
681 context.check_end_deeper(os);
682 // We don't need really a new paragraph, but
683 // we must make sure that the next item gets a \begin_layout.
684 parent_context.new_paragraph(os);
685 // Set the font size to the original value. No need to output it here
686 // (Context::begin_layout() will do that if needed)
687 parent_context.font.size = size;
692 * Output a space if necessary.
693 * This function gets called for every whitespace token.
695 * We have three cases here:
696 * 1. A space must be suppressed. Example: The lyxcode case below
697 * 2. A space may be suppressed. Example: Spaces before "\par"
698 * 3. A space must not be suppressed. Example: A space between two words
700 * We currently handle only 1. and 3 and from 2. only the case of
701 * spaces before newlines as a side effect.
703 * 2. could be used to suppress as many spaces as possible. This has two effects:
704 * - Reimporting LyX generated LaTeX files changes almost no whitespace
705 * - Superflous whitespace from non LyX generated LaTeX files is removed.
706 * The drawback is that the logic inside the function becomes
707 * complicated, and that is the reason why it is not implemented.
709 void check_space(Parser & p, ostream & os, Context & context)
711 Token const next = p.next_token();
712 Token const curr = p.curr_token();
713 // A space before a single newline and vice versa must be ignored
714 // LyX emits a newline before \end{lyxcode}.
715 // This newline must be ignored,
716 // otherwise LyX will add an additional protected space.
717 if (next.cat() == catSpace ||
718 next.cat() == catNewline ||
719 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
722 context.check_layout(os);
728 * Parse all arguments of \p command
730 void parse_arguments(string const & command,
731 vector<ArgumentType> const & template_arguments,
732 Parser & p, ostream & os, bool outer, Context & context)
734 string ert = command;
735 size_t no_arguments = template_arguments.size();
736 for (size_t i = 0; i < no_arguments; ++i) {
737 switch (template_arguments[i]) {
740 // This argument contains regular LaTeX
741 output_ert_inset(os, ert + '{', context);
742 eat_whitespace(p, os, context, false);
743 if (template_arguments[i] == required)
744 parse_text(p, os, FLAG_ITEM, outer, context);
746 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
750 // This argument consists only of a single item.
751 // The presence of '{' or not must be preserved.
753 if (p.next_token().cat() == catBegin)
754 ert += '{' + p.verbatim_item() + '}';
756 ert += p.verbatim_item();
760 // This argument may contain special characters
761 ert += '{' + p.verbatim_item() + '}';
765 // true because we must not eat whitespace
766 // if an optional arg follows we must not strip the
767 // brackets from this one
768 if (i < no_arguments - 1 &&
769 template_arguments[i+1] == optional)
770 ert += p.getFullOpt(true);
772 ert += p.getOpt(true);
776 output_ert_inset(os, ert, context);
781 * Check whether \p command is a known command. If yes,
782 * handle the command with all arguments.
783 * \return true if the command was parsed, false otherwise.
785 bool parse_command(string const & command, Parser & p, ostream & os,
786 bool outer, Context & context)
788 if (known_commands.find(command) != known_commands.end()) {
789 parse_arguments(command, known_commands[command], p, os,
797 /// Parses a minipage or parbox
798 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
799 unsigned inner_flags, bool outer, Context & parent_context,
800 string const & outer_type, string const & special,
801 string const & inner_type)
805 string hor_pos = "c";
806 // We need to set the height to the LaTeX default of 1\\totalheight
807 // for the case when no height argument is given
808 string height_value = "1";
809 string height_unit = "in";
810 string height_special = "totalheight";
815 string width_special = "none";
816 if (!inner_type.empty() && p.hasOpt()) {
817 if (inner_type != "makebox")
818 position = p.getArg('[', ']');
820 latex_width = p.getArg('[', ']');
821 translate_box_len(latex_width, width_value, width_unit, width_special);
824 if (position != "t" && position != "c" && position != "b") {
825 cerr << "invalid position " << position << " for "
826 << inner_type << endl;
830 if (inner_type != "makebox") {
831 latex_height = p.getArg('[', ']');
832 translate_box_len(latex_height, height_value, height_unit, height_special);
834 string const opt = p.getArg('[', ']');
837 if (hor_pos != "l" && hor_pos != "c" &&
838 hor_pos != "r" && hor_pos != "s") {
839 cerr << "invalid hor_pos " << hor_pos
840 << " for " << inner_type << endl;
847 inner_pos = p.getArg('[', ']');
848 if (inner_pos != "c" && inner_pos != "t" &&
849 inner_pos != "b" && inner_pos != "s") {
850 cerr << "invalid inner_pos "
851 << inner_pos << " for "
852 << inner_type << endl;
853 inner_pos = position;
858 if (inner_type.empty()) {
859 if (special.empty() && outer_type != "framebox")
860 latex_width = "1\\columnwidth";
863 latex_width = p2.getArg('[', ']');
864 string const opt = p2.getArg('[', ']');
867 if (hor_pos != "l" && hor_pos != "c" &&
868 hor_pos != "r" && hor_pos != "s") {
869 cerr << "invalid hor_pos " << hor_pos
870 << " for " << outer_type << endl;
875 } else if (inner_type != "makebox")
876 latex_width = p.verbatim_item();
877 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
878 // as this is LyX's standard for such cases (except for makebox)
879 // \framebox is more special and handled below
880 if (latex_width.empty() && inner_type != "makebox"
881 && outer_type != "framebox")
882 latex_width = "1\\columnwidth";
884 translate_len(latex_width, width_value, width_unit);
886 bool shadedparbox = false;
887 if (inner_type == "shaded") {
888 eat_whitespace(p, os, parent_context, false);
889 if (outer_type == "parbox") {
891 if (p.next_token().cat() == catBegin)
893 eat_whitespace(p, os, parent_context, false);
899 // If we already read the inner box we have to push the inner env
900 if (!outer_type.empty() && !inner_type.empty() &&
901 (inner_flags & FLAG_END))
902 active_environments.push_back(inner_type);
903 // LyX can't handle length variables
904 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
905 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
906 // Look whether there is some content after the end of the
907 // inner box, but before the end of the outer box.
908 // If yes, we need to output ERT.
910 if (inner_flags & FLAG_END)
911 p.ertEnvironment(inner_type);
915 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
916 if ((outer_env && p.next_token().asInput() != "\\end") ||
917 (!outer_env && p.next_token().cat() != catEnd)) {
918 // something is between the end of the inner box and
919 // the end of the outer box, so we need to use ERT.
924 // if only \makebox{content} was used we can set its width to 1\width
925 // because this identic and also identic to \mbox
926 // this doesn't work for \framebox{content}, thus we have to use ERT for this
927 if (latex_width.empty() && inner_type == "makebox") {
930 width_special = "width";
931 } else if (latex_width.empty() && outer_type == "framebox") {
934 width_special = "none";
938 if (!outer_type.empty()) {
939 if (outer_flags & FLAG_END)
940 ss << "\\begin{" << outer_type << '}';
942 ss << '\\' << outer_type << '{';
943 if (!special.empty())
947 if (!inner_type.empty()) {
948 if (inner_type != "shaded") {
949 if (inner_flags & FLAG_END)
950 ss << "\\begin{" << inner_type << '}';
952 ss << '\\' << inner_type;
954 if (!position.empty())
955 ss << '[' << position << ']';
956 if (!latex_height.empty())
957 ss << '[' << latex_height << ']';
958 if (!inner_pos.empty())
959 ss << '[' << inner_pos << ']';
960 ss << '{' << latex_width << '}';
961 if (!(inner_flags & FLAG_END))
964 if (inner_type == "shaded")
965 ss << "\\begin{shaded}";
966 output_ert_inset(os, ss.str(), parent_context);
967 if (!inner_type.empty()) {
968 parse_text(p, os, inner_flags, outer, parent_context);
969 if (inner_flags & FLAG_END)
970 output_ert_inset(os, "\\end{" + inner_type + '}',
973 output_ert_inset(os, "}", parent_context);
975 if (!outer_type.empty()) {
976 // If we already read the inner box we have to pop
978 if (!inner_type.empty() && (inner_flags & FLAG_END))
979 active_environments.pop_back();
981 // Ensure that the end of the outer box is parsed correctly:
982 // The opening brace has been eaten by parse_outer_box()
983 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
984 outer_flags &= ~FLAG_ITEM;
985 outer_flags |= FLAG_BRACE_LAST;
987 parse_text(p, os, outer_flags, outer, parent_context);
988 if (outer_flags & FLAG_END)
989 output_ert_inset(os, "\\end{" + outer_type + '}',
992 output_ert_inset(os, "}", parent_context);
995 // LyX does not like empty positions, so we have
996 // to set them to the LaTeX default values here.
997 if (position.empty())
999 if (inner_pos.empty())
1000 inner_pos = position;
1001 parent_context.check_layout(os);
1002 begin_inset(os, "Box ");
1003 if (outer_type == "framed")
1005 else if (outer_type == "framebox" || outer_type == "fbox")
1007 else if (outer_type == "shadowbox")
1008 os << "Shadowbox\n";
1009 else if ((outer_type == "shaded" && inner_type.empty()) ||
1010 (outer_type == "minipage" && inner_type == "shaded") ||
1011 (outer_type == "parbox" && inner_type == "shaded")) {
1013 preamble.registerAutomaticallyLoadedPackage("color");
1014 } else if (outer_type == "doublebox")
1015 os << "Doublebox\n";
1016 else if (outer_type.empty() || outer_type == "mbox")
1017 os << "Frameless\n";
1019 os << outer_type << '\n';
1020 os << "position \"" << position << "\"\n";
1021 os << "hor_pos \"" << hor_pos << "\"\n";
1022 if (outer_type == "mbox")
1023 os << "has_inner_box 1\n";
1025 os << "has_inner_box " << !inner_type.empty() << "\n";
1026 os << "inner_pos \"" << inner_pos << "\"\n";
1027 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1029 if (outer_type == "mbox")
1030 os << "use_makebox 1\n";
1032 os << "use_makebox " << (inner_type == "makebox") << '\n';
1033 if (outer_type == "fbox" || outer_type == "mbox")
1034 os << "width \"\"\n";
1036 os << "width \"" << width_value << width_unit << "\"\n";
1037 os << "special \"" << width_special << "\"\n";
1038 os << "height \"" << height_value << height_unit << "\"\n";
1039 os << "height_special \"" << height_special << "\"\n";
1040 os << "status open\n\n";
1042 // Unfortunately we can't use parse_text_in_inset:
1043 // InsetBox::forcePlainLayout() is hard coded and does not
1044 // use the inset layout. Apart from that do we call parse_text
1045 // up to two times, but need only one check_end_layout.
1046 bool const forcePlainLayout =
1047 (!inner_type.empty() || inner_type == "makebox") &&
1048 outer_type != "shaded" && outer_type != "framed";
1049 Context context(true, parent_context.textclass);
1050 if (forcePlainLayout)
1051 context.layout = &context.textclass.plainLayout();
1053 context.font = parent_context.font;
1055 // If we have no inner box the contents will be read with the outer box
1056 if (!inner_type.empty())
1057 parse_text(p, os, inner_flags, outer, context);
1059 // Ensure that the end of the outer box is parsed correctly:
1060 // The opening brace has been eaten by parse_outer_box()
1061 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1062 outer_flags &= ~FLAG_ITEM;
1063 outer_flags |= FLAG_BRACE_LAST;
1066 // Find end of outer box, output contents if inner_type is
1067 // empty and output possible comments
1068 if (!outer_type.empty()) {
1069 // If we already read the inner box we have to pop
1071 if (!inner_type.empty() && (inner_flags & FLAG_END))
1072 active_environments.pop_back();
1073 // This does not output anything but comments if
1074 // inner_type is not empty (see use_ert)
1075 parse_text(p, os, outer_flags, outer, context);
1078 context.check_end_layout(os);
1080 #ifdef PRESERVE_LAYOUT
1081 // LyX puts a % after the end of the minipage
1082 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1084 //output_ert_inset(os, "%dummy", parent_context);
1087 parent_context.new_paragraph(os);
1089 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1090 //output_ert_inset(os, "%dummy", parent_context);
1093 // We add a protected space if something real follows
1094 if (p.good() && p.next_token().cat() != catComment) {
1095 begin_inset(os, "space ~\n");
1104 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1105 Context & parent_context, string const & outer_type,
1106 string const & special)
1108 eat_whitespace(p, os, parent_context, false);
1109 if (flags & FLAG_ITEM) {
1111 if (p.next_token().cat() == catBegin)
1114 cerr << "Warning: Ignoring missing '{' after \\"
1115 << outer_type << '.' << endl;
1116 eat_whitespace(p, os, parent_context, false);
1119 unsigned int inner_flags = 0;
1121 if (outer_type == "minipage" || outer_type == "parbox") {
1122 p.skip_spaces(true);
1123 while (p.hasOpt()) {
1125 p.skip_spaces(true);
1128 p.skip_spaces(true);
1129 if (outer_type == "parbox") {
1131 if (p.next_token().cat() == catBegin)
1133 p.skip_spaces(true);
1136 if (outer_type == "shaded" || outer_type == "fbox"
1137 || outer_type == "mbox") {
1138 // These boxes never have an inner box
1140 } else if (p.next_token().asInput() == "\\parbox") {
1141 inner = p.get_token().cs();
1142 inner_flags = FLAG_ITEM;
1143 } else if (p.next_token().asInput() == "\\begin") {
1144 // Is this a minipage or shaded box?
1147 inner = p.getArg('{', '}');
1149 if (inner == "minipage" || inner == "shaded")
1150 inner_flags = FLAG_END;
1155 if (inner_flags == FLAG_END) {
1156 if (inner != "shaded")
1160 eat_whitespace(p, os, parent_context, false);
1162 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1163 outer_type, special, inner);
1165 if (inner_flags == FLAG_ITEM) {
1167 eat_whitespace(p, os, parent_context, false);
1169 parse_box(p, os, flags, inner_flags, outer, parent_context,
1170 outer_type, special, inner);
1175 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1177 parent_context.check_layout(os);
1178 begin_inset(os, "listings\n");
1180 string arg = p.verbatimOption();
1181 os << "lstparams " << '"' << arg << '"' << '\n';
1182 if (arg.find("\\color") != string::npos)
1183 preamble.registerAutomaticallyLoadedPackage("color");
1186 os << "inline true\n";
1188 os << "inline false\n";
1189 os << "status collapsed\n";
1190 Context context(true, parent_context.textclass);
1191 context.layout = &parent_context.textclass.plainLayout();
1194 // set catcodes to verbatim early, just in case.
1195 p.setCatcodes(VERBATIM_CATCODES);
1196 string delim = p.get_token().asInput();
1197 //FIXME: handler error condition
1198 s = p.verbatimStuff(delim).second;
1199 // context.new_paragraph(os);
1201 s = p.verbatimEnvironment("lstlisting");
1202 output_ert(os, s, context);
1207 /// parse an unknown environment
1208 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1209 unsigned flags, bool outer,
1210 Context & parent_context)
1212 if (name == "tabbing")
1213 // We need to remember that we have to handle '\=' specially
1214 flags |= FLAG_TABBING;
1216 // We need to translate font changes and paragraphs inside the
1217 // environment to ERT if we have a non standard font.
1218 // Otherwise things like
1219 // \large\begin{foo}\huge bar\end{foo}
1221 bool const specialfont =
1222 (parent_context.font != parent_context.normalfont);
1223 bool const new_layout_allowed = parent_context.new_layout_allowed;
1225 parent_context.new_layout_allowed = false;
1226 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1227 parse_text_snippet(p, os, flags, outer, parent_context);
1228 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1230 parent_context.new_layout_allowed = new_layout_allowed;
1234 void parse_environment(Parser & p, ostream & os, bool outer,
1235 string & last_env, Context & parent_context)
1237 Layout const * newlayout;
1238 InsetLayout const * newinsetlayout = 0;
1239 string const name = p.getArg('{', '}');
1240 const bool is_starred = suffixIs(name, '*');
1241 string const unstarred_name = rtrim(name, "*");
1242 active_environments.push_back(name);
1244 if (is_math_env(name)) {
1245 parent_context.check_layout(os);
1246 begin_inset(os, "Formula ");
1247 os << "\\begin{" << name << "}";
1248 parse_math(p, os, FLAG_END, MATH_MODE);
1249 os << "\\end{" << name << "}";
1251 if (is_display_math_env(name)) {
1252 // Prevent the conversion of a line break to a space
1253 // (bug 7668). This does not change the output, but
1254 // looks ugly in LyX.
1255 eat_whitespace(p, os, parent_context, false);
1259 else if (is_known(name, preamble.polyglossia_languages)) {
1260 // We must begin a new paragraph if not already done
1261 if (! parent_context.atParagraphStart()) {
1262 parent_context.check_end_layout(os);
1263 parent_context.new_paragraph(os);
1265 // save the language in the context so that it is
1266 // handled by parse_text
1267 parent_context.font.language = preamble.polyglossia2lyx(name);
1268 parse_text(p, os, FLAG_END, outer, parent_context);
1269 // Just in case the environment is empty
1270 parent_context.extra_stuff.erase();
1271 // We must begin a new paragraph to reset the language
1272 parent_context.new_paragraph(os);
1276 else if (unstarred_name == "tabular" || name == "longtable") {
1277 eat_whitespace(p, os, parent_context, false);
1278 string width = "0pt";
1279 if (name == "tabular*") {
1280 width = lyx::translate_len(p.getArg('{', '}'));
1281 eat_whitespace(p, os, parent_context, false);
1283 parent_context.check_layout(os);
1284 begin_inset(os, "Tabular ");
1285 handle_tabular(p, os, name, width, parent_context);
1290 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1291 eat_whitespace(p, os, parent_context, false);
1292 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1293 eat_whitespace(p, os, parent_context, false);
1294 parent_context.check_layout(os);
1295 begin_inset(os, "Float " + unstarred_name + "\n");
1296 // store the float type for subfloats
1297 // subfloats only work with figures and tables
1298 if (unstarred_name == "figure")
1299 float_type = unstarred_name;
1300 else if (unstarred_name == "table")
1301 float_type = unstarred_name;
1305 os << "placement " << opt << '\n';
1306 if (contains(opt, "H"))
1307 preamble.registerAutomaticallyLoadedPackage("float");
1309 Floating const & fl = parent_context.textclass.floats()
1310 .getType(unstarred_name);
1311 if (!fl.floattype().empty() && fl.usesFloatPkg())
1312 preamble.registerAutomaticallyLoadedPackage("float");
1315 os << "wide " << convert<string>(is_starred)
1316 << "\nsideways false"
1317 << "\nstatus open\n\n";
1318 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1320 // We don't need really a new paragraph, but
1321 // we must make sure that the next item gets a \begin_layout.
1322 parent_context.new_paragraph(os);
1324 // the float is parsed thus delete the type
1328 else if (unstarred_name == "sidewaysfigure"
1329 || unstarred_name == "sidewaystable") {
1330 eat_whitespace(p, os, parent_context, false);
1331 parent_context.check_layout(os);
1332 if (unstarred_name == "sidewaysfigure")
1333 begin_inset(os, "Float figure\n");
1335 begin_inset(os, "Float table\n");
1336 os << "wide " << convert<string>(is_starred)
1337 << "\nsideways true"
1338 << "\nstatus open\n\n";
1339 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1341 // We don't need really a new paragraph, but
1342 // we must make sure that the next item gets a \begin_layout.
1343 parent_context.new_paragraph(os);
1345 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1348 else if (name == "wrapfigure" || name == "wraptable") {
1349 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1350 eat_whitespace(p, os, parent_context, false);
1351 parent_context.check_layout(os);
1354 string overhang = "0col%";
1357 lines = p.getArg('[', ']');
1358 string const placement = p.getArg('{', '}');
1360 overhang = p.getArg('[', ']');
1361 string const width = p.getArg('{', '}');
1363 if (name == "wrapfigure")
1364 begin_inset(os, "Wrap figure\n");
1366 begin_inset(os, "Wrap table\n");
1367 os << "lines " << lines
1368 << "\nplacement " << placement
1369 << "\noverhang " << lyx::translate_len(overhang)
1370 << "\nwidth " << lyx::translate_len(width)
1371 << "\nstatus open\n\n";
1372 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1374 // We don't need really a new paragraph, but
1375 // we must make sure that the next item gets a \begin_layout.
1376 parent_context.new_paragraph(os);
1378 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1381 else if (name == "minipage") {
1382 eat_whitespace(p, os, parent_context, false);
1383 // Test whether this is an outer box of a shaded box
1385 // swallow arguments
1386 while (p.hasOpt()) {
1388 p.skip_spaces(true);
1391 p.skip_spaces(true);
1392 Token t = p.get_token();
1393 bool shaded = false;
1394 if (t.asInput() == "\\begin") {
1395 p.skip_spaces(true);
1396 if (p.getArg('{', '}') == "shaded")
1401 parse_outer_box(p, os, FLAG_END, outer,
1402 parent_context, name, "shaded");
1404 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1409 else if (name == "comment") {
1410 eat_whitespace(p, os, parent_context, false);
1411 parent_context.check_layout(os);
1412 begin_inset(os, "Note Comment\n");
1413 os << "status open\n";
1414 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1417 skip_braces(p); // eat {} that might by set by LyX behind comments
1418 preamble.registerAutomaticallyLoadedPackage("verbatim");
1421 else if (name == "verbatim") {
1422 // FIXME: this should go in the generic code that
1423 // handles environments defined in layout file that
1424 // have "PassThru 1". However, the code over there is
1425 // already too complicated for my taste.
1426 parent_context.new_paragraph(os);
1427 Context context(true, parent_context.textclass,
1428 &parent_context.textclass[from_ascii("Verbatim")]);
1429 string s = p.verbatimEnvironment("verbatim");
1430 output_ert(os, s, context);
1434 else if (name == "IPA") {
1435 eat_whitespace(p, os, parent_context, false);
1436 parent_context.check_layout(os);
1437 begin_inset(os, "IPA\n");
1438 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1441 preamble.registerAutomaticallyLoadedPackage("tipa");
1442 preamble.registerAutomaticallyLoadedPackage("tipx");
1445 else if (name == "CJK") {
1446 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1447 // It is impossible to decide if a CJK environment was in its own paragraph or within
1448 // a line. We therefore always assume a paragraph since the latter is a rare case.
1449 eat_whitespace(p, os, parent_context, false);
1450 parent_context.check_end_layout(os);
1451 // store the encoding to be able to reset it
1452 string const encoding_old = p.getEncoding();
1453 string const encoding = p.getArg('{', '}');
1454 // FIXME: For some reason JIS does not work. Although the text
1455 // in tests/CJK.tex is identical with the SJIS version if you
1456 // convert both snippets using the recode command line utility,
1457 // the resulting .lyx file contains some extra characters if
1458 // you set buggy_encoding to false for JIS.
1459 bool const buggy_encoding = encoding == "JIS";
1460 if (!buggy_encoding)
1461 p.setEncoding(encoding, Encoding::CJK);
1463 // FIXME: This will read garbage, since the data is not encoded in utf8.
1464 p.setEncoding("UTF-8");
1466 // LyX only supports the same mapping for all CJK
1467 // environments, so we might need to output everything as ERT
1468 string const mapping = trim(p.getArg('{', '}'));
1469 char const * const * const where =
1470 is_known(encoding, supported_CJK_encodings);
1471 if (!buggy_encoding && !preamble.fontCJKSet())
1472 preamble.fontCJK(mapping);
1473 bool knownMapping = mapping == preamble.fontCJK();
1474 if (buggy_encoding || !knownMapping || !where) {
1475 parent_context.check_layout(os);
1476 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1478 // we must parse the content as verbatim because e.g. JIS can contain
1479 // normally invalid characters
1480 // FIXME: This works only for the most simple cases.
1481 // Since TeX control characters are not parsed,
1482 // things like comments are completely wrong.
1483 string const s = p.plainEnvironment("CJK");
1484 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1486 output_ert_inset(os, "\\", parent_context);
1487 else if (*it == '$')
1488 output_ert_inset(os, "$", parent_context);
1489 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1494 output_ert_inset(os, "\\end{" + name + "}",
1498 supported_CJK_languages[where - supported_CJK_encodings];
1499 // store the language because we must reset it at the end
1500 string const lang_old = parent_context.font.language;
1501 parent_context.font.language = lang;
1502 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1503 parent_context.font.language = lang_old;
1504 parent_context.new_paragraph(os);
1506 p.setEncoding(encoding_old);
1510 else if (name == "lyxgreyedout") {
1511 eat_whitespace(p, os, parent_context, false);
1512 parent_context.check_layout(os);
1513 begin_inset(os, "Note Greyedout\n");
1514 os << "status open\n";
1515 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1518 if (!preamble.notefontcolor().empty())
1519 preamble.registerAutomaticallyLoadedPackage("color");
1522 else if (name == "btSect") {
1523 eat_whitespace(p, os, parent_context, false);
1524 parent_context.check_layout(os);
1525 begin_command_inset(os, "bibtex", "bibtex");
1526 string bibstyle = "plain";
1528 bibstyle = p.getArg('[', ']');
1529 p.skip_spaces(true);
1531 string const bibfile = p.getArg('{', '}');
1532 eat_whitespace(p, os, parent_context, false);
1533 Token t = p.get_token();
1534 if (t.asInput() == "\\btPrintCited") {
1535 p.skip_spaces(true);
1536 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1538 if (t.asInput() == "\\btPrintNotCited") {
1539 p.skip_spaces(true);
1540 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1542 if (t.asInput() == "\\btPrintAll") {
1543 p.skip_spaces(true);
1544 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1546 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1547 os << "options " << '"' << bibstyle << '"' << "\n";
1548 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1553 else if (name == "framed" || name == "shaded") {
1554 eat_whitespace(p, os, parent_context, false);
1555 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1559 else if (name == "lstlisting") {
1560 eat_whitespace(p, os, parent_context, false);
1561 parse_listings(p, os, parent_context, false);
1565 else if (!parent_context.new_layout_allowed)
1566 parse_unknown_environment(p, name, os, FLAG_END, outer,
1569 // Alignment and spacing settings
1570 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1571 // therefore are totally broken!
1572 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1573 // they are commands not environments. They are furthermore switches that
1574 // can be ended by another switches, but also by commands like \footnote or
1575 // \parbox. So the only safe way is to leave them untouched.
1576 else if (name == "center" || name == "centering" ||
1577 name == "flushleft" || name == "flushright" ||
1578 name == "singlespace" || name == "onehalfspace" ||
1579 name == "doublespace" || name == "spacing") {
1580 eat_whitespace(p, os, parent_context, false);
1581 // We must begin a new paragraph if not already done
1582 if (! parent_context.atParagraphStart()) {
1583 parent_context.check_end_layout(os);
1584 parent_context.new_paragraph(os);
1586 if (name == "flushleft")
1587 parent_context.add_extra_stuff("\\align left\n");
1588 else if (name == "flushright")
1589 parent_context.add_extra_stuff("\\align right\n");
1590 else if (name == "center" || name == "centering")
1591 parent_context.add_extra_stuff("\\align center\n");
1592 else if (name == "singlespace")
1593 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1594 else if (name == "onehalfspace") {
1595 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1596 preamble.registerAutomaticallyLoadedPackage("setspace");
1597 } else if (name == "doublespace") {
1598 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1599 preamble.registerAutomaticallyLoadedPackage("setspace");
1600 } else if (name == "spacing") {
1601 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1602 preamble.registerAutomaticallyLoadedPackage("setspace");
1604 parse_text(p, os, FLAG_END, outer, parent_context);
1605 // Just in case the environment is empty
1606 parent_context.extra_stuff.erase();
1607 // We must begin a new paragraph to reset the alignment
1608 parent_context.new_paragraph(os);
1612 // The single '=' is meant here.
1613 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1614 eat_whitespace(p, os, parent_context, false);
1615 Context context(true, parent_context.textclass, newlayout,
1616 parent_context.layout, parent_context.font);
1617 if (parent_context.deeper_paragraph) {
1618 // We are beginning a nested environment after a
1619 // deeper paragraph inside the outer list environment.
1620 // Therefore we don't need to output a "begin deeper".
1621 context.need_end_deeper = true;
1623 parent_context.check_end_layout(os);
1624 if (last_env == name) {
1625 // we need to output a separator since LyX would export
1626 // the two environments as one otherwise (bug 5716)
1627 TeX2LyXDocClass const & textclass(parent_context.textclass);
1628 Context newcontext(true, textclass,
1629 &(textclass.defaultLayout()));
1630 newcontext.check_layout(os);
1631 begin_inset(os, "Separator plain\n");
1633 newcontext.check_end_layout(os);
1635 switch (context.layout->latextype) {
1636 case LATEX_LIST_ENVIRONMENT:
1637 context.add_par_extra_stuff("\\labelwidthstring "
1638 + p.verbatim_item() + '\n');
1641 case LATEX_BIB_ENVIRONMENT:
1642 p.verbatim_item(); // swallow next arg
1648 context.check_deeper(os);
1649 // handle known optional and required arguments
1650 // FIXME: Since format 446, layouts do not require anymore all optional
1651 // arguments before the required ones. Needs to be implemented!
1652 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1653 // It is impossible to place anything after the environment name,
1654 // but before the first \\item.
1655 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1656 bool need_layout = true;
1658 while (optargs < context.layout->optArgs()) {
1659 eat_whitespace(p, os, context, false);
1660 if (p.next_token().cat() == catEscape ||
1661 p.next_token().character() != '[')
1663 p.get_token(); // eat '['
1665 context.check_layout(os);
1666 need_layout = false;
1668 // FIXME: Just a workaround. InsetArgument::updateBuffer
1669 // will compute a proper ID for all "999" Arguments
1670 // (which is also what lyx2lyx produces).
1671 // However, tex2lyx should be able to output proper IDs
1673 begin_inset(os, "Argument 999\n");
1674 os << "status collapsed\n\n";
1675 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1677 eat_whitespace(p, os, context, false);
1681 while (reqargs < context.layout->requiredArgs()) {
1682 eat_whitespace(p, os, context, false);
1683 if (p.next_token().cat() != catBegin)
1685 p.get_token(); // eat '{'
1687 context.check_layout(os);
1688 need_layout = false;
1690 // FIXME: Just a workaround. InsetArgument::updateBuffer
1691 // will compute a proper ID for all "999" Arguments
1692 // (which is also what lyx2lyx produces).
1693 // However, tex2lyx should be able to output proper IDs
1695 begin_inset(os, "Argument 999\n");
1696 os << "status collapsed\n\n";
1697 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1699 eat_whitespace(p, os, context, false);
1703 parse_text(p, os, FLAG_END, outer, context);
1704 context.check_end_layout(os);
1705 if (parent_context.deeper_paragraph) {
1706 // We must suppress the "end deeper" because we
1707 // suppressed the "begin deeper" above.
1708 context.need_end_deeper = false;
1710 context.check_end_deeper(os);
1711 parent_context.new_paragraph(os);
1713 if (!preamble.titleLayoutFound())
1714 preamble.titleLayoutFound(newlayout->intitle);
1715 set<string> const & req = newlayout->requires();
1716 set<string>::const_iterator it = req.begin();
1717 set<string>::const_iterator en = req.end();
1718 for (; it != en; ++it)
1719 preamble.registerAutomaticallyLoadedPackage(*it);
1722 // The single '=' is meant here.
1723 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1724 eat_whitespace(p, os, parent_context, false);
1725 parent_context.check_layout(os);
1726 begin_inset(os, "Flex ");
1727 os << to_utf8(newinsetlayout->name()) << '\n'
1728 << "status collapsed\n";
1729 if (newinsetlayout->isPassThru()) {
1730 string const arg = p.verbatimEnvironment(name);
1731 Context context(true, parent_context.textclass,
1732 &parent_context.textclass.plainLayout(),
1733 parent_context.layout);
1734 output_ert(os, arg, parent_context);
1736 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1740 else if (name == "appendix") {
1741 // This is no good latex style, but it works and is used in some documents...
1742 eat_whitespace(p, os, parent_context, false);
1743 parent_context.check_end_layout(os);
1744 Context context(true, parent_context.textclass, parent_context.layout,
1745 parent_context.layout, parent_context.font);
1746 context.check_layout(os);
1747 os << "\\start_of_appendix\n";
1748 parse_text(p, os, FLAG_END, outer, context);
1749 context.check_end_layout(os);
1753 else if (known_environments.find(name) != known_environments.end()) {
1754 vector<ArgumentType> arguments = known_environments[name];
1755 // The last "argument" denotes wether we may translate the
1756 // environment contents to LyX
1757 // The default required if no argument is given makes us
1758 // compatible with the reLyXre environment.
1759 ArgumentType contents = arguments.empty() ?
1762 if (!arguments.empty())
1763 arguments.pop_back();
1764 // See comment in parse_unknown_environment()
1765 bool const specialfont =
1766 (parent_context.font != parent_context.normalfont);
1767 bool const new_layout_allowed =
1768 parent_context.new_layout_allowed;
1770 parent_context.new_layout_allowed = false;
1771 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1772 outer, parent_context);
1773 if (contents == verbatim)
1774 output_ert_inset(os, p.ertEnvironment(name),
1777 parse_text_snippet(p, os, FLAG_END, outer,
1779 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1781 parent_context.new_layout_allowed = new_layout_allowed;
1785 parse_unknown_environment(p, name, os, FLAG_END, outer,
1789 active_environments.pop_back();
1793 /// parses a comment and outputs it to \p os.
1794 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1796 LASSERT(t.cat() == catComment, return);
1797 if (!t.cs().empty()) {
1798 context.check_layout(os);
1799 output_ert_inset(os, '%' + t.cs(), context);
1800 if (p.next_token().cat() == catNewline) {
1801 // A newline after a comment line starts a new
1803 if (context.new_layout_allowed) {
1804 if(!context.atParagraphStart())
1805 // Only start a new paragraph if not already
1806 // done (we might get called recursively)
1807 context.new_paragraph(os);
1809 output_ert_inset(os, "\n", context);
1810 eat_whitespace(p, os, context, true);
1813 // "%\n" combination
1820 * Reads spaces and comments until the first non-space, non-comment token.
1821 * New paragraphs (double newlines or \\par) are handled like simple spaces
1822 * if \p eatParagraph is true.
1823 * Spaces are skipped, but comments are written to \p os.
1825 void eat_whitespace(Parser & p, ostream & os, Context & context,
1829 Token const & t = p.get_token();
1830 if (t.cat() == catComment)
1831 parse_comment(p, os, t, context);
1832 else if ((! eatParagraph && p.isParagraph()) ||
1833 (t.cat() != catSpace && t.cat() != catNewline)) {
1842 * Set a font attribute, parse text and reset the font attribute.
1843 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1844 * \param currentvalue Current value of the attribute. Is set to the new
1845 * value during parsing.
1846 * \param newvalue New value of the attribute
1848 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1849 Context & context, string const & attribute,
1850 string & currentvalue, string const & newvalue)
1852 context.check_layout(os);
1853 string const oldvalue = currentvalue;
1854 currentvalue = newvalue;
1855 os << '\n' << attribute << ' ' << newvalue << "\n";
1856 parse_text_snippet(p, os, flags, outer, context);
1857 context.check_layout(os);
1858 os << '\n' << attribute << ' ' << oldvalue << "\n";
1859 currentvalue = oldvalue;
1863 /// get the arguments of a natbib or jurabib citation command
1864 void get_cite_arguments(Parser & p, bool natbibOrder,
1865 string & before, string & after)
1867 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1869 // text before the citation
1871 // text after the citation
1872 after = p.getFullOpt();
1874 if (!after.empty()) {
1875 before = p.getFullOpt();
1876 if (natbibOrder && !before.empty())
1877 swap(before, after);
1882 /// Convert filenames with TeX macros and/or quotes to something LyX
1884 string const normalize_filename(string const & name)
1889 Token const & t = p.get_token();
1890 if (t.cat() != catEscape)
1892 else if (t.cs() == "lyxdot") {
1893 // This is used by LyX for simple dots in relative
1897 } else if (t.cs() == "space") {
1900 } else if (t.cs() == "string") {
1901 // Convert \string" to " and \string~ to ~
1902 Token const & n = p.next_token();
1903 if (n.asInput() != "\"" && n.asInput() != "~")
1908 // Strip quotes. This is a bit complicated (see latex_path()).
1909 string full = os.str();
1910 if (!full.empty() && full[0] == '"') {
1911 string base = removeExtension(full);
1912 string ext = getExtension(full);
1913 if (!base.empty() && base[base.length()-1] == '"')
1916 return addExtension(trim(base, "\""), ext);
1917 if (full[full.length()-1] == '"')
1920 return trim(full, "\"");
1926 /// Convert \p name from TeX convention (relative to master file) to LyX
1927 /// convention (relative to .lyx file) if it is relative
1928 void fix_child_filename(string & name)
1930 string const absMasterTeX = getMasterFilePath(true);
1931 bool const isabs = FileName::isAbsolute(name);
1932 // convert from "relative to .tex master" to absolute original path
1934 name = makeAbsPath(name, absMasterTeX).absFileName();
1935 bool copyfile = copyFiles();
1936 string const absParentLyX = getParentFilePath(false);
1939 // convert from absolute original path to "relative to master file"
1940 string const rel = to_utf8(makeRelPath(from_utf8(name),
1941 from_utf8(absMasterTeX)));
1942 // re-interpret "relative to .tex file" as "relative to .lyx file"
1943 // (is different if the master .lyx file resides in a
1944 // different path than the master .tex file)
1945 string const absMasterLyX = getMasterFilePath(false);
1946 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1947 // Do not copy if the new path is impossible to create. Example:
1948 // absMasterTeX = "/foo/bar/"
1949 // absMasterLyX = "/bar/"
1950 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1951 if (contains(name, "/../"))
1958 // convert from absolute original path to
1959 // "relative to .lyx file"
1960 name = to_utf8(makeRelPath(from_utf8(abs),
1961 from_utf8(absParentLyX)));
1965 // convert from absolute original path to "relative to .lyx file"
1966 name = to_utf8(makeRelPath(from_utf8(name),
1967 from_utf8(absParentLyX)));
1972 void copy_file(FileName const & src, string dstname)
1976 string const absParent = getParentFilePath(false);
1978 if (FileName::isAbsolute(dstname))
1979 dst = FileName(dstname);
1981 dst = makeAbsPath(dstname, absParent);
1982 string const absMaster = getMasterFilePath(false);
1983 FileName const srcpath = src.onlyPath();
1984 FileName const dstpath = dst.onlyPath();
1985 if (equivalent(srcpath, dstpath))
1987 if (!dstpath.isDirectory()) {
1988 if (!dstpath.createPath()) {
1989 cerr << "Warning: Could not create directory for file `"
1990 << dst.absFileName() << "´." << endl;
1994 if (dst.isReadableFile()) {
1995 if (overwriteFiles())
1996 cerr << "Warning: Overwriting existing file `"
1997 << dst.absFileName() << "´." << endl;
1999 cerr << "Warning: Not overwriting existing file `"
2000 << dst.absFileName() << "´." << endl;
2004 if (!src.copyTo(dst))
2005 cerr << "Warning: Could not copy file `" << src.absFileName()
2006 << "´ to `" << dst.absFileName() << "´." << endl;
2010 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2011 bool parse_chunk(Parser & p, ostream & os, Context & context)
2013 // check whether a chunk is possible here.
2014 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2020 // read the parameters
2021 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2022 if (!params.first) {
2027 Parser::Arg const code = p.verbatimStuff("\n@");
2032 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2033 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2037 // The last newline read is important for paragraph handling
2041 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2042 // We must have a valid layout before outputting the Chunk inset.
2043 context.check_layout(os);
2044 Context chunkcontext(true, context.textclass);
2045 chunkcontext.layout = &context.textclass.plainLayout();
2046 begin_inset(os, "Flex Chunk");
2047 os << "\nstatus open\n";
2048 if (!params.second.empty()) {
2049 chunkcontext.check_layout(os);
2050 Context paramscontext(true, context.textclass);
2051 paramscontext.layout = &context.textclass.plainLayout();
2052 begin_inset(os, "Argument 1");
2053 os << "\nstatus open\n";
2054 output_ert(os, params.second, paramscontext);
2057 output_ert(os, code.second, chunkcontext);
2065 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2066 bool is_macro(Parser & p)
2068 Token first = p.curr_token();
2069 if (first.cat() != catEscape || !p.good())
2071 if (first.cs() == "def")
2073 if (first.cs() != "global" && first.cs() != "long")
2075 Token second = p.get_token();
2077 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2078 second.cat() == catNewline || second.cat() == catComment)) {
2079 second = p.get_token();
2082 bool secondvalid = second.cat() == catEscape;
2084 bool thirdvalid = false;
2085 if (p.good() && first.cs() == "global" && secondvalid &&
2086 second.cs() == "long") {
2087 third = p.get_token();
2089 while (p.good() && !p.isParagraph() &&
2090 (third.cat() == catSpace ||
2091 third.cat() == catNewline ||
2092 third.cat() == catComment)) {
2093 third = p.get_token();
2096 thirdvalid = third.cat() == catEscape;
2098 for (int i = 0; i < pos; ++i)
2103 return (first.cs() == "global" || first.cs() == "long") &&
2104 second.cs() == "def";
2105 return first.cs() == "global" && second.cs() == "long" &&
2106 third.cs() == "def";
2110 /// Parse a macro definition (assumes that is_macro() returned true)
2111 void parse_macro(Parser & p, ostream & os, Context & context)
2113 context.check_layout(os);
2114 Token first = p.curr_token();
2117 string command = first.asInput();
2118 if (first.cs() != "def") {
2120 eat_whitespace(p, os, context, false);
2121 second = p.curr_token();
2122 command += second.asInput();
2123 if (second.cs() != "def") {
2125 eat_whitespace(p, os, context, false);
2126 third = p.curr_token();
2127 command += third.asInput();
2130 eat_whitespace(p, os, context, false);
2131 string const name = p.get_token().cs();
2132 eat_whitespace(p, os, context, false);
2138 while (p.next_token().cat() != catBegin) {
2139 if (p.next_token().cat() == catParameter) {
2144 // followed by number?
2145 if (p.next_token().cat() == catOther) {
2146 string s = p.get_token().asInput();
2148 // number = current arity + 1?
2149 if (s.size() == 1 && s[0] == arity + '0' + 1)
2154 paramtext += p.get_token().cs();
2156 paramtext += p.get_token().cs();
2161 // only output simple (i.e. compatible) macro as FormulaMacros
2162 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2164 context.check_layout(os);
2165 begin_inset(os, "FormulaMacro");
2166 os << "\n\\def" << ert;
2169 output_ert_inset(os, command + ert, context);
2173 void registerExternalTemplatePackages(string const & name)
2175 external::TemplateManager const & etm = external::TemplateManager::get();
2176 external::Template const * const et = etm.getTemplateByName(name);
2179 external::Template::Formats::const_iterator cit = et->formats.end();
2181 cit = et->formats.find("PDFLaTeX");
2182 if (cit == et->formats.end())
2183 // If the template has not specified a PDFLaTeX output,
2184 // we try the LaTeX format.
2185 cit = et->formats.find("LaTeX");
2186 if (cit == et->formats.end())
2188 vector<string>::const_iterator qit = cit->second.requirements.begin();
2189 vector<string>::const_iterator qend = cit->second.requirements.end();
2190 for (; qit != qend; ++qit)
2191 preamble.registerAutomaticallyLoadedPackage(*qit);
2194 } // anonymous namespace
2197 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2200 Layout const * newlayout = 0;
2201 InsetLayout const * newinsetlayout = 0;
2202 char const * const * where = 0;
2203 // Store the latest bibliographystyle, addcontentslineContent and
2204 // nocite{*} option (needed for bibtex inset)
2206 string contentslineContent;
2207 string bibliographystyle = "default";
2208 bool const use_natbib = isProvided("natbib");
2209 bool const use_jurabib = isProvided("jurabib");
2212 // it is impossible to determine the correct encoding for non-CJK Japanese.
2213 // Therefore write a note at the beginning of the document
2214 if (is_nonCJKJapanese) {
2215 context.check_layout(os);
2216 begin_inset(os, "Note Note\n");
2217 os << "status open\n\\begin_layout Plain Layout\n"
2218 << "\\series bold\n"
2219 << "Important information:\n"
2220 << "\\end_layout\n\n"
2221 << "\\begin_layout Plain Layout\n"
2222 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2223 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2224 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2225 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2226 << " and specify the encoding using the -e command-line switch.\n"
2227 << " In addition, you might want to double check that the desired output encoding\n"
2228 << " is correctly selected in Document > Settings > Language.\n"
2229 << "\\end_layout\n";
2231 is_nonCJKJapanese = false;
2235 Token const & t = p.get_token();
2237 debugToken(cerr, t, flags);
2240 if (flags & FLAG_ITEM) {
2241 if (t.cat() == catSpace)
2244 flags &= ~FLAG_ITEM;
2245 if (t.cat() == catBegin) {
2246 // skip the brace and collect everything to the next matching
2248 flags |= FLAG_BRACE_LAST;
2252 // handle only this single token, leave the loop if done
2253 flags |= FLAG_LEAVE;
2256 if (t.cat() != catEscape && t.character() == ']' &&
2257 (flags & FLAG_BRACK_LAST))
2259 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2262 // If there is anything between \end{env} and \begin{env} we
2263 // don't need to output a separator.
2264 if (t.cat() != catSpace && t.cat() != catNewline &&
2265 t.asInput() != "\\begin")
2271 if (t.cat() == catMath) {
2272 // we are inside some text mode thingy, so opening new math is allowed
2273 context.check_layout(os);
2274 begin_inset(os, "Formula ");
2275 Token const & n = p.get_token();
2276 bool const display(n.cat() == catMath && outer);
2278 // TeX's $$...$$ syntax for displayed math
2280 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2282 p.get_token(); // skip the second '$' token
2284 // simple $...$ stuff
2287 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2292 // Prevent the conversion of a line break to a
2293 // space (bug 7668). This does not change the
2294 // output, but looks ugly in LyX.
2295 eat_whitespace(p, os, context, false);
2299 else if (t.cat() == catSuper || t.cat() == catSub)
2300 cerr << "catcode " << t << " illegal in text mode\n";
2302 // Basic support for english quotes. This should be
2303 // extended to other quotes, but is not so easy (a
2304 // left english quote is the same as a right german
2306 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2307 context.check_layout(os);
2308 begin_inset(os, "Quotes ");
2314 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2315 context.check_layout(os);
2316 begin_inset(os, "Quotes ");
2323 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2324 context.check_layout(os);
2325 begin_inset(os, "Quotes ");
2332 else if (t.asInput() == "<"
2333 && p.next_token().asInput() == "<") {
2334 bool has_chunk = false;
2338 has_chunk = parse_chunk(p, os, context);
2344 context.check_layout(os);
2345 begin_inset(os, "Quotes ");
2346 //FIXME: this is a right danish quote;
2347 // why not a left french quote?
2355 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2356 check_space(p, os, context);
2358 else if (t.character() == '[' && noweb_mode &&
2359 p.next_token().character() == '[') {
2360 // These can contain underscores
2362 string const s = p.getFullOpt() + ']';
2363 if (p.next_token().character() == ']')
2366 cerr << "Warning: Inserting missing ']' in '"
2367 << s << "'." << endl;
2368 output_ert_inset(os, s, context);
2371 else if (t.cat() == catLetter) {
2372 context.check_layout(os);
2373 // Workaround for bug 4752.
2374 // FIXME: This whole code block needs to be removed
2375 // when the bug is fixed and tex2lyx produces
2376 // the updated file format.
2377 // The replacement algorithm in LyX is so stupid that
2378 // it even translates a phrase if it is part of a word.
2379 bool handled = false;
2380 for (int const * l = known_phrase_lengths; *l; ++l) {
2381 string phrase = t.cs();
2382 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2383 phrase += p.get_token().cs();
2384 if (is_known(phrase, known_coded_phrases)) {
2385 output_ert_inset(os, phrase, context);
2389 for (size_t i = 1; i < phrase.length(); ++i)
2397 else if (t.cat() == catOther ||
2398 t.cat() == catAlign ||
2399 t.cat() == catParameter) {
2400 // This translates "&" to "\\&" which may be wrong...
2401 context.check_layout(os);
2405 else if (p.isParagraph()) {
2406 if (context.new_layout_allowed)
2407 context.new_paragraph(os);
2409 output_ert_inset(os, "\\par ", context);
2410 eat_whitespace(p, os, context, true);
2413 else if (t.cat() == catActive) {
2414 context.check_layout(os);
2415 if (t.character() == '~') {
2416 if (context.layout->free_spacing)
2419 begin_inset(os, "space ~\n");
2426 else if (t.cat() == catBegin) {
2427 Token const next = p.next_token();
2428 Token const end = p.next_next_token();
2429 if (next.cat() == catEnd) {
2431 Token const prev = p.prev_token();
2433 if (p.next_token().character() == '`' ||
2434 (prev.character() == '-' &&
2435 p.next_token().character() == '-'))
2436 ; // ignore it in {}`` or -{}-
2438 output_ert_inset(os, "{}", context);
2439 } else if (next.cat() == catEscape &&
2440 is_known(next.cs(), known_quotes) &&
2441 end.cat() == catEnd) {
2442 // Something like {\textquoteright} (e.g.
2443 // from writer2latex). LyX writes
2444 // \textquoteright{}, so we may skip the
2445 // braces here for better readability.
2446 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2448 } else if (p.next_token().asInput() == "\\ascii") {
2449 // handle the \ascii characters
2450 // (the case without braces is handled later)
2451 // the code is "{\ascii\xxx}"
2452 p.get_token(); // eat \ascii
2453 string name2 = p.get_token().asInput();
2454 p.get_token(); // eat the final '}'
2455 string const name = "{\\ascii" + name2 + "}";
2459 // get the character from unicodesymbols
2460 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2461 Encodings::TEXT_CMD, termination, rem, &req);
2463 context.check_layout(os);
2466 output_ert_inset(os,
2467 to_utf8(rem), context);
2468 for (set<string>::const_iterator it = req.begin();
2469 it != req.end(); ++it)
2470 preamble.registerAutomaticallyLoadedPackage(*it);
2472 // we did not find a non-ert version
2473 output_ert_inset(os, name, context);
2475 context.check_layout(os);
2476 // special handling of font attribute changes
2477 Token const prev = p.prev_token();
2478 TeXFont const oldFont = context.font;
2479 if (next.character() == '[' ||
2480 next.character() == ']' ||
2481 next.character() == '*') {
2483 if (p.next_token().cat() == catEnd) {
2488 output_ert_inset(os, "{", context);
2489 parse_text_snippet(p, os,
2492 output_ert_inset(os, "}", context);
2494 } else if (! context.new_layout_allowed) {
2495 output_ert_inset(os, "{", context);
2496 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2498 output_ert_inset(os, "}", context);
2499 } else if (is_known(next.cs(), known_sizes)) {
2500 // next will change the size, so we must
2502 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2504 if (!context.atParagraphStart())
2506 << context.font.size << "\n";
2507 } else if (is_known(next.cs(), known_font_families)) {
2508 // next will change the font family, so we
2509 // must reset it here
2510 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2512 if (!context.atParagraphStart())
2514 << context.font.family << "\n";
2515 } else if (is_known(next.cs(), known_font_series)) {
2516 // next will change the font series, so we
2517 // must reset it here
2518 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2520 if (!context.atParagraphStart())
2522 << context.font.series << "\n";
2523 } else if (is_known(next.cs(), known_font_shapes)) {
2524 // next will change the font shape, so we
2525 // must reset it here
2526 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2528 if (!context.atParagraphStart())
2530 << context.font.shape << "\n";
2531 } else if (is_known(next.cs(), known_old_font_families) ||
2532 is_known(next.cs(), known_old_font_series) ||
2533 is_known(next.cs(), known_old_font_shapes)) {
2534 // next will change the font family, series
2535 // and shape, so we must reset it here
2536 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2538 if (!context.atParagraphStart())
2540 << context.font.family
2542 << context.font.series
2544 << context.font.shape << "\n";
2546 output_ert_inset(os, "{", context);
2547 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2549 output_ert_inset(os, "}", context);
2554 else if (t.cat() == catEnd) {
2555 if (flags & FLAG_BRACE_LAST) {
2558 cerr << "stray '}' in text\n";
2559 output_ert_inset(os, "}", context);
2562 else if (t.cat() == catComment)
2563 parse_comment(p, os, t, context);
2566 // control sequences
2569 else if (t.cs() == "(" || t.cs() == "[") {
2570 bool const simple = t.cs() == "(";
2571 context.check_layout(os);
2572 begin_inset(os, "Formula");
2573 os << " \\" << t.cs();
2574 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2575 os << '\\' << (simple ? ')' : ']');
2578 // Prevent the conversion of a line break to a
2579 // space (bug 7668). This does not change the
2580 // output, but looks ugly in LyX.
2581 eat_whitespace(p, os, context, false);
2585 else if (t.cs() == "begin")
2586 parse_environment(p, os, outer, last_env,
2589 else if (t.cs() == "end") {
2590 if (flags & FLAG_END) {
2591 // eat environment name
2592 string const name = p.getArg('{', '}');
2593 if (name != active_environment())
2594 cerr << "\\end{" + name + "} does not match \\begin{"
2595 + active_environment() + "}\n";
2598 p.error("found 'end' unexpectedly");
2601 else if (t.cs() == "item") {
2603 bool const optarg = p.hasOpt();
2605 // FIXME: This swallows comments, but we cannot use
2606 // eat_whitespace() since we must not output
2607 // anything before the item.
2608 p.skip_spaces(true);
2609 s = p.verbatimOption();
2611 p.skip_spaces(false);
2613 context.check_layout(os);
2614 if (context.has_item) {
2615 // An item in an unknown list-like environment
2616 // FIXME: Do this in check_layout()!
2617 context.has_item = false;
2619 output_ert_inset(os, "\\item", context);
2621 output_ert_inset(os, "\\item ", context);
2624 if (context.layout->labeltype != LABEL_MANUAL) {
2625 // handle option of itemize item
2626 begin_inset(os, "Argument item:1\n");
2627 os << "status open\n";
2628 os << "\n\\begin_layout Plain Layout\n";
2630 os << parse_text_snippet(p2,
2631 FLAG_BRACK_LAST, outer, context);
2632 // we must not use context.check_end_layout(os)
2633 // because that would close the outer itemize layout
2634 os << "\n\\end_layout\n";
2636 eat_whitespace(p, os, context, false);
2637 } else if (!s.empty()) {
2638 // LyX adds braces around the argument,
2639 // so we need to remove them here.
2640 if (s.size() > 2 && s[0] == '{' &&
2641 s[s.size()-1] == '}')
2642 s = s.substr(1, s.size()-2);
2643 // If the argument contains a space we
2644 // must put it into ERT: Otherwise LyX
2645 // would misinterpret the space as
2646 // item delimiter (bug 7663)
2647 if (contains(s, ' ')) {
2648 output_ert_inset(os, s, context);
2651 os << parse_text_snippet(p2,
2652 FLAG_BRACK_LAST, outer, context);
2654 // The space is needed to separate the
2655 // item from the rest of the sentence.
2657 eat_whitespace(p, os, context, false);
2662 else if (t.cs() == "bibitem") {
2664 context.check_layout(os);
2665 eat_whitespace(p, os, context, false);
2666 string label = convert_command_inset_arg(p.verbatimOption());
2667 string key = convert_command_inset_arg(p.verbatim_item());
2668 if (contains(label, '\\') || contains(key, '\\')) {
2669 // LyX can't handle LaTeX commands in labels or keys
2670 output_ert_inset(os, t.asInput() + '[' + label +
2671 "]{" + p.verbatim_item() + '}',
2674 begin_command_inset(os, "bibitem", "bibitem");
2675 os << "label \"" << label << "\"\n"
2676 "key \"" << key << "\"\n";
2681 else if (is_macro(p)) {
2682 // catch the case of \def\inputGnumericTable
2684 if (t.cs() == "def") {
2685 Token second = p.next_token();
2686 if (second.cs() == "inputGnumericTable") {
2690 Token third = p.get_token();
2692 if (third.cs() == "input") {
2696 string name = normalize_filename(p.verbatim_item());
2697 string const path = getMasterFilePath(true);
2698 // We want to preserve relative / absolute filenames,
2699 // therefore path is only used for testing
2700 // The file extension is in every case ".tex".
2701 // So we need to remove this extension and check for
2702 // the original one.
2703 name = removeExtension(name);
2704 if (!makeAbsPath(name, path).exists()) {
2705 char const * const Gnumeric_formats[] = {"gnumeric",
2707 string const Gnumeric_name =
2708 find_file(name, path, Gnumeric_formats);
2709 if (!Gnumeric_name.empty())
2710 name = Gnumeric_name;
2712 FileName const absname = makeAbsPath(name, path);
2713 if (absname.exists()) {
2714 fix_child_filename(name);
2715 copy_file(absname, name);
2717 cerr << "Warning: Could not find file '"
2718 << name << "'." << endl;
2719 context.check_layout(os);
2720 begin_inset(os, "External\n\ttemplate ");
2721 os << "GnumericSpreadsheet\n\tfilename "
2724 context.check_layout(os);
2726 // register the packages that are automatically loaded
2727 // by the Gnumeric template
2728 registerExternalTemplatePackages("GnumericSpreadsheet");
2733 parse_macro(p, os, context);
2736 else if (t.cs() == "noindent") {
2738 context.add_par_extra_stuff("\\noindent\n");
2741 else if (t.cs() == "appendix") {
2742 context.add_par_extra_stuff("\\start_of_appendix\n");
2743 // We need to start a new paragraph. Otherwise the
2744 // appendix in 'bla\appendix\chapter{' would start
2746 context.new_paragraph(os);
2747 // We need to make sure that the paragraph is
2748 // generated even if it is empty. Otherwise the
2749 // appendix in '\par\appendix\par\chapter{' would
2751 context.check_layout(os);
2752 // FIXME: This is a hack to prevent paragraph
2753 // deletion if it is empty. Handle this better!
2754 output_ert_inset(os,
2755 "%dummy comment inserted by tex2lyx to "
2756 "ensure that this paragraph is not empty",
2758 // Both measures above may generate an additional
2759 // empty paragraph, but that does not hurt, because
2760 // whitespace does not matter here.
2761 eat_whitespace(p, os, context, true);
2764 // Must catch empty dates before findLayout is called below
2765 else if (t.cs() == "date") {
2766 eat_whitespace(p, os, context, false);
2768 string const date = p.verbatim_item();
2771 preamble.suppressDate(true);
2774 preamble.suppressDate(false);
2775 if (context.new_layout_allowed &&
2776 (newlayout = findLayout(context.textclass,
2779 output_command_layout(os, p, outer,
2780 context, newlayout);
2781 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2782 if (!preamble.titleLayoutFound())
2783 preamble.titleLayoutFound(newlayout->intitle);
2784 set<string> const & req = newlayout->requires();
2785 set<string>::const_iterator it = req.begin();
2786 set<string>::const_iterator en = req.end();
2787 for (; it != en; ++it)
2788 preamble.registerAutomaticallyLoadedPackage(*it);
2790 output_ert_inset(os,
2791 "\\date{" + p.verbatim_item() + '}',
2796 // Starred section headings
2797 // Must attempt to parse "Section*" before "Section".
2798 else if ((p.next_token().asInput() == "*") &&
2799 context.new_layout_allowed &&
2800 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2803 output_command_layout(os, p, outer, context, newlayout);
2805 if (!preamble.titleLayoutFound())
2806 preamble.titleLayoutFound(newlayout->intitle);
2807 set<string> const & req = newlayout->requires();
2808 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2809 preamble.registerAutomaticallyLoadedPackage(*it);
2812 // Section headings and the like
2813 else if (context.new_layout_allowed &&
2814 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2816 output_command_layout(os, p, outer, context, newlayout);
2818 if (!preamble.titleLayoutFound())
2819 preamble.titleLayoutFound(newlayout->intitle);
2820 set<string> const & req = newlayout->requires();
2821 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2822 preamble.registerAutomaticallyLoadedPackage(*it);
2825 else if (t.cs() == "caption" || t.cs() == "captionabove" ||
2826 t.cs() == "captionbelow") {
2827 bool starred = false;
2828 if (p.next_token().asInput() == "*") {
2833 context.check_layout(os);
2835 if (starred && t.cs() == "caption")
2836 begin_inset(os, "Caption LongTableNoNumber\n");
2837 else if (t.cs() == "caption")
2838 begin_inset(os, "Caption Standard\n");
2839 else if (t.cs() == "captionabove")
2840 begin_inset(os, "Caption Above\n");
2841 else if (t.cs() == "captionbelow")
2842 begin_inset(os, "Caption Below\n");
2843 Context newcontext(true, context.textclass, 0, 0, context.font);
2844 newcontext.check_layout(os);
2845 // FIXME InsetArgument is now properly implemented in InsetLayout
2846 // (for captions, but also for others)
2847 if (p.next_token().cat() != catEscape &&
2848 p.next_token().character() == '[') {
2849 p.get_token(); // eat '['
2850 begin_inset(os, "Argument 1\n");
2851 os << "status collapsed\n";
2852 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2854 eat_whitespace(p, os, context, false);
2856 parse_text(p, os, FLAG_ITEM, outer, context);
2857 context.check_end_layout(os);
2858 // We don't need really a new paragraph, but
2859 // we must make sure that the next item gets a \begin_layout.
2860 context.new_paragraph(os);
2863 newcontext.check_end_layout(os);
2866 else if (t.cs() == "subfloat") {
2867 // the syntax is \subfloat[caption]{content}
2868 // if it is a table of figure depends on the surrounding float
2869 bool has_caption = false;
2871 // do nothing if there is no outer float
2872 if (!float_type.empty()) {
2873 context.check_layout(os);
2875 begin_inset(os, "Float " + float_type + "\n");
2877 << "\nsideways false"
2878 << "\nstatus collapsed\n\n";
2881 if (p.next_token().cat() != catEscape &&
2882 p.next_token().character() == '[') {
2883 p.get_token(); // eat '['
2884 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2888 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2889 // the caption comes always as the last
2891 // we must make sure that the caption gets a \begin_layout
2892 os << "\n\\begin_layout Plain Layout";
2894 begin_inset(os, "Caption Standard\n");
2895 Context newcontext(true, context.textclass,
2896 0, 0, context.font);
2897 newcontext.check_layout(os);
2898 os << caption << "\n";
2899 newcontext.check_end_layout(os);
2900 // We don't need really a new paragraph, but
2901 // we must make sure that the next item gets a \begin_layout.
2902 //newcontext.new_paragraph(os);
2906 // We don't need really a new paragraph, but
2907 // we must make sure that the next item gets a \begin_layout.
2909 context.new_paragraph(os);
2912 context.check_end_layout(os);
2913 // close the layout we opened
2915 os << "\n\\end_layout\n";
2917 // if the float type is not supported or there is no surrounding float
2920 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2921 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2922 "]{" + p.verbatim_item() + '}', context);
2924 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2928 else if (t.cs() == "includegraphics") {
2929 bool const clip = p.next_token().asInput() == "*";
2932 string const arg = p.getArg('[', ']');
2933 map<string, string> opts;
2934 vector<string> keys;
2935 split_map(arg, opts, keys);
2937 opts["clip"] = string();
2938 string name = normalize_filename(p.verbatim_item());
2940 string const path = getMasterFilePath(true);
2941 // We want to preserve relative / absolute filenames,
2942 // therefore path is only used for testing
2943 if (!makeAbsPath(name, path).exists()) {
2944 // The file extension is probably missing.
2945 // Now try to find it out.
2946 string const dvips_name =
2947 find_file(name, path,
2948 known_dvips_graphics_formats);
2949 string const pdftex_name =
2950 find_file(name, path,
2951 known_pdftex_graphics_formats);
2952 if (!dvips_name.empty()) {
2953 if (!pdftex_name.empty()) {
2954 cerr << "This file contains the "
2956 "\"\\includegraphics{"
2958 "However, files\n\""
2959 << dvips_name << "\" and\n\""
2960 << pdftex_name << "\"\n"
2961 "both exist, so I had to make a "
2962 "choice and took the first one.\n"
2963 "Please move the unwanted one "
2964 "someplace else and try again\n"
2965 "if my choice was wrong."
2969 } else if (!pdftex_name.empty()) {
2975 FileName const absname = makeAbsPath(name, path);
2976 if (absname.exists()) {
2977 fix_child_filename(name);
2978 copy_file(absname, name);
2980 cerr << "Warning: Could not find graphics file '"
2981 << name << "'." << endl;
2983 context.check_layout(os);
2984 begin_inset(os, "Graphics ");
2985 os << "\n\tfilename " << name << '\n';
2986 if (opts.find("width") != opts.end())
2988 << translate_len(opts["width"]) << '\n';
2989 if (opts.find("height") != opts.end())
2991 << translate_len(opts["height"]) << '\n';
2992 if (opts.find("scale") != opts.end()) {
2993 istringstream iss(opts["scale"]);
2997 os << "\tscale " << val << '\n';
2999 if (opts.find("angle") != opts.end()) {
3000 os << "\trotateAngle "
3001 << opts["angle"] << '\n';
3002 vector<string>::const_iterator a =
3003 find(keys.begin(), keys.end(), "angle");
3004 vector<string>::const_iterator s =
3005 find(keys.begin(), keys.end(), "width");
3006 if (s == keys.end())
3007 s = find(keys.begin(), keys.end(), "height");
3008 if (s == keys.end())
3009 s = find(keys.begin(), keys.end(), "scale");
3010 if (s != keys.end() && distance(s, a) > 0)
3011 os << "\tscaleBeforeRotation\n";
3013 if (opts.find("origin") != opts.end()) {
3015 string const opt = opts["origin"];
3016 if (opt.find('l') != string::npos) ss << "left";
3017 if (opt.find('r') != string::npos) ss << "right";
3018 if (opt.find('c') != string::npos) ss << "center";
3019 if (opt.find('t') != string::npos) ss << "Top";
3020 if (opt.find('b') != string::npos) ss << "Bottom";
3021 if (opt.find('B') != string::npos) ss << "Baseline";
3022 if (!ss.str().empty())
3023 os << "\trotateOrigin " << ss.str() << '\n';
3025 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3027 if (opts.find("keepaspectratio") != opts.end())
3028 os << "\tkeepAspectRatio\n";
3029 if (opts.find("clip") != opts.end())
3031 if (opts.find("draft") != opts.end())
3033 if (opts.find("bb") != opts.end())
3034 os << "\tBoundingBox "
3035 << opts["bb"] << '\n';
3036 int numberOfbbOptions = 0;
3037 if (opts.find("bbllx") != opts.end())
3038 numberOfbbOptions++;
3039 if (opts.find("bblly") != opts.end())
3040 numberOfbbOptions++;
3041 if (opts.find("bburx") != opts.end())
3042 numberOfbbOptions++;
3043 if (opts.find("bbury") != opts.end())
3044 numberOfbbOptions++;
3045 if (numberOfbbOptions == 4)
3046 os << "\tBoundingBox "
3047 << opts["bbllx"] << " " << opts["bblly"] << " "
3048 << opts["bburx"] << " " << opts["bbury"] << '\n';
3049 else if (numberOfbbOptions > 0)
3050 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3051 numberOfbbOptions = 0;
3052 if (opts.find("natwidth") != opts.end())
3053 numberOfbbOptions++;
3054 if (opts.find("natheight") != opts.end())
3055 numberOfbbOptions++;
3056 if (numberOfbbOptions == 2)
3057 os << "\tBoundingBox 0bp 0bp "
3058 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3059 else if (numberOfbbOptions > 0)
3060 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3061 ostringstream special;
3062 if (opts.find("hiresbb") != opts.end())
3063 special << "hiresbb,";
3064 if (opts.find("trim") != opts.end())
3066 if (opts.find("viewport") != opts.end())
3067 special << "viewport=" << opts["viewport"] << ',';
3068 if (opts.find("totalheight") != opts.end())
3069 special << "totalheight=" << opts["totalheight"] << ',';
3070 if (opts.find("type") != opts.end())
3071 special << "type=" << opts["type"] << ',';
3072 if (opts.find("ext") != opts.end())
3073 special << "ext=" << opts["ext"] << ',';
3074 if (opts.find("read") != opts.end())
3075 special << "read=" << opts["read"] << ',';
3076 if (opts.find("command") != opts.end())
3077 special << "command=" << opts["command"] << ',';
3078 string s_special = special.str();
3079 if (!s_special.empty()) {
3080 // We had special arguments. Remove the trailing ','.
3081 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3083 // TODO: Handle the unknown settings better.
3084 // Warn about invalid options.
3085 // Check whether some option was given twice.
3087 preamble.registerAutomaticallyLoadedPackage("graphicx");
3090 else if (t.cs() == "footnote" ||
3091 (t.cs() == "thanks" && context.layout->intitle)) {
3093 context.check_layout(os);
3094 begin_inset(os, "Foot\n");
3095 os << "status collapsed\n\n";
3096 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3100 else if (t.cs() == "marginpar") {
3102 context.check_layout(os);
3103 begin_inset(os, "Marginal\n");
3104 os << "status collapsed\n\n";
3105 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3109 else if (t.cs() == "lstinline") {
3111 parse_listings(p, os, context, true);
3114 else if (t.cs() == "ensuremath") {
3116 context.check_layout(os);
3117 string const s = p.verbatim_item();
3118 //FIXME: this never triggers in UTF8
3119 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3122 output_ert_inset(os, "\\ensuremath{" + s + "}",
3126 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3127 if (preamble.titleLayoutFound()) {
3129 skip_spaces_braces(p);
3131 output_ert_inset(os, t.asInput(), context);
3134 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3135 context.check_layout(os);
3136 begin_command_inset(os, "toc", t.cs());
3138 skip_spaces_braces(p);
3139 if (t.cs() == "lstlistoflistings")
3140 preamble.registerAutomaticallyLoadedPackage("listings");
3143 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3144 context.check_layout(os);
3145 if (t.cs() == "listoffigures")
3146 begin_inset(os, "FloatList figure\n");
3148 begin_inset(os, "FloatList table\n");
3150 skip_spaces_braces(p);
3153 else if (t.cs() == "listof") {
3154 p.skip_spaces(true);
3155 string const name = p.get_token().cs();
3156 if (context.textclass.floats().typeExist(name)) {
3157 context.check_layout(os);
3158 begin_inset(os, "FloatList ");
3161 p.get_token(); // swallow second arg
3163 output_ert_inset(os, "\\listof{" + name + "}", context);
3166 else if ((where = is_known(t.cs(), known_text_font_families)))
3167 parse_text_attributes(p, os, FLAG_ITEM, outer,
3168 context, "\\family", context.font.family,
3169 known_coded_font_families[where - known_text_font_families]);
3171 else if ((where = is_known(t.cs(), known_text_font_series)))
3172 parse_text_attributes(p, os, FLAG_ITEM, outer,
3173 context, "\\series", context.font.series,
3174 known_coded_font_series[where - known_text_font_series]);
3176 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3177 parse_text_attributes(p, os, FLAG_ITEM, outer,
3178 context, "\\shape", context.font.shape,
3179 known_coded_font_shapes[where - known_text_font_shapes]);
3181 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3182 context.check_layout(os);
3183 TeXFont oldFont = context.font;
3184 context.font.init();
3185 context.font.size = oldFont.size;
3186 os << "\n\\family " << context.font.family << "\n";
3187 os << "\n\\series " << context.font.series << "\n";
3188 os << "\n\\shape " << context.font.shape << "\n";
3189 if (t.cs() == "textnormal") {
3190 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3191 output_font_change(os, context.font, oldFont);
3192 context.font = oldFont;
3194 eat_whitespace(p, os, context, false);
3197 else if (t.cs() == "textcolor") {
3198 // scheme is \textcolor{color name}{text}
3199 string const color = p.verbatim_item();
3200 // we only support the predefined colors of the color package
3201 if (color == "black" || color == "blue" || color == "cyan"
3202 || color == "green" || color == "magenta" || color == "red"
3203 || color == "white" || color == "yellow") {
3204 context.check_layout(os);
3205 os << "\n\\color " << color << "\n";
3206 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3207 context.check_layout(os);
3208 os << "\n\\color inherit\n";
3209 preamble.registerAutomaticallyLoadedPackage("color");
3211 // for custom defined colors
3212 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3215 else if (t.cs() == "underbar" || t.cs() == "uline") {
3216 // \underbar is not 100% correct (LyX outputs \uline
3217 // of ulem.sty). The difference is that \ulem allows
3218 // line breaks, and \underbar does not.
3219 // Do NOT handle \underline.
3220 // \underbar cuts through y, g, q, p etc.,
3221 // \underline does not.
3222 context.check_layout(os);
3223 os << "\n\\bar under\n";
3224 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3225 context.check_layout(os);
3226 os << "\n\\bar default\n";
3227 preamble.registerAutomaticallyLoadedPackage("ulem");
3230 else if (t.cs() == "sout") {
3231 context.check_layout(os);
3232 os << "\n\\strikeout on\n";
3233 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3234 context.check_layout(os);
3235 os << "\n\\strikeout default\n";
3236 preamble.registerAutomaticallyLoadedPackage("ulem");
3239 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3240 t.cs() == "emph" || t.cs() == "noun") {
3241 context.check_layout(os);
3242 os << "\n\\" << t.cs() << " on\n";
3243 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3244 context.check_layout(os);
3245 os << "\n\\" << t.cs() << " default\n";
3246 if (t.cs() == "uuline" || t.cs() == "uwave")
3247 preamble.registerAutomaticallyLoadedPackage("ulem");
3250 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3251 context.check_layout(os);
3252 string name = p.getArg('{', '}');
3253 string localtime = p.getArg('{', '}');
3254 preamble.registerAuthor(name);
3255 Author const & author = preamble.getAuthor(name);
3256 // from_asctime_utc() will fail if LyX decides to output the
3257 // time in the text language.
3258 time_t ptime = from_asctime_utc(localtime);
3259 if (ptime == static_cast<time_t>(-1)) {
3260 cerr << "Warning: Could not parse time `" << localtime
3261 << "´ for change tracking, using current time instead.\n";
3262 ptime = current_time();
3264 if (t.cs() == "lyxadded")
3265 os << "\n\\change_inserted ";
3267 os << "\n\\change_deleted ";
3268 os << author.bufferId() << ' ' << ptime << '\n';
3269 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3270 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3271 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3272 LaTeXPackages::isAvailable("xcolor");
3273 // No need to test for luatex, since luatex comes in
3274 // two flavours (dvi and pdf), like latex, and those
3275 // are detected by pdflatex.
3276 if (pdflatex || xetex) {
3278 preamble.registerAutomaticallyLoadedPackage("ulem");
3279 preamble.registerAutomaticallyLoadedPackage("xcolor");
3280 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3284 preamble.registerAutomaticallyLoadedPackage("dvipost");
3285 } else if (xcolorulem) {
3286 preamble.registerAutomaticallyLoadedPackage("ulem");
3287 preamble.registerAutomaticallyLoadedPackage("xcolor");
3292 else if (t.cs() == "textipa") {
3293 context.check_layout(os);
3294 begin_inset(os, "IPA\n");
3295 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3297 preamble.registerAutomaticallyLoadedPackage("tipa");
3298 preamble.registerAutomaticallyLoadedPackage("tipx");
3301 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3302 context.check_layout(os);
3303 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3304 os << "status open\n";
3305 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3310 else if (t.cs() == "textvertline") {
3311 // FIXME: This is not correct, \textvertline is higher than |
3317 else if (t.cs() == "tone" ) {
3318 context.check_layout(os);
3319 // register the tone package
3320 preamble.registerAutomaticallyLoadedPackage("tone");
3321 string content = trimSpaceAndEol(p.verbatim_item());
3322 string command = t.asInput() + "{" + content + "}";
3323 // some tones can be detected by unicodesymbols, some need special code
3324 if (is_known(content, known_tones)) {
3325 os << "\\IPAChar " << command << "\n";
3328 // try to see whether the string is in unicodesymbols
3332 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3333 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3334 termination, rem, &req);
3338 output_ert_inset(os, to_utf8(rem), context);
3339 for (set<string>::const_iterator it = req.begin();
3340 it != req.end(); ++it)
3341 preamble.registerAutomaticallyLoadedPackage(*it);
3343 // we did not find a non-ert version
3344 output_ert_inset(os, command, context);
3347 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3348 t.cs() == "vphantom") {
3349 context.check_layout(os);
3350 if (t.cs() == "phantom")
3351 begin_inset(os, "Phantom Phantom\n");
3352 if (t.cs() == "hphantom")
3353 begin_inset(os, "Phantom HPhantom\n");
3354 if (t.cs() == "vphantom")
3355 begin_inset(os, "Phantom VPhantom\n");
3356 os << "status open\n";
3357 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3362 else if (t.cs() == "href") {
3363 context.check_layout(os);
3364 string target = convert_command_inset_arg(p.verbatim_item());
3365 string name = convert_command_inset_arg(p.verbatim_item());
3367 size_t i = target.find(':');
3368 if (i != string::npos) {
3369 type = target.substr(0, i + 1);
3370 if (type == "mailto:" || type == "file:")
3371 target = target.substr(i + 1);
3372 // handle the case that name is equal to target, except of "http://"
3373 else if (target.substr(i + 3) == name && type == "http:")
3376 begin_command_inset(os, "href", "href");
3378 os << "name \"" << name << "\"\n";
3379 os << "target \"" << target << "\"\n";
3380 if (type == "mailto:" || type == "file:")
3381 os << "type \"" << type << "\"\n";
3383 skip_spaces_braces(p);
3386 else if (t.cs() == "lyxline") {
3387 // swallow size argument (it is not used anyway)
3389 if (!context.atParagraphStart()) {
3390 // so our line is in the middle of a paragraph
3391 // we need to add a new line, lest this line
3392 // follow the other content on that line and
3393 // run off the side of the page
3394 // FIXME: This may create an empty paragraph,
3395 // but without that it would not be
3396 // possible to set noindent below.
3397 // Fortunately LaTeX does not care
3398 // about the empty paragraph.
3399 context.new_paragraph(os);
3401 if (preamble.indentParagraphs()) {
3402 // we need to unindent, lest the line be too long
3403 context.add_par_extra_stuff("\\noindent\n");
3405 context.check_layout(os);
3406 begin_command_inset(os, "line", "rule");
3407 os << "offset \"0.5ex\"\n"
3408 "width \"100line%\"\n"
3413 else if (t.cs() == "rule") {
3414 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3415 string const width = p.getArg('{', '}');
3416 string const thickness = p.getArg('{', '}');
3417 context.check_layout(os);
3418 begin_command_inset(os, "line", "rule");
3419 if (!offset.empty())
3420 os << "offset \"" << translate_len(offset) << "\"\n";
3421 os << "width \"" << translate_len(width) << "\"\n"
3422 "height \"" << translate_len(thickness) << "\"\n";
3426 else if (is_known(t.cs(), known_phrases) ||
3427 (t.cs() == "protect" &&
3428 p.next_token().cat() == catEscape &&
3429 is_known(p.next_token().cs(), known_phrases))) {
3430 // LyX sometimes puts a \protect in front, so we have to ignore it
3431 // FIXME: This needs to be changed when bug 4752 is fixed.
3433 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3435 context.check_layout(os);
3436 os << known_coded_phrases[where - known_phrases];
3437 skip_spaces_braces(p);
3440 // handle refstyle first to catch \eqref which can also occur
3441 // without refstyle. Only recognize these commands if
3442 // refstyle.sty was found in the preamble (otherwise \eqref
3443 // and user defined ref commands could be misdetected).
3444 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3445 preamble.refstyle()) {
3446 context.check_layout(os);
3447 begin_command_inset(os, "ref", "formatted");
3448 os << "reference \"";
3449 os << known_refstyle_prefixes[where - known_refstyle_commands]
3451 os << convert_command_inset_arg(p.verbatim_item())
3454 preamble.registerAutomaticallyLoadedPackage("refstyle");
3457 // if refstyle is used, we must not convert \prettyref to a
3458 // formatted reference, since that would result in a refstyle command.
3459 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3460 (t.cs() != "prettyref" || !preamble.refstyle())) {
3461 string const opt = p.getOpt();
3463 context.check_layout(os);
3464 begin_command_inset(os, "ref",
3465 known_coded_ref_commands[where - known_ref_commands]);
3466 os << "reference \""
3467 << convert_command_inset_arg(p.verbatim_item())
3470 if (t.cs() == "vref" || t.cs() == "vpageref")
3471 preamble.registerAutomaticallyLoadedPackage("varioref");
3472 else if (t.cs() == "prettyref")
3473 preamble.registerAutomaticallyLoadedPackage("prettyref");
3475 // LyX does not yet support optional arguments of ref commands
3476 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3477 p.verbatim_item() + '}', context);
3481 else if (use_natbib &&
3482 is_known(t.cs(), known_natbib_commands) &&
3483 ((t.cs() != "citefullauthor" &&
3484 t.cs() != "citeyear" &&
3485 t.cs() != "citeyearpar") ||
3486 p.next_token().asInput() != "*")) {
3487 context.check_layout(os);
3488 string command = t.cs();
3489 if (p.next_token().asInput() == "*") {
3493 if (command == "citefullauthor")
3494 // alternative name for "\\citeauthor*"
3495 command = "citeauthor*";
3497 // text before the citation
3499 // text after the citation
3501 get_cite_arguments(p, true, before, after);
3503 if (command == "cite") {
3504 // \cite without optional argument means
3505 // \citet, \cite with at least one optional
3506 // argument means \citep.
3507 if (before.empty() && after.empty())
3512 if (before.empty() && after == "[]")
3513 // avoid \citet[]{a}
3515 else if (before == "[]" && after == "[]") {
3516 // avoid \citet[][]{a}
3520 // remove the brackets around after and before
3521 if (!after.empty()) {
3523 after.erase(after.length() - 1, 1);
3524 after = convert_command_inset_arg(after);
3526 if (!before.empty()) {
3528 before.erase(before.length() - 1, 1);
3529 before = convert_command_inset_arg(before);
3531 begin_command_inset(os, "citation", command);
3532 os << "after " << '"' << after << '"' << "\n";
3533 os << "before " << '"' << before << '"' << "\n";
3535 << convert_command_inset_arg(p.verbatim_item())
3538 // Need to set the cite engine if natbib is loaded by
3539 // the document class directly
3540 if (preamble.citeEngine() == "basic")
3541 preamble.citeEngine("natbib");
3544 else if (use_jurabib &&
3545 is_known(t.cs(), known_jurabib_commands) &&
3546 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3547 context.check_layout(os);
3548 string command = t.cs();
3549 if (p.next_token().asInput() == "*") {
3553 char argumentOrder = '\0';
3554 vector<string> const options =
3555 preamble.getPackageOptions("jurabib");
3556 if (find(options.begin(), options.end(),
3557 "natbiborder") != options.end())
3558 argumentOrder = 'n';
3559 else if (find(options.begin(), options.end(),
3560 "jurabiborder") != options.end())
3561 argumentOrder = 'j';
3563 // text before the citation
3565 // text after the citation
3567 get_cite_arguments(p, argumentOrder != 'j', before, after);
3569 string const citation = p.verbatim_item();
3570 if (!before.empty() && argumentOrder == '\0') {
3571 cerr << "Warning: Assuming argument order "
3572 "of jurabib version 0.6 for\n'"
3573 << command << before << after << '{'
3574 << citation << "}'.\n"
3575 "Add 'jurabiborder' to the jurabib "
3576 "package options if you used an\n"
3577 "earlier jurabib version." << endl;
3579 if (!after.empty()) {
3581 after.erase(after.length() - 1, 1);
3583 if (!before.empty()) {
3585 before.erase(before.length() - 1, 1);
3587 begin_command_inset(os, "citation", command);
3588 os << "after " << '"' << after << '"' << "\n";
3589 os << "before " << '"' << before << '"' << "\n";
3590 os << "key " << '"' << citation << '"' << "\n";
3592 // Need to set the cite engine if jurabib is loaded by
3593 // the document class directly
3594 if (preamble.citeEngine() == "basic")
3595 preamble.citeEngine("jurabib");
3598 else if (t.cs() == "cite"
3599 || t.cs() == "nocite") {
3600 context.check_layout(os);
3601 string after = convert_command_inset_arg(p.getArg('[', ']'));
3602 string key = convert_command_inset_arg(p.verbatim_item());
3603 // store the case that it is "\nocite{*}" to use it later for
3606 begin_command_inset(os, "citation", t.cs());
3607 os << "after " << '"' << after << '"' << "\n";
3608 os << "key " << '"' << key << '"' << "\n";
3610 } else if (t.cs() == "nocite")
3614 else if (t.cs() == "index" ||
3615 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3616 context.check_layout(os);
3617 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3618 p.getArg('[', ']') : "";
3619 string const kind = arg.empty() ? "idx" : arg;
3620 begin_inset(os, "Index ");
3621 os << kind << "\nstatus collapsed\n";
3622 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3625 preamble.registerAutomaticallyLoadedPackage("splitidx");
3628 else if (t.cs() == "nomenclature") {
3629 context.check_layout(os);
3630 begin_command_inset(os, "nomenclature", "nomenclature");
3631 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3632 if (!prefix.empty())
3633 os << "prefix " << '"' << prefix << '"' << "\n";
3634 os << "symbol " << '"'
3635 << convert_command_inset_arg(p.verbatim_item());
3636 os << "\"\ndescription \""
3637 << convert_command_inset_arg(p.verbatim_item())
3640 preamble.registerAutomaticallyLoadedPackage("nomencl");
3643 else if (t.cs() == "label") {
3644 context.check_layout(os);
3645 begin_command_inset(os, "label", "label");
3647 << convert_command_inset_arg(p.verbatim_item())
3652 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3653 context.check_layout(os);
3654 string commandname = t.cs();
3656 if (p.next_token().asInput() == "*") {
3661 begin_command_inset(os, "index_print", commandname);
3662 string const indexname = p.getArg('[', ']');
3664 if (indexname.empty())
3665 os << "type \"idx\"\n";
3667 os << "type \"" << indexname << "\"\n";
3670 skip_spaces_braces(p);
3671 preamble.registerAutomaticallyLoadedPackage("makeidx");
3672 if (preamble.use_indices() == "true")
3673 preamble.registerAutomaticallyLoadedPackage("splitidx");
3676 else if (t.cs() == "printnomenclature") {
3678 string width_type = "";
3679 context.check_layout(os);
3680 begin_command_inset(os, "nomencl_print", "printnomenclature");
3681 // case of a custom width
3683 width = p.getArg('[', ']');
3684 width = translate_len(width);
3685 width_type = "custom";
3687 // case of no custom width
3688 // the case of no custom width but the width set
3689 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3690 // because the user could have set anything, not only the width
3691 // of the longest label (which would be width_type = "auto")
3692 string label = convert_command_inset_arg(p.getArg('{', '}'));
3693 if (label.empty() && width_type.empty())
3694 width_type = "none";
3695 os << "set_width \"" << width_type << "\"\n";
3696 if (width_type == "custom")
3697 os << "width \"" << width << '\"';
3699 skip_spaces_braces(p);
3700 preamble.registerAutomaticallyLoadedPackage("nomencl");
3703 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3704 context.check_layout(os);
3705 begin_inset(os, "script ");
3706 os << t.cs().substr(4) << '\n';
3707 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3709 if (t.cs() == "textsubscript")
3710 preamble.registerAutomaticallyLoadedPackage("subscript");
3713 else if ((where = is_known(t.cs(), known_quotes))) {
3714 context.check_layout(os);
3715 begin_inset(os, "Quotes ");
3716 os << known_coded_quotes[where - known_quotes];
3718 // LyX adds {} after the quote, so we have to eat
3719 // spaces here if there are any before a possible
3721 eat_whitespace(p, os, context, false);
3725 else if ((where = is_known(t.cs(), known_sizes)) &&
3726 context.new_layout_allowed) {
3727 context.check_layout(os);
3728 TeXFont const oldFont = context.font;
3729 context.font.size = known_coded_sizes[where - known_sizes];
3730 output_font_change(os, oldFont, context.font);
3731 eat_whitespace(p, os, context, false);
3734 else if ((where = is_known(t.cs(), known_font_families)) &&
3735 context.new_layout_allowed) {
3736 context.check_layout(os);
3737 TeXFont const oldFont = context.font;
3738 context.font.family =
3739 known_coded_font_families[where - known_font_families];
3740 output_font_change(os, oldFont, context.font);
3741 eat_whitespace(p, os, context, false);
3744 else if ((where = is_known(t.cs(), known_font_series)) &&
3745 context.new_layout_allowed) {
3746 context.check_layout(os);
3747 TeXFont const oldFont = context.font;
3748 context.font.series =
3749 known_coded_font_series[where - known_font_series];
3750 output_font_change(os, oldFont, context.font);
3751 eat_whitespace(p, os, context, false);
3754 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3755 context.new_layout_allowed) {
3756 context.check_layout(os);
3757 TeXFont const oldFont = context.font;
3758 context.font.shape =
3759 known_coded_font_shapes[where - known_font_shapes];
3760 output_font_change(os, oldFont, context.font);
3761 eat_whitespace(p, os, context, false);
3763 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3764 context.new_layout_allowed) {
3765 context.check_layout(os);
3766 TeXFont const oldFont = context.font;
3767 context.font.init();
3768 context.font.size = oldFont.size;
3769 context.font.family =
3770 known_coded_font_families[where - known_old_font_families];
3771 output_font_change(os, oldFont, context.font);
3772 eat_whitespace(p, os, context, false);
3775 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3776 context.new_layout_allowed) {
3777 context.check_layout(os);
3778 TeXFont const oldFont = context.font;
3779 context.font.init();
3780 context.font.size = oldFont.size;
3781 context.font.series =
3782 known_coded_font_series[where - known_old_font_series];
3783 output_font_change(os, oldFont, context.font);
3784 eat_whitespace(p, os, context, false);
3787 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3788 context.new_layout_allowed) {
3789 context.check_layout(os);
3790 TeXFont const oldFont = context.font;
3791 context.font.init();
3792 context.font.size = oldFont.size;
3793 context.font.shape =
3794 known_coded_font_shapes[where - known_old_font_shapes];
3795 output_font_change(os, oldFont, context.font);
3796 eat_whitespace(p, os, context, false);
3799 else if (t.cs() == "selectlanguage") {
3800 context.check_layout(os);
3801 // save the language for the case that a
3802 // \foreignlanguage is used
3803 context.font.language = babel2lyx(p.verbatim_item());
3804 os << "\n\\lang " << context.font.language << "\n";
3807 else if (t.cs() == "foreignlanguage") {
3808 string const lang = babel2lyx(p.verbatim_item());
3809 parse_text_attributes(p, os, FLAG_ITEM, outer,
3811 context.font.language, lang);
3814 else if (prefixIs(t.cs(), "text")
3815 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3816 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3818 // We have to output the whole command if it has an option
3819 // because LyX doesn't support this yet, see bug #8214,
3820 // only if there is a single option specifying a variant, we can handle it.
3822 string langopts = p.getOpt();
3823 // check if the option contains a variant, if yes, extract it
3824 string::size_type pos_var = langopts.find("variant");
3825 string::size_type i = langopts.find(',');
3826 string::size_type k = langopts.find('=', pos_var);
3827 if (pos_var != string::npos && i == string::npos) {
3829 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3830 lang = preamble.polyglossia2lyx(variant);
3831 parse_text_attributes(p, os, FLAG_ITEM, outer,
3833 context.font.language, lang);
3835 output_ert_inset(os, t.asInput() + langopts, context);
3837 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3838 parse_text_attributes(p, os, FLAG_ITEM, outer,
3840 context.font.language, lang);
3844 else if (t.cs() == "inputencoding") {
3845 // nothing to write here
3846 string const enc = subst(p.verbatim_item(), "\n", " ");
3847 p.setEncoding(enc, Encoding::inputenc);
3850 else if ((where = is_known(t.cs(), known_special_chars))) {
3851 context.check_layout(os);
3852 os << known_coded_special_chars[where - known_special_chars];
3853 skip_spaces_braces(p);
3856 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3857 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3858 context.check_layout(os);
3859 os << "\\SpecialChar \\" << t.cs()
3860 << p.get_token().asInput() << '\n';
3863 else if (t.cs() == "textquotedbl") {
3864 context.check_layout(os);
3869 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3870 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3871 || t.cs() == "%" || t.cs() == "-") {
3872 context.check_layout(os);
3874 os << "\\SpecialChar \\-\n";
3879 else if (t.cs() == "char") {
3880 context.check_layout(os);
3881 if (p.next_token().character() == '`') {
3883 if (p.next_token().cs() == "\"") {
3888 output_ert_inset(os, "\\char`", context);
3891 output_ert_inset(os, "\\char", context);
3895 else if (t.cs() == "verb") {
3896 context.check_layout(os);
3897 // set catcodes to verbatim early, just in case.
3898 p.setCatcodes(VERBATIM_CATCODES);
3899 string delim = p.get_token().asInput();
3900 Parser::Arg arg = p.verbatimStuff(delim);
3902 output_ert_inset(os, "\\verb" + delim
3903 + arg.second + delim, context);
3905 cerr << "invalid \\verb command. Skipping" << endl;
3908 // Problem: \= creates a tabstop inside the tabbing environment
3909 // and else an accent. In the latter case we really would want
3910 // \={o} instead of \= o.
3911 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3912 output_ert_inset(os, t.asInput(), context);
3914 else if (t.cs() == "\\") {
3915 context.check_layout(os);
3917 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3918 else if (p.next_token().asInput() == "*") {
3920 // getOpt() eats the following space if there
3921 // is no optional argument, but that is OK
3922 // here since it has no effect in the output.
3923 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3926 begin_inset(os, "Newline newline");
3931 else if (t.cs() == "newline" ||
3932 (t.cs() == "linebreak" && !p.hasOpt())) {
3933 context.check_layout(os);
3934 begin_inset(os, "Newline ");
3937 skip_spaces_braces(p);
3940 else if (t.cs() == "input" || t.cs() == "include"
3941 || t.cs() == "verbatiminput") {
3942 string name = t.cs();
3943 if (t.cs() == "verbatiminput"
3944 && p.next_token().asInput() == "*")
3945 name += p.get_token().asInput();
3946 context.check_layout(os);
3947 string filename(normalize_filename(p.getArg('{', '}')));
3948 string const path = getMasterFilePath(true);
3949 // We want to preserve relative / absolute filenames,
3950 // therefore path is only used for testing
3951 if ((t.cs() == "include" || t.cs() == "input") &&
3952 !makeAbsPath(filename, path).exists()) {
3953 // The file extension is probably missing.
3954 // Now try to find it out.
3955 string const tex_name =
3956 find_file(filename, path,
3957 known_tex_extensions);
3958 if (!tex_name.empty())
3959 filename = tex_name;
3961 bool external = false;
3963 if (makeAbsPath(filename, path).exists()) {
3964 string const abstexname =
3965 makeAbsPath(filename, path).absFileName();
3966 string const absfigname =
3967 changeExtension(abstexname, ".fig");
3968 fix_child_filename(filename);
3969 string const lyxname = changeExtension(filename,
3970 roundtripMode() ? ".lyx.lyx" : ".lyx");
3971 string const abslyxname = makeAbsPath(
3972 lyxname, getParentFilePath(false)).absFileName();
3974 if (!skipChildren())
3975 external = FileName(absfigname).exists();
3976 if (t.cs() == "input" && !skipChildren()) {
3977 string const ext = getExtension(abstexname);
3979 // Combined PS/LaTeX:
3980 // x.eps, x.pstex_t (old xfig)
3981 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3982 FileName const absepsname(
3983 changeExtension(abstexname, ".eps"));
3984 FileName const abspstexname(
3985 changeExtension(abstexname, ".pstex"));
3986 bool const xfigeps =
3987 (absepsname.exists() ||
3988 abspstexname.exists()) &&
3991 // Combined PDF/LaTeX:
3992 // x.pdf, x.pdftex_t (old xfig)
3993 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3994 FileName const abspdfname(
3995 changeExtension(abstexname, ".pdf"));
3996 bool const xfigpdf =
3997 abspdfname.exists() &&
3998 (ext == "pdftex_t" || ext == "pdf_t");
4002 // Combined PS/PDF/LaTeX:
4003 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4004 string const absbase2(
4005 removeExtension(abstexname) + "_pspdftex");
4006 FileName const abseps2name(
4007 addExtension(absbase2, ".eps"));
4008 FileName const abspdf2name(
4009 addExtension(absbase2, ".pdf"));
4010 bool const xfigboth =
4011 abspdf2name.exists() &&
4012 abseps2name.exists() && ext == "pspdftex";
4014 xfig = xfigpdf || xfigeps || xfigboth;
4015 external = external && xfig;
4018 outname = changeExtension(filename, ".fig");
4019 FileName abssrc(changeExtension(abstexname, ".fig"));
4020 copy_file(abssrc, outname);
4022 // Don't try to convert, the result
4023 // would be full of ERT.
4025 FileName abssrc(abstexname);
4026 copy_file(abssrc, outname);
4027 } else if (t.cs() != "verbatiminput" &&
4029 tex2lyx(abstexname, FileName(abslyxname),
4032 // no need to call copy_file
4033 // tex2lyx creates the file
4036 FileName abssrc(abstexname);
4037 copy_file(abssrc, outname);
4040 cerr << "Warning: Could not find included file '"
4041 << filename << "'." << endl;
4045 begin_inset(os, "External\n");
4046 os << "\ttemplate XFig\n"
4047 << "\tfilename " << outname << '\n';
4048 registerExternalTemplatePackages("XFig");
4050 begin_command_inset(os, "include", name);
4051 outname = subst(outname, "\"", "\\\"");
4052 os << "preview false\n"
4053 "filename \"" << outname << "\"\n";
4054 if (t.cs() == "verbatiminput")
4055 preamble.registerAutomaticallyLoadedPackage("verbatim");
4060 else if (t.cs() == "bibliographystyle") {
4061 // store new bibliographystyle
4062 bibliographystyle = p.verbatim_item();
4063 // If any other command than \bibliography, \addcontentsline
4064 // and \nocite{*} follows, we need to output the style
4065 // (because it might be used by that command).
4066 // Otherwise, it will automatically be output by LyX.
4069 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4070 if (t2.cat() == catBegin)
4072 if (t2.cat() != catEscape)
4074 if (t2.cs() == "nocite") {
4075 if (p.getArg('{', '}') == "*")
4077 } else if (t2.cs() == "bibliography")
4079 else if (t2.cs() == "phantomsection") {
4083 else if (t2.cs() == "addcontentsline") {
4084 // get the 3 arguments of \addcontentsline
4087 contentslineContent = p.getArg('{', '}');
4088 // if the last argument is not \refname we must output
4089 if (contentslineContent == "\\refname")
4096 output_ert_inset(os,
4097 "\\bibliographystyle{" + bibliographystyle + '}',
4102 else if (t.cs() == "phantomsection") {
4103 // we only support this if it occurs between
4104 // \bibliographystyle and \bibliography
4105 if (bibliographystyle.empty())
4106 output_ert_inset(os, "\\phantomsection", context);
4109 else if (t.cs() == "addcontentsline") {
4110 context.check_layout(os);
4111 // get the 3 arguments of \addcontentsline
4112 string const one = p.getArg('{', '}');
4113 string const two = p.getArg('{', '}');
4114 string const three = p.getArg('{', '}');
4115 // only if it is a \refname, we support if for the bibtex inset
4116 if (contentslineContent != "\\refname") {
4117 output_ert_inset(os,
4118 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4123 else if (t.cs() == "bibliography") {
4124 context.check_layout(os);
4126 begin_command_inset(os, "bibtex", "bibtex");
4127 if (!btprint.empty()) {
4128 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4129 // clear the string because the next BibTeX inset can be without the
4130 // \nocite{*} option
4133 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4134 // Do we have addcontentsline?
4135 if (contentslineContent == "\\refname") {
4136 BibOpts = "bibtotoc";
4137 // clear string because next BibTeX inset can be without addcontentsline
4138 contentslineContent.clear();
4140 // Do we have a bibliographystyle set?
4141 if (!bibliographystyle.empty()) {
4142 if (BibOpts.empty())
4143 BibOpts = bibliographystyle;
4145 BibOpts = BibOpts + ',' + bibliographystyle;
4146 // clear it because each bibtex entry has its style
4147 // and we need an empty string to handle \phantomsection
4148 bibliographystyle.clear();
4150 os << "options " << '"' << BibOpts << '"' << "\n";
4154 else if (t.cs() == "parbox") {
4155 // Test whether this is an outer box of a shaded box
4157 // swallow arguments
4158 while (p.hasOpt()) {
4160 p.skip_spaces(true);
4163 p.skip_spaces(true);
4165 if (p.next_token().cat() == catBegin)
4167 p.skip_spaces(true);
4168 Token to = p.get_token();
4169 bool shaded = false;
4170 if (to.asInput() == "\\begin") {
4171 p.skip_spaces(true);
4172 if (p.getArg('{', '}') == "shaded")
4177 parse_outer_box(p, os, FLAG_ITEM, outer,
4178 context, "parbox", "shaded");
4180 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4184 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4185 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4186 t.cs() == "shadowbox" || t.cs() == "doublebox")
4187 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4189 else if (t.cs() == "framebox") {
4190 if (p.next_token().character() == '(') {
4191 //the syntax is: \framebox(x,y)[position]{content}
4192 string arg = t.asInput();
4193 arg += p.getFullParentheseArg();
4194 arg += p.getFullOpt();
4195 eat_whitespace(p, os, context, false);
4196 output_ert_inset(os, arg + '{', context);
4197 parse_text(p, os, FLAG_ITEM, outer, context);
4198 output_ert_inset(os, "}", context);
4200 //the syntax is: \framebox[width][position]{content}
4201 string special = p.getFullOpt();
4202 special += p.getOpt();
4203 parse_outer_box(p, os, FLAG_ITEM, outer,
4204 context, t.cs(), special);
4208 //\makebox() is part of the picture environment and different from \makebox{}
4209 //\makebox{} will be parsed by parse_box
4210 else if (t.cs() == "makebox") {
4211 if (p.next_token().character() == '(') {
4212 //the syntax is: \makebox(x,y)[position]{content}
4213 string arg = t.asInput();
4214 arg += p.getFullParentheseArg();
4215 arg += p.getFullOpt();
4216 eat_whitespace(p, os, context, false);
4217 output_ert_inset(os, arg + '{', context);
4218 parse_text(p, os, FLAG_ITEM, outer, context);
4219 output_ert_inset(os, "}", context);
4221 //the syntax is: \makebox[width][position]{content}
4222 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4226 else if (t.cs() == "smallskip" ||
4227 t.cs() == "medskip" ||
4228 t.cs() == "bigskip" ||
4229 t.cs() == "vfill") {
4230 context.check_layout(os);
4231 begin_inset(os, "VSpace ");
4234 skip_spaces_braces(p);
4237 else if ((where = is_known(t.cs(), known_spaces))) {
4238 context.check_layout(os);
4239 begin_inset(os, "space ");
4240 os << '\\' << known_coded_spaces[where - known_spaces]
4243 // LaTeX swallows whitespace after all spaces except
4244 // "\\,". We have to do that here, too, because LyX
4245 // adds "{}" which would make the spaces significant.
4247 eat_whitespace(p, os, context, false);
4248 // LyX adds "{}" after all spaces except "\\ " and
4249 // "\\,", so we have to remove "{}".
4250 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4251 // remove the braces after "\\,", too.
4256 else if (t.cs() == "newpage" ||
4257 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4258 t.cs() == "clearpage" ||
4259 t.cs() == "cleardoublepage") {
4260 context.check_layout(os);
4261 begin_inset(os, "Newpage ");
4264 skip_spaces_braces(p);
4267 else if (t.cs() == "DeclareRobustCommand" ||
4268 t.cs() == "DeclareRobustCommandx" ||
4269 t.cs() == "newcommand" ||
4270 t.cs() == "newcommandx" ||
4271 t.cs() == "providecommand" ||
4272 t.cs() == "providecommandx" ||
4273 t.cs() == "renewcommand" ||
4274 t.cs() == "renewcommandx") {
4275 // DeclareRobustCommand, DeclareRobustCommandx,
4276 // providecommand and providecommandx could be handled
4277 // by parse_command(), but we need to call
4278 // add_known_command() here.
4279 string name = t.asInput();
4280 if (p.next_token().asInput() == "*") {
4281 // Starred form. Eat '*'
4285 string const command = p.verbatim_item();
4286 string const opt1 = p.getFullOpt();
4287 string const opt2 = p.getFullOpt();
4288 add_known_command(command, opt1, !opt2.empty());
4289 string const ert = name + '{' + command + '}' +
4291 '{' + p.verbatim_item() + '}';
4293 if (t.cs() == "DeclareRobustCommand" ||
4294 t.cs() == "DeclareRobustCommandx" ||
4295 t.cs() == "providecommand" ||
4296 t.cs() == "providecommandx" ||
4297 name[name.length()-1] == '*')
4298 output_ert_inset(os, ert, context);
4300 context.check_layout(os);
4301 begin_inset(os, "FormulaMacro");
4307 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4308 // let could be handled by parse_command(),
4309 // but we need to call add_known_command() here.
4310 string ert = t.asInput();
4313 if (p.next_token().cat() == catBegin) {
4314 name = p.verbatim_item();
4315 ert += '{' + name + '}';
4317 name = p.verbatim_item();
4322 if (p.next_token().cat() == catBegin) {
4323 command = p.verbatim_item();
4324 ert += '{' + command + '}';
4326 command = p.verbatim_item();
4329 // If command is known, make name known too, to parse
4330 // its arguments correctly. For this reason we also
4331 // have commands in syntax.default that are hardcoded.
4332 CommandMap::iterator it = known_commands.find(command);
4333 if (it != known_commands.end())
4334 known_commands[t.asInput()] = it->second;
4335 output_ert_inset(os, ert, context);
4338 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4339 bool starred = false;
4340 if (p.next_token().asInput() == "*") {
4344 string name = t.asInput();
4345 string const length = p.verbatim_item();
4348 bool valid = splitLatexLength(length, valstring, unit);
4349 bool known_hspace = false;
4350 bool known_vspace = false;
4351 bool known_unit = false;
4354 istringstream iss(valstring);
4357 if (t.cs()[0] == 'h') {
4358 if (unit == "\\fill") {
4363 known_hspace = true;
4366 if (unit == "\\smallskipamount") {
4368 known_vspace = true;
4369 } else if (unit == "\\medskipamount") {
4371 known_vspace = true;
4372 } else if (unit == "\\bigskipamount") {
4374 known_vspace = true;
4375 } else if (unit == "\\fill") {
4377 known_vspace = true;
4381 if (!known_hspace && !known_vspace) {
4382 switch (unitFromString(unit)) {
4398 //unitFromString(unit) fails for relative units like Length::PCW
4399 // therefore handle them separately
4400 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4401 || unit == "\\textwidth" || unit == "\\linewidth"
4402 || unit == "\\textheight" || unit == "\\paperheight")
4410 // check for glue lengths
4411 bool is_gluelength = false;
4412 string gluelength = length;
4413 string::size_type i = length.find(" minus");
4414 if (i == string::npos) {
4415 i = length.find(" plus");
4416 if (i != string::npos)
4417 is_gluelength = true;
4419 is_gluelength = true;
4420 // if yes transform "9xx minus 8yy plus 7zz"
4422 if (is_gluelength) {
4423 i = gluelength.find(" minus");
4424 if (i != string::npos)
4425 gluelength.replace(i, 7, "-");
4426 i = gluelength.find(" plus");
4427 if (i != string::npos)
4428 gluelength.replace(i, 6, "+");
4431 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4432 // Literal horizontal length or known variable
4433 context.check_layout(os);
4434 begin_inset(os, "space ");
4442 if (known_unit && !known_hspace)
4443 os << "\n\\length " << translate_len(length);
4445 os << "\n\\length " << gluelength;
4447 } else if (known_unit || known_vspace || is_gluelength) {
4448 // Literal vertical length or known variable
4449 context.check_layout(os);
4450 begin_inset(os, "VSpace ");
4453 if (known_unit && !known_vspace)
4454 os << translate_len(length);
4461 // LyX can't handle other length variables in Inset VSpace/space
4466 output_ert_inset(os, name + '{' + unit + '}', context);
4467 else if (value == -1.0)
4468 output_ert_inset(os, name + "{-" + unit + '}', context);
4470 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4472 output_ert_inset(os, name + '{' + length + '}', context);
4476 // The single '=' is meant here.
4477 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4479 context.check_layout(os);
4480 begin_inset(os, "Flex ");
4481 os << to_utf8(newinsetlayout->name()) << '\n'
4482 << "status collapsed\n";
4483 if (newinsetlayout->isPassThru()) {
4484 // set catcodes to verbatim early, just in case.
4485 p.setCatcodes(VERBATIM_CATCODES);
4486 string delim = p.get_token().asInput();
4488 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4489 //FIXME: handle error condition
4490 string const arg = p.verbatimStuff("}").second;
4491 Context newcontext(true, context.textclass);
4492 if (newinsetlayout->forcePlainLayout())
4493 newcontext.layout = &context.textclass.plainLayout();
4494 output_ert(os, arg, newcontext);
4496 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4500 else if (t.cs() == "includepdf") {
4502 string const arg = p.getArg('[', ']');
4503 map<string, string> opts;
4504 vector<string> keys;
4505 split_map(arg, opts, keys);
4506 string name = normalize_filename(p.verbatim_item());
4507 string const path = getMasterFilePath(true);
4508 // We want to preserve relative / absolute filenames,
4509 // therefore path is only used for testing
4510 if (!makeAbsPath(name, path).exists()) {
4511 // The file extension is probably missing.
4512 // Now try to find it out.
4513 char const * const pdfpages_format[] = {"pdf", 0};
4514 string const pdftex_name =
4515 find_file(name, path, pdfpages_format);
4516 if (!pdftex_name.empty()) {
4521 FileName const absname = makeAbsPath(name, path);
4522 if (absname.exists())
4524 fix_child_filename(name);
4525 copy_file(absname, name);
4527 cerr << "Warning: Could not find file '"
4528 << name << "'." << endl;
4530 context.check_layout(os);
4531 begin_inset(os, "External\n\ttemplate ");
4532 os << "PDFPages\n\tfilename "
4534 // parse the options
4535 if (opts.find("pages") != opts.end())
4536 os << "\textra LaTeX \"pages="
4537 << opts["pages"] << "\"\n";
4538 if (opts.find("angle") != opts.end())
4539 os << "\trotateAngle "
4540 << opts["angle"] << '\n';
4541 if (opts.find("origin") != opts.end()) {
4543 string const opt = opts["origin"];
4544 if (opt == "tl") ss << "topleft";
4545 if (opt == "bl") ss << "bottomleft";
4546 if (opt == "Bl") ss << "baselineleft";
4547 if (opt == "c") ss << "center";
4548 if (opt == "tc") ss << "topcenter";
4549 if (opt == "bc") ss << "bottomcenter";
4550 if (opt == "Bc") ss << "baselinecenter";
4551 if (opt == "tr") ss << "topright";
4552 if (opt == "br") ss << "bottomright";
4553 if (opt == "Br") ss << "baselineright";
4554 if (!ss.str().empty())
4555 os << "\trotateOrigin " << ss.str() << '\n';
4557 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4559 if (opts.find("width") != opts.end())
4561 << translate_len(opts["width"]) << '\n';
4562 if (opts.find("height") != opts.end())
4564 << translate_len(opts["height"]) << '\n';
4565 if (opts.find("keepaspectratio") != opts.end())
4566 os << "\tkeepAspectRatio\n";
4568 context.check_layout(os);
4569 registerExternalTemplatePackages("PDFPages");
4572 else if (t.cs() == "loadgame") {
4574 string name = normalize_filename(p.verbatim_item());
4575 string const path = getMasterFilePath(true);
4576 // We want to preserve relative / absolute filenames,
4577 // therefore path is only used for testing
4578 if (!makeAbsPath(name, path).exists()) {
4579 // The file extension is probably missing.
4580 // Now try to find it out.
4581 char const * const lyxskak_format[] = {"fen", 0};
4582 string const lyxskak_name =
4583 find_file(name, path, lyxskak_format);
4584 if (!lyxskak_name.empty())
4585 name = lyxskak_name;
4587 FileName const absname = makeAbsPath(name, path);
4588 if (absname.exists())
4590 fix_child_filename(name);
4591 copy_file(absname, name);
4593 cerr << "Warning: Could not find file '"
4594 << name << "'." << endl;
4595 context.check_layout(os);
4596 begin_inset(os, "External\n\ttemplate ");
4597 os << "ChessDiagram\n\tfilename "
4600 context.check_layout(os);
4601 // after a \loadgame follows a \showboard
4602 if (p.get_token().asInput() == "showboard")
4604 registerExternalTemplatePackages("ChessDiagram");
4608 // try to see whether the string is in unicodesymbols
4609 // Only use text mode commands, since we are in text mode here,
4610 // and math commands may be invalid (bug 6797)
4611 string name = t.asInput();
4612 // handle the dingbats and Cyrillic
4613 if (name == "\\ding" || name == "\\textcyr")
4614 name = name + '{' + p.getArg('{', '}') + '}';
4615 // handle the ifsym characters
4616 else if (name == "\\textifsymbol") {
4617 string const optif = p.getFullOpt();
4618 string const argif = p.getArg('{', '}');
4619 name = name + optif + '{' + argif + '}';
4621 // handle the \ascii characters
4622 // the case of \ascii within braces, as LyX outputs it, is already
4623 // handled for t.cat() == catBegin
4624 else if (name == "\\ascii") {
4625 // the code is "\asci\xxx"
4626 name = "{" + name + p.get_token().asInput() + "}";
4629 // handle some TIPA special characters
4630 else if (preamble.isPackageUsed("tipa")) {
4631 if (name == "\\textglobfall") {
4634 } else if (name == "\\s") {
4635 // fromLaTeXCommand() does not yet
4636 // recognize tipa short cuts
4637 name = "\\textsyllabic";
4638 } else if (name == "\\=" &&
4639 p.next_token().asInput() == "*") {
4640 // fromLaTeXCommand() does not yet
4641 // recognize tipa short cuts
4644 } else if (name == "\\textdoublevertline") {
4645 // FIXME: This is not correct,
4646 // \textvertline is higher than \textbardbl
4647 name = "\\textbardbl";
4649 } else if (name == "\\!" ) {
4650 if (p.next_token().asInput() == "b") {
4651 p.get_token(); // eat 'b'
4654 } else if (p.next_token().asInput() == "d") {
4658 } else if (p.next_token().asInput() == "g") {
4662 } else if (p.next_token().asInput() == "G") {
4664 name = "\\texthtscg";
4666 } else if (p.next_token().asInput() == "j") {
4668 name = "\\texthtbardotlessj";
4670 } else if (p.next_token().asInput() == "o") {
4672 name = "\\textbullseye";
4675 } else if (name == "\\*" ) {
4676 if (p.next_token().asInput() == "k") {
4678 name = "\\textturnk";
4680 } else if (p.next_token().asInput() == "r") {
4681 p.get_token(); // eat 'b'
4682 name = "\\textturnr";
4684 } else if (p.next_token().asInput() == "t") {
4686 name = "\\textturnt";
4688 } else if (p.next_token().asInput() == "w") {
4690 name = "\\textturnw";
4695 if ((name.size() == 2 &&
4696 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4697 p.next_token().asInput() != "*") ||
4698 is_known(name.substr(1), known_tipa_marks)) {
4699 // name is a command that corresponds to a
4700 // combining character in unicodesymbols.
4701 // Append the argument, fromLaTeXCommand()
4702 // will either convert it to a single
4703 // character or a combining sequence.
4704 name += '{' + p.verbatim_item() + '}';
4706 // now get the character from unicodesymbols
4710 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4711 Encodings::TEXT_CMD, termination, rem, &req);
4713 context.check_layout(os);
4716 output_ert_inset(os, to_utf8(rem), context);
4718 skip_spaces_braces(p);
4719 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4720 preamble.registerAutomaticallyLoadedPackage(*it);
4722 //cerr << "#: " << t << " mode: " << mode << endl;
4723 // heuristic: read up to next non-nested space
4725 string s = t.asInput();
4726 string z = p.verbatim_item();
4727 while (p.good() && z != " " && !z.empty()) {
4728 //cerr << "read: " << z << endl;
4730 z = p.verbatim_item();
4732 cerr << "found ERT: " << s << endl;
4733 output_ert_inset(os, s + ' ', context);
4736 if (t.asInput() == name &&
4737 p.next_token().asInput() == "*") {
4738 // Starred commands like \vspace*{}
4739 p.get_token(); // Eat '*'
4742 if (!parse_command(name, p, os, outer, context))
4743 output_ert_inset(os, name, context);
4747 if (flags & FLAG_LEAVE) {
4748 flags &= ~FLAG_LEAVE;
4755 string guessLanguage(Parser & p, string const & lang)
4757 typedef std::map<std::string, size_t> LangMap;
4758 // map from language names to number of characters
4761 for (char const * const * i = supported_CJK_languages; *i; i++)
4762 used[string(*i)] = 0;
4765 Token const t = p.get_token();
4766 // comments are not counted for any language
4767 if (t.cat() == catComment)
4769 // commands are not counted as well, but we need to detect
4770 // \begin{CJK} and switch encoding if needed
4771 if (t.cat() == catEscape) {
4772 if (t.cs() == "inputencoding") {
4773 string const enc = subst(p.verbatim_item(), "\n", " ");
4774 p.setEncoding(enc, Encoding::inputenc);
4777 if (t.cs() != "begin")
4780 // Non-CJK content is counted for lang.
4781 // We do not care about the real language here:
4782 // If we have more non-CJK contents than CJK contents,
4783 // we simply use the language that was specified as
4784 // babel main language.
4785 used[lang] += t.asInput().length();
4788 // Now we are starting an environment
4790 string const name = p.getArg('{', '}');
4791 if (name != "CJK") {
4795 // It is a CJK environment
4797 /* name = */ p.getArg('{', '}');
4798 string const encoding = p.getArg('{', '}');
4799 /* mapping = */ p.getArg('{', '}');
4800 string const encoding_old = p.getEncoding();
4801 char const * const * const where =
4802 is_known(encoding, supported_CJK_encodings);
4804 p.setEncoding(encoding, Encoding::CJK);
4806 p.setEncoding("UTF-8");
4807 string const text = p.ertEnvironment("CJK");
4808 p.setEncoding(encoding_old);
4811 // ignore contents in unknown CJK encoding
4814 // the language of the text
4816 supported_CJK_languages[where - supported_CJK_encodings];
4817 used[cjk] += text.length();
4819 LangMap::const_iterator use = used.begin();
4820 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4821 if (it->second > use->second)