2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49 Context const & context, InsetLayout const * layout)
51 bool const forcePlainLayout =
52 layout ? layout->forcePlainLayout() : false;
53 Context newcontext(true, context.textclass);
55 newcontext.layout = &context.textclass.plainLayout();
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context const & context, string const & name)
68 InsetLayout const * layout = 0;
69 DocumentClass::InsetLayouts::const_iterator it =
70 context.textclass.insetLayouts().find(from_ascii(name));
71 if (it != context.textclass.insetLayouts().end())
72 layout = &(it->second);
73 parse_text_in_inset(p, os, flags, outer, context, layout);
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context newcontext(context);
81 // Don't inherit the paragraph-level extra stuff
82 newcontext.par_extra_stuff.clear();
83 parse_text(p, os, flags, outer, newcontext);
84 // Make sure that we don't create invalid .lyx files
85 context.need_layout = newcontext.need_layout;
86 context.need_end_layout = newcontext.need_end_layout;
91 * Thin wrapper around parse_text_snippet() using a string.
93 * We completely ignore \c context.need_layout and \c context.need_end_layout,
94 * because our return value is not used directly (otherwise the stream version
95 * of parse_text_snippet() could be used). That means that the caller needs
96 * to do layout management manually.
97 * This is intended to parse text that does not create any layout changes.
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
102 Context newcontext(context);
103 newcontext.need_layout = false;
104 newcontext.need_end_layout = false;
105 newcontext.new_layout_allowed = false;
106 // Avoid warning by Context::~Context()
107 newcontext.par_extra_stuff.clear();
109 parse_text_snippet(p, os, flags, outer, newcontext);
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115 "vpageref", "prettyref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "eqref", 0 };
120 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
121 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
122 "secref", "subref", "tabref", "thmref", 0 };
124 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
125 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
126 "sec", "sub", "tab", "thm", 0 };
130 * supported CJK encodings
131 * JIS does not work with LyX's encoding conversion
133 const char * const supported_CJK_encodings[] = {
134 "EUC-JP", "KS", "GB", "UTF8",
135 "Bg5", /*"JIS",*/ "SJIS", 0};
138 * the same as supported_CJK_encodings with their corresponding LyX language name
139 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
141 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
142 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
143 * please keep this in sync with supported_CJK_encodings line by line!
145 const char * const supported_CJK_languages[] = {
146 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
147 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
151 * The starred forms are also known except for "citefullauthor",
152 * "citeyear" and "citeyearpar".
154 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
155 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
156 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
160 * No starred form other than "cite*" known.
162 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
163 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
164 // jurabib commands not (yet) supported by LyX:
166 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
167 // "footciteauthor", "footciteyear", "footciteyearpar",
168 "citefield", "citetitle", 0 };
170 /// LaTeX names for quotes
171 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
172 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
173 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
174 "guilsinglleft", "frq", "guilsinglright", 0};
176 /// the same as known_quotes with .lyx names
177 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
178 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
179 "gld", "grd", "gls", "ers", "fls",
180 "fls", "frs", "frs", 0};
182 /// LaTeX names for font sizes
183 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
184 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
186 /// the same as known_sizes with .lyx names
187 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
188 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
190 /// LaTeX 2.09 names for font families
191 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
193 /// LaTeX names for font families
194 char const * const known_font_families[] = { "rmfamily", "sffamily",
197 /// LaTeX names for font family changing commands
198 char const * const known_text_font_families[] = { "textrm", "textsf",
201 /// The same as known_old_font_families, known_font_families and
202 /// known_text_font_families with .lyx names
203 char const * const known_coded_font_families[] = { "roman", "sans",
206 /// LaTeX 2.09 names for font series
207 char const * const known_old_font_series[] = { "bf", 0};
209 /// LaTeX names for font series
210 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
212 /// LaTeX names for font series changing commands
213 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
215 /// The same as known_old_font_series, known_font_series and
216 /// known_text_font_series with .lyx names
217 char const * const known_coded_font_series[] = { "bold", "medium", 0};
219 /// LaTeX 2.09 names for font shapes
220 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
222 /// LaTeX names for font shapes
223 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
226 /// LaTeX names for font shape changing commands
227 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
230 /// The same as known_old_font_shapes, known_font_shapes and
231 /// known_text_font_shapes with .lyx names
232 char const * const known_coded_font_shapes[] = { "italic", "slanted",
233 "smallcaps", "up", 0};
235 /// Known special characters which need skip_spaces_braces() afterwards
236 char const * const known_special_chars[] = {"ldots", "lyxarrow",
237 "textcompwordmark", "slash", 0};
239 /// the same as known_special_chars with .lyx names
240 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
241 "textcompwordmark{}", "slash{}", 0};
244 * Graphics file extensions known by the dvips driver of the graphics package.
245 * These extensions are used to complete the filename of an included
246 * graphics file if it does not contain an extension.
247 * The order must be the same that latex uses to find a file, because we
248 * will use the first extension that matches.
249 * This is only an approximation for the common cases. If we would want to
250 * do it right in all cases, we would need to know which graphics driver is
251 * used and know the extensions of every driver of the graphics package.
253 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
254 "ps.gz", "eps.Z", "ps.Z", 0};
257 * Graphics file extensions known by the pdftex driver of the graphics package.
258 * \sa known_dvips_graphics_formats
260 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
264 * Known file extensions for TeX files as used by \\include.
266 char const * const known_tex_extensions[] = {"tex", 0};
268 /// spaces known by InsetSpace
269 char const * const known_spaces[] = { " ", "space", ",",
270 "thinspace", "quad", "qquad", "enspace", "enskip",
271 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
272 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
273 "upbracefill", "downbracefill", 0};
275 /// the same as known_spaces with .lyx names
276 char const * const known_coded_spaces[] = { "space{}", "space{}",
277 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
278 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
279 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
280 "upbracefill{}", "downbracefill{}", 0};
282 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
283 /// them in ERT. "LaTeXe" must come before "LaTeX"!
284 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
285 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
286 int const known_phrase_lengths[] = {3, 5, 7, 0};
288 /// known TIPA combining diacritical marks
289 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
290 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
291 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
292 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
293 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
294 "texthighrise", "textlowrise", "textrisefall", "textsyllabic", 0};
296 /// tones that need special handling
297 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
299 // string to store the float type to be able to determine the type of subfloats
300 string float_type = "";
303 /// splits "x=z, y=b" into a map and an ordered keyword vector
304 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
309 keys.resize(v.size());
310 for (size_t i = 0; i < v.size(); ++i) {
311 size_t const pos = v[i].find('=');
312 string const index = trimSpaceAndEol(v[i].substr(0, pos));
313 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
321 * Split a LaTeX length into value and unit.
322 * The latter can be a real unit like "pt", or a latex length variable
323 * like "\textwidth". The unit may contain additional stuff like glue
324 * lengths, but we don't care, because such lengths are ERT anyway.
325 * \returns true if \p value and \p unit are valid.
327 bool splitLatexLength(string const & len, string & value, string & unit)
331 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
332 //'4,5' is a valid LaTeX length number. Change it to '4.5'
333 string const length = subst(len, ',', '.');
334 if (i == string::npos)
337 if (len[0] == '\\') {
338 // We had something like \textwidth without a factor
344 value = trimSpaceAndEol(string(length, 0, i));
348 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
349 if (contains(len, '\\'))
350 unit = trimSpaceAndEol(string(len, i));
352 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
357 /// A simple function to translate a latex length to something LyX can
358 /// understand. Not perfect, but rather best-effort.
359 bool translate_len(string const & length, string & valstring, string & unit)
361 if (!splitLatexLength(length, valstring, unit))
363 // LyX uses percent values
365 istringstream iss(valstring);
370 string const percentval = oss.str();
372 if (unit.empty() || unit[0] != '\\')
374 string::size_type const i = unit.find(' ');
375 string const endlen = (i == string::npos) ? string() : string(unit, i);
376 if (unit == "\\textwidth") {
377 valstring = percentval;
378 unit = "text%" + endlen;
379 } else if (unit == "\\columnwidth") {
380 valstring = percentval;
381 unit = "col%" + endlen;
382 } else if (unit == "\\paperwidth") {
383 valstring = percentval;
384 unit = "page%" + endlen;
385 } else if (unit == "\\linewidth") {
386 valstring = percentval;
387 unit = "line%" + endlen;
388 } else if (unit == "\\paperheight") {
389 valstring = percentval;
390 unit = "pheight%" + endlen;
391 } else if (unit == "\\textheight") {
392 valstring = percentval;
393 unit = "theight%" + endlen;
401 string translate_len(string const & length)
405 if (translate_len(length, value, unit))
407 // If the input is invalid, return what we have.
415 * Translates a LaTeX length into \p value, \p unit and
416 * \p special parts suitable for a box inset.
417 * The difference from translate_len() is that a box inset knows about
418 * some special "units" that are stored in \p special.
420 void translate_box_len(string const & length, string & value, string & unit, string & special)
422 if (translate_len(length, value, unit)) {
423 if (unit == "\\height" || unit == "\\depth" ||
424 unit == "\\totalheight" || unit == "\\width") {
425 special = unit.substr(1);
426 // The unit is not used, but LyX requires a dummy setting
439 * Find a file with basename \p name in path \p path and an extension
442 string find_file(string const & name, string const & path,
443 char const * const * extensions)
445 for (char const * const * what = extensions; *what; ++what) {
446 string const trial = addExtension(name, *what);
447 if (makeAbsPath(trial, path).exists())
454 void begin_inset(ostream & os, string const & name)
456 os << "\n\\begin_inset " << name;
460 void begin_command_inset(ostream & os, string const & name,
461 string const & latexname)
463 begin_inset(os, "CommandInset ");
464 os << name << "\nLatexCommand " << latexname << '\n';
468 void end_inset(ostream & os)
470 os << "\n\\end_inset\n\n";
474 bool skip_braces(Parser & p)
476 if (p.next_token().cat() != catBegin)
479 if (p.next_token().cat() == catEnd) {
488 /// replace LaTeX commands in \p s from the unicodesymbols file with their
490 docstring convert_unicodesymbols(docstring s)
493 for (size_t i = 0; i < s.size();) {
502 docstring parsed = encodings.fromLaTeXCommand(s,
503 Encodings::TEXT_CMD, termination, rem, &req);
504 set<string>::const_iterator it = req.begin();
505 set<string>::const_iterator en = req.end();
506 for (; it != en; ++it)
507 preamble.registerAutomaticallyLoadedPackage(*it);
510 if (s.empty() || s[0] != '\\')
519 /// try to convert \p s to a valid InsetCommand argument
520 string convert_command_inset_arg(string s)
523 // since we don't know the input encoding we can't use from_utf8
524 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
525 // LyX cannot handle newlines in a latex command
526 return subst(s, "\n", " ");
530 void output_ert(ostream & os, string const & s, Context & context)
532 context.check_layout(os);
533 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
535 os << "\n\\backslash\n";
536 else if (*it == '\n') {
537 context.new_paragraph(os);
538 context.check_layout(os);
542 context.check_end_layout(os);
546 void output_ert_inset(ostream & os, string const & s, Context & context)
548 // We must have a valid layout before outputting the ERT inset.
549 context.check_layout(os);
550 Context newcontext(true, context.textclass);
551 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
552 if (layout.forcePlainLayout())
553 newcontext.layout = &context.textclass.plainLayout();
554 begin_inset(os, "ERT");
555 os << "\nstatus collapsed\n";
556 output_ert(os, s, newcontext);
561 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
563 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
566 if (checkModule(name, command))
567 return findLayoutWithoutModule(textclass, name, command);
572 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
574 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
577 if (checkModule(name, command))
578 return findInsetLayoutWithoutModule(textclass, name, command);
583 void eat_whitespace(Parser &, ostream &, Context &, bool);
587 * Skips whitespace and braces.
588 * This should be called after a command has been parsed that is not put into
589 * ERT, and where LyX adds "{}" if needed.
591 void skip_spaces_braces(Parser & p, bool keepws = false)
593 /* The following four examples produce the same typeset output and
594 should be handled by this function:
602 // Unfortunately we need to skip comments, too.
603 // We can't use eat_whitespace since writing them after the {}
604 // results in different output in some cases.
605 bool const skipped_spaces = p.skip_spaces(true);
606 bool const skipped_braces = skip_braces(p);
607 if (keepws && skipped_spaces && !skipped_braces)
608 // put back the space (it is better handled by check_space)
609 p.unskip_spaces(true);
613 void output_command_layout(ostream & os, Parser & p, bool outer,
614 Context & parent_context,
615 Layout const * newlayout)
617 TeXFont const oldFont = parent_context.font;
618 // save the current font size
619 string const size = oldFont.size;
620 // reset the font size to default, because the font size switches
621 // don't affect section headings and the like
622 parent_context.font.size = Context::normalfont.size;
623 // we only need to write the font change if we have an open layout
624 if (!parent_context.atParagraphStart())
625 output_font_change(os, oldFont, parent_context.font);
626 parent_context.check_end_layout(os);
627 Context context(true, parent_context.textclass, newlayout,
628 parent_context.layout, parent_context.font);
629 if (parent_context.deeper_paragraph) {
630 // We are beginning a nested environment after a
631 // deeper paragraph inside the outer list environment.
632 // Therefore we don't need to output a "begin deeper".
633 context.need_end_deeper = true;
635 context.check_deeper(os);
636 context.check_layout(os);
637 // FIXME: Adjust to format 446!
638 // Since format 446, layouts do not require anymore all optional
639 // arguments before the required ones. Needs to be implemented!
641 while (optargs < context.layout->optArgs()) {
642 eat_whitespace(p, os, context, false);
643 if (p.next_token().cat() == catEscape ||
644 p.next_token().character() != '[')
646 p.get_token(); // eat '['
647 // FIXME: Just a workaround. InsetArgument::updateBuffer
648 // will compute a proper ID for all "999" Arguments
649 // (which is also what lyx2lyx produces).
650 // However, tex2lyx should be able to output proper IDs
652 begin_inset(os, "Argument 999\n");
653 os << "status collapsed\n\n";
654 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
656 eat_whitespace(p, os, context, false);
660 while (reqargs < context.layout->requiredArgs()) {
661 eat_whitespace(p, os, context, false);
662 if (p.next_token().cat() != catBegin)
664 p.get_token(); // eat '{'
665 // FIXME: Just a workaround. InsetArgument::updateBuffer
666 // will compute a proper ID for all "999" Arguments
667 // (which is also what lyx2lyx produces).
668 // However, tex2lyx should be able to output proper IDs
670 begin_inset(os, "Argument 999\n");
671 os << "status collapsed\n\n";
672 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
674 eat_whitespace(p, os, context, false);
677 parse_text(p, os, FLAG_ITEM, outer, context);
678 context.check_end_layout(os);
679 if (parent_context.deeper_paragraph) {
680 // We must suppress the "end deeper" because we
681 // suppressed the "begin deeper" above.
682 context.need_end_deeper = false;
684 context.check_end_deeper(os);
685 // We don't need really a new paragraph, but
686 // we must make sure that the next item gets a \begin_layout.
687 parent_context.new_paragraph(os);
688 // Set the font size to the original value. No need to output it here
689 // (Context::begin_layout() will do that if needed)
690 parent_context.font.size = size;
695 * Output a space if necessary.
696 * This function gets called for every whitespace token.
698 * We have three cases here:
699 * 1. A space must be suppressed. Example: The lyxcode case below
700 * 2. A space may be suppressed. Example: Spaces before "\par"
701 * 3. A space must not be suppressed. Example: A space between two words
703 * We currently handle only 1. and 3 and from 2. only the case of
704 * spaces before newlines as a side effect.
706 * 2. could be used to suppress as many spaces as possible. This has two effects:
707 * - Reimporting LyX generated LaTeX files changes almost no whitespace
708 * - Superflous whitespace from non LyX generated LaTeX files is removed.
709 * The drawback is that the logic inside the function becomes
710 * complicated, and that is the reason why it is not implemented.
712 void check_space(Parser & p, ostream & os, Context & context)
714 Token const next = p.next_token();
715 Token const curr = p.curr_token();
716 // A space before a single newline and vice versa must be ignored
717 // LyX emits a newline before \end{lyxcode}.
718 // This newline must be ignored,
719 // otherwise LyX will add an additional protected space.
720 if (next.cat() == catSpace ||
721 next.cat() == catNewline ||
722 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
725 context.check_layout(os);
731 * Parse all arguments of \p command
733 void parse_arguments(string const & command,
734 vector<ArgumentType> const & template_arguments,
735 Parser & p, ostream & os, bool outer, Context & context)
737 string ert = command;
738 size_t no_arguments = template_arguments.size();
739 for (size_t i = 0; i < no_arguments; ++i) {
740 switch (template_arguments[i]) {
743 // This argument contains regular LaTeX
744 output_ert_inset(os, ert + '{', context);
745 eat_whitespace(p, os, context, false);
746 if (template_arguments[i] == required)
747 parse_text(p, os, FLAG_ITEM, outer, context);
749 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
753 // This argument consists only of a single item.
754 // The presence of '{' or not must be preserved.
756 if (p.next_token().cat() == catBegin)
757 ert += '{' + p.verbatim_item() + '}';
759 ert += p.verbatim_item();
763 // This argument may contain special characters
764 ert += '{' + p.verbatim_item() + '}';
768 // true because we must not eat whitespace
769 // if an optional arg follows we must not strip the
770 // brackets from this one
771 if (i < no_arguments - 1 &&
772 template_arguments[i+1] == optional)
773 ert += p.getFullOpt(true);
775 ert += p.getOpt(true);
779 output_ert_inset(os, ert, context);
784 * Check whether \p command is a known command. If yes,
785 * handle the command with all arguments.
786 * \return true if the command was parsed, false otherwise.
788 bool parse_command(string const & command, Parser & p, ostream & os,
789 bool outer, Context & context)
791 if (known_commands.find(command) != known_commands.end()) {
792 parse_arguments(command, known_commands[command], p, os,
800 /// Parses a minipage or parbox
801 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
802 unsigned inner_flags, bool outer, Context & parent_context,
803 string const & outer_type, string const & special,
804 string const & inner_type)
808 string hor_pos = "c";
809 // We need to set the height to the LaTeX default of 1\\totalheight
810 // for the case when no height argument is given
811 string height_value = "1";
812 string height_unit = "in";
813 string height_special = "totalheight";
818 string width_special = "none";
819 if (!inner_type.empty() && p.hasOpt()) {
820 if (inner_type != "makebox")
821 position = p.getArg('[', ']');
823 latex_width = p.getArg('[', ']');
824 translate_box_len(latex_width, width_value, width_unit, width_special);
827 if (position != "t" && position != "c" && position != "b") {
828 cerr << "invalid position " << position << " for "
829 << inner_type << endl;
833 if (inner_type != "makebox") {
834 latex_height = p.getArg('[', ']');
835 translate_box_len(latex_height, height_value, height_unit, height_special);
837 string const opt = p.getArg('[', ']');
840 if (hor_pos != "l" && hor_pos != "c" &&
841 hor_pos != "r" && hor_pos != "s") {
842 cerr << "invalid hor_pos " << hor_pos
843 << " for " << inner_type << endl;
850 inner_pos = p.getArg('[', ']');
851 if (inner_pos != "c" && inner_pos != "t" &&
852 inner_pos != "b" && inner_pos != "s") {
853 cerr << "invalid inner_pos "
854 << inner_pos << " for "
855 << inner_type << endl;
856 inner_pos = position;
861 if (inner_type.empty()) {
862 if (special.empty() && outer_type != "framebox")
863 latex_width = "1\\columnwidth";
866 latex_width = p2.getArg('[', ']');
867 string const opt = p2.getArg('[', ']');
870 if (hor_pos != "l" && hor_pos != "c" &&
871 hor_pos != "r" && hor_pos != "s") {
872 cerr << "invalid hor_pos " << hor_pos
873 << " for " << outer_type << endl;
878 } else if (inner_type != "makebox")
879 latex_width = p.verbatim_item();
880 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
881 // as this is LyX's standard for such cases (except for makebox)
882 // \framebox is more special and handled below
883 if (latex_width.empty() && inner_type != "makebox"
884 && outer_type != "framebox")
885 latex_width = "1\\columnwidth";
887 translate_len(latex_width, width_value, width_unit);
889 bool shadedparbox = false;
890 if (inner_type == "shaded") {
891 eat_whitespace(p, os, parent_context, false);
892 if (outer_type == "parbox") {
894 if (p.next_token().cat() == catBegin)
896 eat_whitespace(p, os, parent_context, false);
902 // If we already read the inner box we have to push the inner env
903 if (!outer_type.empty() && !inner_type.empty() &&
904 (inner_flags & FLAG_END))
905 active_environments.push_back(inner_type);
906 // LyX can't handle length variables
907 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
908 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
909 // Look whether there is some content after the end of the
910 // inner box, but before the end of the outer box.
911 // If yes, we need to output ERT.
913 if (inner_flags & FLAG_END)
914 p.ertEnvironment(inner_type);
918 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
919 if ((outer_env && p.next_token().asInput() != "\\end") ||
920 (!outer_env && p.next_token().cat() != catEnd)) {
921 // something is between the end of the inner box and
922 // the end of the outer box, so we need to use ERT.
927 // if only \makebox{content} was used we can set its width to 1\width
928 // because this identic and also identic to \mbox
929 // this doesn't work for \framebox{content}, thus we have to use ERT for this
930 if (latex_width.empty() && inner_type == "makebox") {
933 width_special = "width";
934 } else if (latex_width.empty() && outer_type == "framebox") {
939 if (!outer_type.empty()) {
940 if (outer_flags & FLAG_END)
941 ss << "\\begin{" << outer_type << '}';
943 ss << '\\' << outer_type << '{';
944 if (!special.empty())
948 if (!inner_type.empty()) {
949 if (inner_type != "shaded") {
950 if (inner_flags & FLAG_END)
951 ss << "\\begin{" << inner_type << '}';
953 ss << '\\' << inner_type;
955 if (!position.empty())
956 ss << '[' << position << ']';
957 if (!latex_height.empty())
958 ss << '[' << latex_height << ']';
959 if (!inner_pos.empty())
960 ss << '[' << inner_pos << ']';
961 ss << '{' << latex_width << '}';
962 if (!(inner_flags & FLAG_END))
965 if (inner_type == "shaded")
966 ss << "\\begin{shaded}";
967 output_ert_inset(os, ss.str(), parent_context);
968 if (!inner_type.empty()) {
969 parse_text(p, os, inner_flags, outer, parent_context);
970 if (inner_flags & FLAG_END)
971 output_ert_inset(os, "\\end{" + inner_type + '}',
974 output_ert_inset(os, "}", parent_context);
976 if (!outer_type.empty()) {
977 // If we already read the inner box we have to pop
979 if (!inner_type.empty() && (inner_flags & FLAG_END))
980 active_environments.pop_back();
982 // Ensure that the end of the outer box is parsed correctly:
983 // The opening brace has been eaten by parse_outer_box()
984 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
985 outer_flags &= ~FLAG_ITEM;
986 outer_flags |= FLAG_BRACE_LAST;
988 parse_text(p, os, outer_flags, outer, parent_context);
989 if (outer_flags & FLAG_END)
990 output_ert_inset(os, "\\end{" + outer_type + '}',
992 else if (inner_type.empty() && outer_type == "framebox")
993 // in this case it is already closed later
996 output_ert_inset(os, "}", parent_context);
999 // LyX does not like empty positions, so we have
1000 // to set them to the LaTeX default values here.
1001 if (position.empty())
1003 if (inner_pos.empty())
1004 inner_pos = position;
1005 parent_context.check_layout(os);
1006 begin_inset(os, "Box ");
1007 if (outer_type == "framed")
1009 else if (outer_type == "framebox")
1011 else if (outer_type == "shadowbox")
1012 os << "Shadowbox\n";
1013 else if ((outer_type == "shaded" && inner_type.empty()) ||
1014 (outer_type == "minipage" && inner_type == "shaded") ||
1015 (outer_type == "parbox" && inner_type == "shaded")) {
1017 preamble.registerAutomaticallyLoadedPackage("color");
1018 } else if (outer_type == "doublebox")
1019 os << "Doublebox\n";
1020 else if (outer_type.empty())
1021 os << "Frameless\n";
1023 os << outer_type << '\n';
1024 os << "position \"" << position << "\"\n";
1025 os << "hor_pos \"" << hor_pos << "\"\n";
1026 os << "has_inner_box " << !inner_type.empty() << "\n";
1027 os << "inner_pos \"" << inner_pos << "\"\n";
1028 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1030 os << "use_makebox " << (inner_type == "makebox") << '\n';
1031 os << "width \"" << width_value << width_unit << "\"\n";
1032 os << "special \"" << width_special << "\"\n";
1033 os << "height \"" << height_value << height_unit << "\"\n";
1034 os << "height_special \"" << height_special << "\"\n";
1035 os << "status open\n\n";
1037 // Unfortunately we can't use parse_text_in_inset:
1038 // InsetBox::forcePlainLayout() is hard coded and does not
1039 // use the inset layout. Apart from that do we call parse_text
1040 // up to two times, but need only one check_end_layout.
1041 bool const forcePlainLayout =
1042 (!inner_type.empty() || inner_type == "makebox") &&
1043 outer_type != "shaded" && outer_type != "framed";
1044 Context context(true, parent_context.textclass);
1045 if (forcePlainLayout)
1046 context.layout = &context.textclass.plainLayout();
1048 context.font = parent_context.font;
1050 // If we have no inner box the contents will be read with the outer box
1051 if (!inner_type.empty())
1052 parse_text(p, os, inner_flags, outer, context);
1054 // Ensure that the end of the outer box is parsed correctly:
1055 // The opening brace has been eaten by parse_outer_box()
1056 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1057 outer_flags &= ~FLAG_ITEM;
1058 outer_flags |= FLAG_BRACE_LAST;
1061 // Find end of outer box, output contents if inner_type is
1062 // empty and output possible comments
1063 if (!outer_type.empty()) {
1064 // If we already read the inner box we have to pop
1066 if (!inner_type.empty() && (inner_flags & FLAG_END))
1067 active_environments.pop_back();
1068 // This does not output anything but comments if
1069 // inner_type is not empty (see use_ert)
1070 parse_text(p, os, outer_flags, outer, context);
1073 context.check_end_layout(os);
1075 #ifdef PRESERVE_LAYOUT
1076 // LyX puts a % after the end of the minipage
1077 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1079 //output_ert_inset(os, "%dummy", parent_context);
1082 parent_context.new_paragraph(os);
1084 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1085 //output_ert_inset(os, "%dummy", parent_context);
1088 // We add a protected space if something real follows
1089 if (p.good() && p.next_token().cat() != catComment) {
1090 begin_inset(os, "space ~\n");
1099 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1100 Context & parent_context, string const & outer_type,
1101 string const & special)
1103 eat_whitespace(p, os, parent_context, false);
1104 if (flags & FLAG_ITEM) {
1106 if (p.next_token().cat() == catBegin)
1109 cerr << "Warning: Ignoring missing '{' after \\"
1110 << outer_type << '.' << endl;
1111 eat_whitespace(p, os, parent_context, false);
1114 unsigned int inner_flags = 0;
1116 if (outer_type == "minipage" || outer_type == "parbox") {
1117 p.skip_spaces(true);
1118 while (p.hasOpt()) {
1120 p.skip_spaces(true);
1123 p.skip_spaces(true);
1124 if (outer_type == "parbox") {
1126 if (p.next_token().cat() == catBegin)
1128 p.skip_spaces(true);
1131 if (outer_type == "shaded") {
1132 // These boxes never have an inner box
1134 } else if (p.next_token().asInput() == "\\parbox") {
1135 inner = p.get_token().cs();
1136 inner_flags = FLAG_ITEM;
1137 } else if (p.next_token().asInput() == "\\begin") {
1138 // Is this a minipage or shaded box?
1141 inner = p.getArg('{', '}');
1143 if (inner == "minipage" || inner == "shaded")
1144 inner_flags = FLAG_END;
1149 if (inner_flags == FLAG_END) {
1150 if (inner != "shaded")
1154 eat_whitespace(p, os, parent_context, false);
1156 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1157 outer_type, special, inner);
1159 if (inner_flags == FLAG_ITEM) {
1161 eat_whitespace(p, os, parent_context, false);
1163 parse_box(p, os, flags, inner_flags, outer, parent_context,
1164 outer_type, special, inner);
1169 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1171 parent_context.check_layout(os);
1172 begin_inset(os, "listings\n");
1174 string arg = p.verbatimOption();
1175 os << "lstparams " << '"' << arg << '"' << '\n';
1176 if (arg.find("\\color") != string::npos)
1177 preamble.registerAutomaticallyLoadedPackage("color");
1180 os << "inline true\n";
1182 os << "inline false\n";
1183 os << "status collapsed\n";
1184 Context context(true, parent_context.textclass);
1185 context.layout = &parent_context.textclass.plainLayout();
1188 // set catcodes to verbatim early, just in case.
1189 p.setCatcodes(VERBATIM_CATCODES);
1190 string delim = p.get_token().asInput();
1191 s = p.verbatimStuff(delim);
1192 // context.new_paragraph(os);
1194 s = p.verbatimEnvironment("lstlisting");
1195 output_ert(os, s, context);
1200 /// parse an unknown environment
1201 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1202 unsigned flags, bool outer,
1203 Context & parent_context)
1205 if (name == "tabbing")
1206 // We need to remember that we have to handle '\=' specially
1207 flags |= FLAG_TABBING;
1209 // We need to translate font changes and paragraphs inside the
1210 // environment to ERT if we have a non standard font.
1211 // Otherwise things like
1212 // \large\begin{foo}\huge bar\end{foo}
1214 bool const specialfont =
1215 (parent_context.font != parent_context.normalfont);
1216 bool const new_layout_allowed = parent_context.new_layout_allowed;
1218 parent_context.new_layout_allowed = false;
1219 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1220 parse_text_snippet(p, os, flags, outer, parent_context);
1221 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1223 parent_context.new_layout_allowed = new_layout_allowed;
1227 void parse_environment(Parser & p, ostream & os, bool outer,
1228 string & last_env, Context & parent_context)
1230 Layout const * newlayout;
1231 InsetLayout const * newinsetlayout = 0;
1232 string const name = p.getArg('{', '}');
1233 const bool is_starred = suffixIs(name, '*');
1234 string const unstarred_name = rtrim(name, "*");
1235 active_environments.push_back(name);
1237 if (is_math_env(name)) {
1238 parent_context.check_layout(os);
1239 begin_inset(os, "Formula ");
1240 os << "\\begin{" << name << "}";
1241 parse_math(p, os, FLAG_END, MATH_MODE);
1242 os << "\\end{" << name << "}";
1244 if (is_display_math_env(name)) {
1245 // Prevent the conversion of a line break to a space
1246 // (bug 7668). This does not change the output, but
1247 // looks ugly in LyX.
1248 eat_whitespace(p, os, parent_context, false);
1252 else if (is_known(name, preamble.polyglossia_languages)) {
1253 // We must begin a new paragraph if not already done
1254 if (! parent_context.atParagraphStart()) {
1255 parent_context.check_end_layout(os);
1256 parent_context.new_paragraph(os);
1258 // save the language in the context so that it is
1259 // handled by parse_text
1260 parent_context.font.language = preamble.polyglossia2lyx(name);
1261 parse_text(p, os, FLAG_END, outer, parent_context);
1262 // Just in case the environment is empty
1263 parent_context.extra_stuff.erase();
1264 // We must begin a new paragraph to reset the language
1265 parent_context.new_paragraph(os);
1269 else if (unstarred_name == "tabular" || name == "longtable") {
1270 eat_whitespace(p, os, parent_context, false);
1271 string width = "0pt";
1272 if (name == "tabular*") {
1273 width = lyx::translate_len(p.getArg('{', '}'));
1274 eat_whitespace(p, os, parent_context, false);
1276 parent_context.check_layout(os);
1277 begin_inset(os, "Tabular ");
1278 handle_tabular(p, os, name, width, parent_context);
1283 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1284 eat_whitespace(p, os, parent_context, false);
1285 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1286 eat_whitespace(p, os, parent_context, false);
1287 parent_context.check_layout(os);
1288 begin_inset(os, "Float " + unstarred_name + "\n");
1289 // store the float type for subfloats
1290 // subfloats only work with figures and tables
1291 if (unstarred_name == "figure")
1292 float_type = unstarred_name;
1293 else if (unstarred_name == "table")
1294 float_type = unstarred_name;
1298 os << "placement " << opt << '\n';
1299 if (contains(opt, "H"))
1300 preamble.registerAutomaticallyLoadedPackage("float");
1302 Floating const & fl = parent_context.textclass.floats()
1303 .getType(unstarred_name);
1304 if (!fl.floattype().empty() && fl.usesFloatPkg())
1305 preamble.registerAutomaticallyLoadedPackage("float");
1308 os << "wide " << convert<string>(is_starred)
1309 << "\nsideways false"
1310 << "\nstatus open\n\n";
1311 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1313 // We don't need really a new paragraph, but
1314 // we must make sure that the next item gets a \begin_layout.
1315 parent_context.new_paragraph(os);
1317 // the float is parsed thus delete the type
1321 else if (unstarred_name == "sidewaysfigure"
1322 || unstarred_name == "sidewaystable") {
1323 eat_whitespace(p, os, parent_context, false);
1324 parent_context.check_layout(os);
1325 if (unstarred_name == "sidewaysfigure")
1326 begin_inset(os, "Float figure\n");
1328 begin_inset(os, "Float table\n");
1329 os << "wide " << convert<string>(is_starred)
1330 << "\nsideways true"
1331 << "\nstatus open\n\n";
1332 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1334 // We don't need really a new paragraph, but
1335 // we must make sure that the next item gets a \begin_layout.
1336 parent_context.new_paragraph(os);
1338 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1341 else if (name == "wrapfigure" || name == "wraptable") {
1342 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1343 eat_whitespace(p, os, parent_context, false);
1344 parent_context.check_layout(os);
1347 string overhang = "0col%";
1350 lines = p.getArg('[', ']');
1351 string const placement = p.getArg('{', '}');
1353 overhang = p.getArg('[', ']');
1354 string const width = p.getArg('{', '}');
1356 if (name == "wrapfigure")
1357 begin_inset(os, "Wrap figure\n");
1359 begin_inset(os, "Wrap table\n");
1360 os << "lines " << lines
1361 << "\nplacement " << placement
1362 << "\noverhang " << lyx::translate_len(overhang)
1363 << "\nwidth " << lyx::translate_len(width)
1364 << "\nstatus open\n\n";
1365 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1367 // We don't need really a new paragraph, but
1368 // we must make sure that the next item gets a \begin_layout.
1369 parent_context.new_paragraph(os);
1371 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1374 else if (name == "minipage") {
1375 eat_whitespace(p, os, parent_context, false);
1376 // Test whether this is an outer box of a shaded box
1378 // swallow arguments
1379 while (p.hasOpt()) {
1381 p.skip_spaces(true);
1384 p.skip_spaces(true);
1385 Token t = p.get_token();
1386 bool shaded = false;
1387 if (t.asInput() == "\\begin") {
1388 p.skip_spaces(true);
1389 if (p.getArg('{', '}') == "shaded")
1394 parse_outer_box(p, os, FLAG_END, outer,
1395 parent_context, name, "shaded");
1397 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1402 else if (name == "comment") {
1403 eat_whitespace(p, os, parent_context, false);
1404 parent_context.check_layout(os);
1405 begin_inset(os, "Note Comment\n");
1406 os << "status open\n";
1407 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1410 skip_braces(p); // eat {} that might by set by LyX behind comments
1411 preamble.registerAutomaticallyLoadedPackage("verbatim");
1414 else if (name == "verbatim") {
1415 // FIXME: this should go in the generic code that
1416 // handles environments defined in layout file that
1417 // have "PassThru 1". However, the code over there is
1418 // already too complicated for my taste.
1419 parent_context.new_paragraph(os);
1420 Context context(true, parent_context.textclass,
1421 &parent_context.textclass[from_ascii("Verbatim")]);
1422 string s = p.verbatimEnvironment("verbatim");
1423 output_ert(os, s, context);
1427 else if (name == "IPA") {
1428 eat_whitespace(p, os, parent_context, false);
1429 parent_context.check_layout(os);
1430 begin_inset(os, "IPA\n");
1431 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1434 preamble.registerAutomaticallyLoadedPackage("tipa");
1435 preamble.registerAutomaticallyLoadedPackage("tipx");
1438 else if (name == "CJK") {
1439 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1440 // It is impossible to decide if a CJK environment was in its own paragraph or within
1441 // a line. We therefore always assume a paragraph since the latter is a rare case.
1442 eat_whitespace(p, os, parent_context, false);
1443 parent_context.check_end_layout(os);
1444 // store the encoding to be able to reset it
1445 string const encoding_old = p.getEncoding();
1446 string const encoding = p.getArg('{', '}');
1447 // FIXME: For some reason JIS does not work. Although the text
1448 // in tests/CJK.tex is identical with the SJIS version if you
1449 // convert both snippets using the recode command line utility,
1450 // the resulting .lyx file contains some extra characters if
1451 // you set buggy_encoding to false for JIS.
1452 bool const buggy_encoding = encoding == "JIS";
1453 if (!buggy_encoding)
1454 p.setEncoding(encoding, Encoding::CJK);
1456 // FIXME: This will read garbage, since the data is not encoded in utf8.
1457 p.setEncoding("UTF-8");
1459 // LyX only supports the same mapping for all CJK
1460 // environments, so we might need to output everything as ERT
1461 string const mapping = trim(p.getArg('{', '}'));
1462 char const * const * const where =
1463 is_known(encoding, supported_CJK_encodings);
1464 if (!buggy_encoding && !preamble.fontCJKSet())
1465 preamble.fontCJK(mapping);
1466 bool knownMapping = mapping == preamble.fontCJK();
1467 if (buggy_encoding || !knownMapping || !where) {
1468 parent_context.check_layout(os);
1469 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1471 // we must parse the content as verbatim because e.g. JIS can contain
1472 // normally invalid characters
1473 // FIXME: This works only for the most simple cases.
1474 // Since TeX control characters are not parsed,
1475 // things like comments are completely wrong.
1476 string const s = p.plainEnvironment("CJK");
1477 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1479 output_ert_inset(os, "\\", parent_context);
1480 else if (*it == '$')
1481 output_ert_inset(os, "$", parent_context);
1485 output_ert_inset(os, "\\end{" + name + "}",
1489 supported_CJK_languages[where - supported_CJK_encodings];
1490 // store the language because we must reset it at the end
1491 string const lang_old = parent_context.font.language;
1492 parent_context.font.language = lang;
1493 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1494 parent_context.font.language = lang_old;
1495 parent_context.new_paragraph(os);
1497 p.setEncoding(encoding_old);
1501 else if (name == "lyxgreyedout") {
1502 eat_whitespace(p, os, parent_context, false);
1503 parent_context.check_layout(os);
1504 begin_inset(os, "Note Greyedout\n");
1505 os << "status open\n";
1506 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1509 if (!preamble.notefontcolor().empty())
1510 preamble.registerAutomaticallyLoadedPackage("color");
1513 else if (name == "framed" || name == "shaded") {
1514 eat_whitespace(p, os, parent_context, false);
1515 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1519 else if (name == "lstlisting") {
1520 eat_whitespace(p, os, parent_context, false);
1521 parse_listings(p, os, parent_context, false);
1525 else if (!parent_context.new_layout_allowed)
1526 parse_unknown_environment(p, name, os, FLAG_END, outer,
1529 // Alignment and spacing settings
1530 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1531 // therefore are totally broken!
1532 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1533 // they are commands not environments. They are furthermore switches that
1534 // can be ended by another switches, but also by commands like \footnote or
1535 // \parbox. So the only safe way is to leave them untouched.
1536 else if (name == "center" || name == "centering" ||
1537 name == "flushleft" || name == "flushright" ||
1538 name == "singlespace" || name == "onehalfspace" ||
1539 name == "doublespace" || name == "spacing") {
1540 eat_whitespace(p, os, parent_context, false);
1541 // We must begin a new paragraph if not already done
1542 if (! parent_context.atParagraphStart()) {
1543 parent_context.check_end_layout(os);
1544 parent_context.new_paragraph(os);
1546 if (name == "flushleft")
1547 parent_context.add_extra_stuff("\\align left\n");
1548 else if (name == "flushright")
1549 parent_context.add_extra_stuff("\\align right\n");
1550 else if (name == "center" || name == "centering")
1551 parent_context.add_extra_stuff("\\align center\n");
1552 else if (name == "singlespace")
1553 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1554 else if (name == "onehalfspace") {
1555 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1556 preamble.registerAutomaticallyLoadedPackage("setspace");
1557 } else if (name == "doublespace") {
1558 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1559 preamble.registerAutomaticallyLoadedPackage("setspace");
1560 } else if (name == "spacing") {
1561 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1562 preamble.registerAutomaticallyLoadedPackage("setspace");
1564 parse_text(p, os, FLAG_END, outer, parent_context);
1565 // Just in case the environment is empty
1566 parent_context.extra_stuff.erase();
1567 // We must begin a new paragraph to reset the alignment
1568 parent_context.new_paragraph(os);
1572 // The single '=' is meant here.
1573 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1574 eat_whitespace(p, os, parent_context, false);
1575 Context context(true, parent_context.textclass, newlayout,
1576 parent_context.layout, parent_context.font);
1577 if (parent_context.deeper_paragraph) {
1578 // We are beginning a nested environment after a
1579 // deeper paragraph inside the outer list environment.
1580 // Therefore we don't need to output a "begin deeper".
1581 context.need_end_deeper = true;
1583 parent_context.check_end_layout(os);
1584 if (last_env == name) {
1585 // we need to output a separator since LyX would export
1586 // the two environments as one otherwise (bug 5716)
1587 docstring const sep = from_ascii("--Separator--");
1588 TeX2LyXDocClass const & textclass(parent_context.textclass);
1589 if (textclass.hasLayout(sep)) {
1590 Context newcontext(parent_context);
1591 newcontext.layout = &(textclass[sep]);
1592 newcontext.check_layout(os);
1593 newcontext.check_end_layout(os);
1595 parent_context.check_layout(os);
1596 begin_inset(os, "Note Note\n");
1597 os << "status closed\n";
1598 Context newcontext(true, textclass,
1599 &(textclass.defaultLayout()));
1600 newcontext.check_layout(os);
1601 newcontext.check_end_layout(os);
1603 parent_context.check_end_layout(os);
1606 switch (context.layout->latextype) {
1607 case LATEX_LIST_ENVIRONMENT:
1608 context.add_par_extra_stuff("\\labelwidthstring "
1609 + p.verbatim_item() + '\n');
1612 case LATEX_BIB_ENVIRONMENT:
1613 p.verbatim_item(); // swallow next arg
1619 context.check_deeper(os);
1620 // handle known optional and required arguments
1621 // FIXME: Since format 446, layouts do not require anymore all optional
1622 // arguments before the required ones. Needs to be implemented!
1623 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1624 // It is impossible to place anything after the environment name,
1625 // but before the first \\item.
1626 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1627 bool need_layout = true;
1629 while (optargs < context.layout->optArgs()) {
1630 eat_whitespace(p, os, context, false);
1631 if (p.next_token().cat() == catEscape ||
1632 p.next_token().character() != '[')
1634 p.get_token(); // eat '['
1636 context.check_layout(os);
1637 need_layout = false;
1639 // FIXME: Just a workaround. InsetArgument::updateBuffer
1640 // will compute a proper ID for all "999" Arguments
1641 // (which is also what lyx2lyx produces).
1642 // However, tex2lyx should be able to output proper IDs
1644 begin_inset(os, "Argument 999\n");
1645 os << "status collapsed\n\n";
1646 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1648 eat_whitespace(p, os, context, false);
1652 while (reqargs < context.layout->requiredArgs()) {
1653 eat_whitespace(p, os, context, false);
1654 if (p.next_token().cat() != catBegin)
1656 p.get_token(); // eat '{'
1658 context.check_layout(os);
1659 need_layout = false;
1661 // FIXME: Just a workaround. InsetArgument::updateBuffer
1662 // will compute a proper ID for all "999" Arguments
1663 // (which is also what lyx2lyx produces).
1664 // However, tex2lyx should be able to output proper IDs
1666 begin_inset(os, "Argument 999\n");
1667 os << "status collapsed\n\n";
1668 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1670 eat_whitespace(p, os, context, false);
1674 parse_text(p, os, FLAG_END, outer, context);
1675 context.check_end_layout(os);
1676 if (parent_context.deeper_paragraph) {
1677 // We must suppress the "end deeper" because we
1678 // suppressed the "begin deeper" above.
1679 context.need_end_deeper = false;
1681 context.check_end_deeper(os);
1682 parent_context.new_paragraph(os);
1684 if (!preamble.titleLayoutFound())
1685 preamble.titleLayoutFound(newlayout->intitle);
1686 set<string> const & req = newlayout->requires();
1687 set<string>::const_iterator it = req.begin();
1688 set<string>::const_iterator en = req.end();
1689 for (; it != en; ++it)
1690 preamble.registerAutomaticallyLoadedPackage(*it);
1693 // The single '=' is meant here.
1694 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1695 eat_whitespace(p, os, parent_context, false);
1696 parent_context.check_layout(os);
1697 begin_inset(os, "Flex ");
1698 os << to_utf8(newinsetlayout->name()) << '\n'
1699 << "status collapsed\n";
1700 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1704 else if (name == "appendix") {
1705 // This is no good latex style, but it works and is used in some documents...
1706 eat_whitespace(p, os, parent_context, false);
1707 parent_context.check_end_layout(os);
1708 Context context(true, parent_context.textclass, parent_context.layout,
1709 parent_context.layout, parent_context.font);
1710 context.check_layout(os);
1711 os << "\\start_of_appendix\n";
1712 parse_text(p, os, FLAG_END, outer, context);
1713 context.check_end_layout(os);
1717 else if (known_environments.find(name) != known_environments.end()) {
1718 vector<ArgumentType> arguments = known_environments[name];
1719 // The last "argument" denotes wether we may translate the
1720 // environment contents to LyX
1721 // The default required if no argument is given makes us
1722 // compatible with the reLyXre environment.
1723 ArgumentType contents = arguments.empty() ?
1726 if (!arguments.empty())
1727 arguments.pop_back();
1728 // See comment in parse_unknown_environment()
1729 bool const specialfont =
1730 (parent_context.font != parent_context.normalfont);
1731 bool const new_layout_allowed =
1732 parent_context.new_layout_allowed;
1734 parent_context.new_layout_allowed = false;
1735 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1736 outer, parent_context);
1737 if (contents == verbatim)
1738 output_ert_inset(os, p.ertEnvironment(name),
1741 parse_text_snippet(p, os, FLAG_END, outer,
1743 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1745 parent_context.new_layout_allowed = new_layout_allowed;
1749 parse_unknown_environment(p, name, os, FLAG_END, outer,
1753 active_environments.pop_back();
1757 /// parses a comment and outputs it to \p os.
1758 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1760 LASSERT(t.cat() == catComment, return);
1761 if (!t.cs().empty()) {
1762 context.check_layout(os);
1763 output_ert_inset(os, '%' + t.cs(), context);
1764 if (p.next_token().cat() == catNewline) {
1765 // A newline after a comment line starts a new
1767 if (context.new_layout_allowed) {
1768 if(!context.atParagraphStart())
1769 // Only start a new paragraph if not already
1770 // done (we might get called recursively)
1771 context.new_paragraph(os);
1773 output_ert_inset(os, "\n", context);
1774 eat_whitespace(p, os, context, true);
1777 // "%\n" combination
1784 * Reads spaces and comments until the first non-space, non-comment token.
1785 * New paragraphs (double newlines or \\par) are handled like simple spaces
1786 * if \p eatParagraph is true.
1787 * Spaces are skipped, but comments are written to \p os.
1789 void eat_whitespace(Parser & p, ostream & os, Context & context,
1793 Token const & t = p.get_token();
1794 if (t.cat() == catComment)
1795 parse_comment(p, os, t, context);
1796 else if ((! eatParagraph && p.isParagraph()) ||
1797 (t.cat() != catSpace && t.cat() != catNewline)) {
1806 * Set a font attribute, parse text and reset the font attribute.
1807 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1808 * \param currentvalue Current value of the attribute. Is set to the new
1809 * value during parsing.
1810 * \param newvalue New value of the attribute
1812 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1813 Context & context, string const & attribute,
1814 string & currentvalue, string const & newvalue)
1816 context.check_layout(os);
1817 string const oldvalue = currentvalue;
1818 currentvalue = newvalue;
1819 os << '\n' << attribute << ' ' << newvalue << "\n";
1820 parse_text_snippet(p, os, flags, outer, context);
1821 context.check_layout(os);
1822 os << '\n' << attribute << ' ' << oldvalue << "\n";
1823 currentvalue = oldvalue;
1827 /// get the arguments of a natbib or jurabib citation command
1828 void get_cite_arguments(Parser & p, bool natbibOrder,
1829 string & before, string & after)
1831 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1833 // text before the citation
1835 // text after the citation
1836 after = p.getFullOpt();
1838 if (!after.empty()) {
1839 before = p.getFullOpt();
1840 if (natbibOrder && !before.empty())
1841 swap(before, after);
1846 /// Convert filenames with TeX macros and/or quotes to something LyX
1848 string const normalize_filename(string const & name)
1853 Token const & t = p.get_token();
1854 if (t.cat() != catEscape)
1856 else if (t.cs() == "lyxdot") {
1857 // This is used by LyX for simple dots in relative
1861 } else if (t.cs() == "space") {
1864 } else if (t.cs() == "string") {
1865 // Convert \string" to " and \string~ to ~
1866 Token const & n = p.next_token();
1867 if (n.asInput() != "\"" && n.asInput() != "~")
1872 // Strip quotes. This is a bit complicated (see latex_path()).
1873 string full = os.str();
1874 if (!full.empty() && full[0] == '"') {
1875 string base = removeExtension(full);
1876 string ext = getExtension(full);
1877 if (!base.empty() && base[base.length()-1] == '"')
1880 return addExtension(trim(base, "\""), ext);
1881 if (full[full.length()-1] == '"')
1884 return trim(full, "\"");
1890 /// Convert \p name from TeX convention (relative to master file) to LyX
1891 /// convention (relative to .lyx file) if it is relative
1892 void fix_child_filename(string & name)
1894 string const absMasterTeX = getMasterFilePath(true);
1895 bool const isabs = FileName::isAbsolute(name);
1896 // convert from "relative to .tex master" to absolute original path
1898 name = makeAbsPath(name, absMasterTeX).absFileName();
1899 bool copyfile = copyFiles();
1900 string const absParentLyX = getParentFilePath(false);
1903 // convert from absolute original path to "relative to master file"
1904 string const rel = to_utf8(makeRelPath(from_utf8(name),
1905 from_utf8(absMasterTeX)));
1906 // re-interpret "relative to .tex file" as "relative to .lyx file"
1907 // (is different if the master .lyx file resides in a
1908 // different path than the master .tex file)
1909 string const absMasterLyX = getMasterFilePath(false);
1910 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1911 // Do not copy if the new path is impossible to create. Example:
1912 // absMasterTeX = "/foo/bar/"
1913 // absMasterLyX = "/bar/"
1914 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1915 if (contains(name, "/../"))
1922 // convert from absolute original path to
1923 // "relative to .lyx file"
1924 name = to_utf8(makeRelPath(from_utf8(abs),
1925 from_utf8(absParentLyX)));
1929 // convert from absolute original path to "relative to .lyx file"
1930 name = to_utf8(makeRelPath(from_utf8(name),
1931 from_utf8(absParentLyX)));
1936 void copy_file(FileName const & src, string dstname)
1940 string const absParent = getParentFilePath(false);
1942 if (FileName::isAbsolute(dstname))
1943 dst = FileName(dstname);
1945 dst = makeAbsPath(dstname, absParent);
1946 string const absMaster = getMasterFilePath(false);
1947 FileName const srcpath = src.onlyPath();
1948 FileName const dstpath = dst.onlyPath();
1949 if (equivalent(srcpath, dstpath))
1951 if (!dstpath.isDirectory()) {
1952 if (!dstpath.createPath()) {
1953 cerr << "Warning: Could not create directory for file `"
1954 << dst.absFileName() << "´." << endl;
1958 if (dst.isReadableFile()) {
1959 if (overwriteFiles())
1960 cerr << "Warning: Overwriting existing file `"
1961 << dst.absFileName() << "´." << endl;
1963 cerr << "Warning: Not overwriting existing file `"
1964 << dst.absFileName() << "´." << endl;
1968 if (!src.copyTo(dst))
1969 cerr << "Warning: Could not copy file `" << src.absFileName()
1970 << "´ to `" << dst.absFileName() << "´." << endl;
1974 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1975 void parse_noweb(Parser & p, ostream & os, Context & context)
1977 // assemble the rest of the keyword
1981 Token const & t = p.get_token();
1982 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1985 chunk = (p.good() && p.next_token().asInput() == "=");
1987 name += p.get_token().asInput();
1990 name += t.asInput();
1993 if (!chunk || !context.new_layout_allowed ||
1994 !context.textclass.hasLayout(from_ascii("Chunk"))) {
1995 cerr << "Warning: Could not interpret '" << name
1996 << "'. Ignoring it." << endl;
2000 // We use new_paragraph instead of check_end_layout because the stuff
2001 // following the noweb chunk needs to start with a \begin_layout.
2002 // This may create a new paragraph even if there was none in the
2003 // noweb file, but the alternative is an invalid LyX file. Since
2004 // noweb code chunks are implemented with a layout style in LyX they
2005 // always must be in an own paragraph.
2006 context.new_paragraph(os);
2007 Context newcontext(true, context.textclass,
2008 &context.textclass[from_ascii("Chunk")]);
2009 newcontext.check_layout(os);
2012 Token const & t = p.get_token();
2013 // We abuse the parser a bit, because this is no TeX syntax
2015 if (t.cat() == catEscape)
2016 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2019 Context tmp(false, context.textclass,
2020 &context.textclass[from_ascii("Chunk")]);
2021 tmp.need_end_layout = true;
2022 tmp.check_layout(oss);
2023 os << subst(t.asInput(), "\n", oss.str());
2025 // The chunk is ended by an @ at the beginning of a line.
2026 // After the @ the line may contain a comment and/or
2027 // whitespace, but nothing else.
2028 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2029 (p.next_token().cat() == catSpace ||
2030 p.next_token().cat() == catNewline ||
2031 p.next_token().cat() == catComment)) {
2032 while (p.good() && p.next_token().cat() == catSpace)
2033 os << p.get_token().asInput();
2034 if (p.next_token().cat() == catComment)
2035 // The comment includes a final '\n'
2036 os << p.get_token().asInput();
2038 if (p.next_token().cat() == catNewline)
2045 newcontext.check_end_layout(os);
2049 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2050 bool is_macro(Parser & p)
2052 Token first = p.curr_token();
2053 if (first.cat() != catEscape || !p.good())
2055 if (first.cs() == "def")
2057 if (first.cs() != "global" && first.cs() != "long")
2059 Token second = p.get_token();
2061 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2062 second.cat() == catNewline || second.cat() == catComment)) {
2063 second = p.get_token();
2066 bool secondvalid = second.cat() == catEscape;
2068 bool thirdvalid = false;
2069 if (p.good() && first.cs() == "global" && secondvalid &&
2070 second.cs() == "long") {
2071 third = p.get_token();
2073 while (p.good() && !p.isParagraph() &&
2074 (third.cat() == catSpace ||
2075 third.cat() == catNewline ||
2076 third.cat() == catComment)) {
2077 third = p.get_token();
2080 thirdvalid = third.cat() == catEscape;
2082 for (int i = 0; i < pos; ++i)
2087 return (first.cs() == "global" || first.cs() == "long") &&
2088 second.cs() == "def";
2089 return first.cs() == "global" && second.cs() == "long" &&
2090 third.cs() == "def";
2094 /// Parse a macro definition (assumes that is_macro() returned true)
2095 void parse_macro(Parser & p, ostream & os, Context & context)
2097 context.check_layout(os);
2098 Token first = p.curr_token();
2101 string command = first.asInput();
2102 if (first.cs() != "def") {
2104 eat_whitespace(p, os, context, false);
2105 second = p.curr_token();
2106 command += second.asInput();
2107 if (second.cs() != "def") {
2109 eat_whitespace(p, os, context, false);
2110 third = p.curr_token();
2111 command += third.asInput();
2114 eat_whitespace(p, os, context, false);
2115 string const name = p.get_token().cs();
2116 eat_whitespace(p, os, context, false);
2122 while (p.next_token().cat() != catBegin) {
2123 if (p.next_token().cat() == catParameter) {
2128 // followed by number?
2129 if (p.next_token().cat() == catOther) {
2130 string s = p.get_token().asInput();
2132 // number = current arity + 1?
2133 if (s.size() == 1 && s[0] == arity + '0' + 1)
2138 paramtext += p.get_token().cs();
2140 paramtext += p.get_token().cs();
2145 // only output simple (i.e. compatible) macro as FormulaMacros
2146 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2148 context.check_layout(os);
2149 begin_inset(os, "FormulaMacro");
2150 os << "\n\\def" << ert;
2153 output_ert_inset(os, command + ert, context);
2157 void registerExternalTemplatePackages(string const & name)
2159 external::TemplateManager const & etm = external::TemplateManager::get();
2160 external::Template const * const et = etm.getTemplateByName(name);
2163 external::Template::Formats::const_iterator cit = et->formats.end();
2165 cit = et->formats.find("PDFLaTeX");
2166 if (cit == et->formats.end())
2167 // If the template has not specified a PDFLaTeX output,
2168 // we try the LaTeX format.
2169 cit = et->formats.find("LaTeX");
2170 if (cit == et->formats.end())
2172 vector<string>::const_iterator qit = cit->second.requirements.begin();
2173 vector<string>::const_iterator qend = cit->second.requirements.end();
2174 for (; qit != qend; ++qit)
2175 preamble.registerAutomaticallyLoadedPackage(*qit);
2178 } // anonymous namespace
2181 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2184 Layout const * newlayout = 0;
2185 InsetLayout const * newinsetlayout = 0;
2186 char const * const * where = 0;
2187 // Store the latest bibliographystyle, addcontentslineContent and
2188 // nocite{*} option (needed for bibtex inset)
2190 string contentslineContent;
2191 string bibliographystyle = "default";
2192 bool const use_natbib = isProvided("natbib");
2193 bool const use_jurabib = isProvided("jurabib");
2196 Token const & t = p.get_token();
2198 // it is impossible to determine the correct encoding for non-CJK Japanese.
2199 // Therefore write a note at the beginning of the document
2200 if (is_nonCJKJapanese) {
2201 context.check_layout(os);
2202 begin_inset(os, "Note Note\n");
2203 os << "status open\n\\begin_layout Plain Layout\n"
2204 << "\\series bold\n"
2205 << "Important information:\n"
2206 << "\\end_layout\n\n"
2207 << "\\begin_layout Plain Layout\n"
2208 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2209 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2210 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2211 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2212 << " and specify the encoding using the -e command-line switch.\n"
2213 << " In addition, you might want to double check that the desired output encoding\n"
2214 << " is correctly selected in Document > Settings > Language.\n"
2215 << "\\end_layout\n";
2217 is_nonCJKJapanese = false;
2221 debugToken(cerr, t, flags);
2224 if (flags & FLAG_ITEM) {
2225 if (t.cat() == catSpace)
2228 flags &= ~FLAG_ITEM;
2229 if (t.cat() == catBegin) {
2230 // skip the brace and collect everything to the next matching
2232 flags |= FLAG_BRACE_LAST;
2236 // handle only this single token, leave the loop if done
2237 flags |= FLAG_LEAVE;
2240 if (t.cat() != catEscape && t.character() == ']' &&
2241 (flags & FLAG_BRACK_LAST))
2243 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2246 // If there is anything between \end{env} and \begin{env} we
2247 // don't need to output a separator.
2248 if (t.cat() != catSpace && t.cat() != catNewline &&
2249 t.asInput() != "\\begin")
2255 if (t.cat() == catMath) {
2256 // we are inside some text mode thingy, so opening new math is allowed
2257 context.check_layout(os);
2258 begin_inset(os, "Formula ");
2259 Token const & n = p.get_token();
2260 bool const display(n.cat() == catMath && outer);
2262 // TeX's $$...$$ syntax for displayed math
2264 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2266 p.get_token(); // skip the second '$' token
2268 // simple $...$ stuff
2271 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2276 // Prevent the conversion of a line break to a
2277 // space (bug 7668). This does not change the
2278 // output, but looks ugly in LyX.
2279 eat_whitespace(p, os, context, false);
2283 else if (t.cat() == catSuper || t.cat() == catSub)
2284 cerr << "catcode " << t << " illegal in text mode\n";
2286 // Basic support for english quotes. This should be
2287 // extended to other quotes, but is not so easy (a
2288 // left english quote is the same as a right german
2290 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2291 context.check_layout(os);
2292 begin_inset(os, "Quotes ");
2298 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2299 context.check_layout(os);
2300 begin_inset(os, "Quotes ");
2307 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2308 context.check_layout(os);
2309 begin_inset(os, "Quotes ");
2316 else if (t.asInput() == "<"
2317 && p.next_token().asInput() == "<" && noweb_mode) {
2319 parse_noweb(p, os, context);
2322 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2323 context.check_layout(os);
2324 begin_inset(os, "Quotes ");
2331 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2332 check_space(p, os, context);
2334 else if (t.character() == '[' && noweb_mode &&
2335 p.next_token().character() == '[') {
2336 // These can contain underscores
2338 string const s = p.getFullOpt() + ']';
2339 if (p.next_token().character() == ']')
2342 cerr << "Warning: Inserting missing ']' in '"
2343 << s << "'." << endl;
2344 output_ert_inset(os, s, context);
2347 else if (t.cat() == catLetter) {
2348 context.check_layout(os);
2349 // Workaround for bug 4752.
2350 // FIXME: This whole code block needs to be removed
2351 // when the bug is fixed and tex2lyx produces
2352 // the updated file format.
2353 // The replacement algorithm in LyX is so stupid that
2354 // it even translates a phrase if it is part of a word.
2355 bool handled = false;
2356 for (int const * l = known_phrase_lengths; *l; ++l) {
2357 string phrase = t.cs();
2358 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2359 phrase += p.get_token().cs();
2360 if (is_known(phrase, known_coded_phrases)) {
2361 output_ert_inset(os, phrase, context);
2365 for (size_t i = 1; i < phrase.length(); ++i)
2373 else if (t.cat() == catOther ||
2374 t.cat() == catAlign ||
2375 t.cat() == catParameter) {
2376 // This translates "&" to "\\&" which may be wrong...
2377 context.check_layout(os);
2381 else if (p.isParagraph()) {
2382 if (context.new_layout_allowed)
2383 context.new_paragraph(os);
2385 output_ert_inset(os, "\\par ", context);
2386 eat_whitespace(p, os, context, true);
2389 else if (t.cat() == catActive) {
2390 context.check_layout(os);
2391 if (t.character() == '~') {
2392 if (context.layout->free_spacing)
2395 begin_inset(os, "space ~\n");
2402 else if (t.cat() == catBegin) {
2403 Token const next = p.next_token();
2404 Token const end = p.next_next_token();
2405 if (next.cat() == catEnd) {
2407 Token const prev = p.prev_token();
2409 if (p.next_token().character() == '`' ||
2410 (prev.character() == '-' &&
2411 p.next_token().character() == '-'))
2412 ; // ignore it in {}`` or -{}-
2414 output_ert_inset(os, "{}", context);
2415 } else if (next.cat() == catEscape &&
2416 is_known(next.cs(), known_quotes) &&
2417 end.cat() == catEnd) {
2418 // Something like {\textquoteright} (e.g.
2419 // from writer2latex). LyX writes
2420 // \textquoteright{}, so we may skip the
2421 // braces here for better readability.
2422 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2425 context.check_layout(os);
2426 // special handling of font attribute changes
2427 Token const prev = p.prev_token();
2428 TeXFont const oldFont = context.font;
2429 if (next.character() == '[' ||
2430 next.character() == ']' ||
2431 next.character() == '*') {
2433 if (p.next_token().cat() == catEnd) {
2438 output_ert_inset(os, "{", context);
2439 parse_text_snippet(p, os,
2442 output_ert_inset(os, "}", context);
2444 } else if (! context.new_layout_allowed) {
2445 output_ert_inset(os, "{", context);
2446 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2448 output_ert_inset(os, "}", context);
2449 } else if (is_known(next.cs(), known_sizes)) {
2450 // next will change the size, so we must
2452 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2454 if (!context.atParagraphStart())
2456 << context.font.size << "\n";
2457 } else if (is_known(next.cs(), known_font_families)) {
2458 // next will change the font family, so we
2459 // must reset it here
2460 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2462 if (!context.atParagraphStart())
2464 << context.font.family << "\n";
2465 } else if (is_known(next.cs(), known_font_series)) {
2466 // next will change the font series, so we
2467 // must reset it here
2468 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2470 if (!context.atParagraphStart())
2472 << context.font.series << "\n";
2473 } else if (is_known(next.cs(), known_font_shapes)) {
2474 // next will change the font shape, so we
2475 // must reset it here
2476 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2478 if (!context.atParagraphStart())
2480 << context.font.shape << "\n";
2481 } else if (is_known(next.cs(), known_old_font_families) ||
2482 is_known(next.cs(), known_old_font_series) ||
2483 is_known(next.cs(), known_old_font_shapes)) {
2484 // next will change the font family, series
2485 // and shape, so we must reset it here
2486 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2488 if (!context.atParagraphStart())
2490 << context.font.family
2492 << context.font.series
2494 << context.font.shape << "\n";
2496 output_ert_inset(os, "{", context);
2497 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2499 output_ert_inset(os, "}", context);
2504 else if (t.cat() == catEnd) {
2505 if (flags & FLAG_BRACE_LAST) {
2508 cerr << "stray '}' in text\n";
2509 output_ert_inset(os, "}", context);
2512 else if (t.cat() == catComment)
2513 parse_comment(p, os, t, context);
2516 // control sequences
2519 else if (t.cs() == "(") {
2520 context.check_layout(os);
2521 begin_inset(os, "Formula");
2523 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2528 else if (t.cs() == "[") {
2529 context.check_layout(os);
2530 begin_inset(os, "Formula");
2532 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2535 // Prevent the conversion of a line break to a space
2536 // (bug 7668). This does not change the output, but
2537 // looks ugly in LyX.
2538 eat_whitespace(p, os, context, false);
2541 else if (t.cs() == "begin")
2542 parse_environment(p, os, outer, last_env,
2545 else if (t.cs() == "end") {
2546 if (flags & FLAG_END) {
2547 // eat environment name
2548 string const name = p.getArg('{', '}');
2549 if (name != active_environment())
2550 cerr << "\\end{" + name + "} does not match \\begin{"
2551 + active_environment() + "}\n";
2554 p.error("found 'end' unexpectedly");
2557 else if (t.cs() == "item") {
2559 bool const optarg = p.hasOpt();
2561 // FIXME: This swallows comments, but we cannot use
2562 // eat_whitespace() since we must not output
2563 // anything before the item.
2564 p.skip_spaces(true);
2565 s = p.verbatimOption();
2567 p.skip_spaces(false);
2569 context.check_layout(os);
2570 if (context.has_item) {
2571 // An item in an unknown list-like environment
2572 // FIXME: Do this in check_layout()!
2573 context.has_item = false;
2575 output_ert_inset(os, "\\item", context);
2577 output_ert_inset(os, "\\item ", context);
2580 if (context.layout->labeltype != LABEL_MANUAL) {
2581 // LyX does not support \item[\mybullet]
2582 // in itemize environments
2584 os << parse_text_snippet(p2,
2585 FLAG_BRACK_LAST, outer, context);
2586 } else if (!s.empty()) {
2587 // LyX adds braces around the argument,
2588 // so we need to remove them here.
2589 if (s.size() > 2 && s[0] == '{' &&
2590 s[s.size()-1] == '}')
2591 s = s.substr(1, s.size()-2);
2592 // If the argument contains a space we
2593 // must put it into ERT: Otherwise LyX
2594 // would misinterpret the space as
2595 // item delimiter (bug 7663)
2596 if (contains(s, ' ')) {
2597 output_ert_inset(os, s, context);
2600 os << parse_text_snippet(p2,
2604 // The space is needed to separate the
2605 // item from the rest of the sentence.
2607 eat_whitespace(p, os, context, false);
2612 else if (t.cs() == "bibitem") {
2614 context.check_layout(os);
2615 eat_whitespace(p, os, context, false);
2616 string label = convert_command_inset_arg(p.verbatimOption());
2617 string key = convert_command_inset_arg(p.verbatim_item());
2618 if (contains(label, '\\') || contains(key, '\\')) {
2619 // LyX can't handle LaTeX commands in labels or keys
2620 output_ert_inset(os, t.asInput() + '[' + label +
2621 "]{" + p.verbatim_item() + '}',
2624 begin_command_inset(os, "bibitem", "bibitem");
2625 os << "label \"" << label << "\"\n"
2626 "key \"" << key << "\"\n";
2631 else if (is_macro(p)) {
2632 // catch the case of \def\inputGnumericTable
2634 if (t.cs() == "def") {
2635 Token second = p.next_token();
2636 if (second.cs() == "inputGnumericTable") {
2640 Token third = p.get_token();
2642 if (third.cs() == "input") {
2646 string name = normalize_filename(p.verbatim_item());
2647 string const path = getMasterFilePath(true);
2648 // We want to preserve relative / absolute filenames,
2649 // therefore path is only used for testing
2650 // The file extension is in every case ".tex".
2651 // So we need to remove this extension and check for
2652 // the original one.
2653 name = removeExtension(name);
2654 if (!makeAbsPath(name, path).exists()) {
2655 char const * const Gnumeric_formats[] = {"gnumeric",
2657 string const Gnumeric_name =
2658 find_file(name, path, Gnumeric_formats);
2659 if (!Gnumeric_name.empty())
2660 name = Gnumeric_name;
2662 FileName const absname = makeAbsPath(name, path);
2663 if (absname.exists()) {
2664 fix_child_filename(name);
2665 copy_file(absname, name);
2667 cerr << "Warning: Could not find file '"
2668 << name << "'." << endl;
2669 context.check_layout(os);
2670 begin_inset(os, "External\n\ttemplate ");
2671 os << "GnumericSpreadsheet\n\tfilename "
2674 context.check_layout(os);
2676 // register the packages that are automatically loaded
2677 // by the Gnumeric template
2678 registerExternalTemplatePackages("GnumericSpreadsheet");
2683 parse_macro(p, os, context);
2686 else if (t.cs() == "noindent") {
2688 context.add_par_extra_stuff("\\noindent\n");
2691 else if (t.cs() == "appendix") {
2692 context.add_par_extra_stuff("\\start_of_appendix\n");
2693 // We need to start a new paragraph. Otherwise the
2694 // appendix in 'bla\appendix\chapter{' would start
2696 context.new_paragraph(os);
2697 // We need to make sure that the paragraph is
2698 // generated even if it is empty. Otherwise the
2699 // appendix in '\par\appendix\par\chapter{' would
2701 context.check_layout(os);
2702 // FIXME: This is a hack to prevent paragraph
2703 // deletion if it is empty. Handle this better!
2704 output_ert_inset(os,
2705 "%dummy comment inserted by tex2lyx to "
2706 "ensure that this paragraph is not empty",
2708 // Both measures above may generate an additional
2709 // empty paragraph, but that does not hurt, because
2710 // whitespace does not matter here.
2711 eat_whitespace(p, os, context, true);
2714 // Must catch empty dates before findLayout is called below
2715 else if (t.cs() == "date") {
2716 eat_whitespace(p, os, context, false);
2718 string const date = p.verbatim_item();
2721 preamble.suppressDate(true);
2724 preamble.suppressDate(false);
2725 if (context.new_layout_allowed &&
2726 (newlayout = findLayout(context.textclass,
2729 output_command_layout(os, p, outer,
2730 context, newlayout);
2731 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2732 if (!preamble.titleLayoutFound())
2733 preamble.titleLayoutFound(newlayout->intitle);
2734 set<string> const & req = newlayout->requires();
2735 set<string>::const_iterator it = req.begin();
2736 set<string>::const_iterator en = req.end();
2737 for (; it != en; ++it)
2738 preamble.registerAutomaticallyLoadedPackage(*it);
2740 output_ert_inset(os,
2741 "\\date{" + p.verbatim_item() + '}',
2746 // Starred section headings
2747 // Must attempt to parse "Section*" before "Section".
2748 else if ((p.next_token().asInput() == "*") &&
2749 context.new_layout_allowed &&
2750 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2753 output_command_layout(os, p, outer, context, newlayout);
2755 if (!preamble.titleLayoutFound())
2756 preamble.titleLayoutFound(newlayout->intitle);
2757 set<string> const & req = newlayout->requires();
2758 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2759 preamble.registerAutomaticallyLoadedPackage(*it);
2762 // Section headings and the like
2763 else if (context.new_layout_allowed &&
2764 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2766 output_command_layout(os, p, outer, context, newlayout);
2768 if (!preamble.titleLayoutFound())
2769 preamble.titleLayoutFound(newlayout->intitle);
2770 set<string> const & req = newlayout->requires();
2771 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2772 preamble.registerAutomaticallyLoadedPackage(*it);
2775 else if (t.cs() == "caption") {
2777 context.check_layout(os);
2779 begin_inset(os, "Caption Standard\n");
2780 Context newcontext(true, context.textclass, 0, 0, context.font);
2781 newcontext.check_layout(os);
2782 // FIXME InsetArgument is now properly implemented in InsetLayout
2783 // (for captions, but also for others)
2784 if (p.next_token().cat() != catEscape &&
2785 p.next_token().character() == '[') {
2786 p.get_token(); // eat '['
2787 begin_inset(os, "Argument 1\n");
2788 os << "status collapsed\n";
2789 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2791 eat_whitespace(p, os, context, false);
2793 parse_text(p, os, FLAG_ITEM, outer, context);
2794 context.check_end_layout(os);
2795 // We don't need really a new paragraph, but
2796 // we must make sure that the next item gets a \begin_layout.
2797 context.new_paragraph(os);
2800 newcontext.check_end_layout(os);
2803 else if (t.cs() == "subfloat") {
2804 // the syntax is \subfloat[caption]{content}
2805 // if it is a table of figure depends on the surrounding float
2806 bool has_caption = false;
2808 // do nothing if there is no outer float
2809 if (!float_type.empty()) {
2810 context.check_layout(os);
2812 begin_inset(os, "Float " + float_type + "\n");
2814 << "\nsideways false"
2815 << "\nstatus collapsed\n\n";
2818 if (p.next_token().cat() != catEscape &&
2819 p.next_token().character() == '[') {
2820 p.get_token(); // eat '['
2821 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2825 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2826 // the caption comes always as the last
2828 // we must make sure that the caption gets a \begin_layout
2829 os << "\n\\begin_layout Plain Layout";
2831 begin_inset(os, "Caption Standard\n");
2832 Context newcontext(true, context.textclass,
2833 0, 0, context.font);
2834 newcontext.check_layout(os);
2835 os << caption << "\n";
2836 newcontext.check_end_layout(os);
2837 // We don't need really a new paragraph, but
2838 // we must make sure that the next item gets a \begin_layout.
2839 //newcontext.new_paragraph(os);
2843 // We don't need really a new paragraph, but
2844 // we must make sure that the next item gets a \begin_layout.
2846 context.new_paragraph(os);
2849 context.check_end_layout(os);
2850 // close the layout we opened
2852 os << "\n\\end_layout\n";
2854 // if the float type is not supported or there is no surrounding float
2857 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2858 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2859 "]{" + p.verbatim_item() + '}', context);
2861 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2865 else if (t.cs() == "includegraphics") {
2866 bool const clip = p.next_token().asInput() == "*";
2869 string const arg = p.getArg('[', ']');
2870 map<string, string> opts;
2871 vector<string> keys;
2872 split_map(arg, opts, keys);
2874 opts["clip"] = string();
2875 string name = normalize_filename(p.verbatim_item());
2877 string const path = getMasterFilePath(true);
2878 // We want to preserve relative / absolute filenames,
2879 // therefore path is only used for testing
2880 if (!makeAbsPath(name, path).exists()) {
2881 // The file extension is probably missing.
2882 // Now try to find it out.
2883 string const dvips_name =
2884 find_file(name, path,
2885 known_dvips_graphics_formats);
2886 string const pdftex_name =
2887 find_file(name, path,
2888 known_pdftex_graphics_formats);
2889 if (!dvips_name.empty()) {
2890 if (!pdftex_name.empty()) {
2891 cerr << "This file contains the "
2893 "\"\\includegraphics{"
2895 "However, files\n\""
2896 << dvips_name << "\" and\n\""
2897 << pdftex_name << "\"\n"
2898 "both exist, so I had to make a "
2899 "choice and took the first one.\n"
2900 "Please move the unwanted one "
2901 "someplace else and try again\n"
2902 "if my choice was wrong."
2906 } else if (!pdftex_name.empty()) {
2912 FileName const absname = makeAbsPath(name, path);
2913 if (absname.exists()) {
2914 fix_child_filename(name);
2915 copy_file(absname, name);
2917 cerr << "Warning: Could not find graphics file '"
2918 << name << "'." << endl;
2920 context.check_layout(os);
2921 begin_inset(os, "Graphics ");
2922 os << "\n\tfilename " << name << '\n';
2923 if (opts.find("width") != opts.end())
2925 << translate_len(opts["width"]) << '\n';
2926 if (opts.find("height") != opts.end())
2928 << translate_len(opts["height"]) << '\n';
2929 if (opts.find("scale") != opts.end()) {
2930 istringstream iss(opts["scale"]);
2934 os << "\tscale " << val << '\n';
2936 if (opts.find("angle") != opts.end()) {
2937 os << "\trotateAngle "
2938 << opts["angle"] << '\n';
2939 vector<string>::const_iterator a =
2940 find(keys.begin(), keys.end(), "angle");
2941 vector<string>::const_iterator s =
2942 find(keys.begin(), keys.end(), "width");
2943 if (s == keys.end())
2944 s = find(keys.begin(), keys.end(), "height");
2945 if (s == keys.end())
2946 s = find(keys.begin(), keys.end(), "scale");
2947 if (s != keys.end() && distance(s, a) > 0)
2948 os << "\tscaleBeforeRotation\n";
2950 if (opts.find("origin") != opts.end()) {
2952 string const opt = opts["origin"];
2953 if (opt.find('l') != string::npos) ss << "left";
2954 if (opt.find('r') != string::npos) ss << "right";
2955 if (opt.find('c') != string::npos) ss << "center";
2956 if (opt.find('t') != string::npos) ss << "Top";
2957 if (opt.find('b') != string::npos) ss << "Bottom";
2958 if (opt.find('B') != string::npos) ss << "Baseline";
2959 if (!ss.str().empty())
2960 os << "\trotateOrigin " << ss.str() << '\n';
2962 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2964 if (opts.find("keepaspectratio") != opts.end())
2965 os << "\tkeepAspectRatio\n";
2966 if (opts.find("clip") != opts.end())
2968 if (opts.find("draft") != opts.end())
2970 if (opts.find("bb") != opts.end())
2971 os << "\tBoundingBox "
2972 << opts["bb"] << '\n';
2973 int numberOfbbOptions = 0;
2974 if (opts.find("bbllx") != opts.end())
2975 numberOfbbOptions++;
2976 if (opts.find("bblly") != opts.end())
2977 numberOfbbOptions++;
2978 if (opts.find("bburx") != opts.end())
2979 numberOfbbOptions++;
2980 if (opts.find("bbury") != opts.end())
2981 numberOfbbOptions++;
2982 if (numberOfbbOptions == 4)
2983 os << "\tBoundingBox "
2984 << opts["bbllx"] << " " << opts["bblly"] << " "
2985 << opts["bburx"] << " " << opts["bbury"] << '\n';
2986 else if (numberOfbbOptions > 0)
2987 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2988 numberOfbbOptions = 0;
2989 if (opts.find("natwidth") != opts.end())
2990 numberOfbbOptions++;
2991 if (opts.find("natheight") != opts.end())
2992 numberOfbbOptions++;
2993 if (numberOfbbOptions == 2)
2994 os << "\tBoundingBox 0bp 0bp "
2995 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2996 else if (numberOfbbOptions > 0)
2997 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2998 ostringstream special;
2999 if (opts.find("hiresbb") != opts.end())
3000 special << "hiresbb,";
3001 if (opts.find("trim") != opts.end())
3003 if (opts.find("viewport") != opts.end())
3004 special << "viewport=" << opts["viewport"] << ',';
3005 if (opts.find("totalheight") != opts.end())
3006 special << "totalheight=" << opts["totalheight"] << ',';
3007 if (opts.find("type") != opts.end())
3008 special << "type=" << opts["type"] << ',';
3009 if (opts.find("ext") != opts.end())
3010 special << "ext=" << opts["ext"] << ',';
3011 if (opts.find("read") != opts.end())
3012 special << "read=" << opts["read"] << ',';
3013 if (opts.find("command") != opts.end())
3014 special << "command=" << opts["command"] << ',';
3015 string s_special = special.str();
3016 if (!s_special.empty()) {
3017 // We had special arguments. Remove the trailing ','.
3018 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3020 // TODO: Handle the unknown settings better.
3021 // Warn about invalid options.
3022 // Check whether some option was given twice.
3024 preamble.registerAutomaticallyLoadedPackage("graphicx");
3027 else if (t.cs() == "footnote" ||
3028 (t.cs() == "thanks" && context.layout->intitle)) {
3030 context.check_layout(os);
3031 begin_inset(os, "Foot\n");
3032 os << "status collapsed\n\n";
3033 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3037 else if (t.cs() == "marginpar") {
3039 context.check_layout(os);
3040 begin_inset(os, "Marginal\n");
3041 os << "status collapsed\n\n";
3042 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3046 else if (t.cs() == "lstinline") {
3048 parse_listings(p, os, context, true);
3051 else if (t.cs() == "ensuremath") {
3053 context.check_layout(os);
3054 string const s = p.verbatim_item();
3055 //FIXME: this never triggers in UTF8
3056 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3059 output_ert_inset(os, "\\ensuremath{" + s + "}",
3063 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3064 if (preamble.titleLayoutFound()) {
3066 skip_spaces_braces(p);
3068 output_ert_inset(os, t.asInput(), context);
3071 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3072 context.check_layout(os);
3073 begin_command_inset(os, "toc", t.cs());
3075 skip_spaces_braces(p);
3076 if (t.cs() == "lstlistoflistings")
3077 preamble.registerAutomaticallyLoadedPackage("listings");
3080 else if (t.cs() == "listoffigures") {
3081 context.check_layout(os);
3082 begin_inset(os, "FloatList figure\n");
3084 skip_spaces_braces(p);
3087 else if (t.cs() == "listoftables") {
3088 context.check_layout(os);
3089 begin_inset(os, "FloatList table\n");
3091 skip_spaces_braces(p);
3094 else if (t.cs() == "listof") {
3095 p.skip_spaces(true);
3096 string const name = p.get_token().cs();
3097 if (context.textclass.floats().typeExist(name)) {
3098 context.check_layout(os);
3099 begin_inset(os, "FloatList ");
3102 p.get_token(); // swallow second arg
3104 output_ert_inset(os, "\\listof{" + name + "}", context);
3107 else if ((where = is_known(t.cs(), known_text_font_families)))
3108 parse_text_attributes(p, os, FLAG_ITEM, outer,
3109 context, "\\family", context.font.family,
3110 known_coded_font_families[where - known_text_font_families]);
3112 else if ((where = is_known(t.cs(), known_text_font_series)))
3113 parse_text_attributes(p, os, FLAG_ITEM, outer,
3114 context, "\\series", context.font.series,
3115 known_coded_font_series[where - known_text_font_series]);
3117 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3118 parse_text_attributes(p, os, FLAG_ITEM, outer,
3119 context, "\\shape", context.font.shape,
3120 known_coded_font_shapes[where - known_text_font_shapes]);
3122 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3123 context.check_layout(os);
3124 TeXFont oldFont = context.font;
3125 context.font.init();
3126 context.font.size = oldFont.size;
3127 os << "\n\\family " << context.font.family << "\n";
3128 os << "\n\\series " << context.font.series << "\n";
3129 os << "\n\\shape " << context.font.shape << "\n";
3130 if (t.cs() == "textnormal") {
3131 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3132 output_font_change(os, context.font, oldFont);
3133 context.font = oldFont;
3135 eat_whitespace(p, os, context, false);
3138 else if (t.cs() == "textcolor") {
3139 // scheme is \textcolor{color name}{text}
3140 string const color = p.verbatim_item();
3141 // we only support the predefined colors of the color package
3142 if (color == "black" || color == "blue" || color == "cyan"
3143 || color == "green" || color == "magenta" || color == "red"
3144 || color == "white" || color == "yellow") {
3145 context.check_layout(os);
3146 os << "\n\\color " << color << "\n";
3147 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3148 context.check_layout(os);
3149 os << "\n\\color inherit\n";
3150 preamble.registerAutomaticallyLoadedPackage("color");
3152 // for custom defined colors
3153 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3156 else if (t.cs() == "underbar" || t.cs() == "uline") {
3157 // \underbar is not 100% correct (LyX outputs \uline
3158 // of ulem.sty). The difference is that \ulem allows
3159 // line breaks, and \underbar does not.
3160 // Do NOT handle \underline.
3161 // \underbar cuts through y, g, q, p etc.,
3162 // \underline does not.
3163 context.check_layout(os);
3164 os << "\n\\bar under\n";
3165 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3166 context.check_layout(os);
3167 os << "\n\\bar default\n";
3168 preamble.registerAutomaticallyLoadedPackage("ulem");
3171 else if (t.cs() == "sout") {
3172 context.check_layout(os);
3173 os << "\n\\strikeout on\n";
3174 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3175 context.check_layout(os);
3176 os << "\n\\strikeout default\n";
3177 preamble.registerAutomaticallyLoadedPackage("ulem");
3180 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3181 t.cs() == "emph" || t.cs() == "noun") {
3182 context.check_layout(os);
3183 os << "\n\\" << t.cs() << " on\n";
3184 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3185 context.check_layout(os);
3186 os << "\n\\" << t.cs() << " default\n";
3187 if (t.cs() == "uuline" || t.cs() == "uwave")
3188 preamble.registerAutomaticallyLoadedPackage("ulem");
3191 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3192 context.check_layout(os);
3193 string name = p.getArg('{', '}');
3194 string localtime = p.getArg('{', '}');
3195 preamble.registerAuthor(name);
3196 Author const & author = preamble.getAuthor(name);
3197 // from_asctime_utc() will fail if LyX decides to output the
3198 // time in the text language.
3199 time_t ptime = from_asctime_utc(localtime);
3200 if (ptime == static_cast<time_t>(-1)) {
3201 cerr << "Warning: Could not parse time `" << localtime
3202 << "´ for change tracking, using current time instead.\n";
3203 ptime = current_time();
3205 if (t.cs() == "lyxadded")
3206 os << "\n\\change_inserted ";
3208 os << "\n\\change_deleted ";
3209 os << author.bufferId() << ' ' << ptime << '\n';
3210 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3211 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3212 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3213 LaTeXPackages::isAvailable("xcolor");
3214 // No need to test for luatex, since luatex comes in
3215 // two flavours (dvi and pdf), like latex, and those
3216 // are detected by pdflatex.
3217 if (pdflatex || xetex) {
3219 preamble.registerAutomaticallyLoadedPackage("ulem");
3220 preamble.registerAutomaticallyLoadedPackage("xcolor");
3221 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3225 preamble.registerAutomaticallyLoadedPackage("dvipost");
3226 } else if (xcolorulem) {
3227 preamble.registerAutomaticallyLoadedPackage("ulem");
3228 preamble.registerAutomaticallyLoadedPackage("xcolor");
3233 else if (t.cs() == "textipa") {
3234 context.check_layout(os);
3235 begin_inset(os, "IPA\n");
3236 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3238 preamble.registerAutomaticallyLoadedPackage("tipa");
3239 preamble.registerAutomaticallyLoadedPackage("tipx");
3242 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3243 context.check_layout(os);
3244 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3245 os << "status open\n";
3246 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3251 // the TIPA Combining diacritical marks
3252 else if (is_known(t.cs(), known_tipa_marks)) {
3253 context.check_layout(os);
3254 // try to see whether the string is in unicodesymbols
3257 string content = trimSpaceAndEol(p.verbatim_item());
3258 string command = t.asInput() + "{" + content + "}";
3260 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3261 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3262 termination, rem, &req);
3265 cerr << "When parsing " << command
3266 << ", result is " << to_utf8(s)
3267 << "+" << to_utf8(rem) << endl;
3268 os << content << to_utf8(s);
3269 // tipa is already registered because of the surrounding IPA environment
3270 // or \textipa but it does not harm to register it again if necessary
3271 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3272 preamble.registerAutomaticallyLoadedPackage(*it);
3274 // we did not find a non-ert version
3275 output_ert_inset(os, command, context);
3278 else if (t.cs() == "tone" ) {
3279 context.check_layout(os);
3280 // try to see whether the string is in unicodesymbols
3281 string content = trimSpaceAndEol(p.verbatim_item());
3282 string command = t.asInput() + "{" + content + "}";
3283 // some tones can be detected by unicodesymbols, some need special code
3284 if (is_known(content, known_tones)) {
3285 os << "\\IPAChar " << command << "\n";
3291 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3292 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3293 termination, rem, &req);
3296 cerr << "When parsing " << command
3297 << ", result is " << to_utf8(s)
3298 << "+" << to_utf8(rem) << endl;
3300 // thiw will register the package "tone"
3301 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3302 preamble.registerAutomaticallyLoadedPackage(*it);
3304 // we did not find a non-ert version
3305 output_ert_inset(os, command, context);
3308 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3309 t.cs() == "vphantom") {
3310 context.check_layout(os);
3311 if (t.cs() == "phantom")
3312 begin_inset(os, "Phantom Phantom\n");
3313 if (t.cs() == "hphantom")
3314 begin_inset(os, "Phantom HPhantom\n");
3315 if (t.cs() == "vphantom")
3316 begin_inset(os, "Phantom VPhantom\n");
3317 os << "status open\n";
3318 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3323 else if (t.cs() == "href") {
3324 context.check_layout(os);
3325 string target = convert_command_inset_arg(p.verbatim_item());
3326 string name = convert_command_inset_arg(p.verbatim_item());
3328 size_t i = target.find(':');
3329 if (i != string::npos) {
3330 type = target.substr(0, i + 1);
3331 if (type == "mailto:" || type == "file:")
3332 target = target.substr(i + 1);
3333 // handle the case that name is equal to target, except of "http://"
3334 else if (target.substr(i + 3) == name && type == "http:")
3337 begin_command_inset(os, "href", "href");
3339 os << "name \"" << name << "\"\n";
3340 os << "target \"" << target << "\"\n";
3341 if (type == "mailto:" || type == "file:")
3342 os << "type \"" << type << "\"\n";
3344 skip_spaces_braces(p);
3347 else if (t.cs() == "lyxline") {
3348 // swallow size argument (it is not used anyway)
3350 if (!context.atParagraphStart()) {
3351 // so our line is in the middle of a paragraph
3352 // we need to add a new line, lest this line
3353 // follow the other content on that line and
3354 // run off the side of the page
3355 // FIXME: This may create an empty paragraph,
3356 // but without that it would not be
3357 // possible to set noindent below.
3358 // Fortunately LaTeX does not care
3359 // about the empty paragraph.
3360 context.new_paragraph(os);
3362 if (preamble.indentParagraphs()) {
3363 // we need to unindent, lest the line be too long
3364 context.add_par_extra_stuff("\\noindent\n");
3366 context.check_layout(os);
3367 begin_command_inset(os, "line", "rule");
3368 os << "offset \"0.5ex\"\n"
3369 "width \"100line%\"\n"
3374 else if (t.cs() == "rule") {
3375 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3376 string const width = p.getArg('{', '}');
3377 string const thickness = p.getArg('{', '}');
3378 context.check_layout(os);
3379 begin_command_inset(os, "line", "rule");
3380 if (!offset.empty())
3381 os << "offset \"" << translate_len(offset) << "\"\n";
3382 os << "width \"" << translate_len(width) << "\"\n"
3383 "height \"" << translate_len(thickness) << "\"\n";
3387 else if (is_known(t.cs(), known_phrases) ||
3388 (t.cs() == "protect" &&
3389 p.next_token().cat() == catEscape &&
3390 is_known(p.next_token().cs(), known_phrases))) {
3391 // LyX sometimes puts a \protect in front, so we have to ignore it
3392 // FIXME: This needs to be changed when bug 4752 is fixed.
3394 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3396 context.check_layout(os);
3397 os << known_coded_phrases[where - known_phrases];
3398 skip_spaces_braces(p);
3401 else if ((where = is_known(t.cs(), known_ref_commands))) {
3402 // \eqref can also occur if refstyle is used
3403 if (t.cs() == "eqref" && preamble.refstyle() == "1") {
3404 context.check_layout(os);
3405 begin_command_inset(os, "ref", "formatted");
3406 os << "reference \"eq:"
3407 << convert_command_inset_arg(p.verbatim_item())
3410 preamble.registerAutomaticallyLoadedPackage("refstyle");
3412 string const opt = p.getOpt();
3414 context.check_layout(os);
3415 begin_command_inset(os, "ref",
3416 known_coded_ref_commands[where - known_ref_commands]);
3417 os << "reference \""
3418 << convert_command_inset_arg(p.verbatim_item())
3421 if (t.cs() == "vref" || t.cs() == "vpageref")
3422 preamble.registerAutomaticallyLoadedPackage("varioref");
3424 // LyX does not yet support optional arguments of ref commands
3425 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3426 p.verbatim_item() + "}", context);
3431 else if ((where = is_known(t.cs(), known_refstyle_commands))) {
3432 context.check_layout(os);
3433 // \eqref can also occur if refstyle is not used
3434 // this case is already handled in the previous else if
3435 begin_command_inset(os, "ref", "formatted");
3436 os << "reference \"";
3437 os << known_refstyle_prefixes[where - known_refstyle_commands]
3439 os << convert_command_inset_arg(p.verbatim_item())
3442 preamble.registerAutomaticallyLoadedPackage("refstyle");
3445 else if (use_natbib &&
3446 is_known(t.cs(), known_natbib_commands) &&
3447 ((t.cs() != "citefullauthor" &&
3448 t.cs() != "citeyear" &&
3449 t.cs() != "citeyearpar") ||
3450 p.next_token().asInput() != "*")) {
3451 context.check_layout(os);
3452 string command = t.cs();
3453 if (p.next_token().asInput() == "*") {
3457 if (command == "citefullauthor")
3458 // alternative name for "\\citeauthor*"
3459 command = "citeauthor*";
3461 // text before the citation
3463 // text after the citation
3465 get_cite_arguments(p, true, before, after);
3467 if (command == "cite") {
3468 // \cite without optional argument means
3469 // \citet, \cite with at least one optional
3470 // argument means \citep.
3471 if (before.empty() && after.empty())
3476 if (before.empty() && after == "[]")
3477 // avoid \citet[]{a}
3479 else if (before == "[]" && after == "[]") {
3480 // avoid \citet[][]{a}
3484 // remove the brackets around after and before
3485 if (!after.empty()) {
3487 after.erase(after.length() - 1, 1);
3488 after = convert_command_inset_arg(after);
3490 if (!before.empty()) {
3492 before.erase(before.length() - 1, 1);
3493 before = convert_command_inset_arg(before);
3495 begin_command_inset(os, "citation", command);
3496 os << "after " << '"' << after << '"' << "\n";
3497 os << "before " << '"' << before << '"' << "\n";
3499 << convert_command_inset_arg(p.verbatim_item())
3502 // Need to set the cite engine if natbib is loaded by
3503 // the document class directly
3504 if (preamble.citeEngine() == "basic")
3505 preamble.citeEngine("natbib");
3508 else if (use_jurabib &&
3509 is_known(t.cs(), known_jurabib_commands) &&
3510 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3511 context.check_layout(os);
3512 string command = t.cs();
3513 if (p.next_token().asInput() == "*") {
3517 char argumentOrder = '\0';
3518 vector<string> const options =
3519 preamble.getPackageOptions("jurabib");
3520 if (find(options.begin(), options.end(),
3521 "natbiborder") != options.end())
3522 argumentOrder = 'n';
3523 else if (find(options.begin(), options.end(),
3524 "jurabiborder") != options.end())
3525 argumentOrder = 'j';
3527 // text before the citation
3529 // text after the citation
3531 get_cite_arguments(p, argumentOrder != 'j', before, after);
3533 string const citation = p.verbatim_item();
3534 if (!before.empty() && argumentOrder == '\0') {
3535 cerr << "Warning: Assuming argument order "
3536 "of jurabib version 0.6 for\n'"
3537 << command << before << after << '{'
3538 << citation << "}'.\n"
3539 "Add 'jurabiborder' to the jurabib "
3540 "package options if you used an\n"
3541 "earlier jurabib version." << endl;
3543 if (!after.empty()) {
3545 after.erase(after.length() - 1, 1);
3547 if (!before.empty()) {
3549 before.erase(before.length() - 1, 1);
3551 begin_command_inset(os, "citation", command);
3552 os << "after " << '"' << after << '"' << "\n";
3553 os << "before " << '"' << before << '"' << "\n";
3554 os << "key " << '"' << citation << '"' << "\n";
3556 // Need to set the cite engine if jurabib is loaded by
3557 // the document class directly
3558 if (preamble.citeEngine() == "basic")
3559 preamble.citeEngine("jurabib");
3562 else if (t.cs() == "cite"
3563 || t.cs() == "nocite") {
3564 context.check_layout(os);
3565 string after = convert_command_inset_arg(p.getArg('[', ']'));
3566 string key = convert_command_inset_arg(p.verbatim_item());
3567 // store the case that it is "\nocite{*}" to use it later for
3570 begin_command_inset(os, "citation", t.cs());
3571 os << "after " << '"' << after << '"' << "\n";
3572 os << "key " << '"' << key << '"' << "\n";
3574 } else if (t.cs() == "nocite")
3578 else if (t.cs() == "index" ||
3579 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3580 context.check_layout(os);
3581 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3582 p.getArg('[', ']') : "";
3583 string const kind = arg.empty() ? "idx" : arg;
3584 begin_inset(os, "Index ");
3585 os << kind << "\nstatus collapsed\n";
3586 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3589 preamble.registerAutomaticallyLoadedPackage("splitidx");
3592 else if (t.cs() == "nomenclature") {
3593 context.check_layout(os);
3594 begin_command_inset(os, "nomenclature", "nomenclature");
3595 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3596 if (!prefix.empty())
3597 os << "prefix " << '"' << prefix << '"' << "\n";
3598 os << "symbol " << '"'
3599 << convert_command_inset_arg(p.verbatim_item());
3600 os << "\"\ndescription \""
3601 << convert_command_inset_arg(p.verbatim_item())
3604 preamble.registerAutomaticallyLoadedPackage("nomencl");
3607 else if (t.cs() == "label") {
3608 context.check_layout(os);
3609 begin_command_inset(os, "label", "label");
3611 << convert_command_inset_arg(p.verbatim_item())
3616 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3617 context.check_layout(os);
3618 string commandname = t.cs();
3620 if (p.next_token().asInput() == "*") {
3625 begin_command_inset(os, "index_print", commandname);
3626 string const indexname = p.getArg('[', ']');
3628 if (indexname.empty())
3629 os << "type \"idx\"\n";
3631 os << "type \"" << indexname << "\"\n";
3634 skip_spaces_braces(p);
3635 preamble.registerAutomaticallyLoadedPackage("makeidx");
3636 if (preamble.use_indices() == "true")
3637 preamble.registerAutomaticallyLoadedPackage("splitidx");
3640 else if (t.cs() == "printnomenclature") {
3642 string width_type = "";
3643 context.check_layout(os);
3644 begin_command_inset(os, "nomencl_print", "printnomenclature");
3645 // case of a custom width
3647 width = p.getArg('[', ']');
3648 width = translate_len(width);
3649 width_type = "custom";
3651 // case of no custom width
3652 // the case of no custom width but the width set
3653 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3654 // because the user could have set anything, not only the width
3655 // of the longest label (which would be width_type = "auto")
3656 string label = convert_command_inset_arg(p.getArg('{', '}'));
3657 if (label.empty() && width_type.empty())
3658 width_type = "none";
3659 os << "set_width \"" << width_type << "\"\n";
3660 if (width_type == "custom")
3661 os << "width \"" << width << '\"';
3663 skip_spaces_braces(p);
3664 preamble.registerAutomaticallyLoadedPackage("nomencl");
3667 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3668 context.check_layout(os);
3669 begin_inset(os, "script ");
3670 os << t.cs().substr(4) << '\n';
3671 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3673 if (t.cs() == "textsubscript")
3674 preamble.registerAutomaticallyLoadedPackage("subscript");
3677 else if ((where = is_known(t.cs(), known_quotes))) {
3678 context.check_layout(os);
3679 begin_inset(os, "Quotes ");
3680 os << known_coded_quotes[where - known_quotes];
3682 // LyX adds {} after the quote, so we have to eat
3683 // spaces here if there are any before a possible
3685 eat_whitespace(p, os, context, false);
3689 else if ((where = is_known(t.cs(), known_sizes)) &&
3690 context.new_layout_allowed) {
3691 context.check_layout(os);
3692 TeXFont const oldFont = context.font;
3693 context.font.size = known_coded_sizes[where - known_sizes];
3694 output_font_change(os, oldFont, context.font);
3695 eat_whitespace(p, os, context, false);
3698 else if ((where = is_known(t.cs(), known_font_families)) &&
3699 context.new_layout_allowed) {
3700 context.check_layout(os);
3701 TeXFont const oldFont = context.font;
3702 context.font.family =
3703 known_coded_font_families[where - known_font_families];
3704 output_font_change(os, oldFont, context.font);
3705 eat_whitespace(p, os, context, false);
3708 else if ((where = is_known(t.cs(), known_font_series)) &&
3709 context.new_layout_allowed) {
3710 context.check_layout(os);
3711 TeXFont const oldFont = context.font;
3712 context.font.series =
3713 known_coded_font_series[where - known_font_series];
3714 output_font_change(os, oldFont, context.font);
3715 eat_whitespace(p, os, context, false);
3718 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3719 context.new_layout_allowed) {
3720 context.check_layout(os);
3721 TeXFont const oldFont = context.font;
3722 context.font.shape =
3723 known_coded_font_shapes[where - known_font_shapes];
3724 output_font_change(os, oldFont, context.font);
3725 eat_whitespace(p, os, context, false);
3727 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3728 context.new_layout_allowed) {
3729 context.check_layout(os);
3730 TeXFont const oldFont = context.font;
3731 context.font.init();
3732 context.font.size = oldFont.size;
3733 context.font.family =
3734 known_coded_font_families[where - known_old_font_families];
3735 output_font_change(os, oldFont, context.font);
3736 eat_whitespace(p, os, context, false);
3739 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3740 context.new_layout_allowed) {
3741 context.check_layout(os);
3742 TeXFont const oldFont = context.font;
3743 context.font.init();
3744 context.font.size = oldFont.size;
3745 context.font.series =
3746 known_coded_font_series[where - known_old_font_series];
3747 output_font_change(os, oldFont, context.font);
3748 eat_whitespace(p, os, context, false);
3751 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3752 context.new_layout_allowed) {
3753 context.check_layout(os);
3754 TeXFont const oldFont = context.font;
3755 context.font.init();
3756 context.font.size = oldFont.size;
3757 context.font.shape =
3758 known_coded_font_shapes[where - known_old_font_shapes];
3759 output_font_change(os, oldFont, context.font);
3760 eat_whitespace(p, os, context, false);
3763 else if (t.cs() == "selectlanguage") {
3764 context.check_layout(os);
3765 // save the language for the case that a
3766 // \foreignlanguage is used
3767 context.font.language = babel2lyx(p.verbatim_item());
3768 os << "\n\\lang " << context.font.language << "\n";
3771 else if (t.cs() == "foreignlanguage") {
3772 string const lang = babel2lyx(p.verbatim_item());
3773 parse_text_attributes(p, os, FLAG_ITEM, outer,
3775 context.font.language, lang);
3778 else if (prefixIs(t.cs(), "text")
3779 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3780 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3782 // We have to output the whole command if it has an option
3783 // because LyX doesn't support this yet, see bug #8214,
3784 // only if there is a single option specifying a variant, we can handle it.
3786 string langopts = p.getOpt();
3787 // check if the option contains a variant, if yes, extract it
3788 string::size_type pos_var = langopts.find("variant");
3789 string::size_type i = langopts.find(',');
3790 string::size_type k = langopts.find('=', pos_var);
3791 if (pos_var != string::npos && i == string::npos) {
3793 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3794 lang = preamble.polyglossia2lyx(variant);
3795 parse_text_attributes(p, os, FLAG_ITEM, outer,
3797 context.font.language, lang);
3799 output_ert_inset(os, t.asInput() + langopts, context);
3801 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3802 parse_text_attributes(p, os, FLAG_ITEM, outer,
3804 context.font.language, lang);
3808 else if (t.cs() == "inputencoding") {
3809 // nothing to write here
3810 string const enc = subst(p.verbatim_item(), "\n", " ");
3811 p.setEncoding(enc, Encoding::inputenc);
3814 else if ((where = is_known(t.cs(), known_special_chars))) {
3815 context.check_layout(os);
3816 os << "\\SpecialChar \\"
3817 << known_coded_special_chars[where - known_special_chars]
3819 skip_spaces_braces(p);
3822 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3823 context.check_layout(os);
3824 os << "\\SpecialChar \\nobreakdash-\n";
3828 else if (t.cs() == "textquotedbl") {
3829 context.check_layout(os);
3834 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3835 context.check_layout(os);
3836 os << "\\SpecialChar \\@.\n";
3840 else if (t.cs() == "-") {
3841 context.check_layout(os);
3842 os << "\\SpecialChar \\-\n";
3845 else if (t.cs() == "textasciitilde") {
3846 context.check_layout(os);
3848 skip_spaces_braces(p);
3851 else if (t.cs() == "textasciicircum") {
3852 context.check_layout(os);
3854 skip_spaces_braces(p);
3857 else if (t.cs() == "textbackslash") {
3858 context.check_layout(os);
3859 os << "\n\\backslash\n";
3860 skip_spaces_braces(p);
3863 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3864 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3866 context.check_layout(os);
3870 else if (t.cs() == "char") {
3871 context.check_layout(os);
3872 if (p.next_token().character() == '`') {
3874 if (p.next_token().cs() == "\"") {
3879 output_ert_inset(os, "\\char`", context);
3882 output_ert_inset(os, "\\char", context);
3886 else if (t.cs() == "verb") {
3887 context.check_layout(os);
3888 // set catcodes to verbatim early, just in case.
3889 p.setCatcodes(VERBATIM_CATCODES);
3890 string delim = p.get_token().asInput();
3891 string const arg = p.verbatimStuff(delim);
3892 output_ert_inset(os, "\\verb" + delim + arg + delim, context);
3895 // Problem: \= creates a tabstop inside the tabbing environment
3896 // and else an accent. In the latter case we really would want
3897 // \={o} instead of \= o.
3898 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3899 output_ert_inset(os, t.asInput(), context);
3901 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3902 else if (t.cs().size() == 1
3903 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3904 context.check_layout(os);
3905 // try to see whether the string is in unicodesymbols
3908 string command = t.asInput() + "{"
3909 + trimSpaceAndEol(p.verbatim_item())
3912 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3913 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3914 termination, rem, &req);
3917 cerr << "When parsing " << command
3918 << ", result is " << to_utf8(s)
3919 << "+" << to_utf8(rem) << endl;
3921 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3922 preamble.registerAutomaticallyLoadedPackage(*it);
3924 // we did not find a non-ert version
3925 output_ert_inset(os, command, context);
3928 else if (t.cs() == "\\") {
3929 context.check_layout(os);
3931 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3932 else if (p.next_token().asInput() == "*") {
3934 // getOpt() eats the following space if there
3935 // is no optional argument, but that is OK
3936 // here since it has no effect in the output.
3937 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3940 begin_inset(os, "Newline newline");
3945 else if (t.cs() == "newline" ||
3946 (t.cs() == "linebreak" && !p.hasOpt())) {
3947 context.check_layout(os);
3948 begin_inset(os, "Newline ");
3951 skip_spaces_braces(p);
3954 else if (t.cs() == "input" || t.cs() == "include"
3955 || t.cs() == "verbatiminput") {
3956 string name = t.cs();
3957 if (t.cs() == "verbatiminput"
3958 && p.next_token().asInput() == "*")
3959 name += p.get_token().asInput();
3960 context.check_layout(os);
3961 string filename(normalize_filename(p.getArg('{', '}')));
3962 string const path = getMasterFilePath(true);
3963 // We want to preserve relative / absolute filenames,
3964 // therefore path is only used for testing
3965 if ((t.cs() == "include" || t.cs() == "input") &&
3966 !makeAbsPath(filename, path).exists()) {
3967 // The file extension is probably missing.
3968 // Now try to find it out.
3969 string const tex_name =
3970 find_file(filename, path,
3971 known_tex_extensions);
3972 if (!tex_name.empty())
3973 filename = tex_name;
3975 bool external = false;
3977 if (makeAbsPath(filename, path).exists()) {
3978 string const abstexname =
3979 makeAbsPath(filename, path).absFileName();
3980 string const absfigname =
3981 changeExtension(abstexname, ".fig");
3982 fix_child_filename(filename);
3983 string const lyxname =
3984 changeExtension(filename, ".lyx");
3985 string const abslyxname = makeAbsPath(
3986 lyxname, getParentFilePath(false)).absFileName();
3988 if (!skipChildren())
3989 external = FileName(absfigname).exists();
3990 if (t.cs() == "input" && !skipChildren()) {
3991 string const ext = getExtension(abstexname);
3993 // Combined PS/LaTeX:
3994 // x.eps, x.pstex_t (old xfig)
3995 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3996 FileName const absepsname(
3997 changeExtension(abstexname, ".eps"));
3998 FileName const abspstexname(
3999 changeExtension(abstexname, ".pstex"));
4000 bool const xfigeps =
4001 (absepsname.exists() ||
4002 abspstexname.exists()) &&
4005 // Combined PDF/LaTeX:
4006 // x.pdf, x.pdftex_t (old xfig)
4007 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4008 FileName const abspdfname(
4009 changeExtension(abstexname, ".pdf"));
4010 bool const xfigpdf =
4011 abspdfname.exists() &&
4012 (ext == "pdftex_t" || ext == "pdf_t");
4016 // Combined PS/PDF/LaTeX:
4017 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4018 string const absbase2(
4019 removeExtension(abstexname) + "_pspdftex");
4020 FileName const abseps2name(
4021 addExtension(absbase2, ".eps"));
4022 FileName const abspdf2name(
4023 addExtension(absbase2, ".pdf"));
4024 bool const xfigboth =
4025 abspdf2name.exists() &&
4026 abseps2name.exists() && ext == "pspdftex";
4028 xfig = xfigpdf || xfigeps || xfigboth;
4029 external = external && xfig;
4032 outname = changeExtension(filename, ".fig");
4033 FileName abssrc(changeExtension(abstexname, ".fig"));
4034 copy_file(abssrc, outname);
4036 // Don't try to convert, the result
4037 // would be full of ERT.
4039 FileName abssrc(abstexname);
4040 copy_file(abssrc, outname);
4041 } else if (t.cs() != "verbatiminput" &&
4043 tex2lyx(abstexname, FileName(abslyxname),
4046 // no need to call copy_file
4047 // tex2lyx creates the file
4050 FileName abssrc(abstexname);
4051 copy_file(abssrc, outname);
4054 cerr << "Warning: Could not find included file '"
4055 << filename << "'." << endl;
4059 begin_inset(os, "External\n");
4060 os << "\ttemplate XFig\n"
4061 << "\tfilename " << outname << '\n';
4062 registerExternalTemplatePackages("XFig");
4064 begin_command_inset(os, "include", name);
4065 outname = subst(outname, "\"", "\\\"");
4066 os << "preview false\n"
4067 "filename \"" << outname << "\"\n";
4068 if (t.cs() == "verbatiminput")
4069 preamble.registerAutomaticallyLoadedPackage("verbatim");
4074 else if (t.cs() == "bibliographystyle") {
4075 // store new bibliographystyle
4076 bibliographystyle = p.verbatim_item();
4077 // If any other command than \bibliography, \addcontentsline
4078 // and \nocite{*} follows, we need to output the style
4079 // (because it might be used by that command).
4080 // Otherwise, it will automatically be output by LyX.
4083 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4084 if (t2.cat() == catBegin)
4086 if (t2.cat() != catEscape)
4088 if (t2.cs() == "nocite") {
4089 if (p.getArg('{', '}') == "*")
4091 } else if (t2.cs() == "bibliography")
4093 else if (t2.cs() == "phantomsection") {
4097 else if (t2.cs() == "addcontentsline") {
4098 // get the 3 arguments of \addcontentsline
4101 contentslineContent = p.getArg('{', '}');
4102 // if the last argument is not \refname we must output
4103 if (contentslineContent == "\\refname")
4110 output_ert_inset(os,
4111 "\\bibliographystyle{" + bibliographystyle + '}',
4116 else if (t.cs() == "phantomsection") {
4117 // we only support this if it occurs between
4118 // \bibliographystyle and \bibliography
4119 if (bibliographystyle.empty())
4120 output_ert_inset(os, "\\phantomsection", context);
4123 else if (t.cs() == "addcontentsline") {
4124 context.check_layout(os);
4125 // get the 3 arguments of \addcontentsline
4126 string const one = p.getArg('{', '}');
4127 string const two = p.getArg('{', '}');
4128 string const three = p.getArg('{', '}');
4129 // only if it is a \refname, we support if for the bibtex inset
4130 if (contentslineContent != "\\refname") {
4131 output_ert_inset(os,
4132 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4137 else if (t.cs() == "bibliography") {
4138 context.check_layout(os);
4140 begin_command_inset(os, "bibtex", "bibtex");
4141 if (!btprint.empty()) {
4142 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4143 // clear the string because the next BibTeX inset can be without the
4144 // \nocite{*} option
4147 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4148 // Do we have addcontentsline?
4149 if (contentslineContent == "\\refname") {
4150 BibOpts = "bibtotoc";
4151 // clear string because next BibTeX inset can be without addcontentsline
4152 contentslineContent.clear();
4154 // Do we have a bibliographystyle set?
4155 if (!bibliographystyle.empty()) {
4156 if (BibOpts.empty())
4157 BibOpts = bibliographystyle;
4159 BibOpts = BibOpts + ',' + bibliographystyle;
4160 // clear it because each bibtex entry has its style
4161 // and we need an empty string to handle \phantomsection
4162 bibliographystyle.clear();
4164 os << "options " << '"' << BibOpts << '"' << "\n";
4168 else if (t.cs() == "parbox") {
4169 // Test whether this is an outer box of a shaded box
4171 // swallow arguments
4172 while (p.hasOpt()) {
4174 p.skip_spaces(true);
4177 p.skip_spaces(true);
4179 if (p.next_token().cat() == catBegin)
4181 p.skip_spaces(true);
4182 Token to = p.get_token();
4183 bool shaded = false;
4184 if (to.asInput() == "\\begin") {
4185 p.skip_spaces(true);
4186 if (p.getArg('{', '}') == "shaded")
4191 parse_outer_box(p, os, FLAG_ITEM, outer,
4192 context, "parbox", "shaded");
4194 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4198 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4199 t.cs() == "shadowbox" || t.cs() == "doublebox")
4200 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4202 else if (t.cs() == "framebox") {
4203 if (p.next_token().character() == '(') {
4204 //the syntax is: \framebox(x,y)[position]{content}
4205 string arg = t.asInput();
4206 arg += p.getFullParentheseArg();
4207 arg += p.getFullOpt();
4208 eat_whitespace(p, os, context, false);
4209 output_ert_inset(os, arg + '{', context);
4210 parse_text(p, os, FLAG_ITEM, outer, context);
4211 output_ert_inset(os, "}", context);
4213 string special = p.getFullOpt();
4214 special += p.getOpt();
4215 // LyX does not yet support \framebox without any option
4216 if (!special.empty())
4217 parse_outer_box(p, os, FLAG_ITEM, outer,
4218 context, t.cs(), special);
4220 eat_whitespace(p, os, context, false);
4221 output_ert_inset(os, "\\framebox{", context);
4222 parse_text(p, os, FLAG_ITEM, outer, context);
4223 output_ert_inset(os, "}", context);
4228 //\makebox() is part of the picture environment and different from \makebox{}
4229 //\makebox{} will be parsed by parse_box
4230 else if (t.cs() == "makebox") {
4231 if (p.next_token().character() == '(') {
4232 //the syntax is: \makebox(x,y)[position]{content}
4233 string arg = t.asInput();
4234 arg += p.getFullParentheseArg();
4235 arg += p.getFullOpt();
4236 eat_whitespace(p, os, context, false);
4237 output_ert_inset(os, arg + '{', context);
4238 parse_text(p, os, FLAG_ITEM, outer, context);
4239 output_ert_inset(os, "}", context);
4241 //the syntax is: \makebox[width][position]{content}
4242 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4246 else if (t.cs() == "smallskip" ||
4247 t.cs() == "medskip" ||
4248 t.cs() == "bigskip" ||
4249 t.cs() == "vfill") {
4250 context.check_layout(os);
4251 begin_inset(os, "VSpace ");
4254 skip_spaces_braces(p);
4257 else if ((where = is_known(t.cs(), known_spaces))) {
4258 context.check_layout(os);
4259 begin_inset(os, "space ");
4260 os << '\\' << known_coded_spaces[where - known_spaces]
4263 // LaTeX swallows whitespace after all spaces except
4264 // "\\,". We have to do that here, too, because LyX
4265 // adds "{}" which would make the spaces significant.
4267 eat_whitespace(p, os, context, false);
4268 // LyX adds "{}" after all spaces except "\\ " and
4269 // "\\,", so we have to remove "{}".
4270 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4271 // remove the braces after "\\,", too.
4276 else if (t.cs() == "newpage" ||
4277 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4278 t.cs() == "clearpage" ||
4279 t.cs() == "cleardoublepage") {
4280 context.check_layout(os);
4281 begin_inset(os, "Newpage ");
4284 skip_spaces_braces(p);
4287 else if (t.cs() == "DeclareRobustCommand" ||
4288 t.cs() == "DeclareRobustCommandx" ||
4289 t.cs() == "newcommand" ||
4290 t.cs() == "newcommandx" ||
4291 t.cs() == "providecommand" ||
4292 t.cs() == "providecommandx" ||
4293 t.cs() == "renewcommand" ||
4294 t.cs() == "renewcommandx") {
4295 // DeclareRobustCommand, DeclareRobustCommandx,
4296 // providecommand and providecommandx could be handled
4297 // by parse_command(), but we need to call
4298 // add_known_command() here.
4299 string name = t.asInput();
4300 if (p.next_token().asInput() == "*") {
4301 // Starred form. Eat '*'
4305 string const command = p.verbatim_item();
4306 string const opt1 = p.getFullOpt();
4307 string const opt2 = p.getFullOpt();
4308 add_known_command(command, opt1, !opt2.empty());
4309 string const ert = name + '{' + command + '}' +
4311 '{' + p.verbatim_item() + '}';
4313 if (t.cs() == "DeclareRobustCommand" ||
4314 t.cs() == "DeclareRobustCommandx" ||
4315 t.cs() == "providecommand" ||
4316 t.cs() == "providecommandx" ||
4317 name[name.length()-1] == '*')
4318 output_ert_inset(os, ert, context);
4320 context.check_layout(os);
4321 begin_inset(os, "FormulaMacro");
4327 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4328 // let could be handled by parse_command(),
4329 // but we need to call add_known_command() here.
4330 string ert = t.asInput();
4333 if (p.next_token().cat() == catBegin) {
4334 name = p.verbatim_item();
4335 ert += '{' + name + '}';
4337 name = p.verbatim_item();
4342 if (p.next_token().cat() == catBegin) {
4343 command = p.verbatim_item();
4344 ert += '{' + command + '}';
4346 command = p.verbatim_item();
4349 // If command is known, make name known too, to parse
4350 // its arguments correctly. For this reason we also
4351 // have commands in syntax.default that are hardcoded.
4352 CommandMap::iterator it = known_commands.find(command);
4353 if (it != known_commands.end())
4354 known_commands[t.asInput()] = it->second;
4355 output_ert_inset(os, ert, context);
4358 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4359 bool starred = false;
4360 if (p.next_token().asInput() == "*") {
4364 string name = t.asInput();
4365 string const length = p.verbatim_item();
4368 bool valid = splitLatexLength(length, valstring, unit);
4369 bool known_hspace = false;
4370 bool known_vspace = false;
4371 bool known_unit = false;
4374 istringstream iss(valstring);
4377 if (t.cs()[0] == 'h') {
4378 if (unit == "\\fill") {
4383 known_hspace = true;
4386 if (unit == "\\smallskipamount") {
4388 known_vspace = true;
4389 } else if (unit == "\\medskipamount") {
4391 known_vspace = true;
4392 } else if (unit == "\\bigskipamount") {
4394 known_vspace = true;
4395 } else if (unit == "\\fill") {
4397 known_vspace = true;
4401 if (!known_hspace && !known_vspace) {
4402 switch (unitFromString(unit)) {
4423 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4424 // Literal horizontal length or known variable
4425 context.check_layout(os);
4426 begin_inset(os, "space ");
4434 if (known_unit && !known_hspace)
4436 << translate_len(length);
4438 } else if (known_unit || known_vspace) {
4439 // Literal vertical length or known variable
4440 context.check_layout(os);
4441 begin_inset(os, "VSpace ");
4449 // LyX can't handle other length variables in Inset VSpace/space
4454 output_ert_inset(os, name + '{' + unit + '}', context);
4455 else if (value == -1.0)
4456 output_ert_inset(os, name + "{-" + unit + '}', context);
4458 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4460 output_ert_inset(os, name + '{' + length + '}', context);
4464 // The single '=' is meant here.
4465 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4467 context.check_layout(os);
4468 begin_inset(os, "Flex ");
4469 os << to_utf8(newinsetlayout->name()) << '\n'
4470 << "status collapsed\n";
4471 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4475 else if (t.cs() == "includepdf") {
4477 string const arg = p.getArg('[', ']');
4478 map<string, string> opts;
4479 vector<string> keys;
4480 split_map(arg, opts, keys);
4481 string name = normalize_filename(p.verbatim_item());
4482 string const path = getMasterFilePath(true);
4483 // We want to preserve relative / absolute filenames,
4484 // therefore path is only used for testing
4485 if (!makeAbsPath(name, path).exists()) {
4486 // The file extension is probably missing.
4487 // Now try to find it out.
4488 char const * const pdfpages_format[] = {"pdf", 0};
4489 string const pdftex_name =
4490 find_file(name, path, pdfpages_format);
4491 if (!pdftex_name.empty()) {
4496 FileName const absname = makeAbsPath(name, path);
4497 if (absname.exists())
4499 fix_child_filename(name);
4500 copy_file(absname, name);
4502 cerr << "Warning: Could not find file '"
4503 << name << "'." << endl;
4505 context.check_layout(os);
4506 begin_inset(os, "External\n\ttemplate ");
4507 os << "PDFPages\n\tfilename "
4509 // parse the options
4510 if (opts.find("pages") != opts.end())
4511 os << "\textra LaTeX \"pages="
4512 << opts["pages"] << "\"\n";
4513 if (opts.find("angle") != opts.end())
4514 os << "\trotateAngle "
4515 << opts["angle"] << '\n';
4516 if (opts.find("origin") != opts.end()) {
4518 string const opt = opts["origin"];
4519 if (opt == "tl") ss << "topleft";
4520 if (opt == "bl") ss << "bottomleft";
4521 if (opt == "Bl") ss << "baselineleft";
4522 if (opt == "c") ss << "center";
4523 if (opt == "tc") ss << "topcenter";
4524 if (opt == "bc") ss << "bottomcenter";
4525 if (opt == "Bc") ss << "baselinecenter";
4526 if (opt == "tr") ss << "topright";
4527 if (opt == "br") ss << "bottomright";
4528 if (opt == "Br") ss << "baselineright";
4529 if (!ss.str().empty())
4530 os << "\trotateOrigin " << ss.str() << '\n';
4532 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4534 if (opts.find("width") != opts.end())
4536 << translate_len(opts["width"]) << '\n';
4537 if (opts.find("height") != opts.end())
4539 << translate_len(opts["height"]) << '\n';
4540 if (opts.find("keepaspectratio") != opts.end())
4541 os << "\tkeepAspectRatio\n";
4543 context.check_layout(os);
4544 registerExternalTemplatePackages("PDFPages");
4547 else if (t.cs() == "loadgame") {
4549 string name = normalize_filename(p.verbatim_item());
4550 string const path = getMasterFilePath(true);
4551 // We want to preserve relative / absolute filenames,
4552 // therefore path is only used for testing
4553 if (!makeAbsPath(name, path).exists()) {
4554 // The file extension is probably missing.
4555 // Now try to find it out.
4556 char const * const lyxskak_format[] = {"fen", 0};
4557 string const lyxskak_name =
4558 find_file(name, path, lyxskak_format);
4559 if (!lyxskak_name.empty())
4560 name = lyxskak_name;
4562 FileName const absname = makeAbsPath(name, path);
4563 if (absname.exists())
4565 fix_child_filename(name);
4566 copy_file(absname, name);
4568 cerr << "Warning: Could not find file '"
4569 << name << "'." << endl;
4570 context.check_layout(os);
4571 begin_inset(os, "External\n\ttemplate ");
4572 os << "ChessDiagram\n\tfilename "
4575 context.check_layout(os);
4576 // after a \loadgame follows a \showboard
4577 if (p.get_token().asInput() == "showboard")
4579 registerExternalTemplatePackages("ChessDiagram");
4583 // try to see whether the string is in unicodesymbols
4584 // Only use text mode commands, since we are in text mode here,
4585 // and math commands may be invalid (bug 6797)
4589 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4590 Encodings::TEXT_CMD, termination, rem, &req);
4593 cerr << "When parsing " << t.cs()
4594 << ", result is " << to_utf8(s)
4595 << "+" << to_utf8(rem) << endl;
4596 context.check_layout(os);
4599 skip_spaces_braces(p);
4600 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4601 preamble.registerAutomaticallyLoadedPackage(*it);
4603 //cerr << "#: " << t << " mode: " << mode << endl;
4604 // heuristic: read up to next non-nested space
4606 string s = t.asInput();
4607 string z = p.verbatim_item();
4608 while (p.good() && z != " " && !z.empty()) {
4609 //cerr << "read: " << z << endl;
4611 z = p.verbatim_item();
4613 cerr << "found ERT: " << s << endl;
4614 output_ert_inset(os, s + ' ', context);
4617 string name = t.asInput();
4618 if (p.next_token().asInput() == "*") {
4619 // Starred commands like \vspace*{}
4620 p.get_token(); // Eat '*'
4623 if (!parse_command(name, p, os, outer, context))
4624 output_ert_inset(os, name, context);
4628 if (flags & FLAG_LEAVE) {
4629 flags &= ~FLAG_LEAVE;
4636 string guessLanguage(Parser & p, string const & lang)
4638 typedef std::map<std::string, size_t> LangMap;
4639 // map from language names to number of characters
4642 for (char const * const * i = supported_CJK_languages; *i; i++)
4643 used[string(*i)] = 0;
4646 Token const t = p.get_token();
4647 // comments are not counted for any language
4648 if (t.cat() == catComment)
4650 // commands are not counted as well, but we need to detect
4651 // \begin{CJK} and switch encoding if needed
4652 if (t.cat() == catEscape) {
4653 if (t.cs() == "inputencoding") {
4654 string const enc = subst(p.verbatim_item(), "\n", " ");
4655 p.setEncoding(enc, Encoding::inputenc);
4658 if (t.cs() != "begin")
4661 // Non-CJK content is counted for lang.
4662 // We do not care about the real language here:
4663 // If we have more non-CJK contents than CJK contents,
4664 // we simply use the language that was specified as
4665 // babel main language.
4666 used[lang] += t.asInput().length();
4669 // Now we are starting an environment
4671 string const name = p.getArg('{', '}');
4672 if (name != "CJK") {
4676 // It is a CJK environment
4678 /* name = */ p.getArg('{', '}');
4679 string const encoding = p.getArg('{', '}');
4680 /* mapping = */ p.getArg('{', '}');
4681 string const encoding_old = p.getEncoding();
4682 char const * const * const where =
4683 is_known(encoding, supported_CJK_encodings);
4685 p.setEncoding(encoding, Encoding::CJK);
4687 p.setEncoding("UTF-8");
4688 string const text = p.ertEnvironment("CJK");
4689 p.setEncoding(encoding_old);
4692 // ignore contents in unknown CJK encoding
4695 // the language of the text
4697 supported_CJK_languages[where - supported_CJK_encodings];
4698 used[cjk] += text.length();
4700 LangMap::const_iterator use = used.begin();
4701 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4702 if (it->second > use->second)