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 bool const starred = p.next_token().asInput() == "*";
2272 string const starredname(starred ? (t.cs() + '*') : t.cs());
2273 if (t.cat() == catMath) {
2274 // we are inside some text mode thingy, so opening new math is allowed
2275 context.check_layout(os);
2276 begin_inset(os, "Formula ");
2277 Token const & n = p.get_token();
2278 bool const display(n.cat() == catMath && outer);
2280 // TeX's $$...$$ syntax for displayed math
2282 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2284 p.get_token(); // skip the second '$' token
2286 // simple $...$ stuff
2289 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2294 // Prevent the conversion of a line break to a
2295 // space (bug 7668). This does not change the
2296 // output, but looks ugly in LyX.
2297 eat_whitespace(p, os, context, false);
2301 else if (t.cat() == catSuper || t.cat() == catSub)
2302 cerr << "catcode " << t << " illegal in text mode\n";
2304 // Basic support for english quotes. This should be
2305 // extended to other quotes, but is not so easy (a
2306 // left english quote is the same as a right german
2308 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2309 context.check_layout(os);
2310 begin_inset(os, "Quotes ");
2316 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2317 context.check_layout(os);
2318 begin_inset(os, "Quotes ");
2325 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2326 context.check_layout(os);
2327 begin_inset(os, "Quotes ");
2334 else if (t.asInput() == "<"
2335 && p.next_token().asInput() == "<") {
2336 bool has_chunk = false;
2340 has_chunk = parse_chunk(p, os, context);
2346 context.check_layout(os);
2347 begin_inset(os, "Quotes ");
2348 //FIXME: this is a right danish quote;
2349 // why not a left french quote?
2357 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2358 check_space(p, os, context);
2360 else if (t.character() == '[' && noweb_mode &&
2361 p.next_token().character() == '[') {
2362 // These can contain underscores
2364 string const s = p.getFullOpt() + ']';
2365 if (p.next_token().character() == ']')
2368 cerr << "Warning: Inserting missing ']' in '"
2369 << s << "'." << endl;
2370 output_ert_inset(os, s, context);
2373 else if (t.cat() == catLetter) {
2374 context.check_layout(os);
2375 // Workaround for bug 4752.
2376 // FIXME: This whole code block needs to be removed
2377 // when the bug is fixed and tex2lyx produces
2378 // the updated file format.
2379 // The replacement algorithm in LyX is so stupid that
2380 // it even translates a phrase if it is part of a word.
2381 bool handled = false;
2382 for (int const * l = known_phrase_lengths; *l; ++l) {
2383 string phrase = t.cs();
2384 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2385 phrase += p.get_token().cs();
2386 if (is_known(phrase, known_coded_phrases)) {
2387 output_ert_inset(os, phrase, context);
2391 for (size_t i = 1; i < phrase.length(); ++i)
2399 else if (t.cat() == catOther ||
2400 t.cat() == catAlign ||
2401 t.cat() == catParameter) {
2402 // This translates "&" to "\\&" which may be wrong...
2403 context.check_layout(os);
2407 else if (p.isParagraph()) {
2408 if (context.new_layout_allowed)
2409 context.new_paragraph(os);
2411 output_ert_inset(os, "\\par ", context);
2412 eat_whitespace(p, os, context, true);
2415 else if (t.cat() == catActive) {
2416 context.check_layout(os);
2417 if (t.character() == '~') {
2418 if (context.layout->free_spacing)
2421 begin_inset(os, "space ~\n");
2428 else if (t.cat() == catBegin) {
2429 Token const next = p.next_token();
2430 Token const end = p.next_next_token();
2431 if (next.cat() == catEnd) {
2433 Token const prev = p.prev_token();
2435 if (p.next_token().character() == '`' ||
2436 (prev.character() == '-' &&
2437 p.next_token().character() == '-'))
2438 ; // ignore it in {}`` or -{}-
2440 output_ert_inset(os, "{}", context);
2441 } else if (next.cat() == catEscape &&
2442 is_known(next.cs(), known_quotes) &&
2443 end.cat() == catEnd) {
2444 // Something like {\textquoteright} (e.g.
2445 // from writer2latex). LyX writes
2446 // \textquoteright{}, so we may skip the
2447 // braces here for better readability.
2448 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2450 } else if (p.next_token().asInput() == "\\ascii") {
2451 // handle the \ascii characters
2452 // (the case without braces is handled later)
2453 // the code is "{\ascii\xxx}"
2454 p.get_token(); // eat \ascii
2455 string name2 = p.get_token().asInput();
2456 p.get_token(); // eat the final '}'
2457 string const name = "{\\ascii" + name2 + "}";
2461 // get the character from unicodesymbols
2462 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2463 Encodings::TEXT_CMD, termination, rem, &req);
2465 context.check_layout(os);
2468 output_ert_inset(os,
2469 to_utf8(rem), context);
2470 for (set<string>::const_iterator it = req.begin();
2471 it != req.end(); ++it)
2472 preamble.registerAutomaticallyLoadedPackage(*it);
2474 // we did not find a non-ert version
2475 output_ert_inset(os, name, context);
2477 context.check_layout(os);
2478 // special handling of font attribute changes
2479 Token const prev = p.prev_token();
2480 TeXFont const oldFont = context.font;
2481 if (next.character() == '[' ||
2482 next.character() == ']' ||
2483 next.character() == '*') {
2485 if (p.next_token().cat() == catEnd) {
2490 output_ert_inset(os, "{", context);
2491 parse_text_snippet(p, os,
2494 output_ert_inset(os, "}", context);
2496 } else if (! context.new_layout_allowed) {
2497 output_ert_inset(os, "{", context);
2498 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2500 output_ert_inset(os, "}", context);
2501 } else if (is_known(next.cs(), known_sizes)) {
2502 // next will change the size, so we must
2504 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2506 if (!context.atParagraphStart())
2508 << context.font.size << "\n";
2509 } else if (is_known(next.cs(), known_font_families)) {
2510 // next will change the font family, so we
2511 // must reset it here
2512 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2514 if (!context.atParagraphStart())
2516 << context.font.family << "\n";
2517 } else if (is_known(next.cs(), known_font_series)) {
2518 // next will change the font series, so we
2519 // must reset it here
2520 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2522 if (!context.atParagraphStart())
2524 << context.font.series << "\n";
2525 } else if (is_known(next.cs(), known_font_shapes)) {
2526 // next will change the font shape, so we
2527 // must reset it here
2528 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2530 if (!context.atParagraphStart())
2532 << context.font.shape << "\n";
2533 } else if (is_known(next.cs(), known_old_font_families) ||
2534 is_known(next.cs(), known_old_font_series) ||
2535 is_known(next.cs(), known_old_font_shapes)) {
2536 // next will change the font family, series
2537 // and shape, so we must reset it here
2538 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2540 if (!context.atParagraphStart())
2542 << context.font.family
2544 << context.font.series
2546 << context.font.shape << "\n";
2548 output_ert_inset(os, "{", context);
2549 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2551 output_ert_inset(os, "}", context);
2556 else if (t.cat() == catEnd) {
2557 if (flags & FLAG_BRACE_LAST) {
2560 cerr << "stray '}' in text\n";
2561 output_ert_inset(os, "}", context);
2564 else if (t.cat() == catComment)
2565 parse_comment(p, os, t, context);
2568 // control sequences
2571 else if (t.cs() == "(" || t.cs() == "[") {
2572 bool const simple = t.cs() == "(";
2573 context.check_layout(os);
2574 begin_inset(os, "Formula");
2575 os << " \\" << t.cs();
2576 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2577 os << '\\' << (simple ? ')' : ']');
2580 // Prevent the conversion of a line break to a
2581 // space (bug 7668). This does not change the
2582 // output, but looks ugly in LyX.
2583 eat_whitespace(p, os, context, false);
2587 else if (t.cs() == "begin")
2588 parse_environment(p, os, outer, last_env,
2591 else if (t.cs() == "end") {
2592 if (flags & FLAG_END) {
2593 // eat environment name
2594 string const name = p.getArg('{', '}');
2595 if (name != active_environment())
2596 cerr << "\\end{" + name + "} does not match \\begin{"
2597 + active_environment() + "}\n";
2600 p.error("found 'end' unexpectedly");
2603 else if (t.cs() == "item") {
2605 bool const optarg = p.hasOpt();
2607 // FIXME: This swallows comments, but we cannot use
2608 // eat_whitespace() since we must not output
2609 // anything before the item.
2610 p.skip_spaces(true);
2611 s = p.verbatimOption();
2613 p.skip_spaces(false);
2615 context.check_layout(os);
2616 if (context.has_item) {
2617 // An item in an unknown list-like environment
2618 // FIXME: Do this in check_layout()!
2619 context.has_item = false;
2621 output_ert_inset(os, "\\item", context);
2623 output_ert_inset(os, "\\item ", context);
2626 if (context.layout->labeltype != LABEL_MANUAL) {
2627 // handle option of itemize item
2628 begin_inset(os, "Argument item:1\n");
2629 os << "status open\n";
2630 os << "\n\\begin_layout Plain Layout\n";
2632 os << parse_text_snippet(p2,
2633 FLAG_BRACK_LAST, outer, context);
2634 // we must not use context.check_end_layout(os)
2635 // because that would close the outer itemize layout
2636 os << "\n\\end_layout\n";
2638 eat_whitespace(p, os, context, false);
2639 } else if (!s.empty()) {
2640 // LyX adds braces around the argument,
2641 // so we need to remove them here.
2642 if (s.size() > 2 && s[0] == '{' &&
2643 s[s.size()-1] == '}')
2644 s = s.substr(1, s.size()-2);
2645 // If the argument contains a space we
2646 // must put it into ERT: Otherwise LyX
2647 // would misinterpret the space as
2648 // item delimiter (bug 7663)
2649 if (contains(s, ' ')) {
2650 output_ert_inset(os, s, context);
2653 os << parse_text_snippet(p2,
2654 FLAG_BRACK_LAST, outer, context);
2656 // The space is needed to separate the
2657 // item from the rest of the sentence.
2659 eat_whitespace(p, os, context, false);
2664 else if (t.cs() == "bibitem") {
2666 context.check_layout(os);
2667 eat_whitespace(p, os, context, false);
2668 string label = convert_command_inset_arg(p.verbatimOption());
2669 string key = convert_command_inset_arg(p.verbatim_item());
2670 if (contains(label, '\\') || contains(key, '\\')) {
2671 // LyX can't handle LaTeX commands in labels or keys
2672 output_ert_inset(os, t.asInput() + '[' + label +
2673 "]{" + p.verbatim_item() + '}',
2676 begin_command_inset(os, "bibitem", "bibitem");
2677 os << "label \"" << label << "\"\n"
2678 "key \"" << key << "\"\n";
2683 else if (is_macro(p)) {
2684 // catch the case of \def\inputGnumericTable
2686 if (t.cs() == "def") {
2687 Token second = p.next_token();
2688 if (second.cs() == "inputGnumericTable") {
2692 Token third = p.get_token();
2694 if (third.cs() == "input") {
2698 string name = normalize_filename(p.verbatim_item());
2699 string const path = getMasterFilePath(true);
2700 // We want to preserve relative / absolute filenames,
2701 // therefore path is only used for testing
2702 // The file extension is in every case ".tex".
2703 // So we need to remove this extension and check for
2704 // the original one.
2705 name = removeExtension(name);
2706 if (!makeAbsPath(name, path).exists()) {
2707 char const * const Gnumeric_formats[] = {"gnumeric",
2709 string const Gnumeric_name =
2710 find_file(name, path, Gnumeric_formats);
2711 if (!Gnumeric_name.empty())
2712 name = Gnumeric_name;
2714 FileName const absname = makeAbsPath(name, path);
2715 if (absname.exists()) {
2716 fix_child_filename(name);
2717 copy_file(absname, name);
2719 cerr << "Warning: Could not find file '"
2720 << name << "'." << endl;
2721 context.check_layout(os);
2722 begin_inset(os, "External\n\ttemplate ");
2723 os << "GnumericSpreadsheet\n\tfilename "
2726 context.check_layout(os);
2728 // register the packages that are automatically loaded
2729 // by the Gnumeric template
2730 registerExternalTemplatePackages("GnumericSpreadsheet");
2735 parse_macro(p, os, context);
2738 else if (t.cs() == "noindent") {
2740 context.add_par_extra_stuff("\\noindent\n");
2743 else if (t.cs() == "appendix") {
2744 context.add_par_extra_stuff("\\start_of_appendix\n");
2745 // We need to start a new paragraph. Otherwise the
2746 // appendix in 'bla\appendix\chapter{' would start
2748 context.new_paragraph(os);
2749 // We need to make sure that the paragraph is
2750 // generated even if it is empty. Otherwise the
2751 // appendix in '\par\appendix\par\chapter{' would
2753 context.check_layout(os);
2754 // FIXME: This is a hack to prevent paragraph
2755 // deletion if it is empty. Handle this better!
2756 output_ert_inset(os,
2757 "%dummy comment inserted by tex2lyx to "
2758 "ensure that this paragraph is not empty",
2760 // Both measures above may generate an additional
2761 // empty paragraph, but that does not hurt, because
2762 // whitespace does not matter here.
2763 eat_whitespace(p, os, context, true);
2766 // Must catch empty dates before findLayout is called below
2767 else if (t.cs() == "date") {
2768 eat_whitespace(p, os, context, false);
2770 string const date = p.verbatim_item();
2773 preamble.suppressDate(true);
2776 preamble.suppressDate(false);
2777 if (context.new_layout_allowed &&
2778 (newlayout = findLayout(context.textclass,
2781 output_command_layout(os, p, outer,
2782 context, newlayout);
2783 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2784 if (!preamble.titleLayoutFound())
2785 preamble.titleLayoutFound(newlayout->intitle);
2786 set<string> const & req = newlayout->requires();
2787 set<string>::const_iterator it = req.begin();
2788 set<string>::const_iterator en = req.end();
2789 for (; it != en; ++it)
2790 preamble.registerAutomaticallyLoadedPackage(*it);
2792 output_ert_inset(os,
2793 "\\date{" + p.verbatim_item() + '}',
2798 // Starred section headings
2799 // Must attempt to parse "Section*" before "Section".
2800 else if ((p.next_token().asInput() == "*") &&
2801 context.new_layout_allowed &&
2802 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2805 output_command_layout(os, p, outer, context, newlayout);
2807 if (!preamble.titleLayoutFound())
2808 preamble.titleLayoutFound(newlayout->intitle);
2809 set<string> const & req = newlayout->requires();
2810 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2811 preamble.registerAutomaticallyLoadedPackage(*it);
2814 // Section headings and the like
2815 else if (context.new_layout_allowed &&
2816 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2818 output_command_layout(os, p, outer, context, newlayout);
2820 if (!preamble.titleLayoutFound())
2821 preamble.titleLayoutFound(newlayout->intitle);
2822 set<string> const & req = newlayout->requires();
2823 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2824 preamble.registerAutomaticallyLoadedPackage(*it);
2827 else if (t.cs() == "caption" || t.cs() == "captionabove" ||
2828 t.cs() == "captionbelow") {
2832 context.check_layout(os);
2834 if (starred && t.cs() == "caption")
2835 begin_inset(os, "Caption LongTableNoNumber\n");
2836 else if (t.cs() == "caption")
2837 begin_inset(os, "Caption Standard\n");
2838 else if (t.cs() == "captionabove")
2839 begin_inset(os, "Caption Above\n");
2840 else if (t.cs() == "captionbelow")
2841 begin_inset(os, "Caption Below\n");
2842 Context newcontext(true, context.textclass, 0, 0, context.font);
2843 newcontext.check_layout(os);
2844 // FIXME InsetArgument is now properly implemented in InsetLayout
2845 // (for captions, but also for others)
2846 if (p.next_token().cat() != catEscape &&
2847 p.next_token().character() == '[') {
2848 p.get_token(); // eat '['
2849 begin_inset(os, "Argument 1\n");
2850 os << "status collapsed\n";
2851 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2853 eat_whitespace(p, os, context, false);
2855 parse_text(p, os, FLAG_ITEM, outer, context);
2856 context.check_end_layout(os);
2857 // We don't need really a new paragraph, but
2858 // we must make sure that the next item gets a \begin_layout.
2859 context.new_paragraph(os);
2862 newcontext.check_end_layout(os);
2865 else if (t.cs() == "subfloat") {
2866 // the syntax is \subfloat[caption]{content}
2867 // if it is a table of figure depends on the surrounding float
2868 bool has_caption = false;
2870 // do nothing if there is no outer float
2871 if (!float_type.empty()) {
2872 context.check_layout(os);
2874 begin_inset(os, "Float " + float_type + "\n");
2876 << "\nsideways false"
2877 << "\nstatus collapsed\n\n";
2880 if (p.next_token().cat() != catEscape &&
2881 p.next_token().character() == '[') {
2882 p.get_token(); // eat '['
2883 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2887 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2888 // the caption comes always as the last
2890 // we must make sure that the caption gets a \begin_layout
2891 os << "\n\\begin_layout Plain Layout";
2893 begin_inset(os, "Caption Standard\n");
2894 Context newcontext(true, context.textclass,
2895 0, 0, context.font);
2896 newcontext.check_layout(os);
2897 os << caption << "\n";
2898 newcontext.check_end_layout(os);
2899 // We don't need really a new paragraph, but
2900 // we must make sure that the next item gets a \begin_layout.
2901 //newcontext.new_paragraph(os);
2905 // We don't need really a new paragraph, but
2906 // we must make sure that the next item gets a \begin_layout.
2908 context.new_paragraph(os);
2911 context.check_end_layout(os);
2912 // close the layout we opened
2914 os << "\n\\end_layout\n";
2916 // if the float type is not supported or there is no surrounding float
2919 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2920 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2921 "]{" + p.verbatim_item() + '}', context);
2923 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2927 else if (t.cs() == "includegraphics") {
2928 bool const clip = p.next_token().asInput() == "*";
2931 string const arg = p.getArg('[', ']');
2932 map<string, string> opts;
2933 vector<string> keys;
2934 split_map(arg, opts, keys);
2936 opts["clip"] = string();
2937 string name = normalize_filename(p.verbatim_item());
2939 string const path = getMasterFilePath(true);
2940 // We want to preserve relative / absolute filenames,
2941 // therefore path is only used for testing
2942 if (!makeAbsPath(name, path).exists()) {
2943 // The file extension is probably missing.
2944 // Now try to find it out.
2945 string const dvips_name =
2946 find_file(name, path,
2947 known_dvips_graphics_formats);
2948 string const pdftex_name =
2949 find_file(name, path,
2950 known_pdftex_graphics_formats);
2951 if (!dvips_name.empty()) {
2952 if (!pdftex_name.empty()) {
2953 cerr << "This file contains the "
2955 "\"\\includegraphics{"
2957 "However, files\n\""
2958 << dvips_name << "\" and\n\""
2959 << pdftex_name << "\"\n"
2960 "both exist, so I had to make a "
2961 "choice and took the first one.\n"
2962 "Please move the unwanted one "
2963 "someplace else and try again\n"
2964 "if my choice was wrong."
2968 } else if (!pdftex_name.empty()) {
2974 FileName const absname = makeAbsPath(name, path);
2975 if (absname.exists()) {
2976 fix_child_filename(name);
2977 copy_file(absname, name);
2979 cerr << "Warning: Could not find graphics file '"
2980 << name << "'." << endl;
2982 context.check_layout(os);
2983 begin_inset(os, "Graphics ");
2984 os << "\n\tfilename " << name << '\n';
2985 if (opts.find("width") != opts.end())
2987 << translate_len(opts["width"]) << '\n';
2988 if (opts.find("height") != opts.end())
2990 << translate_len(opts["height"]) << '\n';
2991 if (opts.find("scale") != opts.end()) {
2992 istringstream iss(opts["scale"]);
2996 os << "\tscale " << val << '\n';
2998 if (opts.find("angle") != opts.end()) {
2999 os << "\trotateAngle "
3000 << opts["angle"] << '\n';
3001 vector<string>::const_iterator a =
3002 find(keys.begin(), keys.end(), "angle");
3003 vector<string>::const_iterator s =
3004 find(keys.begin(), keys.end(), "width");
3005 if (s == keys.end())
3006 s = find(keys.begin(), keys.end(), "height");
3007 if (s == keys.end())
3008 s = find(keys.begin(), keys.end(), "scale");
3009 if (s != keys.end() && distance(s, a) > 0)
3010 os << "\tscaleBeforeRotation\n";
3012 if (opts.find("origin") != opts.end()) {
3014 string const opt = opts["origin"];
3015 if (opt.find('l') != string::npos) ss << "left";
3016 if (opt.find('r') != string::npos) ss << "right";
3017 if (opt.find('c') != string::npos) ss << "center";
3018 if (opt.find('t') != string::npos) ss << "Top";
3019 if (opt.find('b') != string::npos) ss << "Bottom";
3020 if (opt.find('B') != string::npos) ss << "Baseline";
3021 if (!ss.str().empty())
3022 os << "\trotateOrigin " << ss.str() << '\n';
3024 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3026 if (opts.find("keepaspectratio") != opts.end())
3027 os << "\tkeepAspectRatio\n";
3028 if (opts.find("clip") != opts.end())
3030 if (opts.find("draft") != opts.end())
3032 if (opts.find("bb") != opts.end())
3033 os << "\tBoundingBox "
3034 << opts["bb"] << '\n';
3035 int numberOfbbOptions = 0;
3036 if (opts.find("bbllx") != opts.end())
3037 numberOfbbOptions++;
3038 if (opts.find("bblly") != opts.end())
3039 numberOfbbOptions++;
3040 if (opts.find("bburx") != opts.end())
3041 numberOfbbOptions++;
3042 if (opts.find("bbury") != opts.end())
3043 numberOfbbOptions++;
3044 if (numberOfbbOptions == 4)
3045 os << "\tBoundingBox "
3046 << opts["bbllx"] << " " << opts["bblly"] << " "
3047 << opts["bburx"] << " " << opts["bbury"] << '\n';
3048 else if (numberOfbbOptions > 0)
3049 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3050 numberOfbbOptions = 0;
3051 if (opts.find("natwidth") != opts.end())
3052 numberOfbbOptions++;
3053 if (opts.find("natheight") != opts.end())
3054 numberOfbbOptions++;
3055 if (numberOfbbOptions == 2)
3056 os << "\tBoundingBox 0bp 0bp "
3057 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3058 else if (numberOfbbOptions > 0)
3059 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3060 ostringstream special;
3061 if (opts.find("hiresbb") != opts.end())
3062 special << "hiresbb,";
3063 if (opts.find("trim") != opts.end())
3065 if (opts.find("viewport") != opts.end())
3066 special << "viewport=" << opts["viewport"] << ',';
3067 if (opts.find("totalheight") != opts.end())
3068 special << "totalheight=" << opts["totalheight"] << ',';
3069 if (opts.find("type") != opts.end())
3070 special << "type=" << opts["type"] << ',';
3071 if (opts.find("ext") != opts.end())
3072 special << "ext=" << opts["ext"] << ',';
3073 if (opts.find("read") != opts.end())
3074 special << "read=" << opts["read"] << ',';
3075 if (opts.find("command") != opts.end())
3076 special << "command=" << opts["command"] << ',';
3077 string s_special = special.str();
3078 if (!s_special.empty()) {
3079 // We had special arguments. Remove the trailing ','.
3080 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3082 // TODO: Handle the unknown settings better.
3083 // Warn about invalid options.
3084 // Check whether some option was given twice.
3086 preamble.registerAutomaticallyLoadedPackage("graphicx");
3089 else if (t.cs() == "footnote" ||
3090 (t.cs() == "thanks" && context.layout->intitle)) {
3092 context.check_layout(os);
3093 begin_inset(os, "Foot\n");
3094 os << "status collapsed\n\n";
3095 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3099 else if (t.cs() == "marginpar") {
3101 context.check_layout(os);
3102 begin_inset(os, "Marginal\n");
3103 os << "status collapsed\n\n";
3104 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3108 else if (t.cs() == "lstinline") {
3110 parse_listings(p, os, context, true);
3113 else if (t.cs() == "ensuremath") {
3115 context.check_layout(os);
3116 string const s = p.verbatim_item();
3117 //FIXME: this never triggers in UTF8
3118 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3121 output_ert_inset(os, "\\ensuremath{" + s + "}",
3125 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3126 if (preamble.titleLayoutFound()) {
3128 skip_spaces_braces(p);
3130 output_ert_inset(os, t.asInput(), context);
3133 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3134 context.check_layout(os);
3135 begin_command_inset(os, "toc", t.cs());
3137 skip_spaces_braces(p);
3138 if (t.cs() == "lstlistoflistings")
3139 preamble.registerAutomaticallyLoadedPackage("listings");
3142 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3143 context.check_layout(os);
3144 if (t.cs() == "listoffigures")
3145 begin_inset(os, "FloatList figure\n");
3147 begin_inset(os, "FloatList table\n");
3149 skip_spaces_braces(p);
3152 else if (t.cs() == "listof") {
3153 p.skip_spaces(true);
3154 string const name = p.get_token().cs();
3155 if (context.textclass.floats().typeExist(name)) {
3156 context.check_layout(os);
3157 begin_inset(os, "FloatList ");
3160 p.get_token(); // swallow second arg
3162 output_ert_inset(os, "\\listof{" + name + "}", context);
3165 else if ((where = is_known(t.cs(), known_text_font_families)))
3166 parse_text_attributes(p, os, FLAG_ITEM, outer,
3167 context, "\\family", context.font.family,
3168 known_coded_font_families[where - known_text_font_families]);
3170 else if ((where = is_known(t.cs(), known_text_font_series)))
3171 parse_text_attributes(p, os, FLAG_ITEM, outer,
3172 context, "\\series", context.font.series,
3173 known_coded_font_series[where - known_text_font_series]);
3175 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3176 parse_text_attributes(p, os, FLAG_ITEM, outer,
3177 context, "\\shape", context.font.shape,
3178 known_coded_font_shapes[where - known_text_font_shapes]);
3180 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3181 context.check_layout(os);
3182 TeXFont oldFont = context.font;
3183 context.font.init();
3184 context.font.size = oldFont.size;
3185 os << "\n\\family " << context.font.family << "\n";
3186 os << "\n\\series " << context.font.series << "\n";
3187 os << "\n\\shape " << context.font.shape << "\n";
3188 if (t.cs() == "textnormal") {
3189 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3190 output_font_change(os, context.font, oldFont);
3191 context.font = oldFont;
3193 eat_whitespace(p, os, context, false);
3196 else if (t.cs() == "textcolor") {
3197 // scheme is \textcolor{color name}{text}
3198 string const color = p.verbatim_item();
3199 // we only support the predefined colors of the color package
3200 if (color == "black" || color == "blue" || color == "cyan"
3201 || color == "green" || color == "magenta" || color == "red"
3202 || color == "white" || color == "yellow") {
3203 context.check_layout(os);
3204 os << "\n\\color " << color << "\n";
3205 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3206 context.check_layout(os);
3207 os << "\n\\color inherit\n";
3208 preamble.registerAutomaticallyLoadedPackage("color");
3210 // for custom defined colors
3211 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3214 else if (t.cs() == "underbar" || t.cs() == "uline") {
3215 // \underbar is not 100% correct (LyX outputs \uline
3216 // of ulem.sty). The difference is that \ulem allows
3217 // line breaks, and \underbar does not.
3218 // Do NOT handle \underline.
3219 // \underbar cuts through y, g, q, p etc.,
3220 // \underline does not.
3221 context.check_layout(os);
3222 os << "\n\\bar under\n";
3223 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3224 context.check_layout(os);
3225 os << "\n\\bar default\n";
3226 preamble.registerAutomaticallyLoadedPackage("ulem");
3229 else if (t.cs() == "sout") {
3230 context.check_layout(os);
3231 os << "\n\\strikeout on\n";
3232 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3233 context.check_layout(os);
3234 os << "\n\\strikeout default\n";
3235 preamble.registerAutomaticallyLoadedPackage("ulem");
3238 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3239 t.cs() == "emph" || t.cs() == "noun") {
3240 context.check_layout(os);
3241 os << "\n\\" << t.cs() << " on\n";
3242 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3243 context.check_layout(os);
3244 os << "\n\\" << t.cs() << " default\n";
3245 if (t.cs() == "uuline" || t.cs() == "uwave")
3246 preamble.registerAutomaticallyLoadedPackage("ulem");
3249 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3250 context.check_layout(os);
3251 string name = p.getArg('{', '}');
3252 string localtime = p.getArg('{', '}');
3253 preamble.registerAuthor(name);
3254 Author const & author = preamble.getAuthor(name);
3255 // from_asctime_utc() will fail if LyX decides to output the
3256 // time in the text language.
3257 time_t ptime = from_asctime_utc(localtime);
3258 if (ptime == static_cast<time_t>(-1)) {
3259 cerr << "Warning: Could not parse time `" << localtime
3260 << "´ for change tracking, using current time instead.\n";
3261 ptime = current_time();
3263 if (t.cs() == "lyxadded")
3264 os << "\n\\change_inserted ";
3266 os << "\n\\change_deleted ";
3267 os << author.bufferId() << ' ' << ptime << '\n';
3268 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3269 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3270 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3271 LaTeXPackages::isAvailable("xcolor");
3272 // No need to test for luatex, since luatex comes in
3273 // two flavours (dvi and pdf), like latex, and those
3274 // are detected by pdflatex.
3275 if (pdflatex || xetex) {
3277 preamble.registerAutomaticallyLoadedPackage("ulem");
3278 preamble.registerAutomaticallyLoadedPackage("xcolor");
3279 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3283 preamble.registerAutomaticallyLoadedPackage("dvipost");
3284 } else if (xcolorulem) {
3285 preamble.registerAutomaticallyLoadedPackage("ulem");
3286 preamble.registerAutomaticallyLoadedPackage("xcolor");
3291 else if (t.cs() == "textipa") {
3292 context.check_layout(os);
3293 begin_inset(os, "IPA\n");
3294 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3296 preamble.registerAutomaticallyLoadedPackage("tipa");
3297 preamble.registerAutomaticallyLoadedPackage("tipx");
3300 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3301 context.check_layout(os);
3302 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3303 os << "status open\n";
3304 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3309 else if (t.cs() == "textvertline") {
3310 // FIXME: This is not correct, \textvertline is higher than |
3316 else if (t.cs() == "tone" ) {
3317 context.check_layout(os);
3318 // register the tone package
3319 preamble.registerAutomaticallyLoadedPackage("tone");
3320 string content = trimSpaceAndEol(p.verbatim_item());
3321 string command = t.asInput() + "{" + content + "}";
3322 // some tones can be detected by unicodesymbols, some need special code
3323 if (is_known(content, known_tones)) {
3324 os << "\\IPAChar " << command << "\n";
3327 // try to see whether the string is in unicodesymbols
3331 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3332 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3333 termination, rem, &req);
3337 output_ert_inset(os, to_utf8(rem), context);
3338 for (set<string>::const_iterator it = req.begin();
3339 it != req.end(); ++it)
3340 preamble.registerAutomaticallyLoadedPackage(*it);
3342 // we did not find a non-ert version
3343 output_ert_inset(os, command, context);
3346 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3347 t.cs() == "vphantom") {
3348 context.check_layout(os);
3349 if (t.cs() == "phantom")
3350 begin_inset(os, "Phantom Phantom\n");
3351 if (t.cs() == "hphantom")
3352 begin_inset(os, "Phantom HPhantom\n");
3353 if (t.cs() == "vphantom")
3354 begin_inset(os, "Phantom VPhantom\n");
3355 os << "status open\n";
3356 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3361 else if (t.cs() == "href") {
3362 context.check_layout(os);
3363 string target = convert_command_inset_arg(p.verbatim_item());
3364 string name = convert_command_inset_arg(p.verbatim_item());
3366 size_t i = target.find(':');
3367 if (i != string::npos) {
3368 type = target.substr(0, i + 1);
3369 if (type == "mailto:" || type == "file:")
3370 target = target.substr(i + 1);
3371 // handle the case that name is equal to target, except of "http://"
3372 else if (target.substr(i + 3) == name && type == "http:")
3375 begin_command_inset(os, "href", "href");
3377 os << "name \"" << name << "\"\n";
3378 os << "target \"" << target << "\"\n";
3379 if (type == "mailto:" || type == "file:")
3380 os << "type \"" << type << "\"\n";
3382 skip_spaces_braces(p);
3385 else if (t.cs() == "lyxline") {
3386 // swallow size argument (it is not used anyway)
3388 if (!context.atParagraphStart()) {
3389 // so our line is in the middle of a paragraph
3390 // we need to add a new line, lest this line
3391 // follow the other content on that line and
3392 // run off the side of the page
3393 // FIXME: This may create an empty paragraph,
3394 // but without that it would not be
3395 // possible to set noindent below.
3396 // Fortunately LaTeX does not care
3397 // about the empty paragraph.
3398 context.new_paragraph(os);
3400 if (preamble.indentParagraphs()) {
3401 // we need to unindent, lest the line be too long
3402 context.add_par_extra_stuff("\\noindent\n");
3404 context.check_layout(os);
3405 begin_command_inset(os, "line", "rule");
3406 os << "offset \"0.5ex\"\n"
3407 "width \"100line%\"\n"
3412 else if (t.cs() == "rule") {
3413 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3414 string const width = p.getArg('{', '}');
3415 string const thickness = p.getArg('{', '}');
3416 context.check_layout(os);
3417 begin_command_inset(os, "line", "rule");
3418 if (!offset.empty())
3419 os << "offset \"" << translate_len(offset) << "\"\n";
3420 os << "width \"" << translate_len(width) << "\"\n"
3421 "height \"" << translate_len(thickness) << "\"\n";
3425 else if (is_known(t.cs(), known_phrases) ||
3426 (t.cs() == "protect" &&
3427 p.next_token().cat() == catEscape &&
3428 is_known(p.next_token().cs(), known_phrases))) {
3429 // LyX sometimes puts a \protect in front, so we have to ignore it
3430 // FIXME: This needs to be changed when bug 4752 is fixed.
3432 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3434 context.check_layout(os);
3435 os << known_coded_phrases[where - known_phrases];
3436 skip_spaces_braces(p);
3439 // handle refstyle first to catch \eqref which can also occur
3440 // without refstyle. Only recognize these commands if
3441 // refstyle.sty was found in the preamble (otherwise \eqref
3442 // and user defined ref commands could be misdetected).
3443 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3444 preamble.refstyle()) {
3445 context.check_layout(os);
3446 begin_command_inset(os, "ref", "formatted");
3447 os << "reference \"";
3448 os << known_refstyle_prefixes[where - known_refstyle_commands]
3450 os << convert_command_inset_arg(p.verbatim_item())
3453 preamble.registerAutomaticallyLoadedPackage("refstyle");
3456 // if refstyle is used, we must not convert \prettyref to a
3457 // formatted reference, since that would result in a refstyle command.
3458 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3459 (t.cs() != "prettyref" || !preamble.refstyle())) {
3460 string const opt = p.getOpt();
3462 context.check_layout(os);
3463 begin_command_inset(os, "ref",
3464 known_coded_ref_commands[where - known_ref_commands]);
3465 os << "reference \""
3466 << convert_command_inset_arg(p.verbatim_item())
3469 if (t.cs() == "vref" || t.cs() == "vpageref")
3470 preamble.registerAutomaticallyLoadedPackage("varioref");
3471 else if (t.cs() == "prettyref")
3472 preamble.registerAutomaticallyLoadedPackage("prettyref");
3474 // LyX does not yet support optional arguments of ref commands
3475 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3476 p.verbatim_item() + '}', context);
3480 else if (use_natbib &&
3481 is_known(t.cs(), known_natbib_commands) &&
3482 ((t.cs() != "citefullauthor" &&
3483 t.cs() != "citeyear" &&
3484 t.cs() != "citeyearpar") ||
3485 p.next_token().asInput() != "*")) {
3486 context.check_layout(os);
3487 string command = t.cs();
3488 if (p.next_token().asInput() == "*") {
3492 if (command == "citefullauthor")
3493 // alternative name for "\\citeauthor*"
3494 command = "citeauthor*";
3496 // text before the citation
3498 // text after the citation
3500 get_cite_arguments(p, true, before, after);
3502 if (command == "cite") {
3503 // \cite without optional argument means
3504 // \citet, \cite with at least one optional
3505 // argument means \citep.
3506 if (before.empty() && after.empty())
3511 if (before.empty() && after == "[]")
3512 // avoid \citet[]{a}
3514 else if (before == "[]" && after == "[]") {
3515 // avoid \citet[][]{a}
3519 // remove the brackets around after and before
3520 if (!after.empty()) {
3522 after.erase(after.length() - 1, 1);
3523 after = convert_command_inset_arg(after);
3525 if (!before.empty()) {
3527 before.erase(before.length() - 1, 1);
3528 before = convert_command_inset_arg(before);
3530 begin_command_inset(os, "citation", command);
3531 os << "after " << '"' << after << '"' << "\n";
3532 os << "before " << '"' << before << '"' << "\n";
3534 << convert_command_inset_arg(p.verbatim_item())
3537 // Need to set the cite engine if natbib is loaded by
3538 // the document class directly
3539 if (preamble.citeEngine() == "basic")
3540 preamble.citeEngine("natbib");
3543 else if (use_jurabib &&
3544 is_known(t.cs(), known_jurabib_commands) &&
3545 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3546 context.check_layout(os);
3547 string command = t.cs();
3548 if (p.next_token().asInput() == "*") {
3552 char argumentOrder = '\0';
3553 vector<string> const options =
3554 preamble.getPackageOptions("jurabib");
3555 if (find(options.begin(), options.end(),
3556 "natbiborder") != options.end())
3557 argumentOrder = 'n';
3558 else if (find(options.begin(), options.end(),
3559 "jurabiborder") != options.end())
3560 argumentOrder = 'j';
3562 // text before the citation
3564 // text after the citation
3566 get_cite_arguments(p, argumentOrder != 'j', before, after);
3568 string const citation = p.verbatim_item();
3569 if (!before.empty() && argumentOrder == '\0') {
3570 cerr << "Warning: Assuming argument order "
3571 "of jurabib version 0.6 for\n'"
3572 << command << before << after << '{'
3573 << citation << "}'.\n"
3574 "Add 'jurabiborder' to the jurabib "
3575 "package options if you used an\n"
3576 "earlier jurabib version." << endl;
3578 if (!after.empty()) {
3580 after.erase(after.length() - 1, 1);
3582 if (!before.empty()) {
3584 before.erase(before.length() - 1, 1);
3586 begin_command_inset(os, "citation", command);
3587 os << "after " << '"' << after << '"' << "\n";
3588 os << "before " << '"' << before << '"' << "\n";
3589 os << "key " << '"' << citation << '"' << "\n";
3591 // Need to set the cite engine if jurabib is loaded by
3592 // the document class directly
3593 if (preamble.citeEngine() == "basic")
3594 preamble.citeEngine("jurabib");
3597 else if (t.cs() == "cite"
3598 || t.cs() == "nocite") {
3599 context.check_layout(os);
3600 string after = convert_command_inset_arg(p.getArg('[', ']'));
3601 string key = convert_command_inset_arg(p.verbatim_item());
3602 // store the case that it is "\nocite{*}" to use it later for
3605 begin_command_inset(os, "citation", t.cs());
3606 os << "after " << '"' << after << '"' << "\n";
3607 os << "key " << '"' << key << '"' << "\n";
3609 } else if (t.cs() == "nocite")
3613 else if (t.cs() == "index" ||
3614 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3615 context.check_layout(os);
3616 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3617 p.getArg('[', ']') : "";
3618 string const kind = arg.empty() ? "idx" : arg;
3619 begin_inset(os, "Index ");
3620 os << kind << "\nstatus collapsed\n";
3621 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3624 preamble.registerAutomaticallyLoadedPackage("splitidx");
3627 else if (t.cs() == "nomenclature") {
3628 context.check_layout(os);
3629 begin_command_inset(os, "nomenclature", "nomenclature");
3630 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3631 if (!prefix.empty())
3632 os << "prefix " << '"' << prefix << '"' << "\n";
3633 os << "symbol " << '"'
3634 << convert_command_inset_arg(p.verbatim_item());
3635 os << "\"\ndescription \""
3636 << convert_command_inset_arg(p.verbatim_item())
3639 preamble.registerAutomaticallyLoadedPackage("nomencl");
3642 else if (t.cs() == "label") {
3643 context.check_layout(os);
3644 begin_command_inset(os, "label", "label");
3646 << convert_command_inset_arg(p.verbatim_item())
3651 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3652 context.check_layout(os);
3653 string commandname = t.cs();
3655 if (p.next_token().asInput() == "*") {
3660 begin_command_inset(os, "index_print", commandname);
3661 string const indexname = p.getArg('[', ']');
3663 if (indexname.empty())
3664 os << "type \"idx\"\n";
3666 os << "type \"" << indexname << "\"\n";
3669 skip_spaces_braces(p);
3670 preamble.registerAutomaticallyLoadedPackage("makeidx");
3671 if (preamble.use_indices() == "true")
3672 preamble.registerAutomaticallyLoadedPackage("splitidx");
3675 else if (t.cs() == "printnomenclature") {
3677 string width_type = "";
3678 context.check_layout(os);
3679 begin_command_inset(os, "nomencl_print", "printnomenclature");
3680 // case of a custom width
3682 width = p.getArg('[', ']');
3683 width = translate_len(width);
3684 width_type = "custom";
3686 // case of no custom width
3687 // the case of no custom width but the width set
3688 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3689 // because the user could have set anything, not only the width
3690 // of the longest label (which would be width_type = "auto")
3691 string label = convert_command_inset_arg(p.getArg('{', '}'));
3692 if (label.empty() && width_type.empty())
3693 width_type = "none";
3694 os << "set_width \"" << width_type << "\"\n";
3695 if (width_type == "custom")
3696 os << "width \"" << width << '\"';
3698 skip_spaces_braces(p);
3699 preamble.registerAutomaticallyLoadedPackage("nomencl");
3702 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3703 context.check_layout(os);
3704 begin_inset(os, "script ");
3705 os << t.cs().substr(4) << '\n';
3706 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3708 if (t.cs() == "textsubscript")
3709 preamble.registerAutomaticallyLoadedPackage("subscript");
3712 else if ((where = is_known(t.cs(), known_quotes))) {
3713 context.check_layout(os);
3714 begin_inset(os, "Quotes ");
3715 os << known_coded_quotes[where - known_quotes];
3717 // LyX adds {} after the quote, so we have to eat
3718 // spaces here if there are any before a possible
3720 eat_whitespace(p, os, context, false);
3724 else if ((where = is_known(t.cs(), known_sizes)) &&
3725 context.new_layout_allowed) {
3726 context.check_layout(os);
3727 TeXFont const oldFont = context.font;
3728 context.font.size = known_coded_sizes[where - known_sizes];
3729 output_font_change(os, oldFont, context.font);
3730 eat_whitespace(p, os, context, false);
3733 else if ((where = is_known(t.cs(), known_font_families)) &&
3734 context.new_layout_allowed) {
3735 context.check_layout(os);
3736 TeXFont const oldFont = context.font;
3737 context.font.family =
3738 known_coded_font_families[where - known_font_families];
3739 output_font_change(os, oldFont, context.font);
3740 eat_whitespace(p, os, context, false);
3743 else if ((where = is_known(t.cs(), known_font_series)) &&
3744 context.new_layout_allowed) {
3745 context.check_layout(os);
3746 TeXFont const oldFont = context.font;
3747 context.font.series =
3748 known_coded_font_series[where - known_font_series];
3749 output_font_change(os, oldFont, context.font);
3750 eat_whitespace(p, os, context, false);
3753 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3754 context.new_layout_allowed) {
3755 context.check_layout(os);
3756 TeXFont const oldFont = context.font;
3757 context.font.shape =
3758 known_coded_font_shapes[where - known_font_shapes];
3759 output_font_change(os, oldFont, context.font);
3760 eat_whitespace(p, os, context, false);
3762 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3763 context.new_layout_allowed) {
3764 context.check_layout(os);
3765 TeXFont const oldFont = context.font;
3766 context.font.init();
3767 context.font.size = oldFont.size;
3768 context.font.family =
3769 known_coded_font_families[where - known_old_font_families];
3770 output_font_change(os, oldFont, context.font);
3771 eat_whitespace(p, os, context, false);
3774 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3775 context.new_layout_allowed) {
3776 context.check_layout(os);
3777 TeXFont const oldFont = context.font;
3778 context.font.init();
3779 context.font.size = oldFont.size;
3780 context.font.series =
3781 known_coded_font_series[where - known_old_font_series];
3782 output_font_change(os, oldFont, context.font);
3783 eat_whitespace(p, os, context, false);
3786 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3787 context.new_layout_allowed) {
3788 context.check_layout(os);
3789 TeXFont const oldFont = context.font;
3790 context.font.init();
3791 context.font.size = oldFont.size;
3792 context.font.shape =
3793 known_coded_font_shapes[where - known_old_font_shapes];
3794 output_font_change(os, oldFont, context.font);
3795 eat_whitespace(p, os, context, false);
3798 else if (t.cs() == "selectlanguage") {
3799 context.check_layout(os);
3800 // save the language for the case that a
3801 // \foreignlanguage is used
3802 context.font.language = babel2lyx(p.verbatim_item());
3803 os << "\n\\lang " << context.font.language << "\n";
3806 else if (t.cs() == "foreignlanguage") {
3807 string const lang = babel2lyx(p.verbatim_item());
3808 parse_text_attributes(p, os, FLAG_ITEM, outer,
3810 context.font.language, lang);
3813 else if (prefixIs(t.cs(), "text")
3814 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3815 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3817 // We have to output the whole command if it has an option
3818 // because LyX doesn't support this yet, see bug #8214,
3819 // only if there is a single option specifying a variant, we can handle it.
3821 string langopts = p.getOpt();
3822 // check if the option contains a variant, if yes, extract it
3823 string::size_type pos_var = langopts.find("variant");
3824 string::size_type i = langopts.find(',');
3825 string::size_type k = langopts.find('=', pos_var);
3826 if (pos_var != string::npos && i == string::npos) {
3828 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3829 lang = preamble.polyglossia2lyx(variant);
3830 parse_text_attributes(p, os, FLAG_ITEM, outer,
3832 context.font.language, lang);
3834 output_ert_inset(os, t.asInput() + langopts, context);
3836 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3837 parse_text_attributes(p, os, FLAG_ITEM, outer,
3839 context.font.language, lang);
3843 else if (t.cs() == "inputencoding") {
3844 // nothing to write here
3845 string const enc = subst(p.verbatim_item(), "\n", " ");
3846 p.setEncoding(enc, Encoding::inputenc);
3849 else if ((where = is_known(t.cs(), known_special_chars))) {
3850 context.check_layout(os);
3851 os << known_coded_special_chars[where - known_special_chars];
3852 skip_spaces_braces(p);
3855 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3856 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3857 context.check_layout(os);
3858 os << "\\SpecialChar \\" << t.cs()
3859 << p.get_token().asInput() << '\n';
3862 else if (t.cs() == "textquotedbl") {
3863 context.check_layout(os);
3868 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3869 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3870 || t.cs() == "%" || t.cs() == "-") {
3871 context.check_layout(os);
3873 os << "\\SpecialChar \\-\n";
3878 else if (t.cs() == "char") {
3879 context.check_layout(os);
3880 if (p.next_token().character() == '`') {
3882 if (p.next_token().cs() == "\"") {
3887 output_ert_inset(os, "\\char`", context);
3890 output_ert_inset(os, "\\char", context);
3894 else if (t.cs() == "verb") {
3895 context.check_layout(os);
3896 // set catcodes to verbatim early, just in case.
3897 p.setCatcodes(VERBATIM_CATCODES);
3898 string delim = p.get_token().asInput();
3899 Parser::Arg arg = p.verbatimStuff(delim);
3901 output_ert_inset(os, "\\verb" + delim
3902 + arg.second + delim, context);
3904 cerr << "invalid \\verb command. Skipping" << endl;
3907 // Problem: \= creates a tabstop inside the tabbing environment
3908 // and else an accent. In the latter case we really would want
3909 // \={o} instead of \= o.
3910 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3911 output_ert_inset(os, t.asInput(), context);
3913 else if (t.cs() == "\\") {
3914 context.check_layout(os);
3916 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3917 else if (p.next_token().asInput() == "*") {
3919 // getOpt() eats the following space if there
3920 // is no optional argument, but that is OK
3921 // here since it has no effect in the output.
3922 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3925 begin_inset(os, "Newline newline");
3930 else if (t.cs() == "newline" ||
3931 (t.cs() == "linebreak" && !p.hasOpt())) {
3932 context.check_layout(os);
3933 begin_inset(os, "Newline ");
3936 skip_spaces_braces(p);
3939 else if (t.cs() == "input" || t.cs() == "include"
3940 || t.cs() == "verbatiminput") {
3941 string name = t.cs();
3942 if (t.cs() == "verbatiminput"
3943 && p.next_token().asInput() == "*")
3944 name += p.get_token().asInput();
3945 context.check_layout(os);
3946 string filename(normalize_filename(p.getArg('{', '}')));
3947 string const path = getMasterFilePath(true);
3948 // We want to preserve relative / absolute filenames,
3949 // therefore path is only used for testing
3950 if ((t.cs() == "include" || t.cs() == "input") &&
3951 !makeAbsPath(filename, path).exists()) {
3952 // The file extension is probably missing.
3953 // Now try to find it out.
3954 string const tex_name =
3955 find_file(filename, path,
3956 known_tex_extensions);
3957 if (!tex_name.empty())
3958 filename = tex_name;
3960 bool external = false;
3962 if (makeAbsPath(filename, path).exists()) {
3963 string const abstexname =
3964 makeAbsPath(filename, path).absFileName();
3965 string const absfigname =
3966 changeExtension(abstexname, ".fig");
3967 fix_child_filename(filename);
3968 string const lyxname = changeExtension(filename,
3969 roundtripMode() ? ".lyx.lyx" : ".lyx");
3970 string const abslyxname = makeAbsPath(
3971 lyxname, getParentFilePath(false)).absFileName();
3973 if (!skipChildren())
3974 external = FileName(absfigname).exists();
3975 if (t.cs() == "input" && !skipChildren()) {
3976 string const ext = getExtension(abstexname);
3978 // Combined PS/LaTeX:
3979 // x.eps, x.pstex_t (old xfig)
3980 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3981 FileName const absepsname(
3982 changeExtension(abstexname, ".eps"));
3983 FileName const abspstexname(
3984 changeExtension(abstexname, ".pstex"));
3985 bool const xfigeps =
3986 (absepsname.exists() ||
3987 abspstexname.exists()) &&
3990 // Combined PDF/LaTeX:
3991 // x.pdf, x.pdftex_t (old xfig)
3992 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3993 FileName const abspdfname(
3994 changeExtension(abstexname, ".pdf"));
3995 bool const xfigpdf =
3996 abspdfname.exists() &&
3997 (ext == "pdftex_t" || ext == "pdf_t");
4001 // Combined PS/PDF/LaTeX:
4002 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4003 string const absbase2(
4004 removeExtension(abstexname) + "_pspdftex");
4005 FileName const abseps2name(
4006 addExtension(absbase2, ".eps"));
4007 FileName const abspdf2name(
4008 addExtension(absbase2, ".pdf"));
4009 bool const xfigboth =
4010 abspdf2name.exists() &&
4011 abseps2name.exists() && ext == "pspdftex";
4013 xfig = xfigpdf || xfigeps || xfigboth;
4014 external = external && xfig;
4017 outname = changeExtension(filename, ".fig");
4018 FileName abssrc(changeExtension(abstexname, ".fig"));
4019 copy_file(abssrc, outname);
4021 // Don't try to convert, the result
4022 // would be full of ERT.
4024 FileName abssrc(abstexname);
4025 copy_file(abssrc, outname);
4026 } else if (t.cs() != "verbatiminput" &&
4028 tex2lyx(abstexname, FileName(abslyxname),
4031 // no need to call copy_file
4032 // tex2lyx creates the file
4035 FileName abssrc(abstexname);
4036 copy_file(abssrc, outname);
4039 cerr << "Warning: Could not find included file '"
4040 << filename << "'." << endl;
4044 begin_inset(os, "External\n");
4045 os << "\ttemplate XFig\n"
4046 << "\tfilename " << outname << '\n';
4047 registerExternalTemplatePackages("XFig");
4049 begin_command_inset(os, "include", name);
4050 outname = subst(outname, "\"", "\\\"");
4051 os << "preview false\n"
4052 "filename \"" << outname << "\"\n";
4053 if (t.cs() == "verbatiminput")
4054 preamble.registerAutomaticallyLoadedPackage("verbatim");
4059 else if (t.cs() == "bibliographystyle") {
4060 // store new bibliographystyle
4061 bibliographystyle = p.verbatim_item();
4062 // If any other command than \bibliography, \addcontentsline
4063 // and \nocite{*} follows, we need to output the style
4064 // (because it might be used by that command).
4065 // Otherwise, it will automatically be output by LyX.
4068 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4069 if (t2.cat() == catBegin)
4071 if (t2.cat() != catEscape)
4073 if (t2.cs() == "nocite") {
4074 if (p.getArg('{', '}') == "*")
4076 } else if (t2.cs() == "bibliography")
4078 else if (t2.cs() == "phantomsection") {
4082 else if (t2.cs() == "addcontentsline") {
4083 // get the 3 arguments of \addcontentsline
4086 contentslineContent = p.getArg('{', '}');
4087 // if the last argument is not \refname we must output
4088 if (contentslineContent == "\\refname")
4095 output_ert_inset(os,
4096 "\\bibliographystyle{" + bibliographystyle + '}',
4101 else if (t.cs() == "phantomsection") {
4102 // we only support this if it occurs between
4103 // \bibliographystyle and \bibliography
4104 if (bibliographystyle.empty())
4105 output_ert_inset(os, "\\phantomsection", context);
4108 else if (t.cs() == "addcontentsline") {
4109 context.check_layout(os);
4110 // get the 3 arguments of \addcontentsline
4111 string const one = p.getArg('{', '}');
4112 string const two = p.getArg('{', '}');
4113 string const three = p.getArg('{', '}');
4114 // only if it is a \refname, we support if for the bibtex inset
4115 if (contentslineContent != "\\refname") {
4116 output_ert_inset(os,
4117 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4122 else if (t.cs() == "bibliography") {
4123 context.check_layout(os);
4125 begin_command_inset(os, "bibtex", "bibtex");
4126 if (!btprint.empty()) {
4127 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4128 // clear the string because the next BibTeX inset can be without the
4129 // \nocite{*} option
4132 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4133 // Do we have addcontentsline?
4134 if (contentslineContent == "\\refname") {
4135 BibOpts = "bibtotoc";
4136 // clear string because next BibTeX inset can be without addcontentsline
4137 contentslineContent.clear();
4139 // Do we have a bibliographystyle set?
4140 if (!bibliographystyle.empty()) {
4141 if (BibOpts.empty())
4142 BibOpts = bibliographystyle;
4144 BibOpts = BibOpts + ',' + bibliographystyle;
4145 // clear it because each bibtex entry has its style
4146 // and we need an empty string to handle \phantomsection
4147 bibliographystyle.clear();
4149 os << "options " << '"' << BibOpts << '"' << "\n";
4153 else if (t.cs() == "parbox") {
4154 // Test whether this is an outer box of a shaded box
4156 // swallow arguments
4157 while (p.hasOpt()) {
4159 p.skip_spaces(true);
4162 p.skip_spaces(true);
4164 if (p.next_token().cat() == catBegin)
4166 p.skip_spaces(true);
4167 Token to = p.get_token();
4168 bool shaded = false;
4169 if (to.asInput() == "\\begin") {
4170 p.skip_spaces(true);
4171 if (p.getArg('{', '}') == "shaded")
4176 parse_outer_box(p, os, FLAG_ITEM, outer,
4177 context, "parbox", "shaded");
4179 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4183 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4184 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4185 t.cs() == "shadowbox" || t.cs() == "doublebox")
4186 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4188 else if (t.cs() == "framebox") {
4189 if (p.next_token().character() == '(') {
4190 //the syntax is: \framebox(x,y)[position]{content}
4191 string arg = t.asInput();
4192 arg += p.getFullParentheseArg();
4193 arg += p.getFullOpt();
4194 eat_whitespace(p, os, context, false);
4195 output_ert_inset(os, arg + '{', context);
4196 parse_text(p, os, FLAG_ITEM, outer, context);
4197 output_ert_inset(os, "}", context);
4199 //the syntax is: \framebox[width][position]{content}
4200 string special = p.getFullOpt();
4201 special += p.getOpt();
4202 parse_outer_box(p, os, FLAG_ITEM, outer,
4203 context, t.cs(), special);
4207 //\makebox() is part of the picture environment and different from \makebox{}
4208 //\makebox{} will be parsed by parse_box
4209 else if (t.cs() == "makebox") {
4210 if (p.next_token().character() == '(') {
4211 //the syntax is: \makebox(x,y)[position]{content}
4212 string arg = t.asInput();
4213 arg += p.getFullParentheseArg();
4214 arg += p.getFullOpt();
4215 eat_whitespace(p, os, context, false);
4216 output_ert_inset(os, arg + '{', context);
4217 parse_text(p, os, FLAG_ITEM, outer, context);
4218 output_ert_inset(os, "}", context);
4220 //the syntax is: \makebox[width][position]{content}
4221 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4225 else if (t.cs() == "smallskip" ||
4226 t.cs() == "medskip" ||
4227 t.cs() == "bigskip" ||
4228 t.cs() == "vfill") {
4229 context.check_layout(os);
4230 begin_inset(os, "VSpace ");
4233 skip_spaces_braces(p);
4236 else if ((where = is_known(t.cs(), known_spaces))) {
4237 context.check_layout(os);
4238 begin_inset(os, "space ");
4239 os << '\\' << known_coded_spaces[where - known_spaces]
4242 // LaTeX swallows whitespace after all spaces except
4243 // "\\,". We have to do that here, too, because LyX
4244 // adds "{}" which would make the spaces significant.
4246 eat_whitespace(p, os, context, false);
4247 // LyX adds "{}" after all spaces except "\\ " and
4248 // "\\,", so we have to remove "{}".
4249 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4250 // remove the braces after "\\,", too.
4255 else if (t.cs() == "newpage" ||
4256 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4257 t.cs() == "clearpage" ||
4258 t.cs() == "cleardoublepage") {
4259 context.check_layout(os);
4260 begin_inset(os, "Newpage ");
4263 skip_spaces_braces(p);
4266 else if (t.cs() == "DeclareRobustCommand" ||
4267 t.cs() == "DeclareRobustCommandx" ||
4268 t.cs() == "newcommand" ||
4269 t.cs() == "newcommandx" ||
4270 t.cs() == "providecommand" ||
4271 t.cs() == "providecommandx" ||
4272 t.cs() == "renewcommand" ||
4273 t.cs() == "renewcommandx") {
4274 // DeclareRobustCommand, DeclareRobustCommandx,
4275 // providecommand and providecommandx could be handled
4276 // by parse_command(), but we need to call
4277 // add_known_command() here.
4278 string name = t.asInput();
4279 if (p.next_token().asInput() == "*") {
4280 // Starred form. Eat '*'
4284 string const command = p.verbatim_item();
4285 string const opt1 = p.getFullOpt();
4286 string const opt2 = p.getFullOpt();
4287 add_known_command(command, opt1, !opt2.empty());
4288 string const ert = name + '{' + command + '}' +
4290 '{' + p.verbatim_item() + '}';
4292 if (t.cs() == "DeclareRobustCommand" ||
4293 t.cs() == "DeclareRobustCommandx" ||
4294 t.cs() == "providecommand" ||
4295 t.cs() == "providecommandx" ||
4296 name[name.length()-1] == '*')
4297 output_ert_inset(os, ert, context);
4299 context.check_layout(os);
4300 begin_inset(os, "FormulaMacro");
4306 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4307 // let could be handled by parse_command(),
4308 // but we need to call add_known_command() here.
4309 string ert = t.asInput();
4312 if (p.next_token().cat() == catBegin) {
4313 name = p.verbatim_item();
4314 ert += '{' + name + '}';
4316 name = p.verbatim_item();
4321 if (p.next_token().cat() == catBegin) {
4322 command = p.verbatim_item();
4323 ert += '{' + command + '}';
4325 command = p.verbatim_item();
4328 // If command is known, make name known too, to parse
4329 // its arguments correctly. For this reason we also
4330 // have commands in syntax.default that are hardcoded.
4331 CommandMap::iterator it = known_commands.find(command);
4332 if (it != known_commands.end())
4333 known_commands[t.asInput()] = it->second;
4334 output_ert_inset(os, ert, context);
4337 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4340 string name = t.asInput();
4341 string const length = p.verbatim_item();
4344 bool valid = splitLatexLength(length, valstring, unit);
4345 bool known_hspace = false;
4346 bool known_vspace = false;
4347 bool known_unit = false;
4350 istringstream iss(valstring);
4353 if (t.cs()[0] == 'h') {
4354 if (unit == "\\fill") {
4359 known_hspace = true;
4362 if (unit == "\\smallskipamount") {
4364 known_vspace = true;
4365 } else if (unit == "\\medskipamount") {
4367 known_vspace = true;
4368 } else if (unit == "\\bigskipamount") {
4370 known_vspace = true;
4371 } else if (unit == "\\fill") {
4373 known_vspace = true;
4377 if (!known_hspace && !known_vspace) {
4378 switch (unitFromString(unit)) {
4394 //unitFromString(unit) fails for relative units like Length::PCW
4395 // therefore handle them separately
4396 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4397 || unit == "\\textwidth" || unit == "\\linewidth"
4398 || unit == "\\textheight" || unit == "\\paperheight")
4406 // check for glue lengths
4407 bool is_gluelength = false;
4408 string gluelength = length;
4409 string::size_type i = length.find(" minus");
4410 if (i == string::npos) {
4411 i = length.find(" plus");
4412 if (i != string::npos)
4413 is_gluelength = true;
4415 is_gluelength = true;
4416 // if yes transform "9xx minus 8yy plus 7zz"
4418 if (is_gluelength) {
4419 i = gluelength.find(" minus");
4420 if (i != string::npos)
4421 gluelength.replace(i, 7, "-");
4422 i = gluelength.find(" plus");
4423 if (i != string::npos)
4424 gluelength.replace(i, 6, "+");
4427 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4428 // Literal horizontal length or known variable
4429 context.check_layout(os);
4430 begin_inset(os, "space ");
4438 if (known_unit && !known_hspace)
4439 os << "\n\\length " << translate_len(length);
4441 os << "\n\\length " << gluelength;
4443 } else if (known_unit || known_vspace || is_gluelength) {
4444 // Literal vertical length or known variable
4445 context.check_layout(os);
4446 begin_inset(os, "VSpace ");
4449 if (known_unit && !known_vspace)
4450 os << translate_len(length);
4457 // LyX can't handle other length variables in Inset VSpace/space
4462 output_ert_inset(os, name + '{' + unit + '}', context);
4463 else if (value == -1.0)
4464 output_ert_inset(os, name + "{-" + unit + '}', context);
4466 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4468 output_ert_inset(os, name + '{' + length + '}', context);
4472 // The single '=' is meant here.
4473 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4477 context.check_layout(os);
4478 begin_inset(os, "Flex ");
4479 os << to_utf8(newinsetlayout->name()) << '\n'
4480 << "status collapsed\n";
4481 if (newinsetlayout->isPassThru()) {
4482 // set catcodes to verbatim early, just in case.
4483 p.setCatcodes(VERBATIM_CATCODES);
4484 string delim = p.get_token().asInput();
4486 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4487 //FIXME: handle error condition
4488 string const arg = p.verbatimStuff("}").second;
4489 Context newcontext(true, context.textclass);
4490 if (newinsetlayout->forcePlainLayout())
4491 newcontext.layout = &context.textclass.plainLayout();
4492 output_ert(os, arg, newcontext);
4494 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4498 else if (t.cs() == "includepdf") {
4500 string const arg = p.getArg('[', ']');
4501 map<string, string> opts;
4502 vector<string> keys;
4503 split_map(arg, opts, keys);
4504 string name = normalize_filename(p.verbatim_item());
4505 string const path = getMasterFilePath(true);
4506 // We want to preserve relative / absolute filenames,
4507 // therefore path is only used for testing
4508 if (!makeAbsPath(name, path).exists()) {
4509 // The file extension is probably missing.
4510 // Now try to find it out.
4511 char const * const pdfpages_format[] = {"pdf", 0};
4512 string const pdftex_name =
4513 find_file(name, path, pdfpages_format);
4514 if (!pdftex_name.empty()) {
4519 FileName const absname = makeAbsPath(name, path);
4520 if (absname.exists())
4522 fix_child_filename(name);
4523 copy_file(absname, name);
4525 cerr << "Warning: Could not find file '"
4526 << name << "'." << endl;
4528 context.check_layout(os);
4529 begin_inset(os, "External\n\ttemplate ");
4530 os << "PDFPages\n\tfilename "
4532 // parse the options
4533 if (opts.find("pages") != opts.end())
4534 os << "\textra LaTeX \"pages="
4535 << opts["pages"] << "\"\n";
4536 if (opts.find("angle") != opts.end())
4537 os << "\trotateAngle "
4538 << opts["angle"] << '\n';
4539 if (opts.find("origin") != opts.end()) {
4541 string const opt = opts["origin"];
4542 if (opt == "tl") ss << "topleft";
4543 if (opt == "bl") ss << "bottomleft";
4544 if (opt == "Bl") ss << "baselineleft";
4545 if (opt == "c") ss << "center";
4546 if (opt == "tc") ss << "topcenter";
4547 if (opt == "bc") ss << "bottomcenter";
4548 if (opt == "Bc") ss << "baselinecenter";
4549 if (opt == "tr") ss << "topright";
4550 if (opt == "br") ss << "bottomright";
4551 if (opt == "Br") ss << "baselineright";
4552 if (!ss.str().empty())
4553 os << "\trotateOrigin " << ss.str() << '\n';
4555 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4557 if (opts.find("width") != opts.end())
4559 << translate_len(opts["width"]) << '\n';
4560 if (opts.find("height") != opts.end())
4562 << translate_len(opts["height"]) << '\n';
4563 if (opts.find("keepaspectratio") != opts.end())
4564 os << "\tkeepAspectRatio\n";
4566 context.check_layout(os);
4567 registerExternalTemplatePackages("PDFPages");
4570 else if (t.cs() == "loadgame") {
4572 string name = normalize_filename(p.verbatim_item());
4573 string const path = getMasterFilePath(true);
4574 // We want to preserve relative / absolute filenames,
4575 // therefore path is only used for testing
4576 if (!makeAbsPath(name, path).exists()) {
4577 // The file extension is probably missing.
4578 // Now try to find it out.
4579 char const * const lyxskak_format[] = {"fen", 0};
4580 string const lyxskak_name =
4581 find_file(name, path, lyxskak_format);
4582 if (!lyxskak_name.empty())
4583 name = lyxskak_name;
4585 FileName const absname = makeAbsPath(name, path);
4586 if (absname.exists())
4588 fix_child_filename(name);
4589 copy_file(absname, name);
4591 cerr << "Warning: Could not find file '"
4592 << name << "'." << endl;
4593 context.check_layout(os);
4594 begin_inset(os, "External\n\ttemplate ");
4595 os << "ChessDiagram\n\tfilename "
4598 context.check_layout(os);
4599 // after a \loadgame follows a \showboard
4600 if (p.get_token().asInput() == "showboard")
4602 registerExternalTemplatePackages("ChessDiagram");
4606 // try to see whether the string is in unicodesymbols
4607 // Only use text mode commands, since we are in text mode here,
4608 // and math commands may be invalid (bug 6797)
4609 string name = t.asInput();
4610 // handle the dingbats and Cyrillic
4611 if (name == "\\ding" || name == "\\textcyr")
4612 name = name + '{' + p.getArg('{', '}') + '}';
4613 // handle the ifsym characters
4614 else if (name == "\\textifsymbol") {
4615 string const optif = p.getFullOpt();
4616 string const argif = p.getArg('{', '}');
4617 name = name + optif + '{' + argif + '}';
4619 // handle the \ascii characters
4620 // the case of \ascii within braces, as LyX outputs it, is already
4621 // handled for t.cat() == catBegin
4622 else if (name == "\\ascii") {
4623 // the code is "\asci\xxx"
4624 name = "{" + name + p.get_token().asInput() + "}";
4627 // handle some TIPA special characters
4628 else if (preamble.isPackageUsed("tipa")) {
4629 if (name == "\\textglobfall") {
4632 } else if (name == "\\s") {
4633 // fromLaTeXCommand() does not yet
4634 // recognize tipa short cuts
4635 name = "\\textsyllabic";
4636 } else if (name == "\\=" &&
4637 p.next_token().asInput() == "*") {
4638 // fromLaTeXCommand() does not yet
4639 // recognize tipa short cuts
4642 } else if (name == "\\textdoublevertline") {
4643 // FIXME: This is not correct,
4644 // \textvertline is higher than \textbardbl
4645 name = "\\textbardbl";
4647 } else if (name == "\\!" ) {
4648 if (p.next_token().asInput() == "b") {
4649 p.get_token(); // eat 'b'
4652 } else if (p.next_token().asInput() == "d") {
4656 } else if (p.next_token().asInput() == "g") {
4660 } else if (p.next_token().asInput() == "G") {
4662 name = "\\texthtscg";
4664 } else if (p.next_token().asInput() == "j") {
4666 name = "\\texthtbardotlessj";
4668 } else if (p.next_token().asInput() == "o") {
4670 name = "\\textbullseye";
4673 } else if (name == "\\*" ) {
4674 if (p.next_token().asInput() == "k") {
4676 name = "\\textturnk";
4678 } else if (p.next_token().asInput() == "r") {
4679 p.get_token(); // eat 'b'
4680 name = "\\textturnr";
4682 } else if (p.next_token().asInput() == "t") {
4684 name = "\\textturnt";
4686 } else if (p.next_token().asInput() == "w") {
4688 name = "\\textturnw";
4693 if ((name.size() == 2 &&
4694 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4695 p.next_token().asInput() != "*") ||
4696 is_known(name.substr(1), known_tipa_marks)) {
4697 // name is a command that corresponds to a
4698 // combining character in unicodesymbols.
4699 // Append the argument, fromLaTeXCommand()
4700 // will either convert it to a single
4701 // character or a combining sequence.
4702 name += '{' + p.verbatim_item() + '}';
4704 // now get the character from unicodesymbols
4708 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4709 Encodings::TEXT_CMD, termination, rem, &req);
4711 context.check_layout(os);
4714 output_ert_inset(os, to_utf8(rem), context);
4716 skip_spaces_braces(p);
4717 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4718 preamble.registerAutomaticallyLoadedPackage(*it);
4720 //cerr << "#: " << t << " mode: " << mode << endl;
4721 // heuristic: read up to next non-nested space
4723 string s = t.asInput();
4724 string z = p.verbatim_item();
4725 while (p.good() && z != " " && !z.empty()) {
4726 //cerr << "read: " << z << endl;
4728 z = p.verbatim_item();
4730 cerr << "found ERT: " << s << endl;
4731 output_ert_inset(os, s + ' ', context);
4734 if (t.asInput() == name &&
4735 p.next_token().asInput() == "*") {
4736 // Starred commands like \vspace*{}
4737 p.get_token(); // Eat '*'
4740 if (!parse_command(name, p, os, outer, context))
4741 output_ert_inset(os, name, context);
4745 if (flags & FLAG_LEAVE) {
4746 flags &= ~FLAG_LEAVE;
4753 string guessLanguage(Parser & p, string const & lang)
4755 typedef std::map<std::string, size_t> LangMap;
4756 // map from language names to number of characters
4759 for (char const * const * i = supported_CJK_languages; *i; i++)
4760 used[string(*i)] = 0;
4763 Token const t = p.get_token();
4764 // comments are not counted for any language
4765 if (t.cat() == catComment)
4767 // commands are not counted as well, but we need to detect
4768 // \begin{CJK} and switch encoding if needed
4769 if (t.cat() == catEscape) {
4770 if (t.cs() == "inputencoding") {
4771 string const enc = subst(p.verbatim_item(), "\n", " ");
4772 p.setEncoding(enc, Encoding::inputenc);
4775 if (t.cs() != "begin")
4778 // Non-CJK content is counted for lang.
4779 // We do not care about the real language here:
4780 // If we have more non-CJK contents than CJK contents,
4781 // we simply use the language that was specified as
4782 // babel main language.
4783 used[lang] += t.asInput().length();
4786 // Now we are starting an environment
4788 string const name = p.getArg('{', '}');
4789 if (name != "CJK") {
4793 // It is a CJK environment
4795 /* name = */ p.getArg('{', '}');
4796 string const encoding = p.getArg('{', '}');
4797 /* mapping = */ p.getArg('{', '}');
4798 string const encoding_old = p.getEncoding();
4799 char const * const * const where =
4800 is_known(encoding, supported_CJK_encodings);
4802 p.setEncoding(encoding, Encoding::CJK);
4804 p.setEncoding("UTF-8");
4805 string const text = p.ertEnvironment("CJK");
4806 p.setEncoding(encoding_old);
4809 // ignore contents in unknown CJK encoding
4812 // the language of the text
4814 supported_CJK_languages[where - supported_CJK_encodings];
4815 used[cjk] += text.length();
4817 LangMap::const_iterator use = used.begin();
4818 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4819 if (it->second > use->second)