2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49 Context const & context, InsetLayout const * layout)
51 bool const forcePlainLayout =
52 layout ? layout->forcePlainLayout() : false;
53 Context newcontext(true, context.textclass);
55 newcontext.layout = &context.textclass.plainLayout();
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context const & context, string const & name)
68 InsetLayout const * layout = 0;
69 DocumentClass::InsetLayouts::const_iterator it =
70 context.textclass.insetLayouts().find(from_ascii(name));
71 if (it != context.textclass.insetLayouts().end())
72 layout = &(it->second);
73 parse_text_in_inset(p, os, flags, outer, context, layout);
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context newcontext(context);
81 // Don't inherit the paragraph-level extra stuff
82 newcontext.par_extra_stuff.clear();
83 parse_text(p, os, flags, outer, newcontext);
84 // Make sure that we don't create invalid .lyx files
85 context.need_layout = newcontext.need_layout;
86 context.need_end_layout = newcontext.need_end_layout;
91 * Thin wrapper around parse_text_snippet() using a string.
93 * We completely ignore \c context.need_layout and \c context.need_end_layout,
94 * because our return value is not used directly (otherwise the stream version
95 * of parse_text_snippet() could be used). That means that the caller needs
96 * to do layout management manually.
97 * This is intended to parse text that does not create any layout changes.
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
102 Context newcontext(context);
103 newcontext.need_layout = false;
104 newcontext.need_end_layout = false;
105 newcontext.new_layout_allowed = false;
106 // Avoid warning by Context::~Context()
107 newcontext.par_extra_stuff.clear();
109 parse_text_snippet(p, os, flags, outer, newcontext);
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115 "vpageref", "prettyref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "eqref", 0 };
120 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
121 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
122 "secref", "subref", "tabref", "thmref", 0 };
124 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
125 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
126 "sec", "sub", "tab", "thm", 0 };
130 * supported CJK encodings
131 * JIS does not work with LyX's encoding conversion
133 const char * const supported_CJK_encodings[] = {
134 "EUC-JP", "KS", "GB", "UTF8",
135 "Bg5", /*"JIS",*/ "SJIS", 0};
138 * the same as supported_CJK_encodings with their corresponding LyX language name
139 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
141 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
142 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
143 * please keep this in sync with supported_CJK_encodings line by line!
145 const char * const supported_CJK_languages[] = {
146 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
147 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
151 * The starred forms are also known except for "citefullauthor",
152 * "citeyear" and "citeyearpar".
154 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
155 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
156 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
160 * No starred form other than "cite*" known.
162 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
163 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
164 // jurabib commands not (yet) supported by LyX:
166 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
167 // "footciteauthor", "footciteyear", "footciteyearpar",
168 "citefield", "citetitle", 0 };
170 /// LaTeX names for quotes
171 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
172 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
173 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
174 "guilsinglleft", "frq", "guilsinglright", 0};
176 /// the same as known_quotes with .lyx names
177 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
178 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
179 "gld", "grd", "gls", "ers", "fls",
180 "fls", "frs", "frs", 0};
182 /// LaTeX names for font sizes
183 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
184 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
186 /// the same as known_sizes with .lyx names
187 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
188 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
190 /// LaTeX 2.09 names for font families
191 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
193 /// LaTeX names for font families
194 char const * const known_font_families[] = { "rmfamily", "sffamily",
197 /// LaTeX names for font family changing commands
198 char const * const known_text_font_families[] = { "textrm", "textsf",
201 /// The same as known_old_font_families, known_font_families and
202 /// known_text_font_families with .lyx names
203 char const * const known_coded_font_families[] = { "roman", "sans",
206 /// LaTeX 2.09 names for font series
207 char const * const known_old_font_series[] = { "bf", 0};
209 /// LaTeX names for font series
210 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
212 /// LaTeX names for font series changing commands
213 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
215 /// The same as known_old_font_series, known_font_series and
216 /// known_text_font_series with .lyx names
217 char const * const known_coded_font_series[] = { "bold", "medium", 0};
219 /// LaTeX 2.09 names for font shapes
220 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
222 /// LaTeX names for font shapes
223 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
226 /// LaTeX names for font shape changing commands
227 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
230 /// The same as known_old_font_shapes, known_font_shapes and
231 /// known_text_font_shapes with .lyx names
232 char const * const known_coded_font_shapes[] = { "italic", "slanted",
233 "smallcaps", "up", 0};
235 /// Known special characters which need skip_spaces_braces() afterwards
236 char const * const known_special_chars[] = {"ldots", "lyxarrow",
237 "textcompwordmark", "slash", 0};
239 /// the same as known_special_chars with .lyx names
240 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
241 "textcompwordmark{}", "slash{}", 0};
244 * Graphics file extensions known by the dvips driver of the graphics package.
245 * These extensions are used to complete the filename of an included
246 * graphics file if it does not contain an extension.
247 * The order must be the same that latex uses to find a file, because we
248 * will use the first extension that matches.
249 * This is only an approximation for the common cases. If we would want to
250 * do it right in all cases, we would need to know which graphics driver is
251 * used and know the extensions of every driver of the graphics package.
253 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
254 "ps.gz", "eps.Z", "ps.Z", 0};
257 * Graphics file extensions known by the pdftex driver of the graphics package.
258 * \sa known_dvips_graphics_formats
260 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
264 * Known file extensions for TeX files as used by \\include.
266 char const * const known_tex_extensions[] = {"tex", 0};
268 /// spaces known by InsetSpace
269 char const * const known_spaces[] = { " ", "space", ",",
270 "thinspace", "quad", "qquad", "enspace", "enskip",
271 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
272 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
273 "upbracefill", "downbracefill", 0};
275 /// the same as known_spaces with .lyx names
276 char const * const known_coded_spaces[] = { "space{}", "space{}",
277 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
278 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
279 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
280 "upbracefill{}", "downbracefill{}", 0};
282 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
283 /// them in ERT. "LaTeXe" must come before "LaTeX"!
284 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
285 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
286 int const known_phrase_lengths[] = {3, 5, 7, 0};
288 /// known TIPA combining diacritical marks
289 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
290 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
291 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
292 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
293 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
294 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
297 /// TIPA tones that need special handling
298 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
300 // string to store the float type to be able to determine the type of subfloats
301 string float_type = "";
304 /// splits "x=z, y=b" into a map and an ordered keyword vector
305 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
310 keys.resize(v.size());
311 for (size_t i = 0; i < v.size(); ++i) {
312 size_t const pos = v[i].find('=');
313 string const index = trimSpaceAndEol(v[i].substr(0, pos));
314 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
322 * Split a LaTeX length into value and unit.
323 * The latter can be a real unit like "pt", or a latex length variable
324 * like "\textwidth". The unit may contain additional stuff like glue
325 * lengths, but we don't care, because such lengths are ERT anyway.
326 * \returns true if \p value and \p unit are valid.
328 bool splitLatexLength(string const & len, string & value, string & unit)
332 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
333 //'4,5' is a valid LaTeX length number. Change it to '4.5'
334 string const length = subst(len, ',', '.');
335 if (i == string::npos)
338 if (len[0] == '\\') {
339 // We had something like \textwidth without a factor
345 value = trimSpaceAndEol(string(length, 0, i));
349 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
350 if (contains(len, '\\'))
351 unit = trimSpaceAndEol(string(len, i));
353 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
358 /// A simple function to translate a latex length to something LyX can
359 /// understand. Not perfect, but rather best-effort.
360 bool translate_len(string const & length, string & valstring, string & unit)
362 if (!splitLatexLength(length, valstring, unit))
364 // LyX uses percent values
366 istringstream iss(valstring);
371 string const percentval = oss.str();
373 if (unit.empty() || unit[0] != '\\')
375 string::size_type const i = unit.find(' ');
376 string const endlen = (i == string::npos) ? string() : string(unit, i);
377 if (unit == "\\textwidth") {
378 valstring = percentval;
379 unit = "text%" + endlen;
380 } else if (unit == "\\columnwidth") {
381 valstring = percentval;
382 unit = "col%" + endlen;
383 } else if (unit == "\\paperwidth") {
384 valstring = percentval;
385 unit = "page%" + endlen;
386 } else if (unit == "\\linewidth") {
387 valstring = percentval;
388 unit = "line%" + endlen;
389 } else if (unit == "\\paperheight") {
390 valstring = percentval;
391 unit = "pheight%" + endlen;
392 } else if (unit == "\\textheight") {
393 valstring = percentval;
394 unit = "theight%" + endlen;
402 string translate_len(string const & length)
406 if (translate_len(length, value, unit))
408 // If the input is invalid, return what we have.
416 * Translates a LaTeX length into \p value, \p unit and
417 * \p special parts suitable for a box inset.
418 * The difference from translate_len() is that a box inset knows about
419 * some special "units" that are stored in \p special.
421 void translate_box_len(string const & length, string & value, string & unit, string & special)
423 if (translate_len(length, value, unit)) {
424 if (unit == "\\height" || unit == "\\depth" ||
425 unit == "\\totalheight" || unit == "\\width") {
426 special = unit.substr(1);
427 // The unit is not used, but LyX requires a dummy setting
440 * Find a file with basename \p name in path \p path and an extension
443 string find_file(string const & name, string const & path,
444 char const * const * extensions)
446 for (char const * const * what = extensions; *what; ++what) {
447 string const trial = addExtension(name, *what);
448 if (makeAbsPath(trial, path).exists())
455 void begin_inset(ostream & os, string const & name)
457 os << "\n\\begin_inset " << name;
461 void begin_command_inset(ostream & os, string const & name,
462 string const & latexname)
464 begin_inset(os, "CommandInset ");
465 os << name << "\nLatexCommand " << latexname << '\n';
469 void end_inset(ostream & os)
471 os << "\n\\end_inset\n\n";
475 bool skip_braces(Parser & p)
477 if (p.next_token().cat() != catBegin)
480 if (p.next_token().cat() == catEnd) {
489 /// replace LaTeX commands in \p s from the unicodesymbols file with their
491 docstring convert_unicodesymbols(docstring s)
494 for (size_t i = 0; i < s.size();) {
503 docstring parsed = encodings.fromLaTeXCommand(s,
504 Encodings::TEXT_CMD, termination, rem, &req);
505 set<string>::const_iterator it = req.begin();
506 set<string>::const_iterator en = req.end();
507 for (; it != en; ++it)
508 preamble.registerAutomaticallyLoadedPackage(*it);
511 if (s.empty() || s[0] != '\\')
520 /// try to convert \p s to a valid InsetCommand argument
521 string convert_command_inset_arg(string s)
524 // since we don't know the input encoding we can't use from_utf8
525 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
526 // LyX cannot handle newlines in a latex command
527 return subst(s, "\n", " ");
531 void output_ert(ostream & os, string const & s, Context & context)
533 context.check_layout(os);
534 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
536 os << "\n\\backslash\n";
537 else if (*it == '\n') {
538 context.new_paragraph(os);
539 context.check_layout(os);
543 context.check_end_layout(os);
547 void output_ert_inset(ostream & os, string const & s, Context & context)
549 // We must have a valid layout before outputting the ERT inset.
550 context.check_layout(os);
551 Context newcontext(true, context.textclass);
552 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
553 if (layout.forcePlainLayout())
554 newcontext.layout = &context.textclass.plainLayout();
555 begin_inset(os, "ERT");
556 os << "\nstatus collapsed\n";
557 output_ert(os, s, newcontext);
562 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
564 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
567 if (checkModule(name, command))
568 return findLayoutWithoutModule(textclass, name, command);
573 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
575 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
578 if (checkModule(name, command))
579 return findInsetLayoutWithoutModule(textclass, name, command);
584 void eat_whitespace(Parser &, ostream &, Context &, bool);
588 * Skips whitespace and braces.
589 * This should be called after a command has been parsed that is not put into
590 * ERT, and where LyX adds "{}" if needed.
592 void skip_spaces_braces(Parser & p, bool keepws = false)
594 /* The following four examples produce the same typeset output and
595 should be handled by this function:
603 // Unfortunately we need to skip comments, too.
604 // We can't use eat_whitespace since writing them after the {}
605 // results in different output in some cases.
606 bool const skipped_spaces = p.skip_spaces(true);
607 bool const skipped_braces = skip_braces(p);
608 if (keepws && skipped_spaces && !skipped_braces)
609 // put back the space (it is better handled by check_space)
610 p.unskip_spaces(true);
614 void output_command_layout(ostream & os, Parser & p, bool outer,
615 Context & parent_context,
616 Layout const * newlayout)
618 TeXFont const oldFont = parent_context.font;
619 // save the current font size
620 string const size = oldFont.size;
621 // reset the font size to default, because the font size switches
622 // don't affect section headings and the like
623 parent_context.font.size = Context::normalfont.size;
624 // we only need to write the font change if we have an open layout
625 if (!parent_context.atParagraphStart())
626 output_font_change(os, oldFont, parent_context.font);
627 parent_context.check_end_layout(os);
628 Context context(true, parent_context.textclass, newlayout,
629 parent_context.layout, parent_context.font);
630 if (parent_context.deeper_paragraph) {
631 // We are beginning a nested environment after a
632 // deeper paragraph inside the outer list environment.
633 // Therefore we don't need to output a "begin deeper".
634 context.need_end_deeper = true;
636 context.check_deeper(os);
637 context.check_layout(os);
638 // FIXME: Adjust to format 446!
639 // Since format 446, layouts do not require anymore all optional
640 // arguments before the required ones. Needs to be implemented!
642 while (optargs < context.layout->optArgs()) {
643 eat_whitespace(p, os, context, false);
644 if (p.next_token().cat() == catEscape ||
645 p.next_token().character() != '[')
647 p.get_token(); // eat '['
648 // FIXME: Just a workaround. InsetArgument::updateBuffer
649 // will compute a proper ID for all "999" Arguments
650 // (which is also what lyx2lyx produces).
651 // However, tex2lyx should be able to output proper IDs
653 begin_inset(os, "Argument 999\n");
654 os << "status collapsed\n\n";
655 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
657 eat_whitespace(p, os, context, false);
661 while (reqargs < context.layout->requiredArgs()) {
662 eat_whitespace(p, os, context, false);
663 if (p.next_token().cat() != catBegin)
665 p.get_token(); // eat '{'
666 // FIXME: Just a workaround. InsetArgument::updateBuffer
667 // will compute a proper ID for all "999" Arguments
668 // (which is also what lyx2lyx produces).
669 // However, tex2lyx should be able to output proper IDs
671 begin_inset(os, "Argument 999\n");
672 os << "status collapsed\n\n";
673 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
675 eat_whitespace(p, os, context, false);
678 parse_text(p, os, FLAG_ITEM, outer, context);
679 context.check_end_layout(os);
680 if (parent_context.deeper_paragraph) {
681 // We must suppress the "end deeper" because we
682 // suppressed the "begin deeper" above.
683 context.need_end_deeper = false;
685 context.check_end_deeper(os);
686 // We don't need really a new paragraph, but
687 // we must make sure that the next item gets a \begin_layout.
688 parent_context.new_paragraph(os);
689 // Set the font size to the original value. No need to output it here
690 // (Context::begin_layout() will do that if needed)
691 parent_context.font.size = size;
696 * Output a space if necessary.
697 * This function gets called for every whitespace token.
699 * We have three cases here:
700 * 1. A space must be suppressed. Example: The lyxcode case below
701 * 2. A space may be suppressed. Example: Spaces before "\par"
702 * 3. A space must not be suppressed. Example: A space between two words
704 * We currently handle only 1. and 3 and from 2. only the case of
705 * spaces before newlines as a side effect.
707 * 2. could be used to suppress as many spaces as possible. This has two effects:
708 * - Reimporting LyX generated LaTeX files changes almost no whitespace
709 * - Superflous whitespace from non LyX generated LaTeX files is removed.
710 * The drawback is that the logic inside the function becomes
711 * complicated, and that is the reason why it is not implemented.
713 void check_space(Parser & p, ostream & os, Context & context)
715 Token const next = p.next_token();
716 Token const curr = p.curr_token();
717 // A space before a single newline and vice versa must be ignored
718 // LyX emits a newline before \end{lyxcode}.
719 // This newline must be ignored,
720 // otherwise LyX will add an additional protected space.
721 if (next.cat() == catSpace ||
722 next.cat() == catNewline ||
723 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
726 context.check_layout(os);
732 * Parse all arguments of \p command
734 void parse_arguments(string const & command,
735 vector<ArgumentType> const & template_arguments,
736 Parser & p, ostream & os, bool outer, Context & context)
738 string ert = command;
739 size_t no_arguments = template_arguments.size();
740 for (size_t i = 0; i < no_arguments; ++i) {
741 switch (template_arguments[i]) {
744 // This argument contains regular LaTeX
745 output_ert_inset(os, ert + '{', context);
746 eat_whitespace(p, os, context, false);
747 if (template_arguments[i] == required)
748 parse_text(p, os, FLAG_ITEM, outer, context);
750 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
754 // This argument consists only of a single item.
755 // The presence of '{' or not must be preserved.
757 if (p.next_token().cat() == catBegin)
758 ert += '{' + p.verbatim_item() + '}';
760 ert += p.verbatim_item();
764 // This argument may contain special characters
765 ert += '{' + p.verbatim_item() + '}';
769 // true because we must not eat whitespace
770 // if an optional arg follows we must not strip the
771 // brackets from this one
772 if (i < no_arguments - 1 &&
773 template_arguments[i+1] == optional)
774 ert += p.getFullOpt(true);
776 ert += p.getOpt(true);
780 output_ert_inset(os, ert, context);
785 * Check whether \p command is a known command. If yes,
786 * handle the command with all arguments.
787 * \return true if the command was parsed, false otherwise.
789 bool parse_command(string const & command, Parser & p, ostream & os,
790 bool outer, Context & context)
792 if (known_commands.find(command) != known_commands.end()) {
793 parse_arguments(command, known_commands[command], p, os,
801 /// Parses a minipage or parbox
802 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
803 unsigned inner_flags, bool outer, Context & parent_context,
804 string const & outer_type, string const & special,
805 string const & inner_type)
809 string hor_pos = "c";
810 // We need to set the height to the LaTeX default of 1\\totalheight
811 // for the case when no height argument is given
812 string height_value = "1";
813 string height_unit = "in";
814 string height_special = "totalheight";
819 string width_special = "none";
820 if (!inner_type.empty() && p.hasOpt()) {
821 if (inner_type != "makebox")
822 position = p.getArg('[', ']');
824 latex_width = p.getArg('[', ']');
825 translate_box_len(latex_width, width_value, width_unit, width_special);
828 if (position != "t" && position != "c" && position != "b") {
829 cerr << "invalid position " << position << " for "
830 << inner_type << endl;
834 if (inner_type != "makebox") {
835 latex_height = p.getArg('[', ']');
836 translate_box_len(latex_height, height_value, height_unit, height_special);
838 string const opt = p.getArg('[', ']');
841 if (hor_pos != "l" && hor_pos != "c" &&
842 hor_pos != "r" && hor_pos != "s") {
843 cerr << "invalid hor_pos " << hor_pos
844 << " for " << inner_type << endl;
851 inner_pos = p.getArg('[', ']');
852 if (inner_pos != "c" && inner_pos != "t" &&
853 inner_pos != "b" && inner_pos != "s") {
854 cerr << "invalid inner_pos "
855 << inner_pos << " for "
856 << inner_type << endl;
857 inner_pos = position;
862 if (inner_type.empty()) {
863 if (special.empty() && outer_type != "framebox")
864 latex_width = "1\\columnwidth";
867 latex_width = p2.getArg('[', ']');
868 string const opt = p2.getArg('[', ']');
871 if (hor_pos != "l" && hor_pos != "c" &&
872 hor_pos != "r" && hor_pos != "s") {
873 cerr << "invalid hor_pos " << hor_pos
874 << " for " << outer_type << endl;
879 } else if (inner_type != "makebox")
880 latex_width = p.verbatim_item();
881 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
882 // as this is LyX's standard for such cases (except for makebox)
883 // \framebox is more special and handled below
884 if (latex_width.empty() && inner_type != "makebox"
885 && outer_type != "framebox")
886 latex_width = "1\\columnwidth";
888 translate_len(latex_width, width_value, width_unit);
890 bool shadedparbox = false;
891 if (inner_type == "shaded") {
892 eat_whitespace(p, os, parent_context, false);
893 if (outer_type == "parbox") {
895 if (p.next_token().cat() == catBegin)
897 eat_whitespace(p, os, parent_context, false);
903 // If we already read the inner box we have to push the inner env
904 if (!outer_type.empty() && !inner_type.empty() &&
905 (inner_flags & FLAG_END))
906 active_environments.push_back(inner_type);
907 // LyX can't handle length variables
908 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
909 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
910 // Look whether there is some content after the end of the
911 // inner box, but before the end of the outer box.
912 // If yes, we need to output ERT.
914 if (inner_flags & FLAG_END)
915 p.ertEnvironment(inner_type);
919 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
920 if ((outer_env && p.next_token().asInput() != "\\end") ||
921 (!outer_env && p.next_token().cat() != catEnd)) {
922 // something is between the end of the inner box and
923 // the end of the outer box, so we need to use ERT.
928 // if only \makebox{content} was used we can set its width to 1\width
929 // because this identic and also identic to \mbox
930 // this doesn't work for \framebox{content}, thus we have to use ERT for this
931 if (latex_width.empty() && inner_type == "makebox") {
934 width_special = "width";
935 } else if (latex_width.empty() && outer_type == "framebox") {
940 if (!outer_type.empty()) {
941 if (outer_flags & FLAG_END)
942 ss << "\\begin{" << outer_type << '}';
944 ss << '\\' << outer_type << '{';
945 if (!special.empty())
949 if (!inner_type.empty()) {
950 if (inner_type != "shaded") {
951 if (inner_flags & FLAG_END)
952 ss << "\\begin{" << inner_type << '}';
954 ss << '\\' << inner_type;
956 if (!position.empty())
957 ss << '[' << position << ']';
958 if (!latex_height.empty())
959 ss << '[' << latex_height << ']';
960 if (!inner_pos.empty())
961 ss << '[' << inner_pos << ']';
962 ss << '{' << latex_width << '}';
963 if (!(inner_flags & FLAG_END))
966 if (inner_type == "shaded")
967 ss << "\\begin{shaded}";
968 output_ert_inset(os, ss.str(), parent_context);
969 if (!inner_type.empty()) {
970 parse_text(p, os, inner_flags, outer, parent_context);
971 if (inner_flags & FLAG_END)
972 output_ert_inset(os, "\\end{" + inner_type + '}',
975 output_ert_inset(os, "}", parent_context);
977 if (!outer_type.empty()) {
978 // If we already read the inner box we have to pop
980 if (!inner_type.empty() && (inner_flags & FLAG_END))
981 active_environments.pop_back();
983 // Ensure that the end of the outer box is parsed correctly:
984 // The opening brace has been eaten by parse_outer_box()
985 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
986 outer_flags &= ~FLAG_ITEM;
987 outer_flags |= FLAG_BRACE_LAST;
989 parse_text(p, os, outer_flags, outer, parent_context);
990 if (outer_flags & FLAG_END)
991 output_ert_inset(os, "\\end{" + outer_type + '}',
993 else if (inner_type.empty() && outer_type == "framebox")
994 // in this case it is already closed later
997 output_ert_inset(os, "}", parent_context);
1000 // LyX does not like empty positions, so we have
1001 // to set them to the LaTeX default values here.
1002 if (position.empty())
1004 if (inner_pos.empty())
1005 inner_pos = position;
1006 parent_context.check_layout(os);
1007 begin_inset(os, "Box ");
1008 if (outer_type == "framed")
1010 else if (outer_type == "framebox")
1012 else if (outer_type == "shadowbox")
1013 os << "Shadowbox\n";
1014 else if ((outer_type == "shaded" && inner_type.empty()) ||
1015 (outer_type == "minipage" && inner_type == "shaded") ||
1016 (outer_type == "parbox" && inner_type == "shaded")) {
1018 preamble.registerAutomaticallyLoadedPackage("color");
1019 } else if (outer_type == "doublebox")
1020 os << "Doublebox\n";
1021 else if (outer_type.empty())
1022 os << "Frameless\n";
1024 os << outer_type << '\n';
1025 os << "position \"" << position << "\"\n";
1026 os << "hor_pos \"" << hor_pos << "\"\n";
1027 os << "has_inner_box " << !inner_type.empty() << "\n";
1028 os << "inner_pos \"" << inner_pos << "\"\n";
1029 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1031 os << "use_makebox " << (inner_type == "makebox") << '\n';
1032 os << "width \"" << width_value << width_unit << "\"\n";
1033 os << "special \"" << width_special << "\"\n";
1034 os << "height \"" << height_value << height_unit << "\"\n";
1035 os << "height_special \"" << height_special << "\"\n";
1036 os << "status open\n\n";
1038 // Unfortunately we can't use parse_text_in_inset:
1039 // InsetBox::forcePlainLayout() is hard coded and does not
1040 // use the inset layout. Apart from that do we call parse_text
1041 // up to two times, but need only one check_end_layout.
1042 bool const forcePlainLayout =
1043 (!inner_type.empty() || inner_type == "makebox") &&
1044 outer_type != "shaded" && outer_type != "framed";
1045 Context context(true, parent_context.textclass);
1046 if (forcePlainLayout)
1047 context.layout = &context.textclass.plainLayout();
1049 context.font = parent_context.font;
1051 // If we have no inner box the contents will be read with the outer box
1052 if (!inner_type.empty())
1053 parse_text(p, os, inner_flags, outer, context);
1055 // Ensure that the end of the outer box is parsed correctly:
1056 // The opening brace has been eaten by parse_outer_box()
1057 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1058 outer_flags &= ~FLAG_ITEM;
1059 outer_flags |= FLAG_BRACE_LAST;
1062 // Find end of outer box, output contents if inner_type is
1063 // empty and output possible comments
1064 if (!outer_type.empty()) {
1065 // If we already read the inner box we have to pop
1067 if (!inner_type.empty() && (inner_flags & FLAG_END))
1068 active_environments.pop_back();
1069 // This does not output anything but comments if
1070 // inner_type is not empty (see use_ert)
1071 parse_text(p, os, outer_flags, outer, context);
1074 context.check_end_layout(os);
1076 #ifdef PRESERVE_LAYOUT
1077 // LyX puts a % after the end of the minipage
1078 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1080 //output_ert_inset(os, "%dummy", parent_context);
1083 parent_context.new_paragraph(os);
1085 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1086 //output_ert_inset(os, "%dummy", parent_context);
1089 // We add a protected space if something real follows
1090 if (p.good() && p.next_token().cat() != catComment) {
1091 begin_inset(os, "space ~\n");
1100 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1101 Context & parent_context, string const & outer_type,
1102 string const & special)
1104 eat_whitespace(p, os, parent_context, false);
1105 if (flags & FLAG_ITEM) {
1107 if (p.next_token().cat() == catBegin)
1110 cerr << "Warning: Ignoring missing '{' after \\"
1111 << outer_type << '.' << endl;
1112 eat_whitespace(p, os, parent_context, false);
1115 unsigned int inner_flags = 0;
1117 if (outer_type == "minipage" || outer_type == "parbox") {
1118 p.skip_spaces(true);
1119 while (p.hasOpt()) {
1121 p.skip_spaces(true);
1124 p.skip_spaces(true);
1125 if (outer_type == "parbox") {
1127 if (p.next_token().cat() == catBegin)
1129 p.skip_spaces(true);
1132 if (outer_type == "shaded") {
1133 // These boxes never have an inner box
1135 } else if (p.next_token().asInput() == "\\parbox") {
1136 inner = p.get_token().cs();
1137 inner_flags = FLAG_ITEM;
1138 } else if (p.next_token().asInput() == "\\begin") {
1139 // Is this a minipage or shaded box?
1142 inner = p.getArg('{', '}');
1144 if (inner == "minipage" || inner == "shaded")
1145 inner_flags = FLAG_END;
1150 if (inner_flags == FLAG_END) {
1151 if (inner != "shaded")
1155 eat_whitespace(p, os, parent_context, false);
1157 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1158 outer_type, special, inner);
1160 if (inner_flags == FLAG_ITEM) {
1162 eat_whitespace(p, os, parent_context, false);
1164 parse_box(p, os, flags, inner_flags, outer, parent_context,
1165 outer_type, special, inner);
1170 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1172 parent_context.check_layout(os);
1173 begin_inset(os, "listings\n");
1175 string arg = p.verbatimOption();
1176 os << "lstparams " << '"' << arg << '"' << '\n';
1177 if (arg.find("\\color") != string::npos)
1178 preamble.registerAutomaticallyLoadedPackage("color");
1181 os << "inline true\n";
1183 os << "inline false\n";
1184 os << "status collapsed\n";
1185 Context context(true, parent_context.textclass);
1186 context.layout = &parent_context.textclass.plainLayout();
1189 // set catcodes to verbatim early, just in case.
1190 p.setCatcodes(VERBATIM_CATCODES);
1191 string delim = p.get_token().asInput();
1192 s = p.verbatimStuff(delim);
1193 // context.new_paragraph(os);
1195 s = p.verbatimEnvironment("lstlisting");
1196 output_ert(os, s, context);
1201 /// parse an unknown environment
1202 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1203 unsigned flags, bool outer,
1204 Context & parent_context)
1206 if (name == "tabbing")
1207 // We need to remember that we have to handle '\=' specially
1208 flags |= FLAG_TABBING;
1210 // We need to translate font changes and paragraphs inside the
1211 // environment to ERT if we have a non standard font.
1212 // Otherwise things like
1213 // \large\begin{foo}\huge bar\end{foo}
1215 bool const specialfont =
1216 (parent_context.font != parent_context.normalfont);
1217 bool const new_layout_allowed = parent_context.new_layout_allowed;
1219 parent_context.new_layout_allowed = false;
1220 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1221 parse_text_snippet(p, os, flags, outer, parent_context);
1222 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1224 parent_context.new_layout_allowed = new_layout_allowed;
1228 void parse_environment(Parser & p, ostream & os, bool outer,
1229 string & last_env, Context & parent_context)
1231 Layout const * newlayout;
1232 InsetLayout const * newinsetlayout = 0;
1233 string const name = p.getArg('{', '}');
1234 const bool is_starred = suffixIs(name, '*');
1235 string const unstarred_name = rtrim(name, "*");
1236 active_environments.push_back(name);
1238 if (is_math_env(name)) {
1239 parent_context.check_layout(os);
1240 begin_inset(os, "Formula ");
1241 os << "\\begin{" << name << "}";
1242 parse_math(p, os, FLAG_END, MATH_MODE);
1243 os << "\\end{" << name << "}";
1245 if (is_display_math_env(name)) {
1246 // Prevent the conversion of a line break to a space
1247 // (bug 7668). This does not change the output, but
1248 // looks ugly in LyX.
1249 eat_whitespace(p, os, parent_context, false);
1253 else if (is_known(name, preamble.polyglossia_languages)) {
1254 // We must begin a new paragraph if not already done
1255 if (! parent_context.atParagraphStart()) {
1256 parent_context.check_end_layout(os);
1257 parent_context.new_paragraph(os);
1259 // save the language in the context so that it is
1260 // handled by parse_text
1261 parent_context.font.language = preamble.polyglossia2lyx(name);
1262 parse_text(p, os, FLAG_END, outer, parent_context);
1263 // Just in case the environment is empty
1264 parent_context.extra_stuff.erase();
1265 // We must begin a new paragraph to reset the language
1266 parent_context.new_paragraph(os);
1270 else if (unstarred_name == "tabular" || name == "longtable") {
1271 eat_whitespace(p, os, parent_context, false);
1272 string width = "0pt";
1273 if (name == "tabular*") {
1274 width = lyx::translate_len(p.getArg('{', '}'));
1275 eat_whitespace(p, os, parent_context, false);
1277 parent_context.check_layout(os);
1278 begin_inset(os, "Tabular ");
1279 handle_tabular(p, os, name, width, parent_context);
1284 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1285 eat_whitespace(p, os, parent_context, false);
1286 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1287 eat_whitespace(p, os, parent_context, false);
1288 parent_context.check_layout(os);
1289 begin_inset(os, "Float " + unstarred_name + "\n");
1290 // store the float type for subfloats
1291 // subfloats only work with figures and tables
1292 if (unstarred_name == "figure")
1293 float_type = unstarred_name;
1294 else if (unstarred_name == "table")
1295 float_type = unstarred_name;
1299 os << "placement " << opt << '\n';
1300 if (contains(opt, "H"))
1301 preamble.registerAutomaticallyLoadedPackage("float");
1303 Floating const & fl = parent_context.textclass.floats()
1304 .getType(unstarred_name);
1305 if (!fl.floattype().empty() && fl.usesFloatPkg())
1306 preamble.registerAutomaticallyLoadedPackage("float");
1309 os << "wide " << convert<string>(is_starred)
1310 << "\nsideways false"
1311 << "\nstatus open\n\n";
1312 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1314 // We don't need really a new paragraph, but
1315 // we must make sure that the next item gets a \begin_layout.
1316 parent_context.new_paragraph(os);
1318 // the float is parsed thus delete the type
1322 else if (unstarred_name == "sidewaysfigure"
1323 || unstarred_name == "sidewaystable") {
1324 eat_whitespace(p, os, parent_context, false);
1325 parent_context.check_layout(os);
1326 if (unstarred_name == "sidewaysfigure")
1327 begin_inset(os, "Float figure\n");
1329 begin_inset(os, "Float table\n");
1330 os << "wide " << convert<string>(is_starred)
1331 << "\nsideways true"
1332 << "\nstatus open\n\n";
1333 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1335 // We don't need really a new paragraph, but
1336 // we must make sure that the next item gets a \begin_layout.
1337 parent_context.new_paragraph(os);
1339 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1342 else if (name == "wrapfigure" || name == "wraptable") {
1343 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1344 eat_whitespace(p, os, parent_context, false);
1345 parent_context.check_layout(os);
1348 string overhang = "0col%";
1351 lines = p.getArg('[', ']');
1352 string const placement = p.getArg('{', '}');
1354 overhang = p.getArg('[', ']');
1355 string const width = p.getArg('{', '}');
1357 if (name == "wrapfigure")
1358 begin_inset(os, "Wrap figure\n");
1360 begin_inset(os, "Wrap table\n");
1361 os << "lines " << lines
1362 << "\nplacement " << placement
1363 << "\noverhang " << lyx::translate_len(overhang)
1364 << "\nwidth " << lyx::translate_len(width)
1365 << "\nstatus open\n\n";
1366 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1368 // We don't need really a new paragraph, but
1369 // we must make sure that the next item gets a \begin_layout.
1370 parent_context.new_paragraph(os);
1372 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1375 else if (name == "minipage") {
1376 eat_whitespace(p, os, parent_context, false);
1377 // Test whether this is an outer box of a shaded box
1379 // swallow arguments
1380 while (p.hasOpt()) {
1382 p.skip_spaces(true);
1385 p.skip_spaces(true);
1386 Token t = p.get_token();
1387 bool shaded = false;
1388 if (t.asInput() == "\\begin") {
1389 p.skip_spaces(true);
1390 if (p.getArg('{', '}') == "shaded")
1395 parse_outer_box(p, os, FLAG_END, outer,
1396 parent_context, name, "shaded");
1398 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1403 else if (name == "comment") {
1404 eat_whitespace(p, os, parent_context, false);
1405 parent_context.check_layout(os);
1406 begin_inset(os, "Note Comment\n");
1407 os << "status open\n";
1408 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1411 skip_braces(p); // eat {} that might by set by LyX behind comments
1412 preamble.registerAutomaticallyLoadedPackage("verbatim");
1415 else if (name == "verbatim") {
1416 // FIXME: this should go in the generic code that
1417 // handles environments defined in layout file that
1418 // have "PassThru 1". However, the code over there is
1419 // already too complicated for my taste.
1420 parent_context.new_paragraph(os);
1421 Context context(true, parent_context.textclass,
1422 &parent_context.textclass[from_ascii("Verbatim")]);
1423 string s = p.verbatimEnvironment("verbatim");
1424 output_ert(os, s, context);
1428 else if (name == "IPA") {
1429 eat_whitespace(p, os, parent_context, false);
1430 parent_context.check_layout(os);
1431 begin_inset(os, "IPA\n");
1432 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1435 preamble.registerAutomaticallyLoadedPackage("tipa");
1436 preamble.registerAutomaticallyLoadedPackage("tipx");
1439 else if (name == "CJK") {
1440 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1441 // It is impossible to decide if a CJK environment was in its own paragraph or within
1442 // a line. We therefore always assume a paragraph since the latter is a rare case.
1443 eat_whitespace(p, os, parent_context, false);
1444 parent_context.check_end_layout(os);
1445 // store the encoding to be able to reset it
1446 string const encoding_old = p.getEncoding();
1447 string const encoding = p.getArg('{', '}');
1448 // FIXME: For some reason JIS does not work. Although the text
1449 // in tests/CJK.tex is identical with the SJIS version if you
1450 // convert both snippets using the recode command line utility,
1451 // the resulting .lyx file contains some extra characters if
1452 // you set buggy_encoding to false for JIS.
1453 bool const buggy_encoding = encoding == "JIS";
1454 if (!buggy_encoding)
1455 p.setEncoding(encoding, Encoding::CJK);
1457 // FIXME: This will read garbage, since the data is not encoded in utf8.
1458 p.setEncoding("UTF-8");
1460 // LyX only supports the same mapping for all CJK
1461 // environments, so we might need to output everything as ERT
1462 string const mapping = trim(p.getArg('{', '}'));
1463 char const * const * const where =
1464 is_known(encoding, supported_CJK_encodings);
1465 if (!buggy_encoding && !preamble.fontCJKSet())
1466 preamble.fontCJK(mapping);
1467 bool knownMapping = mapping == preamble.fontCJK();
1468 if (buggy_encoding || !knownMapping || !where) {
1469 parent_context.check_layout(os);
1470 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1472 // we must parse the content as verbatim because e.g. JIS can contain
1473 // normally invalid characters
1474 // FIXME: This works only for the most simple cases.
1475 // Since TeX control characters are not parsed,
1476 // things like comments are completely wrong.
1477 string const s = p.plainEnvironment("CJK");
1478 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1480 output_ert_inset(os, "\\", parent_context);
1481 else if (*it == '$')
1482 output_ert_inset(os, "$", parent_context);
1483 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1488 output_ert_inset(os, "\\end{" + name + "}",
1492 supported_CJK_languages[where - supported_CJK_encodings];
1493 // store the language because we must reset it at the end
1494 string const lang_old = parent_context.font.language;
1495 parent_context.font.language = lang;
1496 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1497 parent_context.font.language = lang_old;
1498 parent_context.new_paragraph(os);
1500 p.setEncoding(encoding_old);
1504 else if (name == "lyxgreyedout") {
1505 eat_whitespace(p, os, parent_context, false);
1506 parent_context.check_layout(os);
1507 begin_inset(os, "Note Greyedout\n");
1508 os << "status open\n";
1509 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1512 if (!preamble.notefontcolor().empty())
1513 preamble.registerAutomaticallyLoadedPackage("color");
1516 else if (name == "framed" || name == "shaded") {
1517 eat_whitespace(p, os, parent_context, false);
1518 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1522 else if (name == "lstlisting") {
1523 eat_whitespace(p, os, parent_context, false);
1524 parse_listings(p, os, parent_context, false);
1528 else if (!parent_context.new_layout_allowed)
1529 parse_unknown_environment(p, name, os, FLAG_END, outer,
1532 // Alignment and spacing settings
1533 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1534 // therefore are totally broken!
1535 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1536 // they are commands not environments. They are furthermore switches that
1537 // can be ended by another switches, but also by commands like \footnote or
1538 // \parbox. So the only safe way is to leave them untouched.
1539 else if (name == "center" || name == "centering" ||
1540 name == "flushleft" || name == "flushright" ||
1541 name == "singlespace" || name == "onehalfspace" ||
1542 name == "doublespace" || name == "spacing") {
1543 eat_whitespace(p, os, parent_context, false);
1544 // We must begin a new paragraph if not already done
1545 if (! parent_context.atParagraphStart()) {
1546 parent_context.check_end_layout(os);
1547 parent_context.new_paragraph(os);
1549 if (name == "flushleft")
1550 parent_context.add_extra_stuff("\\align left\n");
1551 else if (name == "flushright")
1552 parent_context.add_extra_stuff("\\align right\n");
1553 else if (name == "center" || name == "centering")
1554 parent_context.add_extra_stuff("\\align center\n");
1555 else if (name == "singlespace")
1556 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1557 else if (name == "onehalfspace") {
1558 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1559 preamble.registerAutomaticallyLoadedPackage("setspace");
1560 } else if (name == "doublespace") {
1561 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1562 preamble.registerAutomaticallyLoadedPackage("setspace");
1563 } else if (name == "spacing") {
1564 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1565 preamble.registerAutomaticallyLoadedPackage("setspace");
1567 parse_text(p, os, FLAG_END, outer, parent_context);
1568 // Just in case the environment is empty
1569 parent_context.extra_stuff.erase();
1570 // We must begin a new paragraph to reset the alignment
1571 parent_context.new_paragraph(os);
1575 // The single '=' is meant here.
1576 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1577 eat_whitespace(p, os, parent_context, false);
1578 Context context(true, parent_context.textclass, newlayout,
1579 parent_context.layout, parent_context.font);
1580 if (parent_context.deeper_paragraph) {
1581 // We are beginning a nested environment after a
1582 // deeper paragraph inside the outer list environment.
1583 // Therefore we don't need to output a "begin deeper".
1584 context.need_end_deeper = true;
1586 parent_context.check_end_layout(os);
1587 if (last_env == name) {
1588 // we need to output a separator since LyX would export
1589 // the two environments as one otherwise (bug 5716)
1590 docstring const sep = from_ascii("--Separator--");
1591 TeX2LyXDocClass const & textclass(parent_context.textclass);
1592 if (textclass.hasLayout(sep)) {
1593 Context newcontext(parent_context);
1594 newcontext.layout = &(textclass[sep]);
1595 newcontext.check_layout(os);
1596 newcontext.check_end_layout(os);
1598 parent_context.check_layout(os);
1599 begin_inset(os, "Note Note\n");
1600 os << "status closed\n";
1601 Context newcontext(true, textclass,
1602 &(textclass.defaultLayout()));
1603 newcontext.check_layout(os);
1604 newcontext.check_end_layout(os);
1606 parent_context.check_end_layout(os);
1609 switch (context.layout->latextype) {
1610 case LATEX_LIST_ENVIRONMENT:
1611 context.add_par_extra_stuff("\\labelwidthstring "
1612 + p.verbatim_item() + '\n');
1615 case LATEX_BIB_ENVIRONMENT:
1616 p.verbatim_item(); // swallow next arg
1622 context.check_deeper(os);
1623 // handle known optional and required arguments
1624 // FIXME: Since format 446, layouts do not require anymore all optional
1625 // arguments before the required ones. Needs to be implemented!
1626 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1627 // It is impossible to place anything after the environment name,
1628 // but before the first \\item.
1629 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1630 bool need_layout = true;
1632 while (optargs < context.layout->optArgs()) {
1633 eat_whitespace(p, os, context, false);
1634 if (p.next_token().cat() == catEscape ||
1635 p.next_token().character() != '[')
1637 p.get_token(); // eat '['
1639 context.check_layout(os);
1640 need_layout = false;
1642 // FIXME: Just a workaround. InsetArgument::updateBuffer
1643 // will compute a proper ID for all "999" Arguments
1644 // (which is also what lyx2lyx produces).
1645 // However, tex2lyx should be able to output proper IDs
1647 begin_inset(os, "Argument 999\n");
1648 os << "status collapsed\n\n";
1649 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1651 eat_whitespace(p, os, context, false);
1655 while (reqargs < context.layout->requiredArgs()) {
1656 eat_whitespace(p, os, context, false);
1657 if (p.next_token().cat() != catBegin)
1659 p.get_token(); // eat '{'
1661 context.check_layout(os);
1662 need_layout = false;
1664 // FIXME: Just a workaround. InsetArgument::updateBuffer
1665 // will compute a proper ID for all "999" Arguments
1666 // (which is also what lyx2lyx produces).
1667 // However, tex2lyx should be able to output proper IDs
1669 begin_inset(os, "Argument 999\n");
1670 os << "status collapsed\n\n";
1671 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1673 eat_whitespace(p, os, context, false);
1677 parse_text(p, os, FLAG_END, outer, context);
1678 context.check_end_layout(os);
1679 if (parent_context.deeper_paragraph) {
1680 // We must suppress the "end deeper" because we
1681 // suppressed the "begin deeper" above.
1682 context.need_end_deeper = false;
1684 context.check_end_deeper(os);
1685 parent_context.new_paragraph(os);
1687 if (!preamble.titleLayoutFound())
1688 preamble.titleLayoutFound(newlayout->intitle);
1689 set<string> const & req = newlayout->requires();
1690 set<string>::const_iterator it = req.begin();
1691 set<string>::const_iterator en = req.end();
1692 for (; it != en; ++it)
1693 preamble.registerAutomaticallyLoadedPackage(*it);
1696 // The single '=' is meant here.
1697 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1698 eat_whitespace(p, os, parent_context, false);
1699 parent_context.check_layout(os);
1700 begin_inset(os, "Flex ");
1701 os << to_utf8(newinsetlayout->name()) << '\n'
1702 << "status collapsed\n";
1703 if (newinsetlayout->isPassThru()) {
1704 string const arg = p.verbatimEnvironment(name);
1705 Context context(true, parent_context.textclass,
1706 &parent_context.textclass.plainLayout(),
1707 parent_context.layout);
1708 output_ert(os, arg, parent_context);
1710 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1714 else if (name == "appendix") {
1715 // This is no good latex style, but it works and is used in some documents...
1716 eat_whitespace(p, os, parent_context, false);
1717 parent_context.check_end_layout(os);
1718 Context context(true, parent_context.textclass, parent_context.layout,
1719 parent_context.layout, parent_context.font);
1720 context.check_layout(os);
1721 os << "\\start_of_appendix\n";
1722 parse_text(p, os, FLAG_END, outer, context);
1723 context.check_end_layout(os);
1727 else if (known_environments.find(name) != known_environments.end()) {
1728 vector<ArgumentType> arguments = known_environments[name];
1729 // The last "argument" denotes wether we may translate the
1730 // environment contents to LyX
1731 // The default required if no argument is given makes us
1732 // compatible with the reLyXre environment.
1733 ArgumentType contents = arguments.empty() ?
1736 if (!arguments.empty())
1737 arguments.pop_back();
1738 // See comment in parse_unknown_environment()
1739 bool const specialfont =
1740 (parent_context.font != parent_context.normalfont);
1741 bool const new_layout_allowed =
1742 parent_context.new_layout_allowed;
1744 parent_context.new_layout_allowed = false;
1745 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1746 outer, parent_context);
1747 if (contents == verbatim)
1748 output_ert_inset(os, p.ertEnvironment(name),
1751 parse_text_snippet(p, os, FLAG_END, outer,
1753 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1755 parent_context.new_layout_allowed = new_layout_allowed;
1759 parse_unknown_environment(p, name, os, FLAG_END, outer,
1763 active_environments.pop_back();
1767 /// parses a comment and outputs it to \p os.
1768 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1770 LASSERT(t.cat() == catComment, return);
1771 if (!t.cs().empty()) {
1772 context.check_layout(os);
1773 output_ert_inset(os, '%' + t.cs(), context);
1774 if (p.next_token().cat() == catNewline) {
1775 // A newline after a comment line starts a new
1777 if (context.new_layout_allowed) {
1778 if(!context.atParagraphStart())
1779 // Only start a new paragraph if not already
1780 // done (we might get called recursively)
1781 context.new_paragraph(os);
1783 output_ert_inset(os, "\n", context);
1784 eat_whitespace(p, os, context, true);
1787 // "%\n" combination
1794 * Reads spaces and comments until the first non-space, non-comment token.
1795 * New paragraphs (double newlines or \\par) are handled like simple spaces
1796 * if \p eatParagraph is true.
1797 * Spaces are skipped, but comments are written to \p os.
1799 void eat_whitespace(Parser & p, ostream & os, Context & context,
1803 Token const & t = p.get_token();
1804 if (t.cat() == catComment)
1805 parse_comment(p, os, t, context);
1806 else if ((! eatParagraph && p.isParagraph()) ||
1807 (t.cat() != catSpace && t.cat() != catNewline)) {
1816 * Set a font attribute, parse text and reset the font attribute.
1817 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1818 * \param currentvalue Current value of the attribute. Is set to the new
1819 * value during parsing.
1820 * \param newvalue New value of the attribute
1822 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1823 Context & context, string const & attribute,
1824 string & currentvalue, string const & newvalue)
1826 context.check_layout(os);
1827 string const oldvalue = currentvalue;
1828 currentvalue = newvalue;
1829 os << '\n' << attribute << ' ' << newvalue << "\n";
1830 parse_text_snippet(p, os, flags, outer, context);
1831 context.check_layout(os);
1832 os << '\n' << attribute << ' ' << oldvalue << "\n";
1833 currentvalue = oldvalue;
1837 /// get the arguments of a natbib or jurabib citation command
1838 void get_cite_arguments(Parser & p, bool natbibOrder,
1839 string & before, string & after)
1841 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1843 // text before the citation
1845 // text after the citation
1846 after = p.getFullOpt();
1848 if (!after.empty()) {
1849 before = p.getFullOpt();
1850 if (natbibOrder && !before.empty())
1851 swap(before, after);
1856 /// Convert filenames with TeX macros and/or quotes to something LyX
1858 string const normalize_filename(string const & name)
1863 Token const & t = p.get_token();
1864 if (t.cat() != catEscape)
1866 else if (t.cs() == "lyxdot") {
1867 // This is used by LyX for simple dots in relative
1871 } else if (t.cs() == "space") {
1874 } else if (t.cs() == "string") {
1875 // Convert \string" to " and \string~ to ~
1876 Token const & n = p.next_token();
1877 if (n.asInput() != "\"" && n.asInput() != "~")
1882 // Strip quotes. This is a bit complicated (see latex_path()).
1883 string full = os.str();
1884 if (!full.empty() && full[0] == '"') {
1885 string base = removeExtension(full);
1886 string ext = getExtension(full);
1887 if (!base.empty() && base[base.length()-1] == '"')
1890 return addExtension(trim(base, "\""), ext);
1891 if (full[full.length()-1] == '"')
1894 return trim(full, "\"");
1900 /// Convert \p name from TeX convention (relative to master file) to LyX
1901 /// convention (relative to .lyx file) if it is relative
1902 void fix_child_filename(string & name)
1904 string const absMasterTeX = getMasterFilePath(true);
1905 bool const isabs = FileName::isAbsolute(name);
1906 // convert from "relative to .tex master" to absolute original path
1908 name = makeAbsPath(name, absMasterTeX).absFileName();
1909 bool copyfile = copyFiles();
1910 string const absParentLyX = getParentFilePath(false);
1913 // convert from absolute original path to "relative to master file"
1914 string const rel = to_utf8(makeRelPath(from_utf8(name),
1915 from_utf8(absMasterTeX)));
1916 // re-interpret "relative to .tex file" as "relative to .lyx file"
1917 // (is different if the master .lyx file resides in a
1918 // different path than the master .tex file)
1919 string const absMasterLyX = getMasterFilePath(false);
1920 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1921 // Do not copy if the new path is impossible to create. Example:
1922 // absMasterTeX = "/foo/bar/"
1923 // absMasterLyX = "/bar/"
1924 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1925 if (contains(name, "/../"))
1932 // convert from absolute original path to
1933 // "relative to .lyx file"
1934 name = to_utf8(makeRelPath(from_utf8(abs),
1935 from_utf8(absParentLyX)));
1939 // convert from absolute original path to "relative to .lyx file"
1940 name = to_utf8(makeRelPath(from_utf8(name),
1941 from_utf8(absParentLyX)));
1946 void copy_file(FileName const & src, string dstname)
1950 string const absParent = getParentFilePath(false);
1952 if (FileName::isAbsolute(dstname))
1953 dst = FileName(dstname);
1955 dst = makeAbsPath(dstname, absParent);
1956 string const absMaster = getMasterFilePath(false);
1957 FileName const srcpath = src.onlyPath();
1958 FileName const dstpath = dst.onlyPath();
1959 if (equivalent(srcpath, dstpath))
1961 if (!dstpath.isDirectory()) {
1962 if (!dstpath.createPath()) {
1963 cerr << "Warning: Could not create directory for file `"
1964 << dst.absFileName() << "´." << endl;
1968 if (dst.isReadableFile()) {
1969 if (overwriteFiles())
1970 cerr << "Warning: Overwriting existing file `"
1971 << dst.absFileName() << "´." << endl;
1973 cerr << "Warning: Not overwriting existing file `"
1974 << dst.absFileName() << "´." << endl;
1978 if (!src.copyTo(dst))
1979 cerr << "Warning: Could not copy file `" << src.absFileName()
1980 << "´ to `" << dst.absFileName() << "´." << endl;
1984 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1985 void parse_noweb(Parser & p, ostream & os, Context & context)
1987 // assemble the rest of the keyword
1991 Token const & t = p.get_token();
1992 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1995 chunk = (p.good() && p.next_token().asInput() == "=");
1997 name += p.get_token().asInput();
2000 name += t.asInput();
2003 if (!chunk || !context.new_layout_allowed ||
2004 !context.textclass.hasLayout(from_ascii("Chunk"))) {
2005 cerr << "Warning: Could not interpret '" << name
2006 << "'. Ignoring it." << endl;
2010 // We use new_paragraph instead of check_end_layout because the stuff
2011 // following the noweb chunk needs to start with a \begin_layout.
2012 // This may create a new paragraph even if there was none in the
2013 // noweb file, but the alternative is an invalid LyX file. Since
2014 // noweb code chunks are implemented with a layout style in LyX they
2015 // always must be in an own paragraph.
2016 context.new_paragraph(os);
2017 Context newcontext(true, context.textclass,
2018 &context.textclass[from_ascii("Chunk")]);
2019 newcontext.check_layout(os);
2022 Token const & t = p.get_token();
2023 // We abuse the parser a bit, because this is no TeX syntax
2025 if (t.cat() == catEscape)
2026 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2029 Context tmp(false, context.textclass,
2030 &context.textclass[from_ascii("Chunk")]);
2031 tmp.need_end_layout = true;
2032 tmp.check_layout(oss);
2033 os << subst(t.asInput(), "\n", oss.str());
2035 // The chunk is ended by an @ at the beginning of a line.
2036 // After the @ the line may contain a comment and/or
2037 // whitespace, but nothing else.
2038 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2039 (p.next_token().cat() == catSpace ||
2040 p.next_token().cat() == catNewline ||
2041 p.next_token().cat() == catComment)) {
2042 while (p.good() && p.next_token().cat() == catSpace)
2043 os << p.get_token().asInput();
2044 if (p.next_token().cat() == catComment)
2045 // The comment includes a final '\n'
2046 os << p.get_token().asInput();
2048 if (p.next_token().cat() == catNewline)
2055 newcontext.check_end_layout(os);
2059 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2060 bool is_macro(Parser & p)
2062 Token first = p.curr_token();
2063 if (first.cat() != catEscape || !p.good())
2065 if (first.cs() == "def")
2067 if (first.cs() != "global" && first.cs() != "long")
2069 Token second = p.get_token();
2071 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2072 second.cat() == catNewline || second.cat() == catComment)) {
2073 second = p.get_token();
2076 bool secondvalid = second.cat() == catEscape;
2078 bool thirdvalid = false;
2079 if (p.good() && first.cs() == "global" && secondvalid &&
2080 second.cs() == "long") {
2081 third = p.get_token();
2083 while (p.good() && !p.isParagraph() &&
2084 (third.cat() == catSpace ||
2085 third.cat() == catNewline ||
2086 third.cat() == catComment)) {
2087 third = p.get_token();
2090 thirdvalid = third.cat() == catEscape;
2092 for (int i = 0; i < pos; ++i)
2097 return (first.cs() == "global" || first.cs() == "long") &&
2098 second.cs() == "def";
2099 return first.cs() == "global" && second.cs() == "long" &&
2100 third.cs() == "def";
2104 /// Parse a macro definition (assumes that is_macro() returned true)
2105 void parse_macro(Parser & p, ostream & os, Context & context)
2107 context.check_layout(os);
2108 Token first = p.curr_token();
2111 string command = first.asInput();
2112 if (first.cs() != "def") {
2114 eat_whitespace(p, os, context, false);
2115 second = p.curr_token();
2116 command += second.asInput();
2117 if (second.cs() != "def") {
2119 eat_whitespace(p, os, context, false);
2120 third = p.curr_token();
2121 command += third.asInput();
2124 eat_whitespace(p, os, context, false);
2125 string const name = p.get_token().cs();
2126 eat_whitespace(p, os, context, false);
2132 while (p.next_token().cat() != catBegin) {
2133 if (p.next_token().cat() == catParameter) {
2138 // followed by number?
2139 if (p.next_token().cat() == catOther) {
2140 string s = p.get_token().asInput();
2142 // number = current arity + 1?
2143 if (s.size() == 1 && s[0] == arity + '0' + 1)
2148 paramtext += p.get_token().cs();
2150 paramtext += p.get_token().cs();
2155 // only output simple (i.e. compatible) macro as FormulaMacros
2156 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2158 context.check_layout(os);
2159 begin_inset(os, "FormulaMacro");
2160 os << "\n\\def" << ert;
2163 output_ert_inset(os, command + ert, context);
2167 void registerExternalTemplatePackages(string const & name)
2169 external::TemplateManager const & etm = external::TemplateManager::get();
2170 external::Template const * const et = etm.getTemplateByName(name);
2173 external::Template::Formats::const_iterator cit = et->formats.end();
2175 cit = et->formats.find("PDFLaTeX");
2176 if (cit == et->formats.end())
2177 // If the template has not specified a PDFLaTeX output,
2178 // we try the LaTeX format.
2179 cit = et->formats.find("LaTeX");
2180 if (cit == et->formats.end())
2182 vector<string>::const_iterator qit = cit->second.requirements.begin();
2183 vector<string>::const_iterator qend = cit->second.requirements.end();
2184 for (; qit != qend; ++qit)
2185 preamble.registerAutomaticallyLoadedPackage(*qit);
2188 } // anonymous namespace
2191 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2194 Layout const * newlayout = 0;
2195 InsetLayout const * newinsetlayout = 0;
2196 char const * const * where = 0;
2197 // Store the latest bibliographystyle, addcontentslineContent and
2198 // nocite{*} option (needed for bibtex inset)
2200 string contentslineContent;
2201 string bibliographystyle = "default";
2202 bool const use_natbib = isProvided("natbib");
2203 bool const use_jurabib = isProvided("jurabib");
2206 Token const & t = p.get_token();
2208 // it is impossible to determine the correct encoding for non-CJK Japanese.
2209 // Therefore write a note at the beginning of the document
2210 if (is_nonCJKJapanese) {
2211 context.check_layout(os);
2212 begin_inset(os, "Note Note\n");
2213 os << "status open\n\\begin_layout Plain Layout\n"
2214 << "\\series bold\n"
2215 << "Important information:\n"
2216 << "\\end_layout\n\n"
2217 << "\\begin_layout Plain Layout\n"
2218 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2219 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2220 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2221 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2222 << " and specify the encoding using the -e command-line switch.\n"
2223 << " In addition, you might want to double check that the desired output encoding\n"
2224 << " is correctly selected in Document > Settings > Language.\n"
2225 << "\\end_layout\n";
2227 is_nonCJKJapanese = false;
2231 debugToken(cerr, t, flags);
2234 if (flags & FLAG_ITEM) {
2235 if (t.cat() == catSpace)
2238 flags &= ~FLAG_ITEM;
2239 if (t.cat() == catBegin) {
2240 // skip the brace and collect everything to the next matching
2242 flags |= FLAG_BRACE_LAST;
2246 // handle only this single token, leave the loop if done
2247 flags |= FLAG_LEAVE;
2250 if (t.cat() != catEscape && t.character() == ']' &&
2251 (flags & FLAG_BRACK_LAST))
2253 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2256 // If there is anything between \end{env} and \begin{env} we
2257 // don't need to output a separator.
2258 if (t.cat() != catSpace && t.cat() != catNewline &&
2259 t.asInput() != "\\begin")
2265 if (t.cat() == catMath) {
2266 // we are inside some text mode thingy, so opening new math is allowed
2267 context.check_layout(os);
2268 begin_inset(os, "Formula ");
2269 Token const & n = p.get_token();
2270 bool const display(n.cat() == catMath && outer);
2272 // TeX's $$...$$ syntax for displayed math
2274 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2276 p.get_token(); // skip the second '$' token
2278 // simple $...$ stuff
2281 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2286 // Prevent the conversion of a line break to a
2287 // space (bug 7668). This does not change the
2288 // output, but looks ugly in LyX.
2289 eat_whitespace(p, os, context, false);
2293 else if (t.cat() == catSuper || t.cat() == catSub)
2294 cerr << "catcode " << t << " illegal in text mode\n";
2296 // Basic support for english quotes. This should be
2297 // extended to other quotes, but is not so easy (a
2298 // left english quote is the same as a right german
2300 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2301 context.check_layout(os);
2302 begin_inset(os, "Quotes ");
2308 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2309 context.check_layout(os);
2310 begin_inset(os, "Quotes ");
2317 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2318 context.check_layout(os);
2319 begin_inset(os, "Quotes ");
2326 else if (t.asInput() == "<"
2327 && p.next_token().asInput() == "<" && noweb_mode) {
2329 parse_noweb(p, os, context);
2332 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2333 context.check_layout(os);
2334 begin_inset(os, "Quotes ");
2341 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2342 check_space(p, os, context);
2344 else if (t.character() == '[' && noweb_mode &&
2345 p.next_token().character() == '[') {
2346 // These can contain underscores
2348 string const s = p.getFullOpt() + ']';
2349 if (p.next_token().character() == ']')
2352 cerr << "Warning: Inserting missing ']' in '"
2353 << s << "'." << endl;
2354 output_ert_inset(os, s, context);
2357 else if (t.cat() == catLetter) {
2358 context.check_layout(os);
2359 // Workaround for bug 4752.
2360 // FIXME: This whole code block needs to be removed
2361 // when the bug is fixed and tex2lyx produces
2362 // the updated file format.
2363 // The replacement algorithm in LyX is so stupid that
2364 // it even translates a phrase if it is part of a word.
2365 bool handled = false;
2366 for (int const * l = known_phrase_lengths; *l; ++l) {
2367 string phrase = t.cs();
2368 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2369 phrase += p.get_token().cs();
2370 if (is_known(phrase, known_coded_phrases)) {
2371 output_ert_inset(os, phrase, context);
2375 for (size_t i = 1; i < phrase.length(); ++i)
2383 else if (t.cat() == catOther ||
2384 t.cat() == catAlign ||
2385 t.cat() == catParameter) {
2386 // This translates "&" to "\\&" which may be wrong...
2387 context.check_layout(os);
2391 else if (p.isParagraph()) {
2392 if (context.new_layout_allowed)
2393 context.new_paragraph(os);
2395 output_ert_inset(os, "\\par ", context);
2396 eat_whitespace(p, os, context, true);
2399 else if (t.cat() == catActive) {
2400 context.check_layout(os);
2401 if (t.character() == '~') {
2402 if (context.layout->free_spacing)
2405 begin_inset(os, "space ~\n");
2412 else if (t.cat() == catBegin) {
2413 Token const next = p.next_token();
2414 Token const end = p.next_next_token();
2415 if (next.cat() == catEnd) {
2417 Token const prev = p.prev_token();
2419 if (p.next_token().character() == '`' ||
2420 (prev.character() == '-' &&
2421 p.next_token().character() == '-'))
2422 ; // ignore it in {}`` or -{}-
2424 output_ert_inset(os, "{}", context);
2425 } else if (next.cat() == catEscape &&
2426 is_known(next.cs(), known_quotes) &&
2427 end.cat() == catEnd) {
2428 // Something like {\textquoteright} (e.g.
2429 // from writer2latex). LyX writes
2430 // \textquoteright{}, so we may skip the
2431 // braces here for better readability.
2432 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2434 } else if (p.next_token().asInput() == "\\ascii") {
2435 // handle the \ascii characters
2436 // (the case without braces is handled later)
2437 // the code is "{\ascii\xxx}"
2438 p.get_token(); // eat \ascii
2439 string name2 = p.get_token().asInput();
2440 p.get_token(); // eat the final '}'
2441 string const name = "{\\ascii" + name2 + "}";
2445 // get the character from unicodesymbols
2446 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2447 Encodings::TEXT_CMD, termination, rem, &req);
2449 context.check_layout(os);
2452 // we did not find a non-ert version
2453 output_ert_inset(os, name, context);
2455 context.check_layout(os);
2456 // special handling of font attribute changes
2457 Token const prev = p.prev_token();
2458 TeXFont const oldFont = context.font;
2459 if (next.character() == '[' ||
2460 next.character() == ']' ||
2461 next.character() == '*') {
2463 if (p.next_token().cat() == catEnd) {
2468 output_ert_inset(os, "{", context);
2469 parse_text_snippet(p, os,
2472 output_ert_inset(os, "}", context);
2474 } else if (! context.new_layout_allowed) {
2475 output_ert_inset(os, "{", context);
2476 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2478 output_ert_inset(os, "}", context);
2479 } else if (is_known(next.cs(), known_sizes)) {
2480 // next will change the size, so we must
2482 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2484 if (!context.atParagraphStart())
2486 << context.font.size << "\n";
2487 } else if (is_known(next.cs(), known_font_families)) {
2488 // next will change the font family, so we
2489 // must reset it here
2490 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2492 if (!context.atParagraphStart())
2494 << context.font.family << "\n";
2495 } else if (is_known(next.cs(), known_font_series)) {
2496 // next will change the font series, so we
2497 // must reset it here
2498 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2500 if (!context.atParagraphStart())
2502 << context.font.series << "\n";
2503 } else if (is_known(next.cs(), known_font_shapes)) {
2504 // next will change the font shape, so we
2505 // must reset it here
2506 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2508 if (!context.atParagraphStart())
2510 << context.font.shape << "\n";
2511 } else if (is_known(next.cs(), known_old_font_families) ||
2512 is_known(next.cs(), known_old_font_series) ||
2513 is_known(next.cs(), known_old_font_shapes)) {
2514 // next will change the font family, series
2515 // and shape, so we must reset it here
2516 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2518 if (!context.atParagraphStart())
2520 << context.font.family
2522 << context.font.series
2524 << context.font.shape << "\n";
2526 output_ert_inset(os, "{", context);
2527 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2529 output_ert_inset(os, "}", context);
2534 else if (t.cat() == catEnd) {
2535 if (flags & FLAG_BRACE_LAST) {
2538 cerr << "stray '}' in text\n";
2539 output_ert_inset(os, "}", context);
2542 else if (t.cat() == catComment)
2543 parse_comment(p, os, t, context);
2546 // control sequences
2549 else if (t.cs() == "(") {
2550 context.check_layout(os);
2551 begin_inset(os, "Formula");
2553 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2558 else if (t.cs() == "[") {
2559 context.check_layout(os);
2560 begin_inset(os, "Formula");
2562 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2565 // Prevent the conversion of a line break to a space
2566 // (bug 7668). This does not change the output, but
2567 // looks ugly in LyX.
2568 eat_whitespace(p, os, context, false);
2571 else if (t.cs() == "begin")
2572 parse_environment(p, os, outer, last_env,
2575 else if (t.cs() == "end") {
2576 if (flags & FLAG_END) {
2577 // eat environment name
2578 string const name = p.getArg('{', '}');
2579 if (name != active_environment())
2580 cerr << "\\end{" + name + "} does not match \\begin{"
2581 + active_environment() + "}\n";
2584 p.error("found 'end' unexpectedly");
2587 else if (t.cs() == "item") {
2589 bool const optarg = p.hasOpt();
2591 // FIXME: This swallows comments, but we cannot use
2592 // eat_whitespace() since we must not output
2593 // anything before the item.
2594 p.skip_spaces(true);
2595 s = p.verbatimOption();
2597 p.skip_spaces(false);
2599 context.check_layout(os);
2600 if (context.has_item) {
2601 // An item in an unknown list-like environment
2602 // FIXME: Do this in check_layout()!
2603 context.has_item = false;
2605 output_ert_inset(os, "\\item", context);
2607 output_ert_inset(os, "\\item ", context);
2610 if (context.layout->labeltype != LABEL_MANUAL) {
2611 // LyX does not support \item[\mybullet]
2612 // in itemize environments
2614 os << parse_text_snippet(p2,
2615 FLAG_BRACK_LAST, outer, context);
2616 } else if (!s.empty()) {
2617 // LyX adds braces around the argument,
2618 // so we need to remove them here.
2619 if (s.size() > 2 && s[0] == '{' &&
2620 s[s.size()-1] == '}')
2621 s = s.substr(1, s.size()-2);
2622 // If the argument contains a space we
2623 // must put it into ERT: Otherwise LyX
2624 // would misinterpret the space as
2625 // item delimiter (bug 7663)
2626 if (contains(s, ' ')) {
2627 output_ert_inset(os, s, context);
2630 os << parse_text_snippet(p2,
2634 // The space is needed to separate the
2635 // item from the rest of the sentence.
2637 eat_whitespace(p, os, context, false);
2642 else if (t.cs() == "bibitem") {
2644 context.check_layout(os);
2645 eat_whitespace(p, os, context, false);
2646 string label = convert_command_inset_arg(p.verbatimOption());
2647 string key = convert_command_inset_arg(p.verbatim_item());
2648 if (contains(label, '\\') || contains(key, '\\')) {
2649 // LyX can't handle LaTeX commands in labels or keys
2650 output_ert_inset(os, t.asInput() + '[' + label +
2651 "]{" + p.verbatim_item() + '}',
2654 begin_command_inset(os, "bibitem", "bibitem");
2655 os << "label \"" << label << "\"\n"
2656 "key \"" << key << "\"\n";
2661 else if (is_macro(p)) {
2662 // catch the case of \def\inputGnumericTable
2664 if (t.cs() == "def") {
2665 Token second = p.next_token();
2666 if (second.cs() == "inputGnumericTable") {
2670 Token third = p.get_token();
2672 if (third.cs() == "input") {
2676 string name = normalize_filename(p.verbatim_item());
2677 string const path = getMasterFilePath(true);
2678 // We want to preserve relative / absolute filenames,
2679 // therefore path is only used for testing
2680 // The file extension is in every case ".tex".
2681 // So we need to remove this extension and check for
2682 // the original one.
2683 name = removeExtension(name);
2684 if (!makeAbsPath(name, path).exists()) {
2685 char const * const Gnumeric_formats[] = {"gnumeric",
2687 string const Gnumeric_name =
2688 find_file(name, path, Gnumeric_formats);
2689 if (!Gnumeric_name.empty())
2690 name = Gnumeric_name;
2692 FileName const absname = makeAbsPath(name, path);
2693 if (absname.exists()) {
2694 fix_child_filename(name);
2695 copy_file(absname, name);
2697 cerr << "Warning: Could not find file '"
2698 << name << "'." << endl;
2699 context.check_layout(os);
2700 begin_inset(os, "External\n\ttemplate ");
2701 os << "GnumericSpreadsheet\n\tfilename "
2704 context.check_layout(os);
2706 // register the packages that are automatically loaded
2707 // by the Gnumeric template
2708 registerExternalTemplatePackages("GnumericSpreadsheet");
2713 parse_macro(p, os, context);
2716 else if (t.cs() == "noindent") {
2718 context.add_par_extra_stuff("\\noindent\n");
2721 else if (t.cs() == "appendix") {
2722 context.add_par_extra_stuff("\\start_of_appendix\n");
2723 // We need to start a new paragraph. Otherwise the
2724 // appendix in 'bla\appendix\chapter{' would start
2726 context.new_paragraph(os);
2727 // We need to make sure that the paragraph is
2728 // generated even if it is empty. Otherwise the
2729 // appendix in '\par\appendix\par\chapter{' would
2731 context.check_layout(os);
2732 // FIXME: This is a hack to prevent paragraph
2733 // deletion if it is empty. Handle this better!
2734 output_ert_inset(os,
2735 "%dummy comment inserted by tex2lyx to "
2736 "ensure that this paragraph is not empty",
2738 // Both measures above may generate an additional
2739 // empty paragraph, but that does not hurt, because
2740 // whitespace does not matter here.
2741 eat_whitespace(p, os, context, true);
2744 // Must catch empty dates before findLayout is called below
2745 else if (t.cs() == "date") {
2746 eat_whitespace(p, os, context, false);
2748 string const date = p.verbatim_item();
2751 preamble.suppressDate(true);
2754 preamble.suppressDate(false);
2755 if (context.new_layout_allowed &&
2756 (newlayout = findLayout(context.textclass,
2759 output_command_layout(os, p, outer,
2760 context, newlayout);
2761 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2762 if (!preamble.titleLayoutFound())
2763 preamble.titleLayoutFound(newlayout->intitle);
2764 set<string> const & req = newlayout->requires();
2765 set<string>::const_iterator it = req.begin();
2766 set<string>::const_iterator en = req.end();
2767 for (; it != en; ++it)
2768 preamble.registerAutomaticallyLoadedPackage(*it);
2770 output_ert_inset(os,
2771 "\\date{" + p.verbatim_item() + '}',
2776 // Starred section headings
2777 // Must attempt to parse "Section*" before "Section".
2778 else if ((p.next_token().asInput() == "*") &&
2779 context.new_layout_allowed &&
2780 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2783 output_command_layout(os, p, outer, context, newlayout);
2785 if (!preamble.titleLayoutFound())
2786 preamble.titleLayoutFound(newlayout->intitle);
2787 set<string> const & req = newlayout->requires();
2788 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2789 preamble.registerAutomaticallyLoadedPackage(*it);
2792 // Section headings and the like
2793 else if (context.new_layout_allowed &&
2794 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2796 output_command_layout(os, p, outer, context, newlayout);
2798 if (!preamble.titleLayoutFound())
2799 preamble.titleLayoutFound(newlayout->intitle);
2800 set<string> const & req = newlayout->requires();
2801 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2802 preamble.registerAutomaticallyLoadedPackage(*it);
2805 else if (t.cs() == "caption") {
2807 context.check_layout(os);
2809 begin_inset(os, "Caption Standard\n");
2810 Context newcontext(true, context.textclass, 0, 0, context.font);
2811 newcontext.check_layout(os);
2812 // FIXME InsetArgument is now properly implemented in InsetLayout
2813 // (for captions, but also for others)
2814 if (p.next_token().cat() != catEscape &&
2815 p.next_token().character() == '[') {
2816 p.get_token(); // eat '['
2817 begin_inset(os, "Argument 1\n");
2818 os << "status collapsed\n";
2819 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2821 eat_whitespace(p, os, context, false);
2823 parse_text(p, os, FLAG_ITEM, outer, context);
2824 context.check_end_layout(os);
2825 // We don't need really a new paragraph, but
2826 // we must make sure that the next item gets a \begin_layout.
2827 context.new_paragraph(os);
2830 newcontext.check_end_layout(os);
2833 else if (t.cs() == "subfloat") {
2834 // the syntax is \subfloat[caption]{content}
2835 // if it is a table of figure depends on the surrounding float
2836 bool has_caption = false;
2838 // do nothing if there is no outer float
2839 if (!float_type.empty()) {
2840 context.check_layout(os);
2842 begin_inset(os, "Float " + float_type + "\n");
2844 << "\nsideways false"
2845 << "\nstatus collapsed\n\n";
2848 if (p.next_token().cat() != catEscape &&
2849 p.next_token().character() == '[') {
2850 p.get_token(); // eat '['
2851 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2855 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2856 // the caption comes always as the last
2858 // we must make sure that the caption gets a \begin_layout
2859 os << "\n\\begin_layout Plain Layout";
2861 begin_inset(os, "Caption Standard\n");
2862 Context newcontext(true, context.textclass,
2863 0, 0, context.font);
2864 newcontext.check_layout(os);
2865 os << caption << "\n";
2866 newcontext.check_end_layout(os);
2867 // We don't need really a new paragraph, but
2868 // we must make sure that the next item gets a \begin_layout.
2869 //newcontext.new_paragraph(os);
2873 // We don't need really a new paragraph, but
2874 // we must make sure that the next item gets a \begin_layout.
2876 context.new_paragraph(os);
2879 context.check_end_layout(os);
2880 // close the layout we opened
2882 os << "\n\\end_layout\n";
2884 // if the float type is not supported or there is no surrounding float
2887 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2888 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2889 "]{" + p.verbatim_item() + '}', context);
2891 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2895 else if (t.cs() == "includegraphics") {
2896 bool const clip = p.next_token().asInput() == "*";
2899 string const arg = p.getArg('[', ']');
2900 map<string, string> opts;
2901 vector<string> keys;
2902 split_map(arg, opts, keys);
2904 opts["clip"] = string();
2905 string name = normalize_filename(p.verbatim_item());
2907 string const path = getMasterFilePath(true);
2908 // We want to preserve relative / absolute filenames,
2909 // therefore path is only used for testing
2910 if (!makeAbsPath(name, path).exists()) {
2911 // The file extension is probably missing.
2912 // Now try to find it out.
2913 string const dvips_name =
2914 find_file(name, path,
2915 known_dvips_graphics_formats);
2916 string const pdftex_name =
2917 find_file(name, path,
2918 known_pdftex_graphics_formats);
2919 if (!dvips_name.empty()) {
2920 if (!pdftex_name.empty()) {
2921 cerr << "This file contains the "
2923 "\"\\includegraphics{"
2925 "However, files\n\""
2926 << dvips_name << "\" and\n\""
2927 << pdftex_name << "\"\n"
2928 "both exist, so I had to make a "
2929 "choice and took the first one.\n"
2930 "Please move the unwanted one "
2931 "someplace else and try again\n"
2932 "if my choice was wrong."
2936 } else if (!pdftex_name.empty()) {
2942 FileName const absname = makeAbsPath(name, path);
2943 if (absname.exists()) {
2944 fix_child_filename(name);
2945 copy_file(absname, name);
2947 cerr << "Warning: Could not find graphics file '"
2948 << name << "'." << endl;
2950 context.check_layout(os);
2951 begin_inset(os, "Graphics ");
2952 os << "\n\tfilename " << name << '\n';
2953 if (opts.find("width") != opts.end())
2955 << translate_len(opts["width"]) << '\n';
2956 if (opts.find("height") != opts.end())
2958 << translate_len(opts["height"]) << '\n';
2959 if (opts.find("scale") != opts.end()) {
2960 istringstream iss(opts["scale"]);
2964 os << "\tscale " << val << '\n';
2966 if (opts.find("angle") != opts.end()) {
2967 os << "\trotateAngle "
2968 << opts["angle"] << '\n';
2969 vector<string>::const_iterator a =
2970 find(keys.begin(), keys.end(), "angle");
2971 vector<string>::const_iterator s =
2972 find(keys.begin(), keys.end(), "width");
2973 if (s == keys.end())
2974 s = find(keys.begin(), keys.end(), "height");
2975 if (s == keys.end())
2976 s = find(keys.begin(), keys.end(), "scale");
2977 if (s != keys.end() && distance(s, a) > 0)
2978 os << "\tscaleBeforeRotation\n";
2980 if (opts.find("origin") != opts.end()) {
2982 string const opt = opts["origin"];
2983 if (opt.find('l') != string::npos) ss << "left";
2984 if (opt.find('r') != string::npos) ss << "right";
2985 if (opt.find('c') != string::npos) ss << "center";
2986 if (opt.find('t') != string::npos) ss << "Top";
2987 if (opt.find('b') != string::npos) ss << "Bottom";
2988 if (opt.find('B') != string::npos) ss << "Baseline";
2989 if (!ss.str().empty())
2990 os << "\trotateOrigin " << ss.str() << '\n';
2992 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2994 if (opts.find("keepaspectratio") != opts.end())
2995 os << "\tkeepAspectRatio\n";
2996 if (opts.find("clip") != opts.end())
2998 if (opts.find("draft") != opts.end())
3000 if (opts.find("bb") != opts.end())
3001 os << "\tBoundingBox "
3002 << opts["bb"] << '\n';
3003 int numberOfbbOptions = 0;
3004 if (opts.find("bbllx") != opts.end())
3005 numberOfbbOptions++;
3006 if (opts.find("bblly") != opts.end())
3007 numberOfbbOptions++;
3008 if (opts.find("bburx") != opts.end())
3009 numberOfbbOptions++;
3010 if (opts.find("bbury") != opts.end())
3011 numberOfbbOptions++;
3012 if (numberOfbbOptions == 4)
3013 os << "\tBoundingBox "
3014 << opts["bbllx"] << " " << opts["bblly"] << " "
3015 << opts["bburx"] << " " << opts["bbury"] << '\n';
3016 else if (numberOfbbOptions > 0)
3017 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3018 numberOfbbOptions = 0;
3019 if (opts.find("natwidth") != opts.end())
3020 numberOfbbOptions++;
3021 if (opts.find("natheight") != opts.end())
3022 numberOfbbOptions++;
3023 if (numberOfbbOptions == 2)
3024 os << "\tBoundingBox 0bp 0bp "
3025 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3026 else if (numberOfbbOptions > 0)
3027 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3028 ostringstream special;
3029 if (opts.find("hiresbb") != opts.end())
3030 special << "hiresbb,";
3031 if (opts.find("trim") != opts.end())
3033 if (opts.find("viewport") != opts.end())
3034 special << "viewport=" << opts["viewport"] << ',';
3035 if (opts.find("totalheight") != opts.end())
3036 special << "totalheight=" << opts["totalheight"] << ',';
3037 if (opts.find("type") != opts.end())
3038 special << "type=" << opts["type"] << ',';
3039 if (opts.find("ext") != opts.end())
3040 special << "ext=" << opts["ext"] << ',';
3041 if (opts.find("read") != opts.end())
3042 special << "read=" << opts["read"] << ',';
3043 if (opts.find("command") != opts.end())
3044 special << "command=" << opts["command"] << ',';
3045 string s_special = special.str();
3046 if (!s_special.empty()) {
3047 // We had special arguments. Remove the trailing ','.
3048 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3050 // TODO: Handle the unknown settings better.
3051 // Warn about invalid options.
3052 // Check whether some option was given twice.
3054 preamble.registerAutomaticallyLoadedPackage("graphicx");
3057 else if (t.cs() == "footnote" ||
3058 (t.cs() == "thanks" && context.layout->intitle)) {
3060 context.check_layout(os);
3061 begin_inset(os, "Foot\n");
3062 os << "status collapsed\n\n";
3063 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3067 else if (t.cs() == "marginpar") {
3069 context.check_layout(os);
3070 begin_inset(os, "Marginal\n");
3071 os << "status collapsed\n\n";
3072 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3076 else if (t.cs() == "lstinline") {
3078 parse_listings(p, os, context, true);
3081 else if (t.cs() == "ensuremath") {
3083 context.check_layout(os);
3084 string const s = p.verbatim_item();
3085 //FIXME: this never triggers in UTF8
3086 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3089 output_ert_inset(os, "\\ensuremath{" + s + "}",
3093 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3094 if (preamble.titleLayoutFound()) {
3096 skip_spaces_braces(p);
3098 output_ert_inset(os, t.asInput(), context);
3101 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3102 context.check_layout(os);
3103 begin_command_inset(os, "toc", t.cs());
3105 skip_spaces_braces(p);
3106 if (t.cs() == "lstlistoflistings")
3107 preamble.registerAutomaticallyLoadedPackage("listings");
3110 else if (t.cs() == "listoffigures") {
3111 context.check_layout(os);
3112 begin_inset(os, "FloatList figure\n");
3114 skip_spaces_braces(p);
3117 else if (t.cs() == "listoftables") {
3118 context.check_layout(os);
3119 begin_inset(os, "FloatList table\n");
3121 skip_spaces_braces(p);
3124 else if (t.cs() == "listof") {
3125 p.skip_spaces(true);
3126 string const name = p.get_token().cs();
3127 if (context.textclass.floats().typeExist(name)) {
3128 context.check_layout(os);
3129 begin_inset(os, "FloatList ");
3132 p.get_token(); // swallow second arg
3134 output_ert_inset(os, "\\listof{" + name + "}", context);
3137 else if ((where = is_known(t.cs(), known_text_font_families)))
3138 parse_text_attributes(p, os, FLAG_ITEM, outer,
3139 context, "\\family", context.font.family,
3140 known_coded_font_families[where - known_text_font_families]);
3142 else if ((where = is_known(t.cs(), known_text_font_series)))
3143 parse_text_attributes(p, os, FLAG_ITEM, outer,
3144 context, "\\series", context.font.series,
3145 known_coded_font_series[where - known_text_font_series]);
3147 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3148 parse_text_attributes(p, os, FLAG_ITEM, outer,
3149 context, "\\shape", context.font.shape,
3150 known_coded_font_shapes[where - known_text_font_shapes]);
3152 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3153 context.check_layout(os);
3154 TeXFont oldFont = context.font;
3155 context.font.init();
3156 context.font.size = oldFont.size;
3157 os << "\n\\family " << context.font.family << "\n";
3158 os << "\n\\series " << context.font.series << "\n";
3159 os << "\n\\shape " << context.font.shape << "\n";
3160 if (t.cs() == "textnormal") {
3161 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3162 output_font_change(os, context.font, oldFont);
3163 context.font = oldFont;
3165 eat_whitespace(p, os, context, false);
3168 else if (t.cs() == "textcolor") {
3169 // scheme is \textcolor{color name}{text}
3170 string const color = p.verbatim_item();
3171 // we only support the predefined colors of the color package
3172 if (color == "black" || color == "blue" || color == "cyan"
3173 || color == "green" || color == "magenta" || color == "red"
3174 || color == "white" || color == "yellow") {
3175 context.check_layout(os);
3176 os << "\n\\color " << color << "\n";
3177 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3178 context.check_layout(os);
3179 os << "\n\\color inherit\n";
3180 preamble.registerAutomaticallyLoadedPackage("color");
3182 // for custom defined colors
3183 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3186 else if (t.cs() == "underbar" || t.cs() == "uline") {
3187 // \underbar is not 100% correct (LyX outputs \uline
3188 // of ulem.sty). The difference is that \ulem allows
3189 // line breaks, and \underbar does not.
3190 // Do NOT handle \underline.
3191 // \underbar cuts through y, g, q, p etc.,
3192 // \underline does not.
3193 context.check_layout(os);
3194 os << "\n\\bar under\n";
3195 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3196 context.check_layout(os);
3197 os << "\n\\bar default\n";
3198 preamble.registerAutomaticallyLoadedPackage("ulem");
3201 else if (t.cs() == "sout") {
3202 context.check_layout(os);
3203 os << "\n\\strikeout on\n";
3204 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3205 context.check_layout(os);
3206 os << "\n\\strikeout default\n";
3207 preamble.registerAutomaticallyLoadedPackage("ulem");
3210 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3211 t.cs() == "emph" || t.cs() == "noun") {
3212 context.check_layout(os);
3213 os << "\n\\" << t.cs() << " on\n";
3214 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3215 context.check_layout(os);
3216 os << "\n\\" << t.cs() << " default\n";
3217 if (t.cs() == "uuline" || t.cs() == "uwave")
3218 preamble.registerAutomaticallyLoadedPackage("ulem");
3221 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3222 context.check_layout(os);
3223 string name = p.getArg('{', '}');
3224 string localtime = p.getArg('{', '}');
3225 preamble.registerAuthor(name);
3226 Author const & author = preamble.getAuthor(name);
3227 // from_asctime_utc() will fail if LyX decides to output the
3228 // time in the text language.
3229 time_t ptime = from_asctime_utc(localtime);
3230 if (ptime == static_cast<time_t>(-1)) {
3231 cerr << "Warning: Could not parse time `" << localtime
3232 << "´ for change tracking, using current time instead.\n";
3233 ptime = current_time();
3235 if (t.cs() == "lyxadded")
3236 os << "\n\\change_inserted ";
3238 os << "\n\\change_deleted ";
3239 os << author.bufferId() << ' ' << ptime << '\n';
3240 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3241 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3242 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3243 LaTeXPackages::isAvailable("xcolor");
3244 // No need to test for luatex, since luatex comes in
3245 // two flavours (dvi and pdf), like latex, and those
3246 // are detected by pdflatex.
3247 if (pdflatex || xetex) {
3249 preamble.registerAutomaticallyLoadedPackage("ulem");
3250 preamble.registerAutomaticallyLoadedPackage("xcolor");
3251 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3255 preamble.registerAutomaticallyLoadedPackage("dvipost");
3256 } else if (xcolorulem) {
3257 preamble.registerAutomaticallyLoadedPackage("ulem");
3258 preamble.registerAutomaticallyLoadedPackage("xcolor");
3263 else if (t.cs() == "textipa") {
3264 context.check_layout(os);
3265 begin_inset(os, "IPA\n");
3266 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3268 preamble.registerAutomaticallyLoadedPackage("tipa");
3269 preamble.registerAutomaticallyLoadedPackage("tipx");
3272 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3273 context.check_layout(os);
3274 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3275 os << "status open\n";
3276 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3281 // the TIPA Combining diacritical marks
3282 else if (is_known(t.cs(), known_tipa_marks) || t.cs() == "textvertline") {
3283 preamble.registerAutomaticallyLoadedPackage("tipa");
3284 preamble.registerAutomaticallyLoadedPackage("tipx");
3285 context.check_layout(os);
3286 if (t.cs() == "textvertline") {
3291 // try to see whether the string is in unicodesymbols
3294 string content = trimSpaceAndEol(p.verbatim_item());
3295 string command = t.asInput() + "{" + content + "}";
3297 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3298 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3299 termination, rem, &req);
3302 cerr << "When parsing " << command
3303 << ", result is " << to_utf8(s)
3304 << "+" << to_utf8(rem) << endl;
3305 os << content << to_utf8(s);
3307 // we did not find a non-ert version
3308 output_ert_inset(os, command, context);
3311 else if (t.cs() == "tone" ) {
3312 context.check_layout(os);
3313 // register the tone package
3314 preamble.registerAutomaticallyLoadedPackage("tone");
3315 string content = trimSpaceAndEol(p.verbatim_item());
3316 string command = t.asInput() + "{" + content + "}";
3317 // some tones can be detected by unicodesymbols, some need special code
3318 if (is_known(content, known_tones)) {
3319 os << "\\IPAChar " << command << "\n";
3322 // try to see whether the string is in unicodesymbols
3326 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3327 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3328 termination, rem, &req);
3331 cerr << "When parsing " << command
3332 << ", result is " << to_utf8(s)
3333 << "+" << to_utf8(rem) << endl;
3336 // we did not find a non-ert version
3337 output_ert_inset(os, command, context);
3340 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3341 t.cs() == "vphantom") {
3342 context.check_layout(os);
3343 if (t.cs() == "phantom")
3344 begin_inset(os, "Phantom Phantom\n");
3345 if (t.cs() == "hphantom")
3346 begin_inset(os, "Phantom HPhantom\n");
3347 if (t.cs() == "vphantom")
3348 begin_inset(os, "Phantom VPhantom\n");
3349 os << "status open\n";
3350 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3355 else if (t.cs() == "href") {
3356 context.check_layout(os);
3357 string target = convert_command_inset_arg(p.verbatim_item());
3358 string name = convert_command_inset_arg(p.verbatim_item());
3360 size_t i = target.find(':');
3361 if (i != string::npos) {
3362 type = target.substr(0, i + 1);
3363 if (type == "mailto:" || type == "file:")
3364 target = target.substr(i + 1);
3365 // handle the case that name is equal to target, except of "http://"
3366 else if (target.substr(i + 3) == name && type == "http:")
3369 begin_command_inset(os, "href", "href");
3371 os << "name \"" << name << "\"\n";
3372 os << "target \"" << target << "\"\n";
3373 if (type == "mailto:" || type == "file:")
3374 os << "type \"" << type << "\"\n";
3376 skip_spaces_braces(p);
3379 else if (t.cs() == "lyxline") {
3380 // swallow size argument (it is not used anyway)
3382 if (!context.atParagraphStart()) {
3383 // so our line is in the middle of a paragraph
3384 // we need to add a new line, lest this line
3385 // follow the other content on that line and
3386 // run off the side of the page
3387 // FIXME: This may create an empty paragraph,
3388 // but without that it would not be
3389 // possible to set noindent below.
3390 // Fortunately LaTeX does not care
3391 // about the empty paragraph.
3392 context.new_paragraph(os);
3394 if (preamble.indentParagraphs()) {
3395 // we need to unindent, lest the line be too long
3396 context.add_par_extra_stuff("\\noindent\n");
3398 context.check_layout(os);
3399 begin_command_inset(os, "line", "rule");
3400 os << "offset \"0.5ex\"\n"
3401 "width \"100line%\"\n"
3406 else if (t.cs() == "rule") {
3407 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3408 string const width = p.getArg('{', '}');
3409 string const thickness = p.getArg('{', '}');
3410 context.check_layout(os);
3411 begin_command_inset(os, "line", "rule");
3412 if (!offset.empty())
3413 os << "offset \"" << translate_len(offset) << "\"\n";
3414 os << "width \"" << translate_len(width) << "\"\n"
3415 "height \"" << translate_len(thickness) << "\"\n";
3419 else if (is_known(t.cs(), known_phrases) ||
3420 (t.cs() == "protect" &&
3421 p.next_token().cat() == catEscape &&
3422 is_known(p.next_token().cs(), known_phrases))) {
3423 // LyX sometimes puts a \protect in front, so we have to ignore it
3424 // FIXME: This needs to be changed when bug 4752 is fixed.
3426 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3428 context.check_layout(os);
3429 os << known_coded_phrases[where - known_phrases];
3430 skip_spaces_braces(p);
3433 else if ((where = is_known(t.cs(), known_ref_commands))) {
3434 // \eqref can also occur if refstyle is used
3435 if (t.cs() == "eqref" && preamble.refstyle() == "1") {
3436 context.check_layout(os);
3437 begin_command_inset(os, "ref", "formatted");
3438 os << "reference \"eq:"
3439 << convert_command_inset_arg(p.verbatim_item())
3442 preamble.registerAutomaticallyLoadedPackage("refstyle");
3444 string const opt = p.getOpt();
3446 context.check_layout(os);
3447 begin_command_inset(os, "ref",
3448 known_coded_ref_commands[where - known_ref_commands]);
3449 os << "reference \""
3450 << convert_command_inset_arg(p.verbatim_item())
3453 if (t.cs() == "vref" || t.cs() == "vpageref")
3454 preamble.registerAutomaticallyLoadedPackage("varioref");
3456 // LyX does not yet support optional arguments of ref commands
3457 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3458 p.verbatim_item() + "}", context);
3463 else if ((where = is_known(t.cs(), known_refstyle_commands))) {
3464 context.check_layout(os);
3465 // \eqref can also occur if refstyle is not used
3466 // this case is already handled in the previous else if
3467 begin_command_inset(os, "ref", "formatted");
3468 os << "reference \"";
3469 os << known_refstyle_prefixes[where - known_refstyle_commands]
3471 os << convert_command_inset_arg(p.verbatim_item())
3474 preamble.registerAutomaticallyLoadedPackage("refstyle");
3477 else if (use_natbib &&
3478 is_known(t.cs(), known_natbib_commands) &&
3479 ((t.cs() != "citefullauthor" &&
3480 t.cs() != "citeyear" &&
3481 t.cs() != "citeyearpar") ||
3482 p.next_token().asInput() != "*")) {
3483 context.check_layout(os);
3484 string command = t.cs();
3485 if (p.next_token().asInput() == "*") {
3489 if (command == "citefullauthor")
3490 // alternative name for "\\citeauthor*"
3491 command = "citeauthor*";
3493 // text before the citation
3495 // text after the citation
3497 get_cite_arguments(p, true, before, after);
3499 if (command == "cite") {
3500 // \cite without optional argument means
3501 // \citet, \cite with at least one optional
3502 // argument means \citep.
3503 if (before.empty() && after.empty())
3508 if (before.empty() && after == "[]")
3509 // avoid \citet[]{a}
3511 else if (before == "[]" && after == "[]") {
3512 // avoid \citet[][]{a}
3516 // remove the brackets around after and before
3517 if (!after.empty()) {
3519 after.erase(after.length() - 1, 1);
3520 after = convert_command_inset_arg(after);
3522 if (!before.empty()) {
3524 before.erase(before.length() - 1, 1);
3525 before = convert_command_inset_arg(before);
3527 begin_command_inset(os, "citation", command);
3528 os << "after " << '"' << after << '"' << "\n";
3529 os << "before " << '"' << before << '"' << "\n";
3531 << convert_command_inset_arg(p.verbatim_item())
3534 // Need to set the cite engine if natbib is loaded by
3535 // the document class directly
3536 if (preamble.citeEngine() == "basic")
3537 preamble.citeEngine("natbib");
3540 else if (use_jurabib &&
3541 is_known(t.cs(), known_jurabib_commands) &&
3542 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3543 context.check_layout(os);
3544 string command = t.cs();
3545 if (p.next_token().asInput() == "*") {
3549 char argumentOrder = '\0';
3550 vector<string> const options =
3551 preamble.getPackageOptions("jurabib");
3552 if (find(options.begin(), options.end(),
3553 "natbiborder") != options.end())
3554 argumentOrder = 'n';
3555 else if (find(options.begin(), options.end(),
3556 "jurabiborder") != options.end())
3557 argumentOrder = 'j';
3559 // text before the citation
3561 // text after the citation
3563 get_cite_arguments(p, argumentOrder != 'j', before, after);
3565 string const citation = p.verbatim_item();
3566 if (!before.empty() && argumentOrder == '\0') {
3567 cerr << "Warning: Assuming argument order "
3568 "of jurabib version 0.6 for\n'"
3569 << command << before << after << '{'
3570 << citation << "}'.\n"
3571 "Add 'jurabiborder' to the jurabib "
3572 "package options if you used an\n"
3573 "earlier jurabib version." << endl;
3575 if (!after.empty()) {
3577 after.erase(after.length() - 1, 1);
3579 if (!before.empty()) {
3581 before.erase(before.length() - 1, 1);
3583 begin_command_inset(os, "citation", command);
3584 os << "after " << '"' << after << '"' << "\n";
3585 os << "before " << '"' << before << '"' << "\n";
3586 os << "key " << '"' << citation << '"' << "\n";
3588 // Need to set the cite engine if jurabib is loaded by
3589 // the document class directly
3590 if (preamble.citeEngine() == "basic")
3591 preamble.citeEngine("jurabib");
3594 else if (t.cs() == "cite"
3595 || t.cs() == "nocite") {
3596 context.check_layout(os);
3597 string after = convert_command_inset_arg(p.getArg('[', ']'));
3598 string key = convert_command_inset_arg(p.verbatim_item());
3599 // store the case that it is "\nocite{*}" to use it later for
3602 begin_command_inset(os, "citation", t.cs());
3603 os << "after " << '"' << after << '"' << "\n";
3604 os << "key " << '"' << key << '"' << "\n";
3606 } else if (t.cs() == "nocite")
3610 else if (t.cs() == "index" ||
3611 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3612 context.check_layout(os);
3613 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3614 p.getArg('[', ']') : "";
3615 string const kind = arg.empty() ? "idx" : arg;
3616 begin_inset(os, "Index ");
3617 os << kind << "\nstatus collapsed\n";
3618 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3621 preamble.registerAutomaticallyLoadedPackage("splitidx");
3624 else if (t.cs() == "nomenclature") {
3625 context.check_layout(os);
3626 begin_command_inset(os, "nomenclature", "nomenclature");
3627 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3628 if (!prefix.empty())
3629 os << "prefix " << '"' << prefix << '"' << "\n";
3630 os << "symbol " << '"'
3631 << convert_command_inset_arg(p.verbatim_item());
3632 os << "\"\ndescription \""
3633 << convert_command_inset_arg(p.verbatim_item())
3636 preamble.registerAutomaticallyLoadedPackage("nomencl");
3639 else if (t.cs() == "label") {
3640 context.check_layout(os);
3641 begin_command_inset(os, "label", "label");
3643 << convert_command_inset_arg(p.verbatim_item())
3648 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3649 context.check_layout(os);
3650 string commandname = t.cs();
3652 if (p.next_token().asInput() == "*") {
3657 begin_command_inset(os, "index_print", commandname);
3658 string const indexname = p.getArg('[', ']');
3660 if (indexname.empty())
3661 os << "type \"idx\"\n";
3663 os << "type \"" << indexname << "\"\n";
3666 skip_spaces_braces(p);
3667 preamble.registerAutomaticallyLoadedPackage("makeidx");
3668 if (preamble.use_indices() == "true")
3669 preamble.registerAutomaticallyLoadedPackage("splitidx");
3672 else if (t.cs() == "printnomenclature") {
3674 string width_type = "";
3675 context.check_layout(os);
3676 begin_command_inset(os, "nomencl_print", "printnomenclature");
3677 // case of a custom width
3679 width = p.getArg('[', ']');
3680 width = translate_len(width);
3681 width_type = "custom";
3683 // case of no custom width
3684 // the case of no custom width but the width set
3685 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3686 // because the user could have set anything, not only the width
3687 // of the longest label (which would be width_type = "auto")
3688 string label = convert_command_inset_arg(p.getArg('{', '}'));
3689 if (label.empty() && width_type.empty())
3690 width_type = "none";
3691 os << "set_width \"" << width_type << "\"\n";
3692 if (width_type == "custom")
3693 os << "width \"" << width << '\"';
3695 skip_spaces_braces(p);
3696 preamble.registerAutomaticallyLoadedPackage("nomencl");
3699 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3700 context.check_layout(os);
3701 begin_inset(os, "script ");
3702 os << t.cs().substr(4) << '\n';
3703 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3705 if (t.cs() == "textsubscript")
3706 preamble.registerAutomaticallyLoadedPackage("subscript");
3709 else if ((where = is_known(t.cs(), known_quotes))) {
3710 context.check_layout(os);
3711 begin_inset(os, "Quotes ");
3712 os << known_coded_quotes[where - known_quotes];
3714 // LyX adds {} after the quote, so we have to eat
3715 // spaces here if there are any before a possible
3717 eat_whitespace(p, os, context, false);
3721 else if ((where = is_known(t.cs(), known_sizes)) &&
3722 context.new_layout_allowed) {
3723 context.check_layout(os);
3724 TeXFont const oldFont = context.font;
3725 context.font.size = known_coded_sizes[where - known_sizes];
3726 output_font_change(os, oldFont, context.font);
3727 eat_whitespace(p, os, context, false);
3730 else if ((where = is_known(t.cs(), known_font_families)) &&
3731 context.new_layout_allowed) {
3732 context.check_layout(os);
3733 TeXFont const oldFont = context.font;
3734 context.font.family =
3735 known_coded_font_families[where - known_font_families];
3736 output_font_change(os, oldFont, context.font);
3737 eat_whitespace(p, os, context, false);
3740 else if ((where = is_known(t.cs(), known_font_series)) &&
3741 context.new_layout_allowed) {
3742 context.check_layout(os);
3743 TeXFont const oldFont = context.font;
3744 context.font.series =
3745 known_coded_font_series[where - known_font_series];
3746 output_font_change(os, oldFont, context.font);
3747 eat_whitespace(p, os, context, false);
3750 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3751 context.new_layout_allowed) {
3752 context.check_layout(os);
3753 TeXFont const oldFont = context.font;
3754 context.font.shape =
3755 known_coded_font_shapes[where - known_font_shapes];
3756 output_font_change(os, oldFont, context.font);
3757 eat_whitespace(p, os, context, false);
3759 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3760 context.new_layout_allowed) {
3761 context.check_layout(os);
3762 TeXFont const oldFont = context.font;
3763 context.font.init();
3764 context.font.size = oldFont.size;
3765 context.font.family =
3766 known_coded_font_families[where - known_old_font_families];
3767 output_font_change(os, oldFont, context.font);
3768 eat_whitespace(p, os, context, false);
3771 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3772 context.new_layout_allowed) {
3773 context.check_layout(os);
3774 TeXFont const oldFont = context.font;
3775 context.font.init();
3776 context.font.size = oldFont.size;
3777 context.font.series =
3778 known_coded_font_series[where - known_old_font_series];
3779 output_font_change(os, oldFont, context.font);
3780 eat_whitespace(p, os, context, false);
3783 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3784 context.new_layout_allowed) {
3785 context.check_layout(os);
3786 TeXFont const oldFont = context.font;
3787 context.font.init();
3788 context.font.size = oldFont.size;
3789 context.font.shape =
3790 known_coded_font_shapes[where - known_old_font_shapes];
3791 output_font_change(os, oldFont, context.font);
3792 eat_whitespace(p, os, context, false);
3795 else if (t.cs() == "selectlanguage") {
3796 context.check_layout(os);
3797 // save the language for the case that a
3798 // \foreignlanguage is used
3799 context.font.language = babel2lyx(p.verbatim_item());
3800 os << "\n\\lang " << context.font.language << "\n";
3803 else if (t.cs() == "foreignlanguage") {
3804 string const lang = babel2lyx(p.verbatim_item());
3805 parse_text_attributes(p, os, FLAG_ITEM, outer,
3807 context.font.language, lang);
3810 else if (prefixIs(t.cs(), "text")
3811 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3812 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3814 // We have to output the whole command if it has an option
3815 // because LyX doesn't support this yet, see bug #8214,
3816 // only if there is a single option specifying a variant, we can handle it.
3818 string langopts = p.getOpt();
3819 // check if the option contains a variant, if yes, extract it
3820 string::size_type pos_var = langopts.find("variant");
3821 string::size_type i = langopts.find(',');
3822 string::size_type k = langopts.find('=', pos_var);
3823 if (pos_var != string::npos && i == string::npos) {
3825 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3826 lang = preamble.polyglossia2lyx(variant);
3827 parse_text_attributes(p, os, FLAG_ITEM, outer,
3829 context.font.language, lang);
3831 output_ert_inset(os, t.asInput() + langopts, context);
3833 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3834 parse_text_attributes(p, os, FLAG_ITEM, outer,
3836 context.font.language, lang);
3840 else if (t.cs() == "inputencoding") {
3841 // nothing to write here
3842 string const enc = subst(p.verbatim_item(), "\n", " ");
3843 p.setEncoding(enc, Encoding::inputenc);
3846 else if ((where = is_known(t.cs(), known_special_chars))) {
3847 context.check_layout(os);
3848 os << "\\SpecialChar \\"
3849 << known_coded_special_chars[where - known_special_chars]
3851 skip_spaces_braces(p);
3854 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3855 context.check_layout(os);
3856 os << "\\SpecialChar \\nobreakdash-\n";
3860 else if (t.cs() == "textquotedbl") {
3861 context.check_layout(os);
3866 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3867 context.check_layout(os);
3868 os << "\\SpecialChar \\@.\n";
3872 else if (t.cs() == "-") {
3873 context.check_layout(os);
3874 os << "\\SpecialChar \\-\n";
3877 else if (t.cs() == "textasciitilde") {
3878 context.check_layout(os);
3880 skip_spaces_braces(p);
3883 else if (t.cs() == "textasciicircum") {
3884 context.check_layout(os);
3886 skip_spaces_braces(p);
3889 else if (t.cs() == "textbackslash") {
3890 context.check_layout(os);
3891 os << "\n\\backslash\n";
3892 skip_spaces_braces(p);
3895 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3896 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3898 context.check_layout(os);
3902 else if (t.cs() == "char") {
3903 context.check_layout(os);
3904 if (p.next_token().character() == '`') {
3906 if (p.next_token().cs() == "\"") {
3911 output_ert_inset(os, "\\char`", context);
3914 output_ert_inset(os, "\\char", context);
3918 else if (t.cs() == "verb") {
3919 context.check_layout(os);
3920 // set catcodes to verbatim early, just in case.
3921 p.setCatcodes(VERBATIM_CATCODES);
3922 string delim = p.get_token().asInput();
3923 string const arg = p.verbatimStuff(delim);
3924 output_ert_inset(os, "\\verb" + delim + arg + delim, context);
3927 // Problem: \= creates a tabstop inside the tabbing environment
3928 // and else an accent. In the latter case we really would want
3929 // \={o} instead of \= o.
3930 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3931 output_ert_inset(os, t.asInput(), context);
3933 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3934 else if (t.cs().size() == 1
3935 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3936 context.check_layout(os);
3937 // try to see whether the string is in unicodesymbols
3940 string command = t.asInput() + "{"
3941 + trimSpaceAndEol(p.verbatim_item())
3944 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3945 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3946 termination, rem, &req);
3949 cerr << "When parsing " << command
3950 << ", result is " << to_utf8(s)
3951 << "+" << to_utf8(rem) << endl;
3953 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3954 preamble.registerAutomaticallyLoadedPackage(*it);
3956 // we did not find a non-ert version
3957 output_ert_inset(os, command, context);
3960 else if (t.cs() == "\\") {
3961 context.check_layout(os);
3963 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3964 else if (p.next_token().asInput() == "*") {
3966 // getOpt() eats the following space if there
3967 // is no optional argument, but that is OK
3968 // here since it has no effect in the output.
3969 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3972 begin_inset(os, "Newline newline");
3977 else if (t.cs() == "newline" ||
3978 (t.cs() == "linebreak" && !p.hasOpt())) {
3979 context.check_layout(os);
3980 begin_inset(os, "Newline ");
3983 skip_spaces_braces(p);
3986 else if (t.cs() == "input" || t.cs() == "include"
3987 || t.cs() == "verbatiminput") {
3988 string name = t.cs();
3989 if (t.cs() == "verbatiminput"
3990 && p.next_token().asInput() == "*")
3991 name += p.get_token().asInput();
3992 context.check_layout(os);
3993 string filename(normalize_filename(p.getArg('{', '}')));
3994 string const path = getMasterFilePath(true);
3995 // We want to preserve relative / absolute filenames,
3996 // therefore path is only used for testing
3997 if ((t.cs() == "include" || t.cs() == "input") &&
3998 !makeAbsPath(filename, path).exists()) {
3999 // The file extension is probably missing.
4000 // Now try to find it out.
4001 string const tex_name =
4002 find_file(filename, path,
4003 known_tex_extensions);
4004 if (!tex_name.empty())
4005 filename = tex_name;
4007 bool external = false;
4009 if (makeAbsPath(filename, path).exists()) {
4010 string const abstexname =
4011 makeAbsPath(filename, path).absFileName();
4012 string const absfigname =
4013 changeExtension(abstexname, ".fig");
4014 fix_child_filename(filename);
4015 string const lyxname =
4016 changeExtension(filename, ".lyx");
4017 string const abslyxname = makeAbsPath(
4018 lyxname, getParentFilePath(false)).absFileName();
4020 if (!skipChildren())
4021 external = FileName(absfigname).exists();
4022 if (t.cs() == "input" && !skipChildren()) {
4023 string const ext = getExtension(abstexname);
4025 // Combined PS/LaTeX:
4026 // x.eps, x.pstex_t (old xfig)
4027 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4028 FileName const absepsname(
4029 changeExtension(abstexname, ".eps"));
4030 FileName const abspstexname(
4031 changeExtension(abstexname, ".pstex"));
4032 bool const xfigeps =
4033 (absepsname.exists() ||
4034 abspstexname.exists()) &&
4037 // Combined PDF/LaTeX:
4038 // x.pdf, x.pdftex_t (old xfig)
4039 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4040 FileName const abspdfname(
4041 changeExtension(abstexname, ".pdf"));
4042 bool const xfigpdf =
4043 abspdfname.exists() &&
4044 (ext == "pdftex_t" || ext == "pdf_t");
4048 // Combined PS/PDF/LaTeX:
4049 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4050 string const absbase2(
4051 removeExtension(abstexname) + "_pspdftex");
4052 FileName const abseps2name(
4053 addExtension(absbase2, ".eps"));
4054 FileName const abspdf2name(
4055 addExtension(absbase2, ".pdf"));
4056 bool const xfigboth =
4057 abspdf2name.exists() &&
4058 abseps2name.exists() && ext == "pspdftex";
4060 xfig = xfigpdf || xfigeps || xfigboth;
4061 external = external && xfig;
4064 outname = changeExtension(filename, ".fig");
4065 FileName abssrc(changeExtension(abstexname, ".fig"));
4066 copy_file(abssrc, outname);
4068 // Don't try to convert, the result
4069 // would be full of ERT.
4071 FileName abssrc(abstexname);
4072 copy_file(abssrc, outname);
4073 } else if (t.cs() != "verbatiminput" &&
4075 tex2lyx(abstexname, FileName(abslyxname),
4078 // no need to call copy_file
4079 // tex2lyx creates the file
4082 FileName abssrc(abstexname);
4083 copy_file(abssrc, outname);
4086 cerr << "Warning: Could not find included file '"
4087 << filename << "'." << endl;
4091 begin_inset(os, "External\n");
4092 os << "\ttemplate XFig\n"
4093 << "\tfilename " << outname << '\n';
4094 registerExternalTemplatePackages("XFig");
4096 begin_command_inset(os, "include", name);
4097 outname = subst(outname, "\"", "\\\"");
4098 os << "preview false\n"
4099 "filename \"" << outname << "\"\n";
4100 if (t.cs() == "verbatiminput")
4101 preamble.registerAutomaticallyLoadedPackage("verbatim");
4106 else if (t.cs() == "bibliographystyle") {
4107 // store new bibliographystyle
4108 bibliographystyle = p.verbatim_item();
4109 // If any other command than \bibliography, \addcontentsline
4110 // and \nocite{*} follows, we need to output the style
4111 // (because it might be used by that command).
4112 // Otherwise, it will automatically be output by LyX.
4115 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4116 if (t2.cat() == catBegin)
4118 if (t2.cat() != catEscape)
4120 if (t2.cs() == "nocite") {
4121 if (p.getArg('{', '}') == "*")
4123 } else if (t2.cs() == "bibliography")
4125 else if (t2.cs() == "phantomsection") {
4129 else if (t2.cs() == "addcontentsline") {
4130 // get the 3 arguments of \addcontentsline
4133 contentslineContent = p.getArg('{', '}');
4134 // if the last argument is not \refname we must output
4135 if (contentslineContent == "\\refname")
4142 output_ert_inset(os,
4143 "\\bibliographystyle{" + bibliographystyle + '}',
4148 else if (t.cs() == "phantomsection") {
4149 // we only support this if it occurs between
4150 // \bibliographystyle and \bibliography
4151 if (bibliographystyle.empty())
4152 output_ert_inset(os, "\\phantomsection", context);
4155 else if (t.cs() == "addcontentsline") {
4156 context.check_layout(os);
4157 // get the 3 arguments of \addcontentsline
4158 string const one = p.getArg('{', '}');
4159 string const two = p.getArg('{', '}');
4160 string const three = p.getArg('{', '}');
4161 // only if it is a \refname, we support if for the bibtex inset
4162 if (contentslineContent != "\\refname") {
4163 output_ert_inset(os,
4164 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4169 else if (t.cs() == "bibliography") {
4170 context.check_layout(os);
4172 begin_command_inset(os, "bibtex", "bibtex");
4173 if (!btprint.empty()) {
4174 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4175 // clear the string because the next BibTeX inset can be without the
4176 // \nocite{*} option
4179 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4180 // Do we have addcontentsline?
4181 if (contentslineContent == "\\refname") {
4182 BibOpts = "bibtotoc";
4183 // clear string because next BibTeX inset can be without addcontentsline
4184 contentslineContent.clear();
4186 // Do we have a bibliographystyle set?
4187 if (!bibliographystyle.empty()) {
4188 if (BibOpts.empty())
4189 BibOpts = bibliographystyle;
4191 BibOpts = BibOpts + ',' + bibliographystyle;
4192 // clear it because each bibtex entry has its style
4193 // and we need an empty string to handle \phantomsection
4194 bibliographystyle.clear();
4196 os << "options " << '"' << BibOpts << '"' << "\n";
4200 else if (t.cs() == "parbox") {
4201 // Test whether this is an outer box of a shaded box
4203 // swallow arguments
4204 while (p.hasOpt()) {
4206 p.skip_spaces(true);
4209 p.skip_spaces(true);
4211 if (p.next_token().cat() == catBegin)
4213 p.skip_spaces(true);
4214 Token to = p.get_token();
4215 bool shaded = false;
4216 if (to.asInput() == "\\begin") {
4217 p.skip_spaces(true);
4218 if (p.getArg('{', '}') == "shaded")
4223 parse_outer_box(p, os, FLAG_ITEM, outer,
4224 context, "parbox", "shaded");
4226 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4230 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4231 t.cs() == "shadowbox" || t.cs() == "doublebox")
4232 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4234 else if (t.cs() == "framebox") {
4235 if (p.next_token().character() == '(') {
4236 //the syntax is: \framebox(x,y)[position]{content}
4237 string arg = t.asInput();
4238 arg += p.getFullParentheseArg();
4239 arg += p.getFullOpt();
4240 eat_whitespace(p, os, context, false);
4241 output_ert_inset(os, arg + '{', context);
4242 parse_text(p, os, FLAG_ITEM, outer, context);
4243 output_ert_inset(os, "}", context);
4245 string special = p.getFullOpt();
4246 special += p.getOpt();
4247 // LyX does not yet support \framebox without any option
4248 if (!special.empty())
4249 parse_outer_box(p, os, FLAG_ITEM, outer,
4250 context, t.cs(), special);
4252 eat_whitespace(p, os, context, false);
4253 output_ert_inset(os, "\\framebox{", context);
4254 parse_text(p, os, FLAG_ITEM, outer, context);
4255 output_ert_inset(os, "}", context);
4260 //\makebox() is part of the picture environment and different from \makebox{}
4261 //\makebox{} will be parsed by parse_box
4262 else if (t.cs() == "makebox") {
4263 if (p.next_token().character() == '(') {
4264 //the syntax is: \makebox(x,y)[position]{content}
4265 string arg = t.asInput();
4266 arg += p.getFullParentheseArg();
4267 arg += p.getFullOpt();
4268 eat_whitespace(p, os, context, false);
4269 output_ert_inset(os, arg + '{', context);
4270 parse_text(p, os, FLAG_ITEM, outer, context);
4271 output_ert_inset(os, "}", context);
4273 //the syntax is: \makebox[width][position]{content}
4274 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4278 else if (t.cs() == "smallskip" ||
4279 t.cs() == "medskip" ||
4280 t.cs() == "bigskip" ||
4281 t.cs() == "vfill") {
4282 context.check_layout(os);
4283 begin_inset(os, "VSpace ");
4286 skip_spaces_braces(p);
4289 else if ((where = is_known(t.cs(), known_spaces))) {
4290 context.check_layout(os);
4291 begin_inset(os, "space ");
4292 os << '\\' << known_coded_spaces[where - known_spaces]
4295 // LaTeX swallows whitespace after all spaces except
4296 // "\\,". We have to do that here, too, because LyX
4297 // adds "{}" which would make the spaces significant.
4299 eat_whitespace(p, os, context, false);
4300 // LyX adds "{}" after all spaces except "\\ " and
4301 // "\\,", so we have to remove "{}".
4302 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4303 // remove the braces after "\\,", too.
4308 else if (t.cs() == "newpage" ||
4309 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4310 t.cs() == "clearpage" ||
4311 t.cs() == "cleardoublepage") {
4312 context.check_layout(os);
4313 begin_inset(os, "Newpage ");
4316 skip_spaces_braces(p);
4319 else if (t.cs() == "DeclareRobustCommand" ||
4320 t.cs() == "DeclareRobustCommandx" ||
4321 t.cs() == "newcommand" ||
4322 t.cs() == "newcommandx" ||
4323 t.cs() == "providecommand" ||
4324 t.cs() == "providecommandx" ||
4325 t.cs() == "renewcommand" ||
4326 t.cs() == "renewcommandx") {
4327 // DeclareRobustCommand, DeclareRobustCommandx,
4328 // providecommand and providecommandx could be handled
4329 // by parse_command(), but we need to call
4330 // add_known_command() here.
4331 string name = t.asInput();
4332 if (p.next_token().asInput() == "*") {
4333 // Starred form. Eat '*'
4337 string const command = p.verbatim_item();
4338 string const opt1 = p.getFullOpt();
4339 string const opt2 = p.getFullOpt();
4340 add_known_command(command, opt1, !opt2.empty());
4341 string const ert = name + '{' + command + '}' +
4343 '{' + p.verbatim_item() + '}';
4345 if (t.cs() == "DeclareRobustCommand" ||
4346 t.cs() == "DeclareRobustCommandx" ||
4347 t.cs() == "providecommand" ||
4348 t.cs() == "providecommandx" ||
4349 name[name.length()-1] == '*')
4350 output_ert_inset(os, ert, context);
4352 context.check_layout(os);
4353 begin_inset(os, "FormulaMacro");
4359 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4360 // let could be handled by parse_command(),
4361 // but we need to call add_known_command() here.
4362 string ert = t.asInput();
4365 if (p.next_token().cat() == catBegin) {
4366 name = p.verbatim_item();
4367 ert += '{' + name + '}';
4369 name = p.verbatim_item();
4374 if (p.next_token().cat() == catBegin) {
4375 command = p.verbatim_item();
4376 ert += '{' + command + '}';
4378 command = p.verbatim_item();
4381 // If command is known, make name known too, to parse
4382 // its arguments correctly. For this reason we also
4383 // have commands in syntax.default that are hardcoded.
4384 CommandMap::iterator it = known_commands.find(command);
4385 if (it != known_commands.end())
4386 known_commands[t.asInput()] = it->second;
4387 output_ert_inset(os, ert, context);
4390 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4391 bool starred = false;
4392 if (p.next_token().asInput() == "*") {
4396 string name = t.asInput();
4397 string const length = p.verbatim_item();
4400 bool valid = splitLatexLength(length, valstring, unit);
4401 bool known_hspace = false;
4402 bool known_vspace = false;
4403 bool known_unit = false;
4406 istringstream iss(valstring);
4409 if (t.cs()[0] == 'h') {
4410 if (unit == "\\fill") {
4415 known_hspace = true;
4418 if (unit == "\\smallskipamount") {
4420 known_vspace = true;
4421 } else if (unit == "\\medskipamount") {
4423 known_vspace = true;
4424 } else if (unit == "\\bigskipamount") {
4426 known_vspace = true;
4427 } else if (unit == "\\fill") {
4429 known_vspace = true;
4433 if (!known_hspace && !known_vspace) {
4434 switch (unitFromString(unit)) {
4455 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4456 // Literal horizontal length or known variable
4457 context.check_layout(os);
4458 begin_inset(os, "space ");
4466 if (known_unit && !known_hspace)
4468 << translate_len(length);
4470 } else if (known_unit || known_vspace) {
4471 // Literal vertical length or known variable
4472 context.check_layout(os);
4473 begin_inset(os, "VSpace ");
4481 // LyX can't handle other length variables in Inset VSpace/space
4486 output_ert_inset(os, name + '{' + unit + '}', context);
4487 else if (value == -1.0)
4488 output_ert_inset(os, name + "{-" + unit + '}', context);
4490 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4492 output_ert_inset(os, name + '{' + length + '}', context);
4496 // The single '=' is meant here.
4497 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4499 context.check_layout(os);
4500 begin_inset(os, "Flex ");
4501 os << to_utf8(newinsetlayout->name()) << '\n'
4502 << "status collapsed\n";
4503 if (newinsetlayout->isPassThru()) {
4504 // set catcodes to verbatim early, just in case.
4505 p.setCatcodes(VERBATIM_CATCODES);
4506 string delim = p.get_token().asInput();
4508 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4509 string const arg = p.verbatimStuff("}");
4510 Context newcontext(true, context.textclass);
4511 if (newinsetlayout->forcePlainLayout())
4512 newcontext.layout = &context.textclass.plainLayout();
4513 output_ert(os, arg, newcontext);
4516 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4520 else if (t.cs() == "includepdf") {
4522 string const arg = p.getArg('[', ']');
4523 map<string, string> opts;
4524 vector<string> keys;
4525 split_map(arg, opts, keys);
4526 string name = normalize_filename(p.verbatim_item());
4527 string const path = getMasterFilePath(true);
4528 // We want to preserve relative / absolute filenames,
4529 // therefore path is only used for testing
4530 if (!makeAbsPath(name, path).exists()) {
4531 // The file extension is probably missing.
4532 // Now try to find it out.
4533 char const * const pdfpages_format[] = {"pdf", 0};
4534 string const pdftex_name =
4535 find_file(name, path, pdfpages_format);
4536 if (!pdftex_name.empty()) {
4541 FileName const absname = makeAbsPath(name, path);
4542 if (absname.exists())
4544 fix_child_filename(name);
4545 copy_file(absname, name);
4547 cerr << "Warning: Could not find file '"
4548 << name << "'." << endl;
4550 context.check_layout(os);
4551 begin_inset(os, "External\n\ttemplate ");
4552 os << "PDFPages\n\tfilename "
4554 // parse the options
4555 if (opts.find("pages") != opts.end())
4556 os << "\textra LaTeX \"pages="
4557 << opts["pages"] << "\"\n";
4558 if (opts.find("angle") != opts.end())
4559 os << "\trotateAngle "
4560 << opts["angle"] << '\n';
4561 if (opts.find("origin") != opts.end()) {
4563 string const opt = opts["origin"];
4564 if (opt == "tl") ss << "topleft";
4565 if (opt == "bl") ss << "bottomleft";
4566 if (opt == "Bl") ss << "baselineleft";
4567 if (opt == "c") ss << "center";
4568 if (opt == "tc") ss << "topcenter";
4569 if (opt == "bc") ss << "bottomcenter";
4570 if (opt == "Bc") ss << "baselinecenter";
4571 if (opt == "tr") ss << "topright";
4572 if (opt == "br") ss << "bottomright";
4573 if (opt == "Br") ss << "baselineright";
4574 if (!ss.str().empty())
4575 os << "\trotateOrigin " << ss.str() << '\n';
4577 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4579 if (opts.find("width") != opts.end())
4581 << translate_len(opts["width"]) << '\n';
4582 if (opts.find("height") != opts.end())
4584 << translate_len(opts["height"]) << '\n';
4585 if (opts.find("keepaspectratio") != opts.end())
4586 os << "\tkeepAspectRatio\n";
4588 context.check_layout(os);
4589 registerExternalTemplatePackages("PDFPages");
4592 else if (t.cs() == "loadgame") {
4594 string name = normalize_filename(p.verbatim_item());
4595 string const path = getMasterFilePath(true);
4596 // We want to preserve relative / absolute filenames,
4597 // therefore path is only used for testing
4598 if (!makeAbsPath(name, path).exists()) {
4599 // The file extension is probably missing.
4600 // Now try to find it out.
4601 char const * const lyxskak_format[] = {"fen", 0};
4602 string const lyxskak_name =
4603 find_file(name, path, lyxskak_format);
4604 if (!lyxskak_name.empty())
4605 name = lyxskak_name;
4607 FileName const absname = makeAbsPath(name, path);
4608 if (absname.exists())
4610 fix_child_filename(name);
4611 copy_file(absname, name);
4613 cerr << "Warning: Could not find file '"
4614 << name << "'." << endl;
4615 context.check_layout(os);
4616 begin_inset(os, "External\n\ttemplate ");
4617 os << "ChessDiagram\n\tfilename "
4620 context.check_layout(os);
4621 // after a \loadgame follows a \showboard
4622 if (p.get_token().asInput() == "showboard")
4624 registerExternalTemplatePackages("ChessDiagram");
4628 // try to see whether the string is in unicodesymbols
4629 // Only use text mode commands, since we are in text mode here,
4630 // and math commands may be invalid (bug 6797)
4634 string name = t.asInput();
4635 // handle the dingbats and Cyrillic
4636 if (name == "\\ding" || name == "\\textcyr")
4637 name = name + '{' + p.getArg('{', '}') + '}';
4638 // handle the ifsym characters
4639 if (name == "\\textifsymbol") {
4640 string const optif = p.getFullOpt();
4641 string const argif = p.getArg('{', '}');
4642 name = name + optif + '{' + argif + '}';
4644 // handle the \ascii characters
4645 // the case of \ascii within braces, as LyX outputs it, is already
4646 // handled for t.cat() == catBegin
4647 if (name == "\\ascii") {
4648 // the code is "\asci\xxx"
4649 name = "{" + name + p.get_token().asInput() + "}";
4652 // handle some TIPA special characters
4653 if (name == "\\textglobfall") {
4657 if (name == "\\textdoublevertline") {
4658 name = "\\textbardbl";
4661 if (name == "\\!" ) {
4662 if (p.next_token().asInput() == "b") {
4663 p.get_token(); // eat 'b'
4667 if (p.next_token().asInput() == "d") {
4672 if (p.next_token().asInput() == "g") {
4677 if (p.next_token().asInput() == "G") {
4679 name = "\\texthtscg";
4682 if (p.next_token().asInput() == "j") {
4684 name = "\\texthtbardotlessj";
4687 if (p.next_token().asInput() == "o") {
4689 name = "\\textbullseye";
4693 if (name == "\\*" ) {
4694 if (p.next_token().asInput() == "k") {
4696 name = "\\textturnk";
4699 if (p.next_token().asInput() == "r") {
4700 p.get_token(); // eat 'b'
4701 name = "\\textturnr";
4704 if (p.next_token().asInput() == "t") {
4706 name = "\\textturnt";
4709 if (p.next_token().asInput() == "w") {
4711 name = "\\textturnw";
4715 // now get the character from unicodesymbols
4716 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4717 Encodings::TEXT_CMD, termination, rem, &req);
4720 cerr << "When parsing " << t.cs()
4721 << ", result is " << to_utf8(s)
4722 << "+" << to_utf8(rem) << endl;
4723 context.check_layout(os);
4726 skip_spaces_braces(p);
4727 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4728 preamble.registerAutomaticallyLoadedPackage(*it);
4730 //cerr << "#: " << t << " mode: " << mode << endl;
4731 // heuristic: read up to next non-nested space
4733 string s = t.asInput();
4734 string z = p.verbatim_item();
4735 while (p.good() && z != " " && !z.empty()) {
4736 //cerr << "read: " << z << endl;
4738 z = p.verbatim_item();
4740 cerr << "found ERT: " << s << endl;
4741 output_ert_inset(os, s + ' ', context);
4744 string name2 = t.asInput();
4745 if (p.next_token().asInput() == "*") {
4746 // Starred commands like \vspace*{}
4747 p.get_token(); // Eat '*'
4750 if (!parse_command(name2, p, os, outer, context))
4751 output_ert_inset(os, name2, context);
4755 if (flags & FLAG_LEAVE) {
4756 flags &= ~FLAG_LEAVE;
4763 string guessLanguage(Parser & p, string const & lang)
4765 typedef std::map<std::string, size_t> LangMap;
4766 // map from language names to number of characters
4769 for (char const * const * i = supported_CJK_languages; *i; i++)
4770 used[string(*i)] = 0;
4773 Token const t = p.get_token();
4774 // comments are not counted for any language
4775 if (t.cat() == catComment)
4777 // commands are not counted as well, but we need to detect
4778 // \begin{CJK} and switch encoding if needed
4779 if (t.cat() == catEscape) {
4780 if (t.cs() == "inputencoding") {
4781 string const enc = subst(p.verbatim_item(), "\n", " ");
4782 p.setEncoding(enc, Encoding::inputenc);
4785 if (t.cs() != "begin")
4788 // Non-CJK content is counted for lang.
4789 // We do not care about the real language here:
4790 // If we have more non-CJK contents than CJK contents,
4791 // we simply use the language that was specified as
4792 // babel main language.
4793 used[lang] += t.asInput().length();
4796 // Now we are starting an environment
4798 string const name = p.getArg('{', '}');
4799 if (name != "CJK") {
4803 // It is a CJK environment
4805 /* name = */ p.getArg('{', '}');
4806 string const encoding = p.getArg('{', '}');
4807 /* mapping = */ p.getArg('{', '}');
4808 string const encoding_old = p.getEncoding();
4809 char const * const * const where =
4810 is_known(encoding, supported_CJK_encodings);
4812 p.setEncoding(encoding, Encoding::CJK);
4814 p.setEncoding("UTF-8");
4815 string const text = p.ertEnvironment("CJK");
4816 p.setEncoding(encoding_old);
4819 // ignore contents in unknown CJK encoding
4822 // the language of the text
4824 supported_CJK_languages[where - supported_CJK_encodings];
4825 used[cjk] += text.length();
4827 LangMap::const_iterator use = used.begin();
4828 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4829 if (it->second > use->second)