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;
50 void output_arguments(ostream &, Parser &, bool, bool, bool, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout)
59 bool const forcePlainLayout =
60 layout ? layout->forcePlainLayout() : false;
61 Context newcontext(true, context.textclass);
63 newcontext.layout = &context.textclass.plainLayout();
65 newcontext.font = context.font;
67 output_arguments(os, p, outer, false, false, newcontext,
69 parse_text(p, os, flags, outer, newcontext);
71 output_arguments(os, p, outer, false, true, newcontext,
72 layout->postcommandargs());
73 newcontext.check_end_layout(os);
79 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context const & context, string const & name)
82 InsetLayout const * layout = 0;
83 DocumentClass::InsetLayouts::const_iterator it =
84 context.textclass.insetLayouts().find(from_ascii(name));
85 if (it != context.textclass.insetLayouts().end())
86 layout = &(it->second);
87 parse_text_in_inset(p, os, flags, outer, context, layout);
90 /// parses a paragraph snippet, useful for example for \\emph{...}
91 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
94 Context newcontext(context);
95 // Don't inherit the paragraph-level extra stuff
96 newcontext.par_extra_stuff.clear();
97 parse_text(p, os, flags, outer, newcontext);
98 // Make sure that we don't create invalid .lyx files
99 context.need_layout = newcontext.need_layout;
100 context.need_end_layout = newcontext.need_end_layout;
105 * Thin wrapper around parse_text_snippet() using a string.
107 * We completely ignore \c context.need_layout and \c context.need_end_layout,
108 * because our return value is not used directly (otherwise the stream version
109 * of parse_text_snippet() could be used). That means that the caller needs
110 * to do layout management manually.
111 * This is intended to parse text that does not create any layout changes.
113 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
116 Context newcontext(context);
117 newcontext.need_layout = false;
118 newcontext.need_end_layout = false;
119 newcontext.new_layout_allowed = false;
120 // Avoid warning by Context::~Context()
121 newcontext.par_extra_stuff.clear();
123 parse_text_snippet(p, os, flags, outer, newcontext);
128 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
129 "vpageref", "prettyref", "nameref", "eqref", 0 };
131 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
132 "vpageref", "formatted", "nameref", "eqref", 0 };
134 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
135 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
136 "secref", "subref", "tabref", "thmref", 0 };
138 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
139 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
140 "sec", "sub", "tab", "thm", 0 };
144 * supported CJK encodings
145 * JIS does not work with LyX's encoding conversion
147 const char * const supported_CJK_encodings[] = {
148 "EUC-JP", "KS", "GB", "UTF8",
149 "Bg5", /*"JIS",*/ "SJIS", 0};
152 * the same as supported_CJK_encodings with their corresponding LyX language name
153 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
155 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
156 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
157 * please keep this in sync with supported_CJK_encodings line by line!
159 const char * const supported_CJK_languages[] = {
160 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
161 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
165 * The starred forms are also known except for "citefullauthor",
166 * "citeyear" and "citeyearpar".
168 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
169 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
170 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
174 * No starred form other than "cite*" known.
176 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
177 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
178 // jurabib commands not (yet) supported by LyX:
180 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
181 // "footciteauthor", "footciteyear", "footciteyearpar",
182 "citefield", "citetitle", 0 };
184 /// LaTeX names for quotes
185 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
186 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
187 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
188 "guilsinglleft", "frq", "guilsinglright", 0};
190 /// the same as known_quotes with .lyx names
191 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
192 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
193 "gld", "grd", "gls", "ers", "fls",
194 "fls", "frs", "frs", 0};
196 /// LaTeX names for font sizes
197 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
198 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
200 /// the same as known_sizes with .lyx names
201 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
202 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
204 /// LaTeX 2.09 names for font families
205 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
207 /// LaTeX names for font families
208 char const * const known_font_families[] = { "rmfamily", "sffamily",
211 /// LaTeX names for font family changing commands
212 char const * const known_text_font_families[] = { "textrm", "textsf",
215 /// The same as known_old_font_families, known_font_families and
216 /// known_text_font_families with .lyx names
217 char const * const known_coded_font_families[] = { "roman", "sans",
220 /// LaTeX 2.09 names for font series
221 char const * const known_old_font_series[] = { "bf", 0};
223 /// LaTeX names for font series
224 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
226 /// LaTeX names for font series changing commands
227 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
229 /// The same as known_old_font_series, known_font_series and
230 /// known_text_font_series with .lyx names
231 char const * const known_coded_font_series[] = { "bold", "medium", 0};
233 /// LaTeX 2.09 names for font shapes
234 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
236 /// LaTeX names for font shapes
237 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
240 /// LaTeX names for font shape changing commands
241 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
244 /// The same as known_old_font_shapes, known_font_shapes and
245 /// known_text_font_shapes with .lyx names
246 char const * const known_coded_font_shapes[] = { "italic", "slanted",
247 "smallcaps", "up", 0};
249 /// Known special characters which need skip_spaces_braces() afterwards
250 char const * const known_special_chars[] = {"ldots",
251 "lyxarrow", "textcompwordmark",
252 "slash", "textasciitilde", "textasciicircum", "textbackslash", 0};
254 /// the same as known_special_chars with .lyx names
255 char const * const known_coded_special_chars[] = {"\\SpecialChar \\ldots{}\n",
256 "\\SpecialChar \\menuseparator\n", "\\SpecialChar \\textcompwordmark{}\n",
257 "\\SpecialChar \\slash{}\n", "~", "^", "\n\\backslash\n", 0};
260 * Graphics file extensions known by the dvips driver of the graphics package.
261 * These extensions are used to complete the filename of an included
262 * graphics file if it does not contain an extension.
263 * The order must be the same that latex uses to find a file, because we
264 * will use the first extension that matches.
265 * This is only an approximation for the common cases. If we would want to
266 * do it right in all cases, we would need to know which graphics driver is
267 * used and know the extensions of every driver of the graphics package.
269 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
270 "ps.gz", "eps.Z", "ps.Z", 0};
273 * Graphics file extensions known by the pdftex driver of the graphics package.
274 * \sa known_dvips_graphics_formats
276 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
280 * Known file extensions for TeX files as used by \\include.
282 char const * const known_tex_extensions[] = {"tex", 0};
284 /// spaces known by InsetSpace
285 char const * const known_spaces[] = { " ", "space", ",",
286 "thinspace", "quad", "qquad", "enspace", "enskip",
287 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
288 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
289 "upbracefill", "downbracefill", 0};
291 /// the same as known_spaces with .lyx names
292 char const * const known_coded_spaces[] = { "space{}", "space{}",
293 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
294 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
295 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
296 "upbracefill{}", "downbracefill{}", 0};
298 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
299 /// them in ERT. "LaTeXe" must come before "LaTeX"!
300 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
301 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
302 int const known_phrase_lengths[] = {3, 5, 7, 0};
304 /// known TIPA combining diacritical marks
305 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
306 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
307 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
308 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
309 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
310 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
313 /// TIPA tones that need special handling
314 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
316 // string to store the float type to be able to determine the type of subfloats
317 string float_type = "";
320 /// splits "x=z, y=b" into a map and an ordered keyword vector
321 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
326 keys.resize(v.size());
327 for (size_t i = 0; i < v.size(); ++i) {
328 size_t const pos = v[i].find('=');
329 string const index = trimSpaceAndEol(v[i].substr(0, pos));
330 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
338 * Split a LaTeX length into value and unit.
339 * The latter can be a real unit like "pt", or a latex length variable
340 * like "\textwidth". The unit may contain additional stuff like glue
341 * lengths, but we don't care, because such lengths are ERT anyway.
342 * \returns true if \p value and \p unit are valid.
344 bool splitLatexLength(string const & len, string & value, string & unit)
348 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
349 //'4,5' is a valid LaTeX length number. Change it to '4.5'
350 string const length = subst(len, ',', '.');
351 if (i == string::npos)
354 if (len[0] == '\\') {
355 // We had something like \textwidth without a factor
361 value = trimSpaceAndEol(string(length, 0, i));
365 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
366 if (contains(len, '\\'))
367 unit = trimSpaceAndEol(string(len, i));
369 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
374 /// A simple function to translate a latex length to something LyX can
375 /// understand. Not perfect, but rather best-effort.
376 bool translate_len(string const & length, string & valstring, string & unit)
378 if (!splitLatexLength(length, valstring, unit))
380 // LyX uses percent values
382 istringstream iss(valstring);
387 string const percentval = oss.str();
389 if (unit.empty() || unit[0] != '\\')
391 string::size_type const i = unit.find(' ');
392 string const endlen = (i == string::npos) ? string() : string(unit, i);
393 if (unit == "\\textwidth") {
394 valstring = percentval;
395 unit = "text%" + endlen;
396 } else if (unit == "\\columnwidth") {
397 valstring = percentval;
398 unit = "col%" + endlen;
399 } else if (unit == "\\paperwidth") {
400 valstring = percentval;
401 unit = "page%" + endlen;
402 } else if (unit == "\\linewidth") {
403 valstring = percentval;
404 unit = "line%" + endlen;
405 } else if (unit == "\\paperheight") {
406 valstring = percentval;
407 unit = "pheight%" + endlen;
408 } else if (unit == "\\textheight") {
409 valstring = percentval;
410 unit = "theight%" + endlen;
418 string translate_len(string const & length)
422 if (translate_len(length, value, unit))
424 // If the input is invalid, return what we have.
432 * Translates a LaTeX length into \p value, \p unit and
433 * \p special parts suitable for a box inset.
434 * The difference from translate_len() is that a box inset knows about
435 * some special "units" that are stored in \p special.
437 void translate_box_len(string const & length, string & value, string & unit, string & special)
439 if (translate_len(length, value, unit)) {
440 if (unit == "\\height" || unit == "\\depth" ||
441 unit == "\\totalheight" || unit == "\\width") {
442 special = unit.substr(1);
443 // The unit is not used, but LyX requires a dummy setting
456 * Find a file with basename \p name in path \p path and an extension
459 string find_file(string const & name, string const & path,
460 char const * const * extensions)
462 for (char const * const * what = extensions; *what; ++what) {
463 string const trial = addExtension(name, *what);
464 if (makeAbsPath(trial, path).exists())
471 void begin_inset(ostream & os, string const & name)
473 os << "\n\\begin_inset " << name;
477 void begin_command_inset(ostream & os, string const & name,
478 string const & latexname)
480 begin_inset(os, "CommandInset ");
481 os << name << "\nLatexCommand " << latexname << '\n';
485 void end_inset(ostream & os)
487 os << "\n\\end_inset\n\n";
491 bool skip_braces(Parser & p)
493 if (p.next_token().cat() != catBegin)
496 if (p.next_token().cat() == catEnd) {
505 /// replace LaTeX commands in \p s from the unicodesymbols file with their
507 docstring convert_unicodesymbols(docstring s)
510 for (size_t i = 0; i < s.size();) {
519 docstring parsed = encodings.fromLaTeXCommand(s,
520 Encodings::TEXT_CMD, termination, rem, &req);
521 set<string>::const_iterator it = req.begin();
522 set<string>::const_iterator en = req.end();
523 for (; it != en; ++it)
524 preamble.registerAutomaticallyLoadedPackage(*it);
527 if (s.empty() || s[0] != '\\')
536 /// try to convert \p s to a valid InsetCommand argument
537 string convert_command_inset_arg(string s)
540 // since we don't know the input encoding we can't use from_utf8
541 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
542 // LyX cannot handle newlines in a latex command
543 return subst(s, "\n", " ");
547 void output_ert(ostream & os, string const & s, Context & context)
549 context.check_layout(os);
550 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
552 os << "\n\\backslash\n";
553 else if (*it == '\n') {
554 context.new_paragraph(os);
555 context.check_layout(os);
559 context.check_end_layout(os);
563 void output_ert_inset(ostream & os, string const & s, Context & context)
565 // We must have a valid layout before outputting the ERT inset.
566 context.check_layout(os);
567 Context newcontext(true, context.textclass);
568 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
569 if (layout.forcePlainLayout())
570 newcontext.layout = &context.textclass.plainLayout();
571 begin_inset(os, "ERT");
572 os << "\nstatus collapsed\n";
573 output_ert(os, s, newcontext);
578 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
580 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
583 if (checkModule(name, command))
584 return findLayoutWithoutModule(textclass, name, command);
589 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
591 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
594 if (checkModule(name, command))
595 return findInsetLayoutWithoutModule(textclass, name, command);
600 void eat_whitespace(Parser &, ostream &, Context &, bool);
604 * Skips whitespace and braces.
605 * This should be called after a command has been parsed that is not put into
606 * ERT, and where LyX adds "{}" if needed.
608 void skip_spaces_braces(Parser & p, bool keepws = false)
610 /* The following four examples produce the same typeset output and
611 should be handled by this function:
619 // Unfortunately we need to skip comments, too.
620 // We can't use eat_whitespace since writing them after the {}
621 // results in different output in some cases.
622 bool const skipped_spaces = p.skip_spaces(true);
623 bool const skipped_braces = skip_braces(p);
624 if (keepws && skipped_spaces && !skipped_braces)
625 // put back the space (it is better handled by check_space)
626 p.unskip_spaces(true);
630 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
631 Context & context, Layout::LaTeXArgMap const & latexargs)
634 context.check_layout(os);
639 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
640 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
641 for (; lait != laend; ++lait) {
643 eat_whitespace(p, os, context, false);
644 if (lait->second.mandatory) {
645 if (p.next_token().cat() != catBegin)
647 p.get_token(); // eat '{'
649 context.check_layout(os);
652 begin_inset(os, "Argument ");
655 os << i << "\nstatus collapsed\n\n";
656 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
659 if (p.next_token().cat() == catEscape ||
660 p.next_token().character() != '[')
662 p.get_token(); // eat '['
664 context.check_layout(os);
667 begin_inset(os, "Argument ");
670 os << i << "\nstatus collapsed\n\n";
671 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
674 eat_whitespace(p, os, context, false);
679 void output_command_layout(ostream & os, Parser & p, bool outer,
680 Context & parent_context,
681 Layout const * newlayout)
683 TeXFont const oldFont = parent_context.font;
684 // save the current font size
685 string const size = oldFont.size;
686 // reset the font size to default, because the font size switches
687 // don't affect section headings and the like
688 parent_context.font.size = Context::normalfont.size;
689 // we only need to write the font change if we have an open layout
690 if (!parent_context.atParagraphStart())
691 output_font_change(os, oldFont, parent_context.font);
692 parent_context.check_end_layout(os);
693 Context context(true, parent_context.textclass, newlayout,
694 parent_context.layout, parent_context.font);
695 if (parent_context.deeper_paragraph) {
696 // We are beginning a nested environment after a
697 // deeper paragraph inside the outer list environment.
698 // Therefore we don't need to output a "begin deeper".
699 context.need_end_deeper = true;
701 context.check_deeper(os);
702 output_arguments(os, p, outer, true, false, context,
703 context.layout->latexargs());
704 parse_text(p, os, FLAG_ITEM, outer, context);
705 output_arguments(os, p, outer, false, true, context,
706 context.layout->postcommandargs());
707 context.check_end_layout(os);
708 if (parent_context.deeper_paragraph) {
709 // We must suppress the "end deeper" because we
710 // suppressed the "begin deeper" above.
711 context.need_end_deeper = false;
713 context.check_end_deeper(os);
714 // We don't need really a new paragraph, but
715 // we must make sure that the next item gets a \begin_layout.
716 parent_context.new_paragraph(os);
717 // Set the font size to the original value. No need to output it here
718 // (Context::begin_layout() will do that if needed)
719 parent_context.font.size = size;
724 * Output a space if necessary.
725 * This function gets called for every whitespace token.
727 * We have three cases here:
728 * 1. A space must be suppressed. Example: The lyxcode case below
729 * 2. A space may be suppressed. Example: Spaces before "\par"
730 * 3. A space must not be suppressed. Example: A space between two words
732 * We currently handle only 1. and 3 and from 2. only the case of
733 * spaces before newlines as a side effect.
735 * 2. could be used to suppress as many spaces as possible. This has two effects:
736 * - Reimporting LyX generated LaTeX files changes almost no whitespace
737 * - Superflous whitespace from non LyX generated LaTeX files is removed.
738 * The drawback is that the logic inside the function becomes
739 * complicated, and that is the reason why it is not implemented.
741 void check_space(Parser & p, ostream & os, Context & context)
743 Token const next = p.next_token();
744 Token const curr = p.curr_token();
745 // A space before a single newline and vice versa must be ignored
746 // LyX emits a newline before \end{lyxcode}.
747 // This newline must be ignored,
748 // otherwise LyX will add an additional protected space.
749 if (next.cat() == catSpace ||
750 next.cat() == catNewline ||
751 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
754 context.check_layout(os);
760 * Parse all arguments of \p command
762 void parse_arguments(string const & command,
763 vector<ArgumentType> const & template_arguments,
764 Parser & p, ostream & os, bool outer, Context & context)
766 string ert = command;
767 size_t no_arguments = template_arguments.size();
768 for (size_t i = 0; i < no_arguments; ++i) {
769 switch (template_arguments[i]) {
772 // This argument contains regular LaTeX
773 output_ert_inset(os, ert + '{', context);
774 eat_whitespace(p, os, context, false);
775 if (template_arguments[i] == required)
776 parse_text(p, os, FLAG_ITEM, outer, context);
778 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
782 // This argument consists only of a single item.
783 // The presence of '{' or not must be preserved.
785 if (p.next_token().cat() == catBegin)
786 ert += '{' + p.verbatim_item() + '}';
788 ert += p.verbatim_item();
792 // This argument may contain special characters
793 ert += '{' + p.verbatim_item() + '}';
797 // true because we must not eat whitespace
798 // if an optional arg follows we must not strip the
799 // brackets from this one
800 if (i < no_arguments - 1 &&
801 template_arguments[i+1] == optional)
802 ert += p.getFullOpt(true);
804 ert += p.getOpt(true);
808 output_ert_inset(os, ert, context);
813 * Check whether \p command is a known command. If yes,
814 * handle the command with all arguments.
815 * \return true if the command was parsed, false otherwise.
817 bool parse_command(string const & command, Parser & p, ostream & os,
818 bool outer, Context & context)
820 if (known_commands.find(command) != known_commands.end()) {
821 parse_arguments(command, known_commands[command], p, os,
829 /// Parses a minipage or parbox
830 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
831 unsigned inner_flags, bool outer, Context & parent_context,
832 string const & outer_type, string const & special,
833 string const & inner_type)
837 string hor_pos = "c";
838 // We need to set the height to the LaTeX default of 1\\totalheight
839 // for the case when no height argument is given
840 string height_value = "1";
841 string height_unit = "in";
842 string height_special = "totalheight";
847 string width_special = "none";
848 if (!inner_type.empty() && p.hasOpt()) {
849 if (inner_type != "makebox")
850 position = p.getArg('[', ']');
852 latex_width = p.getArg('[', ']');
853 translate_box_len(latex_width, width_value, width_unit, width_special);
856 if (position != "t" && position != "c" && position != "b") {
857 cerr << "invalid position " << position << " for "
858 << inner_type << endl;
862 if (inner_type != "makebox") {
863 latex_height = p.getArg('[', ']');
864 translate_box_len(latex_height, height_value, height_unit, height_special);
866 string const opt = p.getArg('[', ']');
869 if (hor_pos != "l" && hor_pos != "c" &&
870 hor_pos != "r" && hor_pos != "s") {
871 cerr << "invalid hor_pos " << hor_pos
872 << " for " << inner_type << endl;
879 inner_pos = p.getArg('[', ']');
880 if (inner_pos != "c" && inner_pos != "t" &&
881 inner_pos != "b" && inner_pos != "s") {
882 cerr << "invalid inner_pos "
883 << inner_pos << " for "
884 << inner_type << endl;
885 inner_pos = position;
890 if (inner_type.empty()) {
891 if (special.empty() && outer_type != "framebox")
892 latex_width = "1\\columnwidth";
895 latex_width = p2.getArg('[', ']');
896 string const opt = p2.getArg('[', ']');
899 if (hor_pos != "l" && hor_pos != "c" &&
900 hor_pos != "r" && hor_pos != "s") {
901 cerr << "invalid hor_pos " << hor_pos
902 << " for " << outer_type << endl;
907 } else if (inner_type != "makebox")
908 latex_width = p.verbatim_item();
909 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
910 // as this is LyX's standard for such cases (except for makebox)
911 // \framebox is more special and handled below
912 if (latex_width.empty() && inner_type != "makebox"
913 && outer_type != "framebox")
914 latex_width = "1\\columnwidth";
916 translate_len(latex_width, width_value, width_unit);
918 bool shadedparbox = false;
919 if (inner_type == "shaded") {
920 eat_whitespace(p, os, parent_context, false);
921 if (outer_type == "parbox") {
923 if (p.next_token().cat() == catBegin)
925 eat_whitespace(p, os, parent_context, false);
931 // If we already read the inner box we have to push the inner env
932 if (!outer_type.empty() && !inner_type.empty() &&
933 (inner_flags & FLAG_END))
934 active_environments.push_back(inner_type);
935 // LyX can't handle length variables
936 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
937 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
938 // Look whether there is some content after the end of the
939 // inner box, but before the end of the outer box.
940 // If yes, we need to output ERT.
942 if (inner_flags & FLAG_END)
943 p.ertEnvironment(inner_type);
947 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
948 if ((outer_env && p.next_token().asInput() != "\\end") ||
949 (!outer_env && p.next_token().cat() != catEnd)) {
950 // something is between the end of the inner box and
951 // the end of the outer box, so we need to use ERT.
956 // if only \makebox{content} was used we can set its width to 1\width
957 // because this identic and also identic to \mbox
958 // this doesn't work for \framebox{content}, thus we have to use ERT for this
959 if (latex_width.empty() && inner_type == "makebox") {
962 width_special = "width";
963 } else if (latex_width.empty() && outer_type == "framebox") {
966 width_special = "none";
970 if (!outer_type.empty()) {
971 if (outer_flags & FLAG_END)
972 ss << "\\begin{" << outer_type << '}';
974 ss << '\\' << outer_type << '{';
975 if (!special.empty())
979 if (!inner_type.empty()) {
980 if (inner_type != "shaded") {
981 if (inner_flags & FLAG_END)
982 ss << "\\begin{" << inner_type << '}';
984 ss << '\\' << inner_type;
986 if (!position.empty())
987 ss << '[' << position << ']';
988 if (!latex_height.empty())
989 ss << '[' << latex_height << ']';
990 if (!inner_pos.empty())
991 ss << '[' << inner_pos << ']';
992 ss << '{' << latex_width << '}';
993 if (!(inner_flags & FLAG_END))
996 if (inner_type == "shaded")
997 ss << "\\begin{shaded}";
998 output_ert_inset(os, ss.str(), parent_context);
999 if (!inner_type.empty()) {
1000 parse_text(p, os, inner_flags, outer, parent_context);
1001 if (inner_flags & FLAG_END)
1002 output_ert_inset(os, "\\end{" + inner_type + '}',
1005 output_ert_inset(os, "}", parent_context);
1007 if (!outer_type.empty()) {
1008 // If we already read the inner box we have to pop
1010 if (!inner_type.empty() && (inner_flags & FLAG_END))
1011 active_environments.pop_back();
1013 // Ensure that the end of the outer box is parsed correctly:
1014 // The opening brace has been eaten by parse_outer_box()
1015 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1016 outer_flags &= ~FLAG_ITEM;
1017 outer_flags |= FLAG_BRACE_LAST;
1019 parse_text(p, os, outer_flags, outer, parent_context);
1020 if (outer_flags & FLAG_END)
1021 output_ert_inset(os, "\\end{" + outer_type + '}',
1024 output_ert_inset(os, "}", parent_context);
1027 // LyX does not like empty positions, so we have
1028 // to set them to the LaTeX default values here.
1029 if (position.empty())
1031 if (inner_pos.empty())
1032 inner_pos = position;
1033 parent_context.check_layout(os);
1034 begin_inset(os, "Box ");
1035 if (outer_type == "framed")
1037 else if (outer_type == "framebox" || outer_type == "fbox")
1039 else if (outer_type == "shadowbox")
1040 os << "Shadowbox\n";
1041 else if ((outer_type == "shaded" && inner_type.empty()) ||
1042 (outer_type == "minipage" && inner_type == "shaded") ||
1043 (outer_type == "parbox" && inner_type == "shaded")) {
1045 preamble.registerAutomaticallyLoadedPackage("color");
1046 } else if (outer_type == "doublebox")
1047 os << "Doublebox\n";
1048 else if (outer_type.empty() || outer_type == "mbox")
1049 os << "Frameless\n";
1051 os << outer_type << '\n';
1052 os << "position \"" << position << "\"\n";
1053 os << "hor_pos \"" << hor_pos << "\"\n";
1054 if (outer_type == "mbox")
1055 os << "has_inner_box 1\n";
1057 os << "has_inner_box " << !inner_type.empty() << "\n";
1058 os << "inner_pos \"" << inner_pos << "\"\n";
1059 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1061 if (outer_type == "mbox")
1062 os << "use_makebox 1\n";
1064 os << "use_makebox " << (inner_type == "makebox") << '\n';
1065 if (outer_type == "fbox" || outer_type == "mbox")
1066 os << "width \"\"\n";
1068 os << "width \"" << width_value << width_unit << "\"\n";
1069 os << "special \"" << width_special << "\"\n";
1070 os << "height \"" << height_value << height_unit << "\"\n";
1071 os << "height_special \"" << height_special << "\"\n";
1072 os << "status open\n\n";
1074 // Unfortunately we can't use parse_text_in_inset:
1075 // InsetBox::forcePlainLayout() is hard coded and does not
1076 // use the inset layout. Apart from that do we call parse_text
1077 // up to two times, but need only one check_end_layout.
1078 bool const forcePlainLayout =
1079 (!inner_type.empty() || inner_type == "makebox") &&
1080 outer_type != "shaded" && outer_type != "framed";
1081 Context context(true, parent_context.textclass);
1082 if (forcePlainLayout)
1083 context.layout = &context.textclass.plainLayout();
1085 context.font = parent_context.font;
1087 // If we have no inner box the contents will be read with the outer box
1088 if (!inner_type.empty())
1089 parse_text(p, os, inner_flags, outer, context);
1091 // Ensure that the end of the outer box is parsed correctly:
1092 // The opening brace has been eaten by parse_outer_box()
1093 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1094 outer_flags &= ~FLAG_ITEM;
1095 outer_flags |= FLAG_BRACE_LAST;
1098 // Find end of outer box, output contents if inner_type is
1099 // empty and output possible comments
1100 if (!outer_type.empty()) {
1101 // If we already read the inner box we have to pop
1103 if (!inner_type.empty() && (inner_flags & FLAG_END))
1104 active_environments.pop_back();
1105 // This does not output anything but comments if
1106 // inner_type is not empty (see use_ert)
1107 parse_text(p, os, outer_flags, outer, context);
1110 context.check_end_layout(os);
1112 #ifdef PRESERVE_LAYOUT
1113 // LyX puts a % after the end of the minipage
1114 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1116 //output_ert_inset(os, "%dummy", parent_context);
1119 parent_context.new_paragraph(os);
1121 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1122 //output_ert_inset(os, "%dummy", parent_context);
1125 // We add a protected space if something real follows
1126 if (p.good() && p.next_token().cat() != catComment) {
1127 begin_inset(os, "space ~\n");
1136 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1137 Context & parent_context, string const & outer_type,
1138 string const & special)
1140 eat_whitespace(p, os, parent_context, false);
1141 if (flags & FLAG_ITEM) {
1143 if (p.next_token().cat() == catBegin)
1146 cerr << "Warning: Ignoring missing '{' after \\"
1147 << outer_type << '.' << endl;
1148 eat_whitespace(p, os, parent_context, false);
1151 unsigned int inner_flags = 0;
1153 if (outer_type == "minipage" || outer_type == "parbox") {
1154 p.skip_spaces(true);
1155 while (p.hasOpt()) {
1157 p.skip_spaces(true);
1160 p.skip_spaces(true);
1161 if (outer_type == "parbox") {
1163 if (p.next_token().cat() == catBegin)
1165 p.skip_spaces(true);
1168 if (outer_type == "shaded" || outer_type == "fbox"
1169 || outer_type == "mbox") {
1170 // These boxes never have an inner box
1172 } else if (p.next_token().asInput() == "\\parbox") {
1173 inner = p.get_token().cs();
1174 inner_flags = FLAG_ITEM;
1175 } else if (p.next_token().asInput() == "\\begin") {
1176 // Is this a minipage or shaded box?
1179 inner = p.getArg('{', '}');
1181 if (inner == "minipage" || inner == "shaded")
1182 inner_flags = FLAG_END;
1187 if (inner_flags == FLAG_END) {
1188 if (inner != "shaded")
1192 eat_whitespace(p, os, parent_context, false);
1194 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1195 outer_type, special, inner);
1197 if (inner_flags == FLAG_ITEM) {
1199 eat_whitespace(p, os, parent_context, false);
1201 parse_box(p, os, flags, inner_flags, outer, parent_context,
1202 outer_type, special, inner);
1207 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1209 parent_context.check_layout(os);
1210 begin_inset(os, "listings\n");
1212 string arg = p.verbatimOption();
1213 os << "lstparams " << '"' << arg << '"' << '\n';
1214 if (arg.find("\\color") != string::npos)
1215 preamble.registerAutomaticallyLoadedPackage("color");
1218 os << "inline true\n";
1220 os << "inline false\n";
1221 os << "status collapsed\n";
1222 Context context(true, parent_context.textclass);
1223 context.layout = &parent_context.textclass.plainLayout();
1226 // set catcodes to verbatim early, just in case.
1227 p.setCatcodes(VERBATIM_CATCODES);
1228 string delim = p.get_token().asInput();
1229 //FIXME: handler error condition
1230 s = p.verbatimStuff(delim).second;
1231 // context.new_paragraph(os);
1233 s = p.verbatimEnvironment("lstlisting");
1234 output_ert(os, s, context);
1239 /// parse an unknown environment
1240 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1241 unsigned flags, bool outer,
1242 Context & parent_context)
1244 if (name == "tabbing")
1245 // We need to remember that we have to handle '\=' specially
1246 flags |= FLAG_TABBING;
1248 // We need to translate font changes and paragraphs inside the
1249 // environment to ERT if we have a non standard font.
1250 // Otherwise things like
1251 // \large\begin{foo}\huge bar\end{foo}
1253 bool const specialfont =
1254 (parent_context.font != parent_context.normalfont);
1255 bool const new_layout_allowed = parent_context.new_layout_allowed;
1257 parent_context.new_layout_allowed = false;
1258 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1259 parse_text_snippet(p, os, flags, outer, parent_context);
1260 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1262 parent_context.new_layout_allowed = new_layout_allowed;
1266 void parse_environment(Parser & p, ostream & os, bool outer,
1267 string & last_env, Context & parent_context)
1269 Layout const * newlayout;
1270 InsetLayout const * newinsetlayout = 0;
1271 string const name = p.getArg('{', '}');
1272 const bool is_starred = suffixIs(name, '*');
1273 string const unstarred_name = rtrim(name, "*");
1274 active_environments.push_back(name);
1276 if (is_math_env(name)) {
1277 parent_context.check_layout(os);
1278 begin_inset(os, "Formula ");
1279 os << "\\begin{" << name << "}";
1280 parse_math(p, os, FLAG_END, MATH_MODE);
1281 os << "\\end{" << name << "}";
1283 if (is_display_math_env(name)) {
1284 // Prevent the conversion of a line break to a space
1285 // (bug 7668). This does not change the output, but
1286 // looks ugly in LyX.
1287 eat_whitespace(p, os, parent_context, false);
1291 else if (is_known(name, preamble.polyglossia_languages)) {
1292 // We must begin a new paragraph if not already done
1293 if (! parent_context.atParagraphStart()) {
1294 parent_context.check_end_layout(os);
1295 parent_context.new_paragraph(os);
1297 // save the language in the context so that it is
1298 // handled by parse_text
1299 parent_context.font.language = preamble.polyglossia2lyx(name);
1300 parse_text(p, os, FLAG_END, outer, parent_context);
1301 // Just in case the environment is empty
1302 parent_context.extra_stuff.erase();
1303 // We must begin a new paragraph to reset the language
1304 parent_context.new_paragraph(os);
1308 else if (unstarred_name == "tabular" || name == "longtable") {
1309 eat_whitespace(p, os, parent_context, false);
1310 string width = "0pt";
1311 if (name == "tabular*") {
1312 width = lyx::translate_len(p.getArg('{', '}'));
1313 eat_whitespace(p, os, parent_context, false);
1315 parent_context.check_layout(os);
1316 begin_inset(os, "Tabular ");
1317 handle_tabular(p, os, name, width, parent_context);
1322 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1323 eat_whitespace(p, os, parent_context, false);
1324 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1325 eat_whitespace(p, os, parent_context, false);
1326 parent_context.check_layout(os);
1327 begin_inset(os, "Float " + unstarred_name + "\n");
1328 // store the float type for subfloats
1329 // subfloats only work with figures and tables
1330 if (unstarred_name == "figure")
1331 float_type = unstarred_name;
1332 else if (unstarred_name == "table")
1333 float_type = unstarred_name;
1337 os << "placement " << opt << '\n';
1338 if (contains(opt, "H"))
1339 preamble.registerAutomaticallyLoadedPackage("float");
1341 Floating const & fl = parent_context.textclass.floats()
1342 .getType(unstarred_name);
1343 if (!fl.floattype().empty() && fl.usesFloatPkg())
1344 preamble.registerAutomaticallyLoadedPackage("float");
1347 os << "wide " << convert<string>(is_starred)
1348 << "\nsideways false"
1349 << "\nstatus open\n\n";
1350 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1352 // We don't need really a new paragraph, but
1353 // we must make sure that the next item gets a \begin_layout.
1354 parent_context.new_paragraph(os);
1356 // the float is parsed thus delete the type
1360 else if (unstarred_name == "sidewaysfigure"
1361 || unstarred_name == "sidewaystable") {
1362 eat_whitespace(p, os, parent_context, false);
1363 parent_context.check_layout(os);
1364 if (unstarred_name == "sidewaysfigure")
1365 begin_inset(os, "Float figure\n");
1367 begin_inset(os, "Float table\n");
1368 os << "wide " << convert<string>(is_starred)
1369 << "\nsideways true"
1370 << "\nstatus open\n\n";
1371 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1373 // We don't need really a new paragraph, but
1374 // we must make sure that the next item gets a \begin_layout.
1375 parent_context.new_paragraph(os);
1377 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1380 else if (name == "wrapfigure" || name == "wraptable") {
1381 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1382 eat_whitespace(p, os, parent_context, false);
1383 parent_context.check_layout(os);
1386 string overhang = "0col%";
1389 lines = p.getArg('[', ']');
1390 string const placement = p.getArg('{', '}');
1392 overhang = p.getArg('[', ']');
1393 string const width = p.getArg('{', '}');
1395 if (name == "wrapfigure")
1396 begin_inset(os, "Wrap figure\n");
1398 begin_inset(os, "Wrap table\n");
1399 os << "lines " << lines
1400 << "\nplacement " << placement
1401 << "\noverhang " << lyx::translate_len(overhang)
1402 << "\nwidth " << lyx::translate_len(width)
1403 << "\nstatus open\n\n";
1404 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1406 // We don't need really a new paragraph, but
1407 // we must make sure that the next item gets a \begin_layout.
1408 parent_context.new_paragraph(os);
1410 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1413 else if (name == "minipage") {
1414 eat_whitespace(p, os, parent_context, false);
1415 // Test whether this is an outer box of a shaded box
1417 // swallow arguments
1418 while (p.hasOpt()) {
1420 p.skip_spaces(true);
1423 p.skip_spaces(true);
1424 Token t = p.get_token();
1425 bool shaded = false;
1426 if (t.asInput() == "\\begin") {
1427 p.skip_spaces(true);
1428 if (p.getArg('{', '}') == "shaded")
1433 parse_outer_box(p, os, FLAG_END, outer,
1434 parent_context, name, "shaded");
1436 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1441 else if (name == "comment") {
1442 eat_whitespace(p, os, parent_context, false);
1443 parent_context.check_layout(os);
1444 begin_inset(os, "Note Comment\n");
1445 os << "status open\n";
1446 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1449 skip_braces(p); // eat {} that might by set by LyX behind comments
1450 preamble.registerAutomaticallyLoadedPackage("verbatim");
1453 else if (name == "verbatim") {
1454 // FIXME: this should go in the generic code that
1455 // handles environments defined in layout file that
1456 // have "PassThru 1". However, the code over there is
1457 // already too complicated for my taste.
1458 parent_context.new_paragraph(os);
1459 Context context(true, parent_context.textclass,
1460 &parent_context.textclass[from_ascii("Verbatim")]);
1461 string s = p.verbatimEnvironment("verbatim");
1462 output_ert(os, s, context);
1466 else if (name == "IPA") {
1467 eat_whitespace(p, os, parent_context, false);
1468 parent_context.check_layout(os);
1469 begin_inset(os, "IPA\n");
1470 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1473 preamble.registerAutomaticallyLoadedPackage("tipa");
1474 preamble.registerAutomaticallyLoadedPackage("tipx");
1477 else if (name == "CJK") {
1478 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1479 // It is impossible to decide if a CJK environment was in its own paragraph or within
1480 // a line. We therefore always assume a paragraph since the latter is a rare case.
1481 eat_whitespace(p, os, parent_context, false);
1482 parent_context.check_end_layout(os);
1483 // store the encoding to be able to reset it
1484 string const encoding_old = p.getEncoding();
1485 string const encoding = p.getArg('{', '}');
1486 // FIXME: For some reason JIS does not work. Although the text
1487 // in tests/CJK.tex is identical with the SJIS version if you
1488 // convert both snippets using the recode command line utility,
1489 // the resulting .lyx file contains some extra characters if
1490 // you set buggy_encoding to false for JIS.
1491 bool const buggy_encoding = encoding == "JIS";
1492 if (!buggy_encoding)
1493 p.setEncoding(encoding, Encoding::CJK);
1495 // FIXME: This will read garbage, since the data is not encoded in utf8.
1496 p.setEncoding("UTF-8");
1498 // LyX only supports the same mapping for all CJK
1499 // environments, so we might need to output everything as ERT
1500 string const mapping = trim(p.getArg('{', '}'));
1501 char const * const * const where =
1502 is_known(encoding, supported_CJK_encodings);
1503 if (!buggy_encoding && !preamble.fontCJKSet())
1504 preamble.fontCJK(mapping);
1505 bool knownMapping = mapping == preamble.fontCJK();
1506 if (buggy_encoding || !knownMapping || !where) {
1507 parent_context.check_layout(os);
1508 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1510 // we must parse the content as verbatim because e.g. JIS can contain
1511 // normally invalid characters
1512 // FIXME: This works only for the most simple cases.
1513 // Since TeX control characters are not parsed,
1514 // things like comments are completely wrong.
1515 string const s = p.plainEnvironment("CJK");
1516 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1518 output_ert_inset(os, "\\", parent_context);
1519 else if (*it == '$')
1520 output_ert_inset(os, "$", parent_context);
1521 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1526 output_ert_inset(os, "\\end{" + name + "}",
1530 supported_CJK_languages[where - supported_CJK_encodings];
1531 // store the language because we must reset it at the end
1532 string const lang_old = parent_context.font.language;
1533 parent_context.font.language = lang;
1534 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1535 parent_context.font.language = lang_old;
1536 parent_context.new_paragraph(os);
1538 p.setEncoding(encoding_old);
1542 else if (name == "lyxgreyedout") {
1543 eat_whitespace(p, os, parent_context, false);
1544 parent_context.check_layout(os);
1545 begin_inset(os, "Note Greyedout\n");
1546 os << "status open\n";
1547 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1550 if (!preamble.notefontcolor().empty())
1551 preamble.registerAutomaticallyLoadedPackage("color");
1554 else if (name == "btSect") {
1555 eat_whitespace(p, os, parent_context, false);
1556 parent_context.check_layout(os);
1557 begin_command_inset(os, "bibtex", "bibtex");
1558 string bibstyle = "plain";
1560 bibstyle = p.getArg('[', ']');
1561 p.skip_spaces(true);
1563 string const bibfile = p.getArg('{', '}');
1564 eat_whitespace(p, os, parent_context, false);
1565 Token t = p.get_token();
1566 if (t.asInput() == "\\btPrintCited") {
1567 p.skip_spaces(true);
1568 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1570 if (t.asInput() == "\\btPrintNotCited") {
1571 p.skip_spaces(true);
1572 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1574 if (t.asInput() == "\\btPrintAll") {
1575 p.skip_spaces(true);
1576 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1578 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1579 os << "options " << '"' << bibstyle << '"' << "\n";
1580 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1585 else if (name == "framed" || name == "shaded") {
1586 eat_whitespace(p, os, parent_context, false);
1587 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1591 else if (name == "lstlisting") {
1592 eat_whitespace(p, os, parent_context, false);
1593 parse_listings(p, os, parent_context, false);
1597 else if (!parent_context.new_layout_allowed)
1598 parse_unknown_environment(p, name, os, FLAG_END, outer,
1601 // Alignment and spacing settings
1602 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1603 // therefore are totally broken!
1604 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1605 // they are commands not environments. They are furthermore switches that
1606 // can be ended by another switches, but also by commands like \footnote or
1607 // \parbox. So the only safe way is to leave them untouched.
1608 else if (name == "center" || name == "centering" ||
1609 name == "flushleft" || name == "flushright" ||
1610 name == "singlespace" || name == "onehalfspace" ||
1611 name == "doublespace" || name == "spacing") {
1612 eat_whitespace(p, os, parent_context, false);
1613 // We must begin a new paragraph if not already done
1614 if (! parent_context.atParagraphStart()) {
1615 parent_context.check_end_layout(os);
1616 parent_context.new_paragraph(os);
1618 if (name == "flushleft")
1619 parent_context.add_extra_stuff("\\align left\n");
1620 else if (name == "flushright")
1621 parent_context.add_extra_stuff("\\align right\n");
1622 else if (name == "center" || name == "centering")
1623 parent_context.add_extra_stuff("\\align center\n");
1624 else if (name == "singlespace")
1625 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1626 else if (name == "onehalfspace") {
1627 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1628 preamble.registerAutomaticallyLoadedPackage("setspace");
1629 } else if (name == "doublespace") {
1630 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1631 preamble.registerAutomaticallyLoadedPackage("setspace");
1632 } else if (name == "spacing") {
1633 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1634 preamble.registerAutomaticallyLoadedPackage("setspace");
1636 parse_text(p, os, FLAG_END, outer, parent_context);
1637 // Just in case the environment is empty
1638 parent_context.extra_stuff.erase();
1639 // We must begin a new paragraph to reset the alignment
1640 parent_context.new_paragraph(os);
1644 // The single '=' is meant here.
1645 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1646 eat_whitespace(p, os, parent_context, false);
1647 Context context(true, parent_context.textclass, newlayout,
1648 parent_context.layout, parent_context.font);
1649 if (parent_context.deeper_paragraph) {
1650 // We are beginning a nested environment after a
1651 // deeper paragraph inside the outer list environment.
1652 // Therefore we don't need to output a "begin deeper".
1653 context.need_end_deeper = true;
1655 parent_context.check_end_layout(os);
1656 if (last_env == name) {
1657 // we need to output a separator since LyX would export
1658 // the two environments as one otherwise (bug 5716)
1659 TeX2LyXDocClass const & textclass(parent_context.textclass);
1660 Context newcontext(true, textclass,
1661 &(textclass.defaultLayout()));
1662 newcontext.check_layout(os);
1663 begin_inset(os, "Separator plain\n");
1665 newcontext.check_end_layout(os);
1667 switch (context.layout->latextype) {
1668 case LATEX_LIST_ENVIRONMENT:
1669 context.add_par_extra_stuff("\\labelwidthstring "
1670 + p.verbatim_item() + '\n');
1673 case LATEX_BIB_ENVIRONMENT:
1674 p.verbatim_item(); // swallow next arg
1680 context.check_deeper(os);
1681 // handle known optional and required arguments
1682 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1683 // It is impossible to place anything after the environment name,
1684 // but before the first \\item.
1685 if (context.layout->latextype == LATEX_ENVIRONMENT)
1686 output_arguments(os, p, outer, false, false, context,
1687 context.layout->latexargs());
1688 parse_text(p, os, FLAG_END, outer, context);
1689 if (context.layout->latextype == LATEX_ENVIRONMENT)
1690 output_arguments(os, p, outer, false, true, context,
1691 context.layout->postcommandargs());
1692 context.check_end_layout(os);
1693 if (parent_context.deeper_paragraph) {
1694 // We must suppress the "end deeper" because we
1695 // suppressed the "begin deeper" above.
1696 context.need_end_deeper = false;
1698 context.check_end_deeper(os);
1699 parent_context.new_paragraph(os);
1701 if (!preamble.titleLayoutFound())
1702 preamble.titleLayoutFound(newlayout->intitle);
1703 set<string> const & req = newlayout->requires();
1704 set<string>::const_iterator it = req.begin();
1705 set<string>::const_iterator en = req.end();
1706 for (; it != en; ++it)
1707 preamble.registerAutomaticallyLoadedPackage(*it);
1710 // The single '=' is meant here.
1711 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1712 eat_whitespace(p, os, parent_context, false);
1713 parent_context.check_layout(os);
1714 begin_inset(os, "Flex ");
1715 os << to_utf8(newinsetlayout->name()) << '\n'
1716 << "status collapsed\n";
1717 if (newinsetlayout->isPassThru()) {
1718 string const arg = p.verbatimEnvironment(name);
1719 Context context(true, parent_context.textclass,
1720 &parent_context.textclass.plainLayout(),
1721 parent_context.layout);
1722 output_ert(os, arg, parent_context);
1724 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1728 else if (name == "appendix") {
1729 // This is no good latex style, but it works and is used in some documents...
1730 eat_whitespace(p, os, parent_context, false);
1731 parent_context.check_end_layout(os);
1732 Context context(true, parent_context.textclass, parent_context.layout,
1733 parent_context.layout, parent_context.font);
1734 context.check_layout(os);
1735 os << "\\start_of_appendix\n";
1736 parse_text(p, os, FLAG_END, outer, context);
1737 context.check_end_layout(os);
1741 else if (known_environments.find(name) != known_environments.end()) {
1742 vector<ArgumentType> arguments = known_environments[name];
1743 // The last "argument" denotes wether we may translate the
1744 // environment contents to LyX
1745 // The default required if no argument is given makes us
1746 // compatible with the reLyXre environment.
1747 ArgumentType contents = arguments.empty() ?
1750 if (!arguments.empty())
1751 arguments.pop_back();
1752 // See comment in parse_unknown_environment()
1753 bool const specialfont =
1754 (parent_context.font != parent_context.normalfont);
1755 bool const new_layout_allowed =
1756 parent_context.new_layout_allowed;
1758 parent_context.new_layout_allowed = false;
1759 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1760 outer, parent_context);
1761 if (contents == verbatim)
1762 output_ert_inset(os, p.ertEnvironment(name),
1765 parse_text_snippet(p, os, FLAG_END, outer,
1767 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1769 parent_context.new_layout_allowed = new_layout_allowed;
1773 parse_unknown_environment(p, name, os, FLAG_END, outer,
1777 active_environments.pop_back();
1781 /// parses a comment and outputs it to \p os.
1782 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1784 LASSERT(t.cat() == catComment, return);
1785 if (!t.cs().empty()) {
1786 context.check_layout(os);
1787 output_ert_inset(os, '%' + t.cs(), context);
1788 if (p.next_token().cat() == catNewline) {
1789 // A newline after a comment line starts a new
1791 if (context.new_layout_allowed) {
1792 if(!context.atParagraphStart())
1793 // Only start a new paragraph if not already
1794 // done (we might get called recursively)
1795 context.new_paragraph(os);
1797 output_ert_inset(os, "\n", context);
1798 eat_whitespace(p, os, context, true);
1801 // "%\n" combination
1808 * Reads spaces and comments until the first non-space, non-comment token.
1809 * New paragraphs (double newlines or \\par) are handled like simple spaces
1810 * if \p eatParagraph is true.
1811 * Spaces are skipped, but comments are written to \p os.
1813 void eat_whitespace(Parser & p, ostream & os, Context & context,
1817 Token const & t = p.get_token();
1818 if (t.cat() == catComment)
1819 parse_comment(p, os, t, context);
1820 else if ((! eatParagraph && p.isParagraph()) ||
1821 (t.cat() != catSpace && t.cat() != catNewline)) {
1830 * Set a font attribute, parse text and reset the font attribute.
1831 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1832 * \param currentvalue Current value of the attribute. Is set to the new
1833 * value during parsing.
1834 * \param newvalue New value of the attribute
1836 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1837 Context & context, string const & attribute,
1838 string & currentvalue, string const & newvalue)
1840 context.check_layout(os);
1841 string const oldvalue = currentvalue;
1842 currentvalue = newvalue;
1843 os << '\n' << attribute << ' ' << newvalue << "\n";
1844 parse_text_snippet(p, os, flags, outer, context);
1845 context.check_layout(os);
1846 os << '\n' << attribute << ' ' << oldvalue << "\n";
1847 currentvalue = oldvalue;
1851 /// get the arguments of a natbib or jurabib citation command
1852 void get_cite_arguments(Parser & p, bool natbibOrder,
1853 string & before, string & after)
1855 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1857 // text before the citation
1859 // text after the citation
1860 after = p.getFullOpt();
1862 if (!after.empty()) {
1863 before = p.getFullOpt();
1864 if (natbibOrder && !before.empty())
1865 swap(before, after);
1870 /// Convert filenames with TeX macros and/or quotes to something LyX
1872 string const normalize_filename(string const & name)
1877 Token const & t = p.get_token();
1878 if (t.cat() != catEscape)
1880 else if (t.cs() == "lyxdot") {
1881 // This is used by LyX for simple dots in relative
1885 } else if (t.cs() == "space") {
1888 } else if (t.cs() == "string") {
1889 // Convert \string" to " and \string~ to ~
1890 Token const & n = p.next_token();
1891 if (n.asInput() != "\"" && n.asInput() != "~")
1896 // Strip quotes. This is a bit complicated (see latex_path()).
1897 string full = os.str();
1898 if (!full.empty() && full[0] == '"') {
1899 string base = removeExtension(full);
1900 string ext = getExtension(full);
1901 if (!base.empty() && base[base.length()-1] == '"')
1904 return addExtension(trim(base, "\""), ext);
1905 if (full[full.length()-1] == '"')
1908 return trim(full, "\"");
1914 /// Convert \p name from TeX convention (relative to master file) to LyX
1915 /// convention (relative to .lyx file) if it is relative
1916 void fix_child_filename(string & name)
1918 string const absMasterTeX = getMasterFilePath(true);
1919 bool const isabs = FileName::isAbsolute(name);
1920 // convert from "relative to .tex master" to absolute original path
1922 name = makeAbsPath(name, absMasterTeX).absFileName();
1923 bool copyfile = copyFiles();
1924 string const absParentLyX = getParentFilePath(false);
1927 // convert from absolute original path to "relative to master file"
1928 string const rel = to_utf8(makeRelPath(from_utf8(name),
1929 from_utf8(absMasterTeX)));
1930 // re-interpret "relative to .tex file" as "relative to .lyx file"
1931 // (is different if the master .lyx file resides in a
1932 // different path than the master .tex file)
1933 string const absMasterLyX = getMasterFilePath(false);
1934 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1935 // Do not copy if the new path is impossible to create. Example:
1936 // absMasterTeX = "/foo/bar/"
1937 // absMasterLyX = "/bar/"
1938 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1939 if (contains(name, "/../"))
1946 // convert from absolute original path to
1947 // "relative to .lyx file"
1948 name = to_utf8(makeRelPath(from_utf8(abs),
1949 from_utf8(absParentLyX)));
1953 // convert from absolute original path to "relative to .lyx file"
1954 name = to_utf8(makeRelPath(from_utf8(name),
1955 from_utf8(absParentLyX)));
1960 void copy_file(FileName const & src, string dstname)
1964 string const absParent = getParentFilePath(false);
1966 if (FileName::isAbsolute(dstname))
1967 dst = FileName(dstname);
1969 dst = makeAbsPath(dstname, absParent);
1970 string const absMaster = getMasterFilePath(false);
1971 FileName const srcpath = src.onlyPath();
1972 FileName const dstpath = dst.onlyPath();
1973 if (equivalent(srcpath, dstpath))
1975 if (!dstpath.isDirectory()) {
1976 if (!dstpath.createPath()) {
1977 cerr << "Warning: Could not create directory for file `"
1978 << dst.absFileName() << "´." << endl;
1982 if (dst.isReadableFile()) {
1983 if (overwriteFiles())
1984 cerr << "Warning: Overwriting existing file `"
1985 << dst.absFileName() << "´." << endl;
1987 cerr << "Warning: Not overwriting existing file `"
1988 << dst.absFileName() << "´." << endl;
1992 if (!src.copyTo(dst))
1993 cerr << "Warning: Could not copy file `" << src.absFileName()
1994 << "´ to `" << dst.absFileName() << "´." << endl;
1998 /// Parse a literate Chunk section. The initial "<<" is already parsed.
1999 bool parse_chunk(Parser & p, ostream & os, Context & context)
2001 // check whether a chunk is possible here.
2002 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2008 // read the parameters
2009 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2010 if (!params.first) {
2015 Parser::Arg const code = p.verbatimStuff("\n@");
2020 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2021 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2025 // The last newline read is important for paragraph handling
2029 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2030 // We must have a valid layout before outputting the Chunk inset.
2031 context.check_layout(os);
2032 Context chunkcontext(true, context.textclass);
2033 chunkcontext.layout = &context.textclass.plainLayout();
2034 begin_inset(os, "Flex Chunk");
2035 os << "\nstatus open\n";
2036 if (!params.second.empty()) {
2037 chunkcontext.check_layout(os);
2038 Context paramscontext(true, context.textclass);
2039 paramscontext.layout = &context.textclass.plainLayout();
2040 begin_inset(os, "Argument 1");
2041 os << "\nstatus open\n";
2042 output_ert(os, params.second, paramscontext);
2045 output_ert(os, code.second, chunkcontext);
2053 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2054 bool is_macro(Parser & p)
2056 Token first = p.curr_token();
2057 if (first.cat() != catEscape || !p.good())
2059 if (first.cs() == "def")
2061 if (first.cs() != "global" && first.cs() != "long")
2063 Token second = p.get_token();
2065 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2066 second.cat() == catNewline || second.cat() == catComment)) {
2067 second = p.get_token();
2070 bool secondvalid = second.cat() == catEscape;
2072 bool thirdvalid = false;
2073 if (p.good() && first.cs() == "global" && secondvalid &&
2074 second.cs() == "long") {
2075 third = p.get_token();
2077 while (p.good() && !p.isParagraph() &&
2078 (third.cat() == catSpace ||
2079 third.cat() == catNewline ||
2080 third.cat() == catComment)) {
2081 third = p.get_token();
2084 thirdvalid = third.cat() == catEscape;
2086 for (int i = 0; i < pos; ++i)
2091 return (first.cs() == "global" || first.cs() == "long") &&
2092 second.cs() == "def";
2093 return first.cs() == "global" && second.cs() == "long" &&
2094 third.cs() == "def";
2098 /// Parse a macro definition (assumes that is_macro() returned true)
2099 void parse_macro(Parser & p, ostream & os, Context & context)
2101 context.check_layout(os);
2102 Token first = p.curr_token();
2105 string command = first.asInput();
2106 if (first.cs() != "def") {
2108 eat_whitespace(p, os, context, false);
2109 second = p.curr_token();
2110 command += second.asInput();
2111 if (second.cs() != "def") {
2113 eat_whitespace(p, os, context, false);
2114 third = p.curr_token();
2115 command += third.asInput();
2118 eat_whitespace(p, os, context, false);
2119 string const name = p.get_token().cs();
2120 eat_whitespace(p, os, context, false);
2126 while (p.next_token().cat() != catBegin) {
2127 if (p.next_token().cat() == catParameter) {
2132 // followed by number?
2133 if (p.next_token().cat() == catOther) {
2134 string s = p.get_token().asInput();
2136 // number = current arity + 1?
2137 if (s.size() == 1 && s[0] == arity + '0' + 1)
2142 paramtext += p.get_token().cs();
2144 paramtext += p.get_token().cs();
2149 // only output simple (i.e. compatible) macro as FormulaMacros
2150 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2152 context.check_layout(os);
2153 begin_inset(os, "FormulaMacro");
2154 os << "\n\\def" << ert;
2157 output_ert_inset(os, command + ert, context);
2161 void registerExternalTemplatePackages(string const & name)
2163 external::TemplateManager const & etm = external::TemplateManager::get();
2164 external::Template const * const et = etm.getTemplateByName(name);
2167 external::Template::Formats::const_iterator cit = et->formats.end();
2169 cit = et->formats.find("PDFLaTeX");
2170 if (cit == et->formats.end())
2171 // If the template has not specified a PDFLaTeX output,
2172 // we try the LaTeX format.
2173 cit = et->formats.find("LaTeX");
2174 if (cit == et->formats.end())
2176 vector<string>::const_iterator qit = cit->second.requirements.begin();
2177 vector<string>::const_iterator qend = cit->second.requirements.end();
2178 for (; qit != qend; ++qit)
2179 preamble.registerAutomaticallyLoadedPackage(*qit);
2182 } // anonymous namespace
2185 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2188 Layout const * newlayout = 0;
2189 InsetLayout const * newinsetlayout = 0;
2190 char const * const * where = 0;
2191 // Store the latest bibliographystyle, addcontentslineContent and
2192 // nocite{*} option (needed for bibtex inset)
2194 string contentslineContent;
2195 string bibliographystyle = "default";
2196 bool const use_natbib = isProvided("natbib");
2197 bool const use_jurabib = isProvided("jurabib");
2200 // it is impossible to determine the correct encoding for non-CJK Japanese.
2201 // Therefore write a note at the beginning of the document
2202 if (is_nonCJKJapanese) {
2203 context.check_layout(os);
2204 begin_inset(os, "Note Note\n");
2205 os << "status open\n\\begin_layout Plain Layout\n"
2206 << "\\series bold\n"
2207 << "Important information:\n"
2208 << "\\end_layout\n\n"
2209 << "\\begin_layout Plain Layout\n"
2210 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2211 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2212 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2213 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2214 << " and specify the encoding using the -e command-line switch.\n"
2215 << " In addition, you might want to double check that the desired output encoding\n"
2216 << " is correctly selected in Document > Settings > Language.\n"
2217 << "\\end_layout\n";
2219 is_nonCJKJapanese = false;
2223 Token const & t = p.get_token();
2225 debugToken(cerr, t, flags);
2228 if (flags & FLAG_ITEM) {
2229 if (t.cat() == catSpace)
2232 flags &= ~FLAG_ITEM;
2233 if (t.cat() == catBegin) {
2234 // skip the brace and collect everything to the next matching
2236 flags |= FLAG_BRACE_LAST;
2240 // handle only this single token, leave the loop if done
2241 flags |= FLAG_LEAVE;
2244 if (t.cat() != catEscape && t.character() == ']' &&
2245 (flags & FLAG_BRACK_LAST))
2247 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2250 // If there is anything between \end{env} and \begin{env} we
2251 // don't need to output a separator.
2252 if (t.cat() != catSpace && t.cat() != catNewline &&
2253 t.asInput() != "\\begin")
2259 bool const starred = p.next_token().asInput() == "*";
2260 string const starredname(starred ? (t.cs() + '*') : t.cs());
2261 if (t.cat() == catMath) {
2262 // we are inside some text mode thingy, so opening new math is allowed
2263 context.check_layout(os);
2264 begin_inset(os, "Formula ");
2265 Token const & n = p.get_token();
2266 bool const display(n.cat() == catMath && outer);
2268 // TeX's $$...$$ syntax for displayed math
2270 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2272 p.get_token(); // skip the second '$' token
2274 // simple $...$ stuff
2277 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2282 // Prevent the conversion of a line break to a
2283 // space (bug 7668). This does not change the
2284 // output, but looks ugly in LyX.
2285 eat_whitespace(p, os, context, false);
2289 else if (t.cat() == catSuper || t.cat() == catSub)
2290 cerr << "catcode " << t << " illegal in text mode\n";
2292 // Basic support for english quotes. This should be
2293 // extended to other quotes, but is not so easy (a
2294 // left english quote is the same as a right german
2296 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2297 context.check_layout(os);
2298 begin_inset(os, "Quotes ");
2304 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2305 context.check_layout(os);
2306 begin_inset(os, "Quotes ");
2313 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2314 context.check_layout(os);
2315 begin_inset(os, "Quotes ");
2322 else if (t.asInput() == "<"
2323 && p.next_token().asInput() == "<") {
2324 bool has_chunk = false;
2328 has_chunk = parse_chunk(p, os, context);
2334 context.check_layout(os);
2335 begin_inset(os, "Quotes ");
2336 //FIXME: this is a right danish quote;
2337 // why not a left french quote?
2345 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2346 check_space(p, os, context);
2348 else if (t.character() == '[' && noweb_mode &&
2349 p.next_token().character() == '[') {
2350 // These can contain underscores
2352 string const s = p.getFullOpt() + ']';
2353 if (p.next_token().character() == ']')
2356 cerr << "Warning: Inserting missing ']' in '"
2357 << s << "'." << endl;
2358 output_ert_inset(os, s, context);
2361 else if (t.cat() == catLetter) {
2362 context.check_layout(os);
2363 // Workaround for bug 4752.
2364 // FIXME: This whole code block needs to be removed
2365 // when the bug is fixed and tex2lyx produces
2366 // the updated file format.
2367 // The replacement algorithm in LyX is so stupid that
2368 // it even translates a phrase if it is part of a word.
2369 bool handled = false;
2370 for (int const * l = known_phrase_lengths; *l; ++l) {
2371 string phrase = t.cs();
2372 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2373 phrase += p.get_token().cs();
2374 if (is_known(phrase, known_coded_phrases)) {
2375 output_ert_inset(os, phrase, context);
2379 for (size_t i = 1; i < phrase.length(); ++i)
2387 else if (t.cat() == catOther ||
2388 t.cat() == catAlign ||
2389 t.cat() == catParameter) {
2390 context.check_layout(os);
2391 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2392 context.merging_hyphens_allowed &&
2393 context.font.family != "ttfamily" &&
2394 !context.layout->pass_thru) {
2395 if (p.next_next_token().asInput() == "-") {
2397 os << to_utf8(docstring(1, 0x2014));
2401 os << to_utf8(docstring(1, 0x2013));
2404 // This translates "&" to "\\&" which may be wrong...
2408 else if (p.isParagraph()) {
2409 if (context.new_layout_allowed)
2410 context.new_paragraph(os);
2412 output_ert_inset(os, "\\par ", context);
2413 eat_whitespace(p, os, context, true);
2416 else if (t.cat() == catActive) {
2417 context.check_layout(os);
2418 if (t.character() == '~') {
2419 if (context.layout->free_spacing)
2422 begin_inset(os, "space ~\n");
2429 else if (t.cat() == catBegin) {
2430 Token const next = p.next_token();
2431 Token const end = p.next_next_token();
2432 if (next.cat() == catEnd) {
2434 Token const prev = p.prev_token();
2436 if (p.next_token().character() == '`')
2437 ; // ignore it in {}``
2439 output_ert_inset(os, "{}", context);
2440 } else if (next.cat() == catEscape &&
2441 is_known(next.cs(), known_quotes) &&
2442 end.cat() == catEnd) {
2443 // Something like {\textquoteright} (e.g.
2444 // from writer2latex). LyX writes
2445 // \textquoteright{}, so we may skip the
2446 // braces here for better readability.
2447 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2449 } else if (p.next_token().asInput() == "\\ascii") {
2450 // handle the \ascii characters
2451 // (the case without braces is handled later)
2452 // the code is "{\ascii\xxx}"
2453 p.get_token(); // eat \ascii
2454 string name2 = p.get_token().asInput();
2455 p.get_token(); // eat the final '}'
2456 string const name = "{\\ascii" + name2 + "}";
2460 // get the character from unicodesymbols
2461 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2462 Encodings::TEXT_CMD, termination, rem, &req);
2464 context.check_layout(os);
2467 output_ert_inset(os,
2468 to_utf8(rem), context);
2469 for (set<string>::const_iterator it = req.begin();
2470 it != req.end(); ++it)
2471 preamble.registerAutomaticallyLoadedPackage(*it);
2473 // we did not find a non-ert version
2474 output_ert_inset(os, name, context);
2476 context.check_layout(os);
2477 // special handling of font attribute changes
2478 Token const prev = p.prev_token();
2479 TeXFont const oldFont = context.font;
2480 if (next.character() == '[' ||
2481 next.character() == ']' ||
2482 next.character() == '*') {
2484 if (p.next_token().cat() == catEnd) {
2489 output_ert_inset(os, "{", context);
2490 parse_text_snippet(p, os,
2493 output_ert_inset(os, "}", context);
2495 } else if (! context.new_layout_allowed) {
2496 output_ert_inset(os, "{", context);
2497 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2499 output_ert_inset(os, "}", context);
2500 } else if (is_known(next.cs(), known_sizes)) {
2501 // next will change the size, so we must
2503 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2505 if (!context.atParagraphStart())
2507 << context.font.size << "\n";
2508 } else if (is_known(next.cs(), known_font_families)) {
2509 // next will change the font family, so we
2510 // must reset it here
2511 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2513 if (!context.atParagraphStart())
2515 << context.font.family << "\n";
2516 } else if (is_known(next.cs(), known_font_series)) {
2517 // next will change the font series, so we
2518 // must reset it here
2519 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2521 if (!context.atParagraphStart())
2523 << context.font.series << "\n";
2524 } else if (is_known(next.cs(), known_font_shapes)) {
2525 // next will change the font shape, so we
2526 // must reset it here
2527 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2529 if (!context.atParagraphStart())
2531 << context.font.shape << "\n";
2532 } else if (is_known(next.cs(), known_old_font_families) ||
2533 is_known(next.cs(), known_old_font_series) ||
2534 is_known(next.cs(), known_old_font_shapes)) {
2535 // next will change the font family, series
2536 // and shape, so we must reset it here
2537 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2539 if (!context.atParagraphStart())
2541 << context.font.family
2543 << context.font.series
2545 << context.font.shape << "\n";
2547 output_ert_inset(os, "{", context);
2548 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2550 output_ert_inset(os, "}", context);
2555 else if (t.cat() == catEnd) {
2556 if (flags & FLAG_BRACE_LAST) {
2559 cerr << "stray '}' in text\n";
2560 output_ert_inset(os, "}", context);
2563 else if (t.cat() == catComment)
2564 parse_comment(p, os, t, context);
2567 // control sequences
2570 else if (t.cs() == "(" || t.cs() == "[") {
2571 bool const simple = t.cs() == "(";
2572 context.check_layout(os);
2573 begin_inset(os, "Formula");
2574 os << " \\" << t.cs();
2575 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2576 os << '\\' << (simple ? ')' : ']');
2579 // Prevent the conversion of a line break to a
2580 // space (bug 7668). This does not change the
2581 // output, but looks ugly in LyX.
2582 eat_whitespace(p, os, context, false);
2586 else if (t.cs() == "begin")
2587 parse_environment(p, os, outer, last_env,
2590 else if (t.cs() == "end") {
2591 if (flags & FLAG_END) {
2592 // eat environment name
2593 string const name = p.getArg('{', '}');
2594 if (name != active_environment())
2595 cerr << "\\end{" + name + "} does not match \\begin{"
2596 + active_environment() + "}\n";
2599 p.error("found 'end' unexpectedly");
2602 else if (t.cs() == "item") {
2604 bool const optarg = p.hasOpt();
2606 // FIXME: This swallows comments, but we cannot use
2607 // eat_whitespace() since we must not output
2608 // anything before the item.
2609 p.skip_spaces(true);
2610 s = p.verbatimOption();
2612 p.skip_spaces(false);
2614 context.check_layout(os);
2615 if (context.has_item) {
2616 // An item in an unknown list-like environment
2617 // FIXME: Do this in check_layout()!
2618 context.has_item = false;
2620 output_ert_inset(os, "\\item", context);
2622 output_ert_inset(os, "\\item ", context);
2625 if (context.layout->labeltype != LABEL_MANUAL) {
2626 // handle option of itemize item
2627 begin_inset(os, "Argument item:1\n");
2628 os << "status open\n";
2629 os << "\n\\begin_layout Plain Layout\n";
2631 os << parse_text_snippet(p2,
2632 FLAG_BRACK_LAST, outer, context);
2633 // we must not use context.check_end_layout(os)
2634 // because that would close the outer itemize layout
2635 os << "\n\\end_layout\n";
2637 eat_whitespace(p, os, context, false);
2638 } else if (!s.empty()) {
2639 // LyX adds braces around the argument,
2640 // so we need to remove them here.
2641 if (s.size() > 2 && s[0] == '{' &&
2642 s[s.size()-1] == '}')
2643 s = s.substr(1, s.size()-2);
2644 // If the argument contains a space we
2645 // must put it into ERT: Otherwise LyX
2646 // would misinterpret the space as
2647 // item delimiter (bug 7663)
2648 if (contains(s, ' ')) {
2649 output_ert_inset(os, s, context);
2652 os << parse_text_snippet(p2,
2653 FLAG_BRACK_LAST, outer, context);
2655 // The space is needed to separate the
2656 // item from the rest of the sentence.
2658 eat_whitespace(p, os, context, false);
2663 else if (t.cs() == "bibitem") {
2665 context.check_layout(os);
2666 eat_whitespace(p, os, context, false);
2667 string label = convert_command_inset_arg(p.verbatimOption());
2668 string key = convert_command_inset_arg(p.verbatim_item());
2669 if (contains(label, '\\') || contains(key, '\\')) {
2670 // LyX can't handle LaTeX commands in labels or keys
2671 output_ert_inset(os, t.asInput() + '[' + label +
2672 "]{" + p.verbatim_item() + '}',
2675 begin_command_inset(os, "bibitem", "bibitem");
2676 os << "label \"" << label << "\"\n"
2677 "key \"" << key << "\"\n";
2682 else if (is_macro(p)) {
2683 // catch the case of \def\inputGnumericTable
2685 if (t.cs() == "def") {
2686 Token second = p.next_token();
2687 if (second.cs() == "inputGnumericTable") {
2691 Token third = p.get_token();
2693 if (third.cs() == "input") {
2697 string name = normalize_filename(p.verbatim_item());
2698 string const path = getMasterFilePath(true);
2699 // We want to preserve relative / absolute filenames,
2700 // therefore path is only used for testing
2701 // The file extension is in every case ".tex".
2702 // So we need to remove this extension and check for
2703 // the original one.
2704 name = removeExtension(name);
2705 if (!makeAbsPath(name, path).exists()) {
2706 char const * const Gnumeric_formats[] = {"gnumeric",
2708 string const Gnumeric_name =
2709 find_file(name, path, Gnumeric_formats);
2710 if (!Gnumeric_name.empty())
2711 name = Gnumeric_name;
2713 FileName const absname = makeAbsPath(name, path);
2714 if (absname.exists()) {
2715 fix_child_filename(name);
2716 copy_file(absname, name);
2718 cerr << "Warning: Could not find file '"
2719 << name << "'." << endl;
2720 context.check_layout(os);
2721 begin_inset(os, "External\n\ttemplate ");
2722 os << "GnumericSpreadsheet\n\tfilename "
2725 context.check_layout(os);
2727 // register the packages that are automatically loaded
2728 // by the Gnumeric template
2729 registerExternalTemplatePackages("GnumericSpreadsheet");
2734 parse_macro(p, os, context);
2737 else if (t.cs() == "noindent") {
2739 context.add_par_extra_stuff("\\noindent\n");
2742 else if (t.cs() == "appendix") {
2743 context.add_par_extra_stuff("\\start_of_appendix\n");
2744 // We need to start a new paragraph. Otherwise the
2745 // appendix in 'bla\appendix\chapter{' would start
2747 context.new_paragraph(os);
2748 // We need to make sure that the paragraph is
2749 // generated even if it is empty. Otherwise the
2750 // appendix in '\par\appendix\par\chapter{' would
2752 context.check_layout(os);
2753 // FIXME: This is a hack to prevent paragraph
2754 // deletion if it is empty. Handle this better!
2755 output_ert_inset(os,
2756 "%dummy comment inserted by tex2lyx to "
2757 "ensure that this paragraph is not empty",
2759 // Both measures above may generate an additional
2760 // empty paragraph, but that does not hurt, because
2761 // whitespace does not matter here.
2762 eat_whitespace(p, os, context, true);
2765 // Must catch empty dates before findLayout is called below
2766 else if (t.cs() == "date") {
2767 eat_whitespace(p, os, context, false);
2769 string const date = p.verbatim_item();
2772 preamble.suppressDate(true);
2775 preamble.suppressDate(false);
2776 if (context.new_layout_allowed &&
2777 (newlayout = findLayout(context.textclass,
2780 output_command_layout(os, p, outer,
2781 context, newlayout);
2782 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2783 if (!preamble.titleLayoutFound())
2784 preamble.titleLayoutFound(newlayout->intitle);
2785 set<string> const & req = newlayout->requires();
2786 set<string>::const_iterator it = req.begin();
2787 set<string>::const_iterator en = req.end();
2788 for (; it != en; ++it)
2789 preamble.registerAutomaticallyLoadedPackage(*it);
2791 output_ert_inset(os,
2792 "\\date{" + p.verbatim_item() + '}',
2797 // Starred section headings
2798 // Must attempt to parse "Section*" before "Section".
2799 else if ((p.next_token().asInput() == "*") &&
2800 context.new_layout_allowed &&
2801 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2804 output_command_layout(os, p, outer, context, newlayout);
2806 if (!preamble.titleLayoutFound())
2807 preamble.titleLayoutFound(newlayout->intitle);
2808 set<string> const & req = newlayout->requires();
2809 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2810 preamble.registerAutomaticallyLoadedPackage(*it);
2813 // Section headings and the like
2814 else if (context.new_layout_allowed &&
2815 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2817 output_command_layout(os, p, outer, context, newlayout);
2819 if (!preamble.titleLayoutFound())
2820 preamble.titleLayoutFound(newlayout->intitle);
2821 set<string> const & req = newlayout->requires();
2822 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2823 preamble.registerAutomaticallyLoadedPackage(*it);
2826 else if (t.cs() == "subfloat") {
2827 // the syntax is \subfloat[list entry][sub caption]{content}
2828 // if it is a table of figure depends on the surrounding float
2829 // FIXME: second optional argument is not parsed
2830 bool has_caption = false;
2832 // do nothing if there is no outer float
2833 if (!float_type.empty()) {
2834 context.check_layout(os);
2836 begin_inset(os, "Float " + float_type + "\n");
2838 << "\nsideways false"
2839 << "\nstatus collapsed\n\n";
2842 if (p.next_token().cat() != catEscape &&
2843 p.next_token().character() == '[') {
2844 p.get_token(); // eat '['
2845 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2849 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2850 // the caption comes always as the last
2852 // we must make sure that the caption gets a \begin_layout
2853 os << "\n\\begin_layout Plain Layout";
2855 begin_inset(os, "Caption Standard\n");
2856 Context newcontext(true, context.textclass,
2857 0, 0, context.font);
2858 newcontext.check_layout(os);
2859 os << caption << "\n";
2860 newcontext.check_end_layout(os);
2861 // We don't need really a new paragraph, but
2862 // we must make sure that the next item gets a \begin_layout.
2863 //newcontext.new_paragraph(os);
2867 // We don't need really a new paragraph, but
2868 // we must make sure that the next item gets a \begin_layout.
2870 context.new_paragraph(os);
2873 context.check_end_layout(os);
2874 // close the layout we opened
2876 os << "\n\\end_layout\n";
2878 // if the float type is not supported or there is no surrounding float
2881 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2882 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2883 "]{" + p.verbatim_item() + '}', context);
2885 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2889 else if (t.cs() == "includegraphics") {
2890 bool const clip = p.next_token().asInput() == "*";
2893 string const arg = p.getArg('[', ']');
2894 map<string, string> opts;
2895 vector<string> keys;
2896 split_map(arg, opts, keys);
2898 opts["clip"] = string();
2899 string name = normalize_filename(p.verbatim_item());
2901 string const path = getMasterFilePath(true);
2902 // We want to preserve relative / absolute filenames,
2903 // therefore path is only used for testing
2904 if (!makeAbsPath(name, path).exists()) {
2905 // The file extension is probably missing.
2906 // Now try to find it out.
2907 string const dvips_name =
2908 find_file(name, path,
2909 known_dvips_graphics_formats);
2910 string const pdftex_name =
2911 find_file(name, path,
2912 known_pdftex_graphics_formats);
2913 if (!dvips_name.empty()) {
2914 if (!pdftex_name.empty()) {
2915 cerr << "This file contains the "
2917 "\"\\includegraphics{"
2919 "However, files\n\""
2920 << dvips_name << "\" and\n\""
2921 << pdftex_name << "\"\n"
2922 "both exist, so I had to make a "
2923 "choice and took the first one.\n"
2924 "Please move the unwanted one "
2925 "someplace else and try again\n"
2926 "if my choice was wrong."
2930 } else if (!pdftex_name.empty()) {
2936 FileName const absname = makeAbsPath(name, path);
2937 if (absname.exists()) {
2938 fix_child_filename(name);
2939 copy_file(absname, name);
2941 cerr << "Warning: Could not find graphics file '"
2942 << name << "'." << endl;
2944 context.check_layout(os);
2945 begin_inset(os, "Graphics ");
2946 os << "\n\tfilename " << name << '\n';
2947 if (opts.find("width") != opts.end())
2949 << translate_len(opts["width"]) << '\n';
2950 if (opts.find("height") != opts.end())
2952 << translate_len(opts["height"]) << '\n';
2953 if (opts.find("scale") != opts.end()) {
2954 istringstream iss(opts["scale"]);
2958 os << "\tscale " << val << '\n';
2960 if (opts.find("angle") != opts.end()) {
2961 os << "\trotateAngle "
2962 << opts["angle"] << '\n';
2963 vector<string>::const_iterator a =
2964 find(keys.begin(), keys.end(), "angle");
2965 vector<string>::const_iterator s =
2966 find(keys.begin(), keys.end(), "width");
2967 if (s == keys.end())
2968 s = find(keys.begin(), keys.end(), "height");
2969 if (s == keys.end())
2970 s = find(keys.begin(), keys.end(), "scale");
2971 if (s != keys.end() && distance(s, a) > 0)
2972 os << "\tscaleBeforeRotation\n";
2974 if (opts.find("origin") != opts.end()) {
2976 string const opt = opts["origin"];
2977 if (opt.find('l') != string::npos) ss << "left";
2978 if (opt.find('r') != string::npos) ss << "right";
2979 if (opt.find('c') != string::npos) ss << "center";
2980 if (opt.find('t') != string::npos) ss << "Top";
2981 if (opt.find('b') != string::npos) ss << "Bottom";
2982 if (opt.find('B') != string::npos) ss << "Baseline";
2983 if (!ss.str().empty())
2984 os << "\trotateOrigin " << ss.str() << '\n';
2986 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2988 if (opts.find("keepaspectratio") != opts.end())
2989 os << "\tkeepAspectRatio\n";
2990 if (opts.find("clip") != opts.end())
2992 if (opts.find("draft") != opts.end())
2994 if (opts.find("bb") != opts.end())
2995 os << "\tBoundingBox "
2996 << opts["bb"] << '\n';
2997 int numberOfbbOptions = 0;
2998 if (opts.find("bbllx") != opts.end())
2999 numberOfbbOptions++;
3000 if (opts.find("bblly") != opts.end())
3001 numberOfbbOptions++;
3002 if (opts.find("bburx") != opts.end())
3003 numberOfbbOptions++;
3004 if (opts.find("bbury") != opts.end())
3005 numberOfbbOptions++;
3006 if (numberOfbbOptions == 4)
3007 os << "\tBoundingBox "
3008 << opts["bbllx"] << " " << opts["bblly"] << " "
3009 << opts["bburx"] << " " << opts["bbury"] << '\n';
3010 else if (numberOfbbOptions > 0)
3011 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3012 numberOfbbOptions = 0;
3013 if (opts.find("natwidth") != opts.end())
3014 numberOfbbOptions++;
3015 if (opts.find("natheight") != opts.end())
3016 numberOfbbOptions++;
3017 if (numberOfbbOptions == 2)
3018 os << "\tBoundingBox 0bp 0bp "
3019 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3020 else if (numberOfbbOptions > 0)
3021 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3022 ostringstream special;
3023 if (opts.find("hiresbb") != opts.end())
3024 special << "hiresbb,";
3025 if (opts.find("trim") != opts.end())
3027 if (opts.find("viewport") != opts.end())
3028 special << "viewport=" << opts["viewport"] << ',';
3029 if (opts.find("totalheight") != opts.end())
3030 special << "totalheight=" << opts["totalheight"] << ',';
3031 if (opts.find("type") != opts.end())
3032 special << "type=" << opts["type"] << ',';
3033 if (opts.find("ext") != opts.end())
3034 special << "ext=" << opts["ext"] << ',';
3035 if (opts.find("read") != opts.end())
3036 special << "read=" << opts["read"] << ',';
3037 if (opts.find("command") != opts.end())
3038 special << "command=" << opts["command"] << ',';
3039 string s_special = special.str();
3040 if (!s_special.empty()) {
3041 // We had special arguments. Remove the trailing ','.
3042 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3044 // TODO: Handle the unknown settings better.
3045 // Warn about invalid options.
3046 // Check whether some option was given twice.
3048 preamble.registerAutomaticallyLoadedPackage("graphicx");
3051 else if (t.cs() == "footnote" ||
3052 (t.cs() == "thanks" && context.layout->intitle)) {
3054 context.check_layout(os);
3055 begin_inset(os, "Foot\n");
3056 os << "status collapsed\n\n";
3057 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3061 else if (t.cs() == "marginpar") {
3063 context.check_layout(os);
3064 begin_inset(os, "Marginal\n");
3065 os << "status collapsed\n\n";
3066 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3070 else if (t.cs() == "lstinline") {
3072 parse_listings(p, os, context, true);
3075 else if (t.cs() == "ensuremath") {
3077 context.check_layout(os);
3078 string const s = p.verbatim_item();
3079 //FIXME: this never triggers in UTF8
3080 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3083 output_ert_inset(os, "\\ensuremath{" + s + "}",
3087 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3088 if (preamble.titleLayoutFound()) {
3090 skip_spaces_braces(p);
3092 output_ert_inset(os, t.asInput(), context);
3095 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3096 context.check_layout(os);
3097 begin_command_inset(os, "toc", t.cs());
3099 skip_spaces_braces(p);
3100 if (t.cs() == "lstlistoflistings")
3101 preamble.registerAutomaticallyLoadedPackage("listings");
3104 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3105 context.check_layout(os);
3106 if (t.cs() == "listoffigures")
3107 begin_inset(os, "FloatList figure\n");
3109 begin_inset(os, "FloatList table\n");
3111 skip_spaces_braces(p);
3114 else if (t.cs() == "listof") {
3115 p.skip_spaces(true);
3116 string const name = p.get_token().cs();
3117 if (context.textclass.floats().typeExist(name)) {
3118 context.check_layout(os);
3119 begin_inset(os, "FloatList ");
3122 p.get_token(); // swallow second arg
3124 output_ert_inset(os, "\\listof{" + name + "}", context);
3127 else if ((where = is_known(t.cs(), known_text_font_families)))
3128 parse_text_attributes(p, os, FLAG_ITEM, outer,
3129 context, "\\family", context.font.family,
3130 known_coded_font_families[where - known_text_font_families]);
3132 else if ((where = is_known(t.cs(), known_text_font_series)))
3133 parse_text_attributes(p, os, FLAG_ITEM, outer,
3134 context, "\\series", context.font.series,
3135 known_coded_font_series[where - known_text_font_series]);
3137 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3138 parse_text_attributes(p, os, FLAG_ITEM, outer,
3139 context, "\\shape", context.font.shape,
3140 known_coded_font_shapes[where - known_text_font_shapes]);
3142 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3143 context.check_layout(os);
3144 TeXFont oldFont = context.font;
3145 context.font.init();
3146 context.font.size = oldFont.size;
3147 os << "\n\\family " << context.font.family << "\n";
3148 os << "\n\\series " << context.font.series << "\n";
3149 os << "\n\\shape " << context.font.shape << "\n";
3150 if (t.cs() == "textnormal") {
3151 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3152 output_font_change(os, context.font, oldFont);
3153 context.font = oldFont;
3155 eat_whitespace(p, os, context, false);
3158 else if (t.cs() == "textcolor") {
3159 // scheme is \textcolor{color name}{text}
3160 string const color = p.verbatim_item();
3161 // we only support the predefined colors of the color package
3162 if (color == "black" || color == "blue" || color == "cyan"
3163 || color == "green" || color == "magenta" || color == "red"
3164 || color == "white" || color == "yellow") {
3165 context.check_layout(os);
3166 os << "\n\\color " << color << "\n";
3167 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3168 context.check_layout(os);
3169 os << "\n\\color inherit\n";
3170 preamble.registerAutomaticallyLoadedPackage("color");
3172 // for custom defined colors
3173 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3176 else if (t.cs() == "underbar" || t.cs() == "uline") {
3177 // \underbar is not 100% correct (LyX outputs \uline
3178 // of ulem.sty). The difference is that \ulem allows
3179 // line breaks, and \underbar does not.
3180 // Do NOT handle \underline.
3181 // \underbar cuts through y, g, q, p etc.,
3182 // \underline does not.
3183 context.check_layout(os);
3184 os << "\n\\bar under\n";
3185 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3186 context.check_layout(os);
3187 os << "\n\\bar default\n";
3188 preamble.registerAutomaticallyLoadedPackage("ulem");
3191 else if (t.cs() == "sout") {
3192 context.check_layout(os);
3193 os << "\n\\strikeout on\n";
3194 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3195 context.check_layout(os);
3196 os << "\n\\strikeout default\n";
3197 preamble.registerAutomaticallyLoadedPackage("ulem");
3200 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3201 t.cs() == "emph" || t.cs() == "noun") {
3202 context.check_layout(os);
3203 os << "\n\\" << t.cs() << " on\n";
3204 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3205 context.check_layout(os);
3206 os << "\n\\" << t.cs() << " default\n";
3207 if (t.cs() == "uuline" || t.cs() == "uwave")
3208 preamble.registerAutomaticallyLoadedPackage("ulem");
3211 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3212 context.check_layout(os);
3213 string name = p.getArg('{', '}');
3214 string localtime = p.getArg('{', '}');
3215 preamble.registerAuthor(name);
3216 Author const & author = preamble.getAuthor(name);
3217 // from_asctime_utc() will fail if LyX decides to output the
3218 // time in the text language.
3219 time_t ptime = from_asctime_utc(localtime);
3220 if (ptime == static_cast<time_t>(-1)) {
3221 cerr << "Warning: Could not parse time `" << localtime
3222 << "´ for change tracking, using current time instead.\n";
3223 ptime = current_time();
3225 if (t.cs() == "lyxadded")
3226 os << "\n\\change_inserted ";
3228 os << "\n\\change_deleted ";
3229 os << author.bufferId() << ' ' << ptime << '\n';
3230 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3231 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3232 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3233 LaTeXPackages::isAvailable("xcolor");
3234 // No need to test for luatex, since luatex comes in
3235 // two flavours (dvi and pdf), like latex, and those
3236 // are detected by pdflatex.
3237 if (pdflatex || xetex) {
3239 preamble.registerAutomaticallyLoadedPackage("ulem");
3240 preamble.registerAutomaticallyLoadedPackage("xcolor");
3241 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3245 preamble.registerAutomaticallyLoadedPackage("dvipost");
3246 } else if (xcolorulem) {
3247 preamble.registerAutomaticallyLoadedPackage("ulem");
3248 preamble.registerAutomaticallyLoadedPackage("xcolor");
3253 else if (t.cs() == "textipa") {
3254 context.check_layout(os);
3255 begin_inset(os, "IPA\n");
3256 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3257 context.merging_hyphens_allowed = false;
3258 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3259 context.merging_hyphens_allowed = merging_hyphens_allowed;
3261 preamble.registerAutomaticallyLoadedPackage("tipa");
3262 preamble.registerAutomaticallyLoadedPackage("tipx");
3265 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3266 context.check_layout(os);
3267 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3268 os << "status open\n";
3269 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3274 else if (t.cs() == "textvertline") {
3275 // FIXME: This is not correct, \textvertline is higher than |
3281 else if (t.cs() == "tone" ) {
3282 context.check_layout(os);
3283 // register the tone package
3284 preamble.registerAutomaticallyLoadedPackage("tone");
3285 string content = trimSpaceAndEol(p.verbatim_item());
3286 string command = t.asInput() + "{" + content + "}";
3287 // some tones can be detected by unicodesymbols, some need special code
3288 if (is_known(content, known_tones)) {
3289 os << "\\IPAChar " << command << "\n";
3292 // try to see whether the string is in unicodesymbols
3296 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3297 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3298 termination, rem, &req);
3302 output_ert_inset(os, to_utf8(rem), context);
3303 for (set<string>::const_iterator it = req.begin();
3304 it != req.end(); ++it)
3305 preamble.registerAutomaticallyLoadedPackage(*it);
3307 // we did not find a non-ert version
3308 output_ert_inset(os, command, context);
3311 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3312 t.cs() == "vphantom") {
3313 context.check_layout(os);
3314 if (t.cs() == "phantom")
3315 begin_inset(os, "Phantom Phantom\n");
3316 if (t.cs() == "hphantom")
3317 begin_inset(os, "Phantom HPhantom\n");
3318 if (t.cs() == "vphantom")
3319 begin_inset(os, "Phantom VPhantom\n");
3320 os << "status open\n";
3321 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3326 else if (t.cs() == "href") {
3327 context.check_layout(os);
3328 string target = convert_command_inset_arg(p.verbatim_item());
3329 string name = convert_command_inset_arg(p.verbatim_item());
3331 size_t i = target.find(':');
3332 if (i != string::npos) {
3333 type = target.substr(0, i + 1);
3334 if (type == "mailto:" || type == "file:")
3335 target = target.substr(i + 1);
3336 // handle the case that name is equal to target, except of "http://"
3337 else if (target.substr(i + 3) == name && type == "http:")
3340 begin_command_inset(os, "href", "href");
3342 os << "name \"" << name << "\"\n";
3343 os << "target \"" << target << "\"\n";
3344 if (type == "mailto:" || type == "file:")
3345 os << "type \"" << type << "\"\n";
3347 skip_spaces_braces(p);
3350 else if (t.cs() == "lyxline") {
3351 // swallow size argument (it is not used anyway)
3353 if (!context.atParagraphStart()) {
3354 // so our line is in the middle of a paragraph
3355 // we need to add a new line, lest this line
3356 // follow the other content on that line and
3357 // run off the side of the page
3358 // FIXME: This may create an empty paragraph,
3359 // but without that it would not be
3360 // possible to set noindent below.
3361 // Fortunately LaTeX does not care
3362 // about the empty paragraph.
3363 context.new_paragraph(os);
3365 if (preamble.indentParagraphs()) {
3366 // we need to unindent, lest the line be too long
3367 context.add_par_extra_stuff("\\noindent\n");
3369 context.check_layout(os);
3370 begin_command_inset(os, "line", "rule");
3371 os << "offset \"0.5ex\"\n"
3372 "width \"100line%\"\n"
3377 else if (t.cs() == "rule") {
3378 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3379 string const width = p.getArg('{', '}');
3380 string const thickness = p.getArg('{', '}');
3381 context.check_layout(os);
3382 begin_command_inset(os, "line", "rule");
3383 if (!offset.empty())
3384 os << "offset \"" << translate_len(offset) << "\"\n";
3385 os << "width \"" << translate_len(width) << "\"\n"
3386 "height \"" << translate_len(thickness) << "\"\n";
3390 else if (is_known(t.cs(), known_phrases) ||
3391 (t.cs() == "protect" &&
3392 p.next_token().cat() == catEscape &&
3393 is_known(p.next_token().cs(), known_phrases))) {
3394 // LyX sometimes puts a \protect in front, so we have to ignore it
3395 // FIXME: This needs to be changed when bug 4752 is fixed.
3397 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3399 context.check_layout(os);
3400 os << known_coded_phrases[where - known_phrases];
3401 skip_spaces_braces(p);
3404 // handle refstyle first to catch \eqref which can also occur
3405 // without refstyle. Only recognize these commands if
3406 // refstyle.sty was found in the preamble (otherwise \eqref
3407 // and user defined ref commands could be misdetected).
3408 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3409 preamble.refstyle()) {
3410 context.check_layout(os);
3411 begin_command_inset(os, "ref", "formatted");
3412 os << "reference \"";
3413 os << known_refstyle_prefixes[where - known_refstyle_commands]
3415 os << convert_command_inset_arg(p.verbatim_item())
3418 preamble.registerAutomaticallyLoadedPackage("refstyle");
3421 // if refstyle is used, we must not convert \prettyref to a
3422 // formatted reference, since that would result in a refstyle command.
3423 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3424 (t.cs() != "prettyref" || !preamble.refstyle())) {
3425 string const opt = p.getOpt();
3427 context.check_layout(os);
3428 begin_command_inset(os, "ref",
3429 known_coded_ref_commands[where - known_ref_commands]);
3430 os << "reference \""
3431 << convert_command_inset_arg(p.verbatim_item())
3434 if (t.cs() == "vref" || t.cs() == "vpageref")
3435 preamble.registerAutomaticallyLoadedPackage("varioref");
3436 else if (t.cs() == "prettyref")
3437 preamble.registerAutomaticallyLoadedPackage("prettyref");
3439 // LyX does not yet support optional arguments of ref commands
3440 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3441 p.verbatim_item() + '}', context);
3445 else if (use_natbib &&
3446 is_known(t.cs(), known_natbib_commands) &&
3447 ((t.cs() != "citefullauthor" &&
3448 t.cs() != "citeyear" &&
3449 t.cs() != "citeyearpar") ||
3450 p.next_token().asInput() != "*")) {
3451 context.check_layout(os);
3452 string command = t.cs();
3453 if (p.next_token().asInput() == "*") {
3457 if (command == "citefullauthor")
3458 // alternative name for "\\citeauthor*"
3459 command = "citeauthor*";
3461 // text before the citation
3463 // text after the citation
3465 get_cite_arguments(p, true, before, after);
3467 if (command == "cite") {
3468 // \cite without optional argument means
3469 // \citet, \cite with at least one optional
3470 // argument means \citep.
3471 if (before.empty() && after.empty())
3476 if (before.empty() && after == "[]")
3477 // avoid \citet[]{a}
3479 else if (before == "[]" && after == "[]") {
3480 // avoid \citet[][]{a}
3484 // remove the brackets around after and before
3485 if (!after.empty()) {
3487 after.erase(after.length() - 1, 1);
3488 after = convert_command_inset_arg(after);
3490 if (!before.empty()) {
3492 before.erase(before.length() - 1, 1);
3493 before = convert_command_inset_arg(before);
3495 begin_command_inset(os, "citation", command);
3496 os << "after " << '"' << after << '"' << "\n";
3497 os << "before " << '"' << before << '"' << "\n";
3499 << convert_command_inset_arg(p.verbatim_item())
3502 // Need to set the cite engine if natbib is loaded by
3503 // the document class directly
3504 if (preamble.citeEngine() == "basic")
3505 preamble.citeEngine("natbib");
3508 else if (use_jurabib &&
3509 is_known(t.cs(), known_jurabib_commands) &&
3510 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3511 context.check_layout(os);
3512 string command = t.cs();
3513 if (p.next_token().asInput() == "*") {
3517 char argumentOrder = '\0';
3518 vector<string> const options =
3519 preamble.getPackageOptions("jurabib");
3520 if (find(options.begin(), options.end(),
3521 "natbiborder") != options.end())
3522 argumentOrder = 'n';
3523 else if (find(options.begin(), options.end(),
3524 "jurabiborder") != options.end())
3525 argumentOrder = 'j';
3527 // text before the citation
3529 // text after the citation
3531 get_cite_arguments(p, argumentOrder != 'j', before, after);
3533 string const citation = p.verbatim_item();
3534 if (!before.empty() && argumentOrder == '\0') {
3535 cerr << "Warning: Assuming argument order "
3536 "of jurabib version 0.6 for\n'"
3537 << command << before << after << '{'
3538 << citation << "}'.\n"
3539 "Add 'jurabiborder' to the jurabib "
3540 "package options if you used an\n"
3541 "earlier jurabib version." << endl;
3543 if (!after.empty()) {
3545 after.erase(after.length() - 1, 1);
3547 if (!before.empty()) {
3549 before.erase(before.length() - 1, 1);
3551 begin_command_inset(os, "citation", command);
3552 os << "after " << '"' << after << '"' << "\n";
3553 os << "before " << '"' << before << '"' << "\n";
3554 os << "key " << '"' << citation << '"' << "\n";
3556 // Need to set the cite engine if jurabib is loaded by
3557 // the document class directly
3558 if (preamble.citeEngine() == "basic")
3559 preamble.citeEngine("jurabib");
3562 else if (t.cs() == "cite"
3563 || t.cs() == "nocite") {
3564 context.check_layout(os);
3565 string after = convert_command_inset_arg(p.getArg('[', ']'));
3566 string key = convert_command_inset_arg(p.verbatim_item());
3567 // store the case that it is "\nocite{*}" to use it later for
3570 begin_command_inset(os, "citation", t.cs());
3571 os << "after " << '"' << after << '"' << "\n";
3572 os << "key " << '"' << key << '"' << "\n";
3574 } else if (t.cs() == "nocite")
3578 else if (t.cs() == "index" ||
3579 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3580 context.check_layout(os);
3581 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3582 p.getArg('[', ']') : "";
3583 string const kind = arg.empty() ? "idx" : arg;
3584 begin_inset(os, "Index ");
3585 os << kind << "\nstatus collapsed\n";
3586 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3589 preamble.registerAutomaticallyLoadedPackage("splitidx");
3592 else if (t.cs() == "nomenclature") {
3593 context.check_layout(os);
3594 begin_command_inset(os, "nomenclature", "nomenclature");
3595 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3596 if (!prefix.empty())
3597 os << "prefix " << '"' << prefix << '"' << "\n";
3598 os << "symbol " << '"'
3599 << convert_command_inset_arg(p.verbatim_item());
3600 os << "\"\ndescription \""
3601 << convert_command_inset_arg(p.verbatim_item())
3604 preamble.registerAutomaticallyLoadedPackage("nomencl");
3607 else if (t.cs() == "label") {
3608 context.check_layout(os);
3609 begin_command_inset(os, "label", "label");
3611 << convert_command_inset_arg(p.verbatim_item())
3616 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3617 context.check_layout(os);
3618 string commandname = t.cs();
3620 if (p.next_token().asInput() == "*") {
3625 begin_command_inset(os, "index_print", commandname);
3626 string const indexname = p.getArg('[', ']');
3628 if (indexname.empty())
3629 os << "type \"idx\"\n";
3631 os << "type \"" << indexname << "\"\n";
3634 skip_spaces_braces(p);
3635 preamble.registerAutomaticallyLoadedPackage("makeidx");
3636 if (preamble.use_indices() == "true")
3637 preamble.registerAutomaticallyLoadedPackage("splitidx");
3640 else if (t.cs() == "printnomenclature") {
3642 string width_type = "";
3643 context.check_layout(os);
3644 begin_command_inset(os, "nomencl_print", "printnomenclature");
3645 // case of a custom width
3647 width = p.getArg('[', ']');
3648 width = translate_len(width);
3649 width_type = "custom";
3651 // case of no custom width
3652 // the case of no custom width but the width set
3653 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3654 // because the user could have set anything, not only the width
3655 // of the longest label (which would be width_type = "auto")
3656 string label = convert_command_inset_arg(p.getArg('{', '}'));
3657 if (label.empty() && width_type.empty())
3658 width_type = "none";
3659 os << "set_width \"" << width_type << "\"\n";
3660 if (width_type == "custom")
3661 os << "width \"" << width << '\"';
3663 skip_spaces_braces(p);
3664 preamble.registerAutomaticallyLoadedPackage("nomencl");
3667 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3668 context.check_layout(os);
3669 begin_inset(os, "script ");
3670 os << t.cs().substr(4) << '\n';
3671 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3673 if (t.cs() == "textsubscript")
3674 preamble.registerAutomaticallyLoadedPackage("subscript");
3677 else if ((where = is_known(t.cs(), known_quotes))) {
3678 context.check_layout(os);
3679 begin_inset(os, "Quotes ");
3680 os << known_coded_quotes[where - known_quotes];
3682 // LyX adds {} after the quote, so we have to eat
3683 // spaces here if there are any before a possible
3685 eat_whitespace(p, os, context, false);
3689 else if ((where = is_known(t.cs(), known_sizes)) &&
3690 context.new_layout_allowed) {
3691 context.check_layout(os);
3692 TeXFont const oldFont = context.font;
3693 context.font.size = known_coded_sizes[where - known_sizes];
3694 output_font_change(os, oldFont, context.font);
3695 eat_whitespace(p, os, context, false);
3698 else if ((where = is_known(t.cs(), known_font_families)) &&
3699 context.new_layout_allowed) {
3700 context.check_layout(os);
3701 TeXFont const oldFont = context.font;
3702 context.font.family =
3703 known_coded_font_families[where - known_font_families];
3704 output_font_change(os, oldFont, context.font);
3705 eat_whitespace(p, os, context, false);
3708 else if ((where = is_known(t.cs(), known_font_series)) &&
3709 context.new_layout_allowed) {
3710 context.check_layout(os);
3711 TeXFont const oldFont = context.font;
3712 context.font.series =
3713 known_coded_font_series[where - known_font_series];
3714 output_font_change(os, oldFont, context.font);
3715 eat_whitespace(p, os, context, false);
3718 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3719 context.new_layout_allowed) {
3720 context.check_layout(os);
3721 TeXFont const oldFont = context.font;
3722 context.font.shape =
3723 known_coded_font_shapes[where - known_font_shapes];
3724 output_font_change(os, oldFont, context.font);
3725 eat_whitespace(p, os, context, false);
3727 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3728 context.new_layout_allowed) {
3729 context.check_layout(os);
3730 TeXFont const oldFont = context.font;
3731 context.font.init();
3732 context.font.size = oldFont.size;
3733 context.font.family =
3734 known_coded_font_families[where - known_old_font_families];
3735 output_font_change(os, oldFont, context.font);
3736 eat_whitespace(p, os, context, false);
3739 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3740 context.new_layout_allowed) {
3741 context.check_layout(os);
3742 TeXFont const oldFont = context.font;
3743 context.font.init();
3744 context.font.size = oldFont.size;
3745 context.font.series =
3746 known_coded_font_series[where - known_old_font_series];
3747 output_font_change(os, oldFont, context.font);
3748 eat_whitespace(p, os, context, false);
3751 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3752 context.new_layout_allowed) {
3753 context.check_layout(os);
3754 TeXFont const oldFont = context.font;
3755 context.font.init();
3756 context.font.size = oldFont.size;
3757 context.font.shape =
3758 known_coded_font_shapes[where - known_old_font_shapes];
3759 output_font_change(os, oldFont, context.font);
3760 eat_whitespace(p, os, context, false);
3763 else if (t.cs() == "selectlanguage") {
3764 context.check_layout(os);
3765 // save the language for the case that a
3766 // \foreignlanguage is used
3767 context.font.language = babel2lyx(p.verbatim_item());
3768 os << "\n\\lang " << context.font.language << "\n";
3771 else if (t.cs() == "foreignlanguage") {
3772 string const lang = babel2lyx(p.verbatim_item());
3773 parse_text_attributes(p, os, FLAG_ITEM, outer,
3775 context.font.language, lang);
3778 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
3779 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3780 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3782 // We have to output the whole command if it has an option
3783 // because LyX doesn't support this yet, see bug #8214,
3784 // only if there is a single option specifying a variant, we can handle it.
3786 string langopts = p.getOpt();
3787 // check if the option contains a variant, if yes, extract it
3788 string::size_type pos_var = langopts.find("variant");
3789 string::size_type i = langopts.find(',');
3790 string::size_type k = langopts.find('=', pos_var);
3791 if (pos_var != string::npos && i == string::npos) {
3793 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3794 lang = preamble.polyglossia2lyx(variant);
3795 parse_text_attributes(p, os, FLAG_ITEM, outer,
3797 context.font.language, lang);
3799 output_ert_inset(os, t.asInput() + langopts, context);
3801 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3802 parse_text_attributes(p, os, FLAG_ITEM, outer,
3804 context.font.language, lang);
3808 else if (t.cs() == "inputencoding") {
3809 // nothing to write here
3810 string const enc = subst(p.verbatim_item(), "\n", " ");
3811 p.setEncoding(enc, Encoding::inputenc);
3814 else if ((where = is_known(t.cs(), known_special_chars))) {
3815 context.check_layout(os);
3816 os << known_coded_special_chars[where - known_special_chars];
3817 skip_spaces_braces(p);
3820 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3821 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3822 context.check_layout(os);
3823 os << "\\SpecialChar \\" << t.cs()
3824 << p.get_token().asInput() << '\n';
3827 else if (t.cs() == "textquotedbl") {
3828 context.check_layout(os);
3833 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3834 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3835 || t.cs() == "%" || t.cs() == "-") {
3836 context.check_layout(os);
3838 os << "\\SpecialChar \\-\n";
3843 else if (t.cs() == "char") {
3844 context.check_layout(os);
3845 if (p.next_token().character() == '`') {
3847 if (p.next_token().cs() == "\"") {
3852 output_ert_inset(os, "\\char`", context);
3855 output_ert_inset(os, "\\char", context);
3859 else if (t.cs() == "verb") {
3860 context.check_layout(os);
3861 // set catcodes to verbatim early, just in case.
3862 p.setCatcodes(VERBATIM_CATCODES);
3863 string delim = p.get_token().asInput();
3864 Parser::Arg arg = p.verbatimStuff(delim);
3866 output_ert_inset(os, "\\verb" + delim
3867 + arg.second + delim, context);
3869 cerr << "invalid \\verb command. Skipping" << endl;
3872 // Problem: \= creates a tabstop inside the tabbing environment
3873 // and else an accent. In the latter case we really would want
3874 // \={o} instead of \= o.
3875 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3876 output_ert_inset(os, t.asInput(), context);
3878 else if (t.cs() == "\\") {
3879 context.check_layout(os);
3881 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3882 else if (p.next_token().asInput() == "*") {
3884 // getOpt() eats the following space if there
3885 // is no optional argument, but that is OK
3886 // here since it has no effect in the output.
3887 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3890 begin_inset(os, "Newline newline");
3895 else if (t.cs() == "newline" ||
3896 (t.cs() == "linebreak" && !p.hasOpt())) {
3897 context.check_layout(os);
3898 begin_inset(os, "Newline ");
3901 skip_spaces_braces(p);
3904 else if (t.cs() == "input" || t.cs() == "include"
3905 || t.cs() == "verbatiminput") {
3906 string name = t.cs();
3907 if (t.cs() == "verbatiminput"
3908 && p.next_token().asInput() == "*")
3909 name += p.get_token().asInput();
3910 context.check_layout(os);
3911 string filename(normalize_filename(p.getArg('{', '}')));
3912 string const path = getMasterFilePath(true);
3913 // We want to preserve relative / absolute filenames,
3914 // therefore path is only used for testing
3915 if ((t.cs() == "include" || t.cs() == "input") &&
3916 !makeAbsPath(filename, path).exists()) {
3917 // The file extension is probably missing.
3918 // Now try to find it out.
3919 string const tex_name =
3920 find_file(filename, path,
3921 known_tex_extensions);
3922 if (!tex_name.empty())
3923 filename = tex_name;
3925 bool external = false;
3927 if (makeAbsPath(filename, path).exists()) {
3928 string const abstexname =
3929 makeAbsPath(filename, path).absFileName();
3930 string const absfigname =
3931 changeExtension(abstexname, ".fig");
3932 fix_child_filename(filename);
3933 string const lyxname = changeExtension(filename,
3934 roundtripMode() ? ".lyx.lyx" : ".lyx");
3935 string const abslyxname = makeAbsPath(
3936 lyxname, getParentFilePath(false)).absFileName();
3938 if (!skipChildren())
3939 external = FileName(absfigname).exists();
3940 if (t.cs() == "input" && !skipChildren()) {
3941 string const ext = getExtension(abstexname);
3943 // Combined PS/LaTeX:
3944 // x.eps, x.pstex_t (old xfig)
3945 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3946 FileName const absepsname(
3947 changeExtension(abstexname, ".eps"));
3948 FileName const abspstexname(
3949 changeExtension(abstexname, ".pstex"));
3950 bool const xfigeps =
3951 (absepsname.exists() ||
3952 abspstexname.exists()) &&
3955 // Combined PDF/LaTeX:
3956 // x.pdf, x.pdftex_t (old xfig)
3957 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3958 FileName const abspdfname(
3959 changeExtension(abstexname, ".pdf"));
3960 bool const xfigpdf =
3961 abspdfname.exists() &&
3962 (ext == "pdftex_t" || ext == "pdf_t");
3966 // Combined PS/PDF/LaTeX:
3967 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3968 string const absbase2(
3969 removeExtension(abstexname) + "_pspdftex");
3970 FileName const abseps2name(
3971 addExtension(absbase2, ".eps"));
3972 FileName const abspdf2name(
3973 addExtension(absbase2, ".pdf"));
3974 bool const xfigboth =
3975 abspdf2name.exists() &&
3976 abseps2name.exists() && ext == "pspdftex";
3978 xfig = xfigpdf || xfigeps || xfigboth;
3979 external = external && xfig;
3982 outname = changeExtension(filename, ".fig");
3983 FileName abssrc(changeExtension(abstexname, ".fig"));
3984 copy_file(abssrc, outname);
3986 // Don't try to convert, the result
3987 // would be full of ERT.
3989 FileName abssrc(abstexname);
3990 copy_file(abssrc, outname);
3991 } else if (t.cs() != "verbatiminput" &&
3993 tex2lyx(abstexname, FileName(abslyxname),
3996 // no need to call copy_file
3997 // tex2lyx creates the file
4000 FileName abssrc(abstexname);
4001 copy_file(abssrc, outname);
4004 cerr << "Warning: Could not find included file '"
4005 << filename << "'." << endl;
4009 begin_inset(os, "External\n");
4010 os << "\ttemplate XFig\n"
4011 << "\tfilename " << outname << '\n';
4012 registerExternalTemplatePackages("XFig");
4014 begin_command_inset(os, "include", name);
4015 outname = subst(outname, "\"", "\\\"");
4016 os << "preview false\n"
4017 "filename \"" << outname << "\"\n";
4018 if (t.cs() == "verbatiminput")
4019 preamble.registerAutomaticallyLoadedPackage("verbatim");
4024 else if (t.cs() == "bibliographystyle") {
4025 // store new bibliographystyle
4026 bibliographystyle = p.verbatim_item();
4027 // If any other command than \bibliography, \addcontentsline
4028 // and \nocite{*} follows, we need to output the style
4029 // (because it might be used by that command).
4030 // Otherwise, it will automatically be output by LyX.
4033 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4034 if (t2.cat() == catBegin)
4036 if (t2.cat() != catEscape)
4038 if (t2.cs() == "nocite") {
4039 if (p.getArg('{', '}') == "*")
4041 } else if (t2.cs() == "bibliography")
4043 else if (t2.cs() == "phantomsection") {
4047 else if (t2.cs() == "addcontentsline") {
4048 // get the 3 arguments of \addcontentsline
4051 contentslineContent = p.getArg('{', '}');
4052 // if the last argument is not \refname we must output
4053 if (contentslineContent == "\\refname")
4060 output_ert_inset(os,
4061 "\\bibliographystyle{" + bibliographystyle + '}',
4066 else if (t.cs() == "phantomsection") {
4067 // we only support this if it occurs between
4068 // \bibliographystyle and \bibliography
4069 if (bibliographystyle.empty())
4070 output_ert_inset(os, "\\phantomsection", context);
4073 else if (t.cs() == "addcontentsline") {
4074 context.check_layout(os);
4075 // get the 3 arguments of \addcontentsline
4076 string const one = p.getArg('{', '}');
4077 string const two = p.getArg('{', '}');
4078 string const three = p.getArg('{', '}');
4079 // only if it is a \refname, we support if for the bibtex inset
4080 if (contentslineContent != "\\refname") {
4081 output_ert_inset(os,
4082 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4087 else if (t.cs() == "bibliography") {
4088 context.check_layout(os);
4090 begin_command_inset(os, "bibtex", "bibtex");
4091 if (!btprint.empty()) {
4092 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4093 // clear the string because the next BibTeX inset can be without the
4094 // \nocite{*} option
4097 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4098 // Do we have addcontentsline?
4099 if (contentslineContent == "\\refname") {
4100 BibOpts = "bibtotoc";
4101 // clear string because next BibTeX inset can be without addcontentsline
4102 contentslineContent.clear();
4104 // Do we have a bibliographystyle set?
4105 if (!bibliographystyle.empty()) {
4106 if (BibOpts.empty())
4107 BibOpts = bibliographystyle;
4109 BibOpts = BibOpts + ',' + bibliographystyle;
4110 // clear it because each bibtex entry has its style
4111 // and we need an empty string to handle \phantomsection
4112 bibliographystyle.clear();
4114 os << "options " << '"' << BibOpts << '"' << "\n";
4118 else if (t.cs() == "parbox") {
4119 // Test whether this is an outer box of a shaded box
4121 // swallow arguments
4122 while (p.hasOpt()) {
4124 p.skip_spaces(true);
4127 p.skip_spaces(true);
4129 if (p.next_token().cat() == catBegin)
4131 p.skip_spaces(true);
4132 Token to = p.get_token();
4133 bool shaded = false;
4134 if (to.asInput() == "\\begin") {
4135 p.skip_spaces(true);
4136 if (p.getArg('{', '}') == "shaded")
4141 parse_outer_box(p, os, FLAG_ITEM, outer,
4142 context, "parbox", "shaded");
4144 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4148 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4149 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4150 t.cs() == "shadowbox" || t.cs() == "doublebox")
4151 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4153 else if (t.cs() == "framebox") {
4154 if (p.next_token().character() == '(') {
4155 //the syntax is: \framebox(x,y)[position]{content}
4156 string arg = t.asInput();
4157 arg += p.getFullParentheseArg();
4158 arg += p.getFullOpt();
4159 eat_whitespace(p, os, context, false);
4160 output_ert_inset(os, arg + '{', context);
4161 parse_text(p, os, FLAG_ITEM, outer, context);
4162 output_ert_inset(os, "}", context);
4164 //the syntax is: \framebox[width][position]{content}
4165 string special = p.getFullOpt();
4166 special += p.getOpt();
4167 parse_outer_box(p, os, FLAG_ITEM, outer,
4168 context, t.cs(), special);
4172 //\makebox() is part of the picture environment and different from \makebox{}
4173 //\makebox{} will be parsed by parse_box
4174 else if (t.cs() == "makebox") {
4175 if (p.next_token().character() == '(') {
4176 //the syntax is: \makebox(x,y)[position]{content}
4177 string arg = t.asInput();
4178 arg += p.getFullParentheseArg();
4179 arg += p.getFullOpt();
4180 eat_whitespace(p, os, context, false);
4181 output_ert_inset(os, arg + '{', context);
4182 parse_text(p, os, FLAG_ITEM, outer, context);
4183 output_ert_inset(os, "}", context);
4185 //the syntax is: \makebox[width][position]{content}
4186 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4190 else if (t.cs() == "smallskip" ||
4191 t.cs() == "medskip" ||
4192 t.cs() == "bigskip" ||
4193 t.cs() == "vfill") {
4194 context.check_layout(os);
4195 begin_inset(os, "VSpace ");
4198 skip_spaces_braces(p);
4201 else if ((where = is_known(t.cs(), known_spaces))) {
4202 context.check_layout(os);
4203 begin_inset(os, "space ");
4204 os << '\\' << known_coded_spaces[where - known_spaces]
4207 // LaTeX swallows whitespace after all spaces except
4208 // "\\,". We have to do that here, too, because LyX
4209 // adds "{}" which would make the spaces significant.
4211 eat_whitespace(p, os, context, false);
4212 // LyX adds "{}" after all spaces except "\\ " and
4213 // "\\,", so we have to remove "{}".
4214 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4215 // remove the braces after "\\,", too.
4220 else if (t.cs() == "newpage" ||
4221 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4222 t.cs() == "clearpage" ||
4223 t.cs() == "cleardoublepage") {
4224 context.check_layout(os);
4225 begin_inset(os, "Newpage ");
4228 skip_spaces_braces(p);
4231 else if (t.cs() == "DeclareRobustCommand" ||
4232 t.cs() == "DeclareRobustCommandx" ||
4233 t.cs() == "newcommand" ||
4234 t.cs() == "newcommandx" ||
4235 t.cs() == "providecommand" ||
4236 t.cs() == "providecommandx" ||
4237 t.cs() == "renewcommand" ||
4238 t.cs() == "renewcommandx") {
4239 // DeclareRobustCommand, DeclareRobustCommandx,
4240 // providecommand and providecommandx could be handled
4241 // by parse_command(), but we need to call
4242 // add_known_command() here.
4243 string name = t.asInput();
4244 if (p.next_token().asInput() == "*") {
4245 // Starred form. Eat '*'
4249 string const command = p.verbatim_item();
4250 string const opt1 = p.getFullOpt();
4251 string const opt2 = p.getFullOpt();
4252 add_known_command(command, opt1, !opt2.empty());
4253 string const ert = name + '{' + command + '}' +
4255 '{' + p.verbatim_item() + '}';
4257 if (t.cs() == "DeclareRobustCommand" ||
4258 t.cs() == "DeclareRobustCommandx" ||
4259 t.cs() == "providecommand" ||
4260 t.cs() == "providecommandx" ||
4261 name[name.length()-1] == '*')
4262 output_ert_inset(os, ert, context);
4264 context.check_layout(os);
4265 begin_inset(os, "FormulaMacro");
4271 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4272 // let could be handled by parse_command(),
4273 // but we need to call add_known_command() here.
4274 string ert = t.asInput();
4277 if (p.next_token().cat() == catBegin) {
4278 name = p.verbatim_item();
4279 ert += '{' + name + '}';
4281 name = p.verbatim_item();
4286 if (p.next_token().cat() == catBegin) {
4287 command = p.verbatim_item();
4288 ert += '{' + command + '}';
4290 command = p.verbatim_item();
4293 // If command is known, make name known too, to parse
4294 // its arguments correctly. For this reason we also
4295 // have commands in syntax.default that are hardcoded.
4296 CommandMap::iterator it = known_commands.find(command);
4297 if (it != known_commands.end())
4298 known_commands[t.asInput()] = it->second;
4299 output_ert_inset(os, ert, context);
4302 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4305 string name = t.asInput();
4306 string const length = p.verbatim_item();
4309 bool valid = splitLatexLength(length, valstring, unit);
4310 bool known_hspace = false;
4311 bool known_vspace = false;
4312 bool known_unit = false;
4315 istringstream iss(valstring);
4318 if (t.cs()[0] == 'h') {
4319 if (unit == "\\fill") {
4324 known_hspace = true;
4327 if (unit == "\\smallskipamount") {
4329 known_vspace = true;
4330 } else if (unit == "\\medskipamount") {
4332 known_vspace = true;
4333 } else if (unit == "\\bigskipamount") {
4335 known_vspace = true;
4336 } else if (unit == "\\fill") {
4338 known_vspace = true;
4342 if (!known_hspace && !known_vspace) {
4343 switch (unitFromString(unit)) {
4359 //unitFromString(unit) fails for relative units like Length::PCW
4360 // therefore handle them separately
4361 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4362 || unit == "\\textwidth" || unit == "\\linewidth"
4363 || unit == "\\textheight" || unit == "\\paperheight")
4371 // check for glue lengths
4372 bool is_gluelength = false;
4373 string gluelength = length;
4374 string::size_type i = length.find(" minus");
4375 if (i == string::npos) {
4376 i = length.find(" plus");
4377 if (i != string::npos)
4378 is_gluelength = true;
4380 is_gluelength = true;
4381 // if yes transform "9xx minus 8yy plus 7zz"
4383 if (is_gluelength) {
4384 i = gluelength.find(" minus");
4385 if (i != string::npos)
4386 gluelength.replace(i, 7, "-");
4387 i = gluelength.find(" plus");
4388 if (i != string::npos)
4389 gluelength.replace(i, 6, "+");
4392 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4393 // Literal horizontal length or known variable
4394 context.check_layout(os);
4395 begin_inset(os, "space ");
4403 if (known_unit && !known_hspace)
4404 os << "\n\\length " << translate_len(length);
4406 os << "\n\\length " << gluelength;
4408 } else if (known_unit || known_vspace || is_gluelength) {
4409 // Literal vertical length or known variable
4410 context.check_layout(os);
4411 begin_inset(os, "VSpace ");
4414 if (known_unit && !known_vspace)
4415 os << translate_len(length);
4422 // LyX can't handle other length variables in Inset VSpace/space
4427 output_ert_inset(os, name + '{' + unit + '}', context);
4428 else if (value == -1.0)
4429 output_ert_inset(os, name + "{-" + unit + '}', context);
4431 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4433 output_ert_inset(os, name + '{' + length + '}', context);
4437 // The single '=' is meant here.
4438 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4442 context.check_layout(os);
4443 docstring const name = newinsetlayout->name();
4444 bool const caption = name.find(from_ascii("Caption:")) == 0;
4446 begin_inset(os, "Caption ");
4447 os << to_utf8(name.substr(8)) << '\n';
4449 begin_inset(os, "Flex ");
4450 os << to_utf8(name) << '\n'
4451 << "status collapsed\n";
4453 if (newinsetlayout->isPassThru()) {
4454 // set catcodes to verbatim early, just in case.
4455 p.setCatcodes(VERBATIM_CATCODES);
4456 string delim = p.get_token().asInput();
4458 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4459 //FIXME: handle error condition
4460 string const arg = p.verbatimStuff("}").second;
4461 Context newcontext(true, context.textclass);
4462 if (newinsetlayout->forcePlainLayout())
4463 newcontext.layout = &context.textclass.plainLayout();
4464 output_ert(os, arg, newcontext);
4466 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4472 else if (t.cs() == "includepdf") {
4474 string const arg = p.getArg('[', ']');
4475 map<string, string> opts;
4476 vector<string> keys;
4477 split_map(arg, opts, keys);
4478 string name = normalize_filename(p.verbatim_item());
4479 string const path = getMasterFilePath(true);
4480 // We want to preserve relative / absolute filenames,
4481 // therefore path is only used for testing
4482 if (!makeAbsPath(name, path).exists()) {
4483 // The file extension is probably missing.
4484 // Now try to find it out.
4485 char const * const pdfpages_format[] = {"pdf", 0};
4486 string const pdftex_name =
4487 find_file(name, path, pdfpages_format);
4488 if (!pdftex_name.empty()) {
4493 FileName const absname = makeAbsPath(name, path);
4494 if (absname.exists())
4496 fix_child_filename(name);
4497 copy_file(absname, name);
4499 cerr << "Warning: Could not find file '"
4500 << name << "'." << endl;
4502 context.check_layout(os);
4503 begin_inset(os, "External\n\ttemplate ");
4504 os << "PDFPages\n\tfilename "
4506 // parse the options
4507 if (opts.find("pages") != opts.end())
4508 os << "\textra LaTeX \"pages="
4509 << opts["pages"] << "\"\n";
4510 if (opts.find("angle") != opts.end())
4511 os << "\trotateAngle "
4512 << opts["angle"] << '\n';
4513 if (opts.find("origin") != opts.end()) {
4515 string const opt = opts["origin"];
4516 if (opt == "tl") ss << "topleft";
4517 if (opt == "bl") ss << "bottomleft";
4518 if (opt == "Bl") ss << "baselineleft";
4519 if (opt == "c") ss << "center";
4520 if (opt == "tc") ss << "topcenter";
4521 if (opt == "bc") ss << "bottomcenter";
4522 if (opt == "Bc") ss << "baselinecenter";
4523 if (opt == "tr") ss << "topright";
4524 if (opt == "br") ss << "bottomright";
4525 if (opt == "Br") ss << "baselineright";
4526 if (!ss.str().empty())
4527 os << "\trotateOrigin " << ss.str() << '\n';
4529 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4531 if (opts.find("width") != opts.end())
4533 << translate_len(opts["width"]) << '\n';
4534 if (opts.find("height") != opts.end())
4536 << translate_len(opts["height"]) << '\n';
4537 if (opts.find("keepaspectratio") != opts.end())
4538 os << "\tkeepAspectRatio\n";
4540 context.check_layout(os);
4541 registerExternalTemplatePackages("PDFPages");
4544 else if (t.cs() == "loadgame") {
4546 string name = normalize_filename(p.verbatim_item());
4547 string const path = getMasterFilePath(true);
4548 // We want to preserve relative / absolute filenames,
4549 // therefore path is only used for testing
4550 if (!makeAbsPath(name, path).exists()) {
4551 // The file extension is probably missing.
4552 // Now try to find it out.
4553 char const * const lyxskak_format[] = {"fen", 0};
4554 string const lyxskak_name =
4555 find_file(name, path, lyxskak_format);
4556 if (!lyxskak_name.empty())
4557 name = lyxskak_name;
4559 FileName const absname = makeAbsPath(name, path);
4560 if (absname.exists())
4562 fix_child_filename(name);
4563 copy_file(absname, name);
4565 cerr << "Warning: Could not find file '"
4566 << name << "'." << endl;
4567 context.check_layout(os);
4568 begin_inset(os, "External\n\ttemplate ");
4569 os << "ChessDiagram\n\tfilename "
4572 context.check_layout(os);
4573 // after a \loadgame follows a \showboard
4574 if (p.get_token().asInput() == "showboard")
4576 registerExternalTemplatePackages("ChessDiagram");
4580 // try to see whether the string is in unicodesymbols
4581 // Only use text mode commands, since we are in text mode here,
4582 // and math commands may be invalid (bug 6797)
4583 string name = t.asInput();
4584 // handle the dingbats, cyrillic and greek
4585 if (name == "\\ding" || name == "\\textcyr" ||
4586 (name == "\\textgreek" && !preamble.usePolyglossia()))
4587 name = name + '{' + p.getArg('{', '}') + '}';
4588 // handle the ifsym characters
4589 else if (name == "\\textifsymbol") {
4590 string const optif = p.getFullOpt();
4591 string const argif = p.getArg('{', '}');
4592 name = name + optif + '{' + argif + '}';
4594 // handle the \ascii characters
4595 // the case of \ascii within braces, as LyX outputs it, is already
4596 // handled for t.cat() == catBegin
4597 else if (name == "\\ascii") {
4598 // the code is "\asci\xxx"
4599 name = "{" + name + p.get_token().asInput() + "}";
4602 // handle some TIPA special characters
4603 else if (preamble.isPackageUsed("tipa")) {
4604 if (name == "\\textglobfall") {
4607 } else if (name == "\\s") {
4608 // fromLaTeXCommand() does not yet
4609 // recognize tipa short cuts
4610 name = "\\textsyllabic";
4611 } else if (name == "\\=" &&
4612 p.next_token().asInput() == "*") {
4613 // fromLaTeXCommand() does not yet
4614 // recognize tipa short cuts
4617 } else if (name == "\\textdoublevertline") {
4618 // FIXME: This is not correct,
4619 // \textvertline is higher than \textbardbl
4620 name = "\\textbardbl";
4622 } else if (name == "\\!" ) {
4623 if (p.next_token().asInput() == "b") {
4624 p.get_token(); // eat 'b'
4627 } else if (p.next_token().asInput() == "d") {
4631 } else if (p.next_token().asInput() == "g") {
4635 } else if (p.next_token().asInput() == "G") {
4637 name = "\\texthtscg";
4639 } else if (p.next_token().asInput() == "j") {
4641 name = "\\texthtbardotlessj";
4643 } else if (p.next_token().asInput() == "o") {
4645 name = "\\textbullseye";
4648 } else if (name == "\\*" ) {
4649 if (p.next_token().asInput() == "k") {
4651 name = "\\textturnk";
4653 } else if (p.next_token().asInput() == "r") {
4654 p.get_token(); // eat 'b'
4655 name = "\\textturnr";
4657 } else if (p.next_token().asInput() == "t") {
4659 name = "\\textturnt";
4661 } else if (p.next_token().asInput() == "w") {
4663 name = "\\textturnw";
4668 if ((name.size() == 2 &&
4669 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4670 p.next_token().asInput() != "*") ||
4671 is_known(name.substr(1), known_tipa_marks)) {
4672 // name is a command that corresponds to a
4673 // combining character in unicodesymbols.
4674 // Append the argument, fromLaTeXCommand()
4675 // will either convert it to a single
4676 // character or a combining sequence.
4677 name += '{' + p.verbatim_item() + '}';
4679 // now get the character from unicodesymbols
4683 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4684 Encodings::TEXT_CMD, termination, rem, &req);
4686 context.check_layout(os);
4689 output_ert_inset(os, to_utf8(rem), context);
4691 skip_spaces_braces(p);
4692 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4693 preamble.registerAutomaticallyLoadedPackage(*it);
4695 //cerr << "#: " << t << " mode: " << mode << endl;
4696 // heuristic: read up to next non-nested space
4698 string s = t.asInput();
4699 string z = p.verbatim_item();
4700 while (p.good() && z != " " && !z.empty()) {
4701 //cerr << "read: " << z << endl;
4703 z = p.verbatim_item();
4705 cerr << "found ERT: " << s << endl;
4706 output_ert_inset(os, s + ' ', context);
4709 if (t.asInput() == name &&
4710 p.next_token().asInput() == "*") {
4711 // Starred commands like \vspace*{}
4712 p.get_token(); // Eat '*'
4715 if (!parse_command(name, p, os, outer, context))
4716 output_ert_inset(os, name, context);
4720 if (flags & FLAG_LEAVE) {
4721 flags &= ~FLAG_LEAVE;
4728 string guessLanguage(Parser & p, string const & lang)
4730 typedef std::map<std::string, size_t> LangMap;
4731 // map from language names to number of characters
4734 for (char const * const * i = supported_CJK_languages; *i; i++)
4735 used[string(*i)] = 0;
4738 Token const t = p.get_token();
4739 // comments are not counted for any language
4740 if (t.cat() == catComment)
4742 // commands are not counted as well, but we need to detect
4743 // \begin{CJK} and switch encoding if needed
4744 if (t.cat() == catEscape) {
4745 if (t.cs() == "inputencoding") {
4746 string const enc = subst(p.verbatim_item(), "\n", " ");
4747 p.setEncoding(enc, Encoding::inputenc);
4750 if (t.cs() != "begin")
4753 // Non-CJK content is counted for lang.
4754 // We do not care about the real language here:
4755 // If we have more non-CJK contents than CJK contents,
4756 // we simply use the language that was specified as
4757 // babel main language.
4758 used[lang] += t.asInput().length();
4761 // Now we are starting an environment
4763 string const name = p.getArg('{', '}');
4764 if (name != "CJK") {
4768 // It is a CJK environment
4770 /* name = */ p.getArg('{', '}');
4771 string const encoding = p.getArg('{', '}');
4772 /* mapping = */ p.getArg('{', '}');
4773 string const encoding_old = p.getEncoding();
4774 char const * const * const where =
4775 is_known(encoding, supported_CJK_encodings);
4777 p.setEncoding(encoding, Encoding::CJK);
4779 p.setEncoding("UTF-8");
4780 string const text = p.ertEnvironment("CJK");
4781 p.setEncoding(encoding_old);
4784 // ignore contents in unknown CJK encoding
4787 // the language of the text
4789 supported_CJK_languages[where - supported_CJK_encodings];
4790 used[cjk] += text.length();
4792 LangMap::const_iterator use = used.begin();
4793 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4794 if (it->second > use->second)