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, 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, newcontext, layout->latexargs());
68 parse_text(p, os, flags, outer, newcontext);
69 newcontext.check_end_layout(os);
75 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
76 Context const & context, string const & name)
78 InsetLayout const * layout = 0;
79 DocumentClass::InsetLayouts::const_iterator it =
80 context.textclass.insetLayouts().find(from_ascii(name));
81 if (it != context.textclass.insetLayouts().end())
82 layout = &(it->second);
83 parse_text_in_inset(p, os, flags, outer, context, layout);
86 /// parses a paragraph snippet, useful for example for \\emph{...}
87 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
90 Context newcontext(context);
91 // Don't inherit the paragraph-level extra stuff
92 newcontext.par_extra_stuff.clear();
93 parse_text(p, os, flags, outer, newcontext);
94 // Make sure that we don't create invalid .lyx files
95 context.need_layout = newcontext.need_layout;
96 context.need_end_layout = newcontext.need_end_layout;
101 * Thin wrapper around parse_text_snippet() using a string.
103 * We completely ignore \c context.need_layout and \c context.need_end_layout,
104 * because our return value is not used directly (otherwise the stream version
105 * of parse_text_snippet() could be used). That means that the caller needs
106 * to do layout management manually.
107 * This is intended to parse text that does not create any layout changes.
109 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
112 Context newcontext(context);
113 newcontext.need_layout = false;
114 newcontext.need_end_layout = false;
115 newcontext.new_layout_allowed = false;
116 // Avoid warning by Context::~Context()
117 newcontext.par_extra_stuff.clear();
119 parse_text_snippet(p, os, flags, outer, newcontext);
124 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
125 "vpageref", "prettyref", "nameref", "eqref", 0 };
127 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
128 "vpageref", "formatted", "nameref", "eqref", 0 };
130 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
131 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
132 "secref", "subref", "tabref", "thmref", 0 };
134 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
135 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
136 "sec", "sub", "tab", "thm", 0 };
140 * supported CJK encodings
141 * JIS does not work with LyX's encoding conversion
143 const char * const supported_CJK_encodings[] = {
144 "EUC-JP", "KS", "GB", "UTF8",
145 "Bg5", /*"JIS",*/ "SJIS", 0};
148 * the same as supported_CJK_encodings with their corresponding LyX language name
149 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
151 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
152 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
153 * please keep this in sync with supported_CJK_encodings line by line!
155 const char * const supported_CJK_languages[] = {
156 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
157 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
161 * The starred forms are also known except for "citefullauthor",
162 * "citeyear" and "citeyearpar".
164 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
165 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
166 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
170 * No starred form other than "cite*" known.
172 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
173 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
174 // jurabib commands not (yet) supported by LyX:
176 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
177 // "footciteauthor", "footciteyear", "footciteyearpar",
178 "citefield", "citetitle", 0 };
180 /// LaTeX names for quotes
181 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
182 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
183 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
184 "guilsinglleft", "frq", "guilsinglright", 0};
186 /// the same as known_quotes with .lyx names
187 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
188 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
189 "gld", "grd", "gls", "ers", "fls",
190 "fls", "frs", "frs", 0};
192 /// LaTeX names for font sizes
193 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
194 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
196 /// the same as known_sizes with .lyx names
197 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
198 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
200 /// LaTeX 2.09 names for font families
201 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
203 /// LaTeX names for font families
204 char const * const known_font_families[] = { "rmfamily", "sffamily",
207 /// LaTeX names for font family changing commands
208 char const * const known_text_font_families[] = { "textrm", "textsf",
211 /// The same as known_old_font_families, known_font_families and
212 /// known_text_font_families with .lyx names
213 char const * const known_coded_font_families[] = { "roman", "sans",
216 /// LaTeX 2.09 names for font series
217 char const * const known_old_font_series[] = { "bf", 0};
219 /// LaTeX names for font series
220 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
222 /// LaTeX names for font series changing commands
223 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
225 /// The same as known_old_font_series, known_font_series and
226 /// known_text_font_series with .lyx names
227 char const * const known_coded_font_series[] = { "bold", "medium", 0};
229 /// LaTeX 2.09 names for font shapes
230 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
232 /// LaTeX names for font shapes
233 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
236 /// LaTeX names for font shape changing commands
237 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
240 /// The same as known_old_font_shapes, known_font_shapes and
241 /// known_text_font_shapes with .lyx names
242 char const * const known_coded_font_shapes[] = { "italic", "slanted",
243 "smallcaps", "up", 0};
245 /// Known special characters which need skip_spaces_braces() afterwards
246 char const * const known_special_chars[] = {"ldots",
247 "lyxarrow", "textcompwordmark",
248 "slash", "textasciitilde", "textasciicircum", "textbackslash", 0};
250 /// the same as known_special_chars with .lyx names
251 char const * const known_coded_special_chars[] = {"\\SpecialChar \\ldots{}\n",
252 "\\SpecialChar \\menuseparator\n", "\\SpecialChar \\textcompwordmark{}\n",
253 "\\SpecialChar \\slash{}\n", "~", "^", "\n\\backslash\n", 0};
256 * Graphics file extensions known by the dvips driver of the graphics package.
257 * These extensions are used to complete the filename of an included
258 * graphics file if it does not contain an extension.
259 * The order must be the same that latex uses to find a file, because we
260 * will use the first extension that matches.
261 * This is only an approximation for the common cases. If we would want to
262 * do it right in all cases, we would need to know which graphics driver is
263 * used and know the extensions of every driver of the graphics package.
265 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
266 "ps.gz", "eps.Z", "ps.Z", 0};
269 * Graphics file extensions known by the pdftex driver of the graphics package.
270 * \sa known_dvips_graphics_formats
272 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
276 * Known file extensions for TeX files as used by \\include.
278 char const * const known_tex_extensions[] = {"tex", 0};
280 /// spaces known by InsetSpace
281 char const * const known_spaces[] = { " ", "space", ",",
282 "thinspace", "quad", "qquad", "enspace", "enskip",
283 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
284 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
285 "upbracefill", "downbracefill", 0};
287 /// the same as known_spaces with .lyx names
288 char const * const known_coded_spaces[] = { "space{}", "space{}",
289 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
290 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
291 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
292 "upbracefill{}", "downbracefill{}", 0};
294 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
295 /// them in ERT. "LaTeXe" must come before "LaTeX"!
296 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
297 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
298 int const known_phrase_lengths[] = {3, 5, 7, 0};
300 /// known TIPA combining diacritical marks
301 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
302 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
303 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
304 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
305 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
306 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
309 /// TIPA tones that need special handling
310 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
312 // string to store the float type to be able to determine the type of subfloats
313 string float_type = "";
316 /// splits "x=z, y=b" into a map and an ordered keyword vector
317 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
322 keys.resize(v.size());
323 for (size_t i = 0; i < v.size(); ++i) {
324 size_t const pos = v[i].find('=');
325 string const index = trimSpaceAndEol(v[i].substr(0, pos));
326 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
334 * Split a LaTeX length into value and unit.
335 * The latter can be a real unit like "pt", or a latex length variable
336 * like "\textwidth". The unit may contain additional stuff like glue
337 * lengths, but we don't care, because such lengths are ERT anyway.
338 * \returns true if \p value and \p unit are valid.
340 bool splitLatexLength(string const & len, string & value, string & unit)
344 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
345 //'4,5' is a valid LaTeX length number. Change it to '4.5'
346 string const length = subst(len, ',', '.');
347 if (i == string::npos)
350 if (len[0] == '\\') {
351 // We had something like \textwidth without a factor
357 value = trimSpaceAndEol(string(length, 0, i));
361 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
362 if (contains(len, '\\'))
363 unit = trimSpaceAndEol(string(len, i));
365 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
370 /// A simple function to translate a latex length to something LyX can
371 /// understand. Not perfect, but rather best-effort.
372 bool translate_len(string const & length, string & valstring, string & unit)
374 if (!splitLatexLength(length, valstring, unit))
376 // LyX uses percent values
378 istringstream iss(valstring);
383 string const percentval = oss.str();
385 if (unit.empty() || unit[0] != '\\')
387 string::size_type const i = unit.find(' ');
388 string const endlen = (i == string::npos) ? string() : string(unit, i);
389 if (unit == "\\textwidth") {
390 valstring = percentval;
391 unit = "text%" + endlen;
392 } else if (unit == "\\columnwidth") {
393 valstring = percentval;
394 unit = "col%" + endlen;
395 } else if (unit == "\\paperwidth") {
396 valstring = percentval;
397 unit = "page%" + endlen;
398 } else if (unit == "\\linewidth") {
399 valstring = percentval;
400 unit = "line%" + endlen;
401 } else if (unit == "\\paperheight") {
402 valstring = percentval;
403 unit = "pheight%" + endlen;
404 } else if (unit == "\\textheight") {
405 valstring = percentval;
406 unit = "theight%" + endlen;
414 string translate_len(string const & length)
418 if (translate_len(length, value, unit))
420 // If the input is invalid, return what we have.
428 * Translates a LaTeX length into \p value, \p unit and
429 * \p special parts suitable for a box inset.
430 * The difference from translate_len() is that a box inset knows about
431 * some special "units" that are stored in \p special.
433 void translate_box_len(string const & length, string & value, string & unit, string & special)
435 if (translate_len(length, value, unit)) {
436 if (unit == "\\height" || unit == "\\depth" ||
437 unit == "\\totalheight" || unit == "\\width") {
438 special = unit.substr(1);
439 // The unit is not used, but LyX requires a dummy setting
452 * Find a file with basename \p name in path \p path and an extension
455 string find_file(string const & name, string const & path,
456 char const * const * extensions)
458 for (char const * const * what = extensions; *what; ++what) {
459 string const trial = addExtension(name, *what);
460 if (makeAbsPath(trial, path).exists())
467 void begin_inset(ostream & os, string const & name)
469 os << "\n\\begin_inset " << name;
473 void begin_command_inset(ostream & os, string const & name,
474 string const & latexname)
476 begin_inset(os, "CommandInset ");
477 os << name << "\nLatexCommand " << latexname << '\n';
481 void end_inset(ostream & os)
483 os << "\n\\end_inset\n\n";
487 bool skip_braces(Parser & p)
489 if (p.next_token().cat() != catBegin)
492 if (p.next_token().cat() == catEnd) {
501 /// replace LaTeX commands in \p s from the unicodesymbols file with their
503 docstring convert_unicodesymbols(docstring s)
506 for (size_t i = 0; i < s.size();) {
515 docstring parsed = encodings.fromLaTeXCommand(s,
516 Encodings::TEXT_CMD, termination, rem, &req);
517 set<string>::const_iterator it = req.begin();
518 set<string>::const_iterator en = req.end();
519 for (; it != en; ++it)
520 preamble.registerAutomaticallyLoadedPackage(*it);
523 if (s.empty() || s[0] != '\\')
532 /// try to convert \p s to a valid InsetCommand argument
533 string convert_command_inset_arg(string s)
536 // since we don't know the input encoding we can't use from_utf8
537 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
538 // LyX cannot handle newlines in a latex command
539 return subst(s, "\n", " ");
543 void output_ert(ostream & os, string const & s, Context & context)
545 context.check_layout(os);
546 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
548 os << "\n\\backslash\n";
549 else if (*it == '\n') {
550 context.new_paragraph(os);
551 context.check_layout(os);
555 context.check_end_layout(os);
559 void output_ert_inset(ostream & os, string const & s, Context & context)
561 // We must have a valid layout before outputting the ERT inset.
562 context.check_layout(os);
563 Context newcontext(true, context.textclass);
564 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
565 if (layout.forcePlainLayout())
566 newcontext.layout = &context.textclass.plainLayout();
567 begin_inset(os, "ERT");
568 os << "\nstatus collapsed\n";
569 output_ert(os, s, newcontext);
574 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
576 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
579 if (checkModule(name, command))
580 return findLayoutWithoutModule(textclass, name, command);
585 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
587 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
590 if (checkModule(name, command))
591 return findInsetLayoutWithoutModule(textclass, name, command);
596 void eat_whitespace(Parser &, ostream &, Context &, bool);
600 * Skips whitespace and braces.
601 * This should be called after a command has been parsed that is not put into
602 * ERT, and where LyX adds "{}" if needed.
604 void skip_spaces_braces(Parser & p, bool keepws = false)
606 /* The following four examples produce the same typeset output and
607 should be handled by this function:
615 // Unfortunately we need to skip comments, too.
616 // We can't use eat_whitespace since writing them after the {}
617 // results in different output in some cases.
618 bool const skipped_spaces = p.skip_spaces(true);
619 bool const skipped_braces = skip_braces(p);
620 if (keepws && skipped_spaces && !skipped_braces)
621 // put back the space (it is better handled by check_space)
622 p.unskip_spaces(true);
626 void output_arguments(ostream & os, Parser & p, bool outer, Context & context,
627 Layout::LaTeXArgMap const & latexargs)
629 context.check_layout(os);
631 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
632 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
633 for (; lait != laend; ++lait) {
635 eat_whitespace(p, os, context, false);
636 if (lait->second.mandatory) {
637 if (p.next_token().cat() != catBegin)
639 p.get_token(); // eat '{'
640 begin_inset(os, "Argument ");
641 os << i << "\nstatus collapsed\n\n";
642 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
645 if (p.next_token().cat() == catEscape ||
646 p.next_token().character() != '[')
648 p.get_token(); // eat '['
649 begin_inset(os, "Argument ");
650 os << i << "\nstatus collapsed\n\n";
651 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
654 eat_whitespace(p, os, context, false);
659 void output_command_layout(ostream & os, Parser & p, bool outer,
660 Context & parent_context,
661 Layout const * newlayout)
663 TeXFont const oldFont = parent_context.font;
664 // save the current font size
665 string const size = oldFont.size;
666 // reset the font size to default, because the font size switches
667 // don't affect section headings and the like
668 parent_context.font.size = Context::normalfont.size;
669 // we only need to write the font change if we have an open layout
670 if (!parent_context.atParagraphStart())
671 output_font_change(os, oldFont, parent_context.font);
672 parent_context.check_end_layout(os);
673 Context context(true, parent_context.textclass, newlayout,
674 parent_context.layout, parent_context.font);
675 if (parent_context.deeper_paragraph) {
676 // We are beginning a nested environment after a
677 // deeper paragraph inside the outer list environment.
678 // Therefore we don't need to output a "begin deeper".
679 context.need_end_deeper = true;
681 context.check_deeper(os);
682 output_arguments(os, p, outer, context, context.layout->latexargs());
683 parse_text(p, os, FLAG_ITEM, outer, context);
684 context.check_end_layout(os);
685 if (parent_context.deeper_paragraph) {
686 // We must suppress the "end deeper" because we
687 // suppressed the "begin deeper" above.
688 context.need_end_deeper = false;
690 context.check_end_deeper(os);
691 // We don't need really a new paragraph, but
692 // we must make sure that the next item gets a \begin_layout.
693 parent_context.new_paragraph(os);
694 // Set the font size to the original value. No need to output it here
695 // (Context::begin_layout() will do that if needed)
696 parent_context.font.size = size;
701 * Output a space if necessary.
702 * This function gets called for every whitespace token.
704 * We have three cases here:
705 * 1. A space must be suppressed. Example: The lyxcode case below
706 * 2. A space may be suppressed. Example: Spaces before "\par"
707 * 3. A space must not be suppressed. Example: A space between two words
709 * We currently handle only 1. and 3 and from 2. only the case of
710 * spaces before newlines as a side effect.
712 * 2. could be used to suppress as many spaces as possible. This has two effects:
713 * - Reimporting LyX generated LaTeX files changes almost no whitespace
714 * - Superflous whitespace from non LyX generated LaTeX files is removed.
715 * The drawback is that the logic inside the function becomes
716 * complicated, and that is the reason why it is not implemented.
718 void check_space(Parser & p, ostream & os, Context & context)
720 Token const next = p.next_token();
721 Token const curr = p.curr_token();
722 // A space before a single newline and vice versa must be ignored
723 // LyX emits a newline before \end{lyxcode}.
724 // This newline must be ignored,
725 // otherwise LyX will add an additional protected space.
726 if (next.cat() == catSpace ||
727 next.cat() == catNewline ||
728 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
731 context.check_layout(os);
737 * Parse all arguments of \p command
739 void parse_arguments(string const & command,
740 vector<ArgumentType> const & template_arguments,
741 Parser & p, ostream & os, bool outer, Context & context)
743 string ert = command;
744 size_t no_arguments = template_arguments.size();
745 for (size_t i = 0; i < no_arguments; ++i) {
746 switch (template_arguments[i]) {
749 // This argument contains regular LaTeX
750 output_ert_inset(os, ert + '{', context);
751 eat_whitespace(p, os, context, false);
752 if (template_arguments[i] == required)
753 parse_text(p, os, FLAG_ITEM, outer, context);
755 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
759 // This argument consists only of a single item.
760 // The presence of '{' or not must be preserved.
762 if (p.next_token().cat() == catBegin)
763 ert += '{' + p.verbatim_item() + '}';
765 ert += p.verbatim_item();
769 // This argument may contain special characters
770 ert += '{' + p.verbatim_item() + '}';
774 // true because we must not eat whitespace
775 // if an optional arg follows we must not strip the
776 // brackets from this one
777 if (i < no_arguments - 1 &&
778 template_arguments[i+1] == optional)
779 ert += p.getFullOpt(true);
781 ert += p.getOpt(true);
785 output_ert_inset(os, ert, context);
790 * Check whether \p command is a known command. If yes,
791 * handle the command with all arguments.
792 * \return true if the command was parsed, false otherwise.
794 bool parse_command(string const & command, Parser & p, ostream & os,
795 bool outer, Context & context)
797 if (known_commands.find(command) != known_commands.end()) {
798 parse_arguments(command, known_commands[command], p, os,
806 /// Parses a minipage or parbox
807 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
808 unsigned inner_flags, bool outer, Context & parent_context,
809 string const & outer_type, string const & special,
810 string const & inner_type)
814 string hor_pos = "c";
815 // We need to set the height to the LaTeX default of 1\\totalheight
816 // for the case when no height argument is given
817 string height_value = "1";
818 string height_unit = "in";
819 string height_special = "totalheight";
824 string width_special = "none";
825 if (!inner_type.empty() && p.hasOpt()) {
826 if (inner_type != "makebox")
827 position = p.getArg('[', ']');
829 latex_width = p.getArg('[', ']');
830 translate_box_len(latex_width, width_value, width_unit, width_special);
833 if (position != "t" && position != "c" && position != "b") {
834 cerr << "invalid position " << position << " for "
835 << inner_type << endl;
839 if (inner_type != "makebox") {
840 latex_height = p.getArg('[', ']');
841 translate_box_len(latex_height, height_value, height_unit, height_special);
843 string const opt = p.getArg('[', ']');
846 if (hor_pos != "l" && hor_pos != "c" &&
847 hor_pos != "r" && hor_pos != "s") {
848 cerr << "invalid hor_pos " << hor_pos
849 << " for " << inner_type << endl;
856 inner_pos = p.getArg('[', ']');
857 if (inner_pos != "c" && inner_pos != "t" &&
858 inner_pos != "b" && inner_pos != "s") {
859 cerr << "invalid inner_pos "
860 << inner_pos << " for "
861 << inner_type << endl;
862 inner_pos = position;
867 if (inner_type.empty()) {
868 if (special.empty() && outer_type != "framebox")
869 latex_width = "1\\columnwidth";
872 latex_width = p2.getArg('[', ']');
873 string const opt = p2.getArg('[', ']');
876 if (hor_pos != "l" && hor_pos != "c" &&
877 hor_pos != "r" && hor_pos != "s") {
878 cerr << "invalid hor_pos " << hor_pos
879 << " for " << outer_type << endl;
884 } else if (inner_type != "makebox")
885 latex_width = p.verbatim_item();
886 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
887 // as this is LyX's standard for such cases (except for makebox)
888 // \framebox is more special and handled below
889 if (latex_width.empty() && inner_type != "makebox"
890 && outer_type != "framebox")
891 latex_width = "1\\columnwidth";
893 translate_len(latex_width, width_value, width_unit);
895 bool shadedparbox = false;
896 if (inner_type == "shaded") {
897 eat_whitespace(p, os, parent_context, false);
898 if (outer_type == "parbox") {
900 if (p.next_token().cat() == catBegin)
902 eat_whitespace(p, os, parent_context, false);
908 // If we already read the inner box we have to push the inner env
909 if (!outer_type.empty() && !inner_type.empty() &&
910 (inner_flags & FLAG_END))
911 active_environments.push_back(inner_type);
912 // LyX can't handle length variables
913 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
914 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
915 // Look whether there is some content after the end of the
916 // inner box, but before the end of the outer box.
917 // If yes, we need to output ERT.
919 if (inner_flags & FLAG_END)
920 p.ertEnvironment(inner_type);
924 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
925 if ((outer_env && p.next_token().asInput() != "\\end") ||
926 (!outer_env && p.next_token().cat() != catEnd)) {
927 // something is between the end of the inner box and
928 // the end of the outer box, so we need to use ERT.
933 // if only \makebox{content} was used we can set its width to 1\width
934 // because this identic and also identic to \mbox
935 // this doesn't work for \framebox{content}, thus we have to use ERT for this
936 if (latex_width.empty() && inner_type == "makebox") {
939 width_special = "width";
940 } else if (latex_width.empty() && outer_type == "framebox") {
943 width_special = "none";
947 if (!outer_type.empty()) {
948 if (outer_flags & FLAG_END)
949 ss << "\\begin{" << outer_type << '}';
951 ss << '\\' << outer_type << '{';
952 if (!special.empty())
956 if (!inner_type.empty()) {
957 if (inner_type != "shaded") {
958 if (inner_flags & FLAG_END)
959 ss << "\\begin{" << inner_type << '}';
961 ss << '\\' << inner_type;
963 if (!position.empty())
964 ss << '[' << position << ']';
965 if (!latex_height.empty())
966 ss << '[' << latex_height << ']';
967 if (!inner_pos.empty())
968 ss << '[' << inner_pos << ']';
969 ss << '{' << latex_width << '}';
970 if (!(inner_flags & FLAG_END))
973 if (inner_type == "shaded")
974 ss << "\\begin{shaded}";
975 output_ert_inset(os, ss.str(), parent_context);
976 if (!inner_type.empty()) {
977 parse_text(p, os, inner_flags, outer, parent_context);
978 if (inner_flags & FLAG_END)
979 output_ert_inset(os, "\\end{" + inner_type + '}',
982 output_ert_inset(os, "}", parent_context);
984 if (!outer_type.empty()) {
985 // If we already read the inner box we have to pop
987 if (!inner_type.empty() && (inner_flags & FLAG_END))
988 active_environments.pop_back();
990 // Ensure that the end of the outer box is parsed correctly:
991 // The opening brace has been eaten by parse_outer_box()
992 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
993 outer_flags &= ~FLAG_ITEM;
994 outer_flags |= FLAG_BRACE_LAST;
996 parse_text(p, os, outer_flags, outer, parent_context);
997 if (outer_flags & FLAG_END)
998 output_ert_inset(os, "\\end{" + outer_type + '}',
1001 output_ert_inset(os, "}", parent_context);
1004 // LyX does not like empty positions, so we have
1005 // to set them to the LaTeX default values here.
1006 if (position.empty())
1008 if (inner_pos.empty())
1009 inner_pos = position;
1010 parent_context.check_layout(os);
1011 begin_inset(os, "Box ");
1012 if (outer_type == "framed")
1014 else if (outer_type == "framebox" || outer_type == "fbox")
1016 else if (outer_type == "shadowbox")
1017 os << "Shadowbox\n";
1018 else if ((outer_type == "shaded" && inner_type.empty()) ||
1019 (outer_type == "minipage" && inner_type == "shaded") ||
1020 (outer_type == "parbox" && inner_type == "shaded")) {
1022 preamble.registerAutomaticallyLoadedPackage("color");
1023 } else if (outer_type == "doublebox")
1024 os << "Doublebox\n";
1025 else if (outer_type.empty() || outer_type == "mbox")
1026 os << "Frameless\n";
1028 os << outer_type << '\n';
1029 os << "position \"" << position << "\"\n";
1030 os << "hor_pos \"" << hor_pos << "\"\n";
1031 if (outer_type == "mbox")
1032 os << "has_inner_box 1\n";
1034 os << "has_inner_box " << !inner_type.empty() << "\n";
1035 os << "inner_pos \"" << inner_pos << "\"\n";
1036 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1038 if (outer_type == "mbox")
1039 os << "use_makebox 1\n";
1041 os << "use_makebox " << (inner_type == "makebox") << '\n';
1042 if (outer_type == "fbox" || outer_type == "mbox")
1043 os << "width \"\"\n";
1045 os << "width \"" << width_value << width_unit << "\"\n";
1046 os << "special \"" << width_special << "\"\n";
1047 os << "height \"" << height_value << height_unit << "\"\n";
1048 os << "height_special \"" << height_special << "\"\n";
1049 os << "status open\n\n";
1051 // Unfortunately we can't use parse_text_in_inset:
1052 // InsetBox::forcePlainLayout() is hard coded and does not
1053 // use the inset layout. Apart from that do we call parse_text
1054 // up to two times, but need only one check_end_layout.
1055 bool const forcePlainLayout =
1056 (!inner_type.empty() || inner_type == "makebox") &&
1057 outer_type != "shaded" && outer_type != "framed";
1058 Context context(true, parent_context.textclass);
1059 if (forcePlainLayout)
1060 context.layout = &context.textclass.plainLayout();
1062 context.font = parent_context.font;
1064 // If we have no inner box the contents will be read with the outer box
1065 if (!inner_type.empty())
1066 parse_text(p, os, inner_flags, outer, context);
1068 // Ensure that the end of the outer box is parsed correctly:
1069 // The opening brace has been eaten by parse_outer_box()
1070 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1071 outer_flags &= ~FLAG_ITEM;
1072 outer_flags |= FLAG_BRACE_LAST;
1075 // Find end of outer box, output contents if inner_type is
1076 // empty and output possible comments
1077 if (!outer_type.empty()) {
1078 // If we already read the inner box we have to pop
1080 if (!inner_type.empty() && (inner_flags & FLAG_END))
1081 active_environments.pop_back();
1082 // This does not output anything but comments if
1083 // inner_type is not empty (see use_ert)
1084 parse_text(p, os, outer_flags, outer, context);
1087 context.check_end_layout(os);
1089 #ifdef PRESERVE_LAYOUT
1090 // LyX puts a % after the end of the minipage
1091 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1093 //output_ert_inset(os, "%dummy", parent_context);
1096 parent_context.new_paragraph(os);
1098 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1099 //output_ert_inset(os, "%dummy", parent_context);
1102 // We add a protected space if something real follows
1103 if (p.good() && p.next_token().cat() != catComment) {
1104 begin_inset(os, "space ~\n");
1113 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1114 Context & parent_context, string const & outer_type,
1115 string const & special)
1117 eat_whitespace(p, os, parent_context, false);
1118 if (flags & FLAG_ITEM) {
1120 if (p.next_token().cat() == catBegin)
1123 cerr << "Warning: Ignoring missing '{' after \\"
1124 << outer_type << '.' << endl;
1125 eat_whitespace(p, os, parent_context, false);
1128 unsigned int inner_flags = 0;
1130 if (outer_type == "minipage" || outer_type == "parbox") {
1131 p.skip_spaces(true);
1132 while (p.hasOpt()) {
1134 p.skip_spaces(true);
1137 p.skip_spaces(true);
1138 if (outer_type == "parbox") {
1140 if (p.next_token().cat() == catBegin)
1142 p.skip_spaces(true);
1145 if (outer_type == "shaded" || outer_type == "fbox"
1146 || outer_type == "mbox") {
1147 // These boxes never have an inner box
1149 } else if (p.next_token().asInput() == "\\parbox") {
1150 inner = p.get_token().cs();
1151 inner_flags = FLAG_ITEM;
1152 } else if (p.next_token().asInput() == "\\begin") {
1153 // Is this a minipage or shaded box?
1156 inner = p.getArg('{', '}');
1158 if (inner == "minipage" || inner == "shaded")
1159 inner_flags = FLAG_END;
1164 if (inner_flags == FLAG_END) {
1165 if (inner != "shaded")
1169 eat_whitespace(p, os, parent_context, false);
1171 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1172 outer_type, special, inner);
1174 if (inner_flags == FLAG_ITEM) {
1176 eat_whitespace(p, os, parent_context, false);
1178 parse_box(p, os, flags, inner_flags, outer, parent_context,
1179 outer_type, special, inner);
1184 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1186 parent_context.check_layout(os);
1187 begin_inset(os, "listings\n");
1189 string arg = p.verbatimOption();
1190 os << "lstparams " << '"' << arg << '"' << '\n';
1191 if (arg.find("\\color") != string::npos)
1192 preamble.registerAutomaticallyLoadedPackage("color");
1195 os << "inline true\n";
1197 os << "inline false\n";
1198 os << "status collapsed\n";
1199 Context context(true, parent_context.textclass);
1200 context.layout = &parent_context.textclass.plainLayout();
1203 // set catcodes to verbatim early, just in case.
1204 p.setCatcodes(VERBATIM_CATCODES);
1205 string delim = p.get_token().asInput();
1206 //FIXME: handler error condition
1207 s = p.verbatimStuff(delim).second;
1208 // context.new_paragraph(os);
1210 s = p.verbatimEnvironment("lstlisting");
1211 output_ert(os, s, context);
1216 /// parse an unknown environment
1217 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1218 unsigned flags, bool outer,
1219 Context & parent_context)
1221 if (name == "tabbing")
1222 // We need to remember that we have to handle '\=' specially
1223 flags |= FLAG_TABBING;
1225 // We need to translate font changes and paragraphs inside the
1226 // environment to ERT if we have a non standard font.
1227 // Otherwise things like
1228 // \large\begin{foo}\huge bar\end{foo}
1230 bool const specialfont =
1231 (parent_context.font != parent_context.normalfont);
1232 bool const new_layout_allowed = parent_context.new_layout_allowed;
1234 parent_context.new_layout_allowed = false;
1235 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1236 parse_text_snippet(p, os, flags, outer, parent_context);
1237 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1239 parent_context.new_layout_allowed = new_layout_allowed;
1243 void parse_environment(Parser & p, ostream & os, bool outer,
1244 string & last_env, Context & parent_context)
1246 Layout const * newlayout;
1247 InsetLayout const * newinsetlayout = 0;
1248 string const name = p.getArg('{', '}');
1249 const bool is_starred = suffixIs(name, '*');
1250 string const unstarred_name = rtrim(name, "*");
1251 active_environments.push_back(name);
1253 if (is_math_env(name)) {
1254 parent_context.check_layout(os);
1255 begin_inset(os, "Formula ");
1256 os << "\\begin{" << name << "}";
1257 parse_math(p, os, FLAG_END, MATH_MODE);
1258 os << "\\end{" << name << "}";
1260 if (is_display_math_env(name)) {
1261 // Prevent the conversion of a line break to a space
1262 // (bug 7668). This does not change the output, but
1263 // looks ugly in LyX.
1264 eat_whitespace(p, os, parent_context, false);
1268 else if (is_known(name, preamble.polyglossia_languages)) {
1269 // We must begin a new paragraph if not already done
1270 if (! parent_context.atParagraphStart()) {
1271 parent_context.check_end_layout(os);
1272 parent_context.new_paragraph(os);
1274 // save the language in the context so that it is
1275 // handled by parse_text
1276 parent_context.font.language = preamble.polyglossia2lyx(name);
1277 parse_text(p, os, FLAG_END, outer, parent_context);
1278 // Just in case the environment is empty
1279 parent_context.extra_stuff.erase();
1280 // We must begin a new paragraph to reset the language
1281 parent_context.new_paragraph(os);
1285 else if (unstarred_name == "tabular" || name == "longtable") {
1286 eat_whitespace(p, os, parent_context, false);
1287 string width = "0pt";
1288 if (name == "tabular*") {
1289 width = lyx::translate_len(p.getArg('{', '}'));
1290 eat_whitespace(p, os, parent_context, false);
1292 parent_context.check_layout(os);
1293 begin_inset(os, "Tabular ");
1294 handle_tabular(p, os, name, width, parent_context);
1299 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1300 eat_whitespace(p, os, parent_context, false);
1301 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1302 eat_whitespace(p, os, parent_context, false);
1303 parent_context.check_layout(os);
1304 begin_inset(os, "Float " + unstarred_name + "\n");
1305 // store the float type for subfloats
1306 // subfloats only work with figures and tables
1307 if (unstarred_name == "figure")
1308 float_type = unstarred_name;
1309 else if (unstarred_name == "table")
1310 float_type = unstarred_name;
1314 os << "placement " << opt << '\n';
1315 if (contains(opt, "H"))
1316 preamble.registerAutomaticallyLoadedPackage("float");
1318 Floating const & fl = parent_context.textclass.floats()
1319 .getType(unstarred_name);
1320 if (!fl.floattype().empty() && fl.usesFloatPkg())
1321 preamble.registerAutomaticallyLoadedPackage("float");
1324 os << "wide " << convert<string>(is_starred)
1325 << "\nsideways false"
1326 << "\nstatus open\n\n";
1327 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1329 // We don't need really a new paragraph, but
1330 // we must make sure that the next item gets a \begin_layout.
1331 parent_context.new_paragraph(os);
1333 // the float is parsed thus delete the type
1337 else if (unstarred_name == "sidewaysfigure"
1338 || unstarred_name == "sidewaystable") {
1339 eat_whitespace(p, os, parent_context, false);
1340 parent_context.check_layout(os);
1341 if (unstarred_name == "sidewaysfigure")
1342 begin_inset(os, "Float figure\n");
1344 begin_inset(os, "Float table\n");
1345 os << "wide " << convert<string>(is_starred)
1346 << "\nsideways true"
1347 << "\nstatus open\n\n";
1348 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1350 // We don't need really a new paragraph, but
1351 // we must make sure that the next item gets a \begin_layout.
1352 parent_context.new_paragraph(os);
1354 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1357 else if (name == "wrapfigure" || name == "wraptable") {
1358 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1359 eat_whitespace(p, os, parent_context, false);
1360 parent_context.check_layout(os);
1363 string overhang = "0col%";
1366 lines = p.getArg('[', ']');
1367 string const placement = p.getArg('{', '}');
1369 overhang = p.getArg('[', ']');
1370 string const width = p.getArg('{', '}');
1372 if (name == "wrapfigure")
1373 begin_inset(os, "Wrap figure\n");
1375 begin_inset(os, "Wrap table\n");
1376 os << "lines " << lines
1377 << "\nplacement " << placement
1378 << "\noverhang " << lyx::translate_len(overhang)
1379 << "\nwidth " << lyx::translate_len(width)
1380 << "\nstatus open\n\n";
1381 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1383 // We don't need really a new paragraph, but
1384 // we must make sure that the next item gets a \begin_layout.
1385 parent_context.new_paragraph(os);
1387 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1390 else if (name == "minipage") {
1391 eat_whitespace(p, os, parent_context, false);
1392 // Test whether this is an outer box of a shaded box
1394 // swallow arguments
1395 while (p.hasOpt()) {
1397 p.skip_spaces(true);
1400 p.skip_spaces(true);
1401 Token t = p.get_token();
1402 bool shaded = false;
1403 if (t.asInput() == "\\begin") {
1404 p.skip_spaces(true);
1405 if (p.getArg('{', '}') == "shaded")
1410 parse_outer_box(p, os, FLAG_END, outer,
1411 parent_context, name, "shaded");
1413 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1418 else if (name == "comment") {
1419 eat_whitespace(p, os, parent_context, false);
1420 parent_context.check_layout(os);
1421 begin_inset(os, "Note Comment\n");
1422 os << "status open\n";
1423 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1426 skip_braces(p); // eat {} that might by set by LyX behind comments
1427 preamble.registerAutomaticallyLoadedPackage("verbatim");
1430 else if (name == "verbatim") {
1431 // FIXME: this should go in the generic code that
1432 // handles environments defined in layout file that
1433 // have "PassThru 1". However, the code over there is
1434 // already too complicated for my taste.
1435 parent_context.new_paragraph(os);
1436 Context context(true, parent_context.textclass,
1437 &parent_context.textclass[from_ascii("Verbatim")]);
1438 string s = p.verbatimEnvironment("verbatim");
1439 output_ert(os, s, context);
1443 else if (name == "IPA") {
1444 eat_whitespace(p, os, parent_context, false);
1445 parent_context.check_layout(os);
1446 begin_inset(os, "IPA\n");
1447 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1450 preamble.registerAutomaticallyLoadedPackage("tipa");
1451 preamble.registerAutomaticallyLoadedPackage("tipx");
1454 else if (name == "CJK") {
1455 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1456 // It is impossible to decide if a CJK environment was in its own paragraph or within
1457 // a line. We therefore always assume a paragraph since the latter is a rare case.
1458 eat_whitespace(p, os, parent_context, false);
1459 parent_context.check_end_layout(os);
1460 // store the encoding to be able to reset it
1461 string const encoding_old = p.getEncoding();
1462 string const encoding = p.getArg('{', '}');
1463 // FIXME: For some reason JIS does not work. Although the text
1464 // in tests/CJK.tex is identical with the SJIS version if you
1465 // convert both snippets using the recode command line utility,
1466 // the resulting .lyx file contains some extra characters if
1467 // you set buggy_encoding to false for JIS.
1468 bool const buggy_encoding = encoding == "JIS";
1469 if (!buggy_encoding)
1470 p.setEncoding(encoding, Encoding::CJK);
1472 // FIXME: This will read garbage, since the data is not encoded in utf8.
1473 p.setEncoding("UTF-8");
1475 // LyX only supports the same mapping for all CJK
1476 // environments, so we might need to output everything as ERT
1477 string const mapping = trim(p.getArg('{', '}'));
1478 char const * const * const where =
1479 is_known(encoding, supported_CJK_encodings);
1480 if (!buggy_encoding && !preamble.fontCJKSet())
1481 preamble.fontCJK(mapping);
1482 bool knownMapping = mapping == preamble.fontCJK();
1483 if (buggy_encoding || !knownMapping || !where) {
1484 parent_context.check_layout(os);
1485 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1487 // we must parse the content as verbatim because e.g. JIS can contain
1488 // normally invalid characters
1489 // FIXME: This works only for the most simple cases.
1490 // Since TeX control characters are not parsed,
1491 // things like comments are completely wrong.
1492 string const s = p.plainEnvironment("CJK");
1493 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1495 output_ert_inset(os, "\\", parent_context);
1496 else if (*it == '$')
1497 output_ert_inset(os, "$", parent_context);
1498 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1503 output_ert_inset(os, "\\end{" + name + "}",
1507 supported_CJK_languages[where - supported_CJK_encodings];
1508 // store the language because we must reset it at the end
1509 string const lang_old = parent_context.font.language;
1510 parent_context.font.language = lang;
1511 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1512 parent_context.font.language = lang_old;
1513 parent_context.new_paragraph(os);
1515 p.setEncoding(encoding_old);
1519 else if (name == "lyxgreyedout") {
1520 eat_whitespace(p, os, parent_context, false);
1521 parent_context.check_layout(os);
1522 begin_inset(os, "Note Greyedout\n");
1523 os << "status open\n";
1524 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1527 if (!preamble.notefontcolor().empty())
1528 preamble.registerAutomaticallyLoadedPackage("color");
1531 else if (name == "btSect") {
1532 eat_whitespace(p, os, parent_context, false);
1533 parent_context.check_layout(os);
1534 begin_command_inset(os, "bibtex", "bibtex");
1535 string bibstyle = "plain";
1537 bibstyle = p.getArg('[', ']');
1538 p.skip_spaces(true);
1540 string const bibfile = p.getArg('{', '}');
1541 eat_whitespace(p, os, parent_context, false);
1542 Token t = p.get_token();
1543 if (t.asInput() == "\\btPrintCited") {
1544 p.skip_spaces(true);
1545 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1547 if (t.asInput() == "\\btPrintNotCited") {
1548 p.skip_spaces(true);
1549 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1551 if (t.asInput() == "\\btPrintAll") {
1552 p.skip_spaces(true);
1553 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1555 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1556 os << "options " << '"' << bibstyle << '"' << "\n";
1557 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1562 else if (name == "framed" || name == "shaded") {
1563 eat_whitespace(p, os, parent_context, false);
1564 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1568 else if (name == "lstlisting") {
1569 eat_whitespace(p, os, parent_context, false);
1570 parse_listings(p, os, parent_context, false);
1574 else if (!parent_context.new_layout_allowed)
1575 parse_unknown_environment(p, name, os, FLAG_END, outer,
1578 // Alignment and spacing settings
1579 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1580 // therefore are totally broken!
1581 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1582 // they are commands not environments. They are furthermore switches that
1583 // can be ended by another switches, but also by commands like \footnote or
1584 // \parbox. So the only safe way is to leave them untouched.
1585 else if (name == "center" || name == "centering" ||
1586 name == "flushleft" || name == "flushright" ||
1587 name == "singlespace" || name == "onehalfspace" ||
1588 name == "doublespace" || name == "spacing") {
1589 eat_whitespace(p, os, parent_context, false);
1590 // We must begin a new paragraph if not already done
1591 if (! parent_context.atParagraphStart()) {
1592 parent_context.check_end_layout(os);
1593 parent_context.new_paragraph(os);
1595 if (name == "flushleft")
1596 parent_context.add_extra_stuff("\\align left\n");
1597 else if (name == "flushright")
1598 parent_context.add_extra_stuff("\\align right\n");
1599 else if (name == "center" || name == "centering")
1600 parent_context.add_extra_stuff("\\align center\n");
1601 else if (name == "singlespace")
1602 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1603 else if (name == "onehalfspace") {
1604 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1605 preamble.registerAutomaticallyLoadedPackage("setspace");
1606 } else if (name == "doublespace") {
1607 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1608 preamble.registerAutomaticallyLoadedPackage("setspace");
1609 } else if (name == "spacing") {
1610 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1611 preamble.registerAutomaticallyLoadedPackage("setspace");
1613 parse_text(p, os, FLAG_END, outer, parent_context);
1614 // Just in case the environment is empty
1615 parent_context.extra_stuff.erase();
1616 // We must begin a new paragraph to reset the alignment
1617 parent_context.new_paragraph(os);
1621 // The single '=' is meant here.
1622 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1623 eat_whitespace(p, os, parent_context, false);
1624 Context context(true, parent_context.textclass, newlayout,
1625 parent_context.layout, parent_context.font);
1626 if (parent_context.deeper_paragraph) {
1627 // We are beginning a nested environment after a
1628 // deeper paragraph inside the outer list environment.
1629 // Therefore we don't need to output a "begin deeper".
1630 context.need_end_deeper = true;
1632 parent_context.check_end_layout(os);
1633 if (last_env == name) {
1634 // we need to output a separator since LyX would export
1635 // the two environments as one otherwise (bug 5716)
1636 TeX2LyXDocClass const & textclass(parent_context.textclass);
1637 Context newcontext(true, textclass,
1638 &(textclass.defaultLayout()));
1639 newcontext.check_layout(os);
1640 begin_inset(os, "Separator plain\n");
1642 newcontext.check_end_layout(os);
1644 switch (context.layout->latextype) {
1645 case LATEX_LIST_ENVIRONMENT:
1646 context.add_par_extra_stuff("\\labelwidthstring "
1647 + p.verbatim_item() + '\n');
1650 case LATEX_BIB_ENVIRONMENT:
1651 p.verbatim_item(); // swallow next arg
1657 context.check_deeper(os);
1658 // handle known optional and required arguments
1659 // FIXME: Since format 446, layouts do not require anymore all optional
1660 // arguments before the required ones. Needs to be implemented!
1661 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1662 // It is impossible to place anything after the environment name,
1663 // but before the first \\item.
1664 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1665 bool need_layout = true;
1667 while (optargs < context.layout->optArgs()) {
1668 eat_whitespace(p, os, context, false);
1669 if (p.next_token().cat() == catEscape ||
1670 p.next_token().character() != '[')
1672 p.get_token(); // eat '['
1674 context.check_layout(os);
1675 need_layout = false;
1677 // FIXME: Just a workaround. InsetArgument::updateBuffer
1678 // will compute a proper ID for all "999" Arguments
1679 // (which is also what lyx2lyx produces).
1680 // However, tex2lyx should be able to output proper IDs
1682 begin_inset(os, "Argument 999\n");
1683 os << "status collapsed\n\n";
1684 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1686 eat_whitespace(p, os, context, false);
1690 while (reqargs < context.layout->requiredArgs()) {
1691 eat_whitespace(p, os, context, false);
1692 if (p.next_token().cat() != catBegin)
1694 p.get_token(); // eat '{'
1696 context.check_layout(os);
1697 need_layout = false;
1699 // FIXME: Just a workaround. InsetArgument::updateBuffer
1700 // will compute a proper ID for all "999" Arguments
1701 // (which is also what lyx2lyx produces).
1702 // However, tex2lyx should be able to output proper IDs
1704 begin_inset(os, "Argument 999\n");
1705 os << "status collapsed\n\n";
1706 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1708 eat_whitespace(p, os, context, false);
1712 parse_text(p, os, FLAG_END, outer, context);
1713 context.check_end_layout(os);
1714 if (parent_context.deeper_paragraph) {
1715 // We must suppress the "end deeper" because we
1716 // suppressed the "begin deeper" above.
1717 context.need_end_deeper = false;
1719 context.check_end_deeper(os);
1720 parent_context.new_paragraph(os);
1722 if (!preamble.titleLayoutFound())
1723 preamble.titleLayoutFound(newlayout->intitle);
1724 set<string> const & req = newlayout->requires();
1725 set<string>::const_iterator it = req.begin();
1726 set<string>::const_iterator en = req.end();
1727 for (; it != en; ++it)
1728 preamble.registerAutomaticallyLoadedPackage(*it);
1731 // The single '=' is meant here.
1732 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1733 eat_whitespace(p, os, parent_context, false);
1734 parent_context.check_layout(os);
1735 begin_inset(os, "Flex ");
1736 os << to_utf8(newinsetlayout->name()) << '\n'
1737 << "status collapsed\n";
1738 if (newinsetlayout->isPassThru()) {
1739 string const arg = p.verbatimEnvironment(name);
1740 Context context(true, parent_context.textclass,
1741 &parent_context.textclass.plainLayout(),
1742 parent_context.layout);
1743 output_ert(os, arg, parent_context);
1745 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1749 else if (name == "appendix") {
1750 // This is no good latex style, but it works and is used in some documents...
1751 eat_whitespace(p, os, parent_context, false);
1752 parent_context.check_end_layout(os);
1753 Context context(true, parent_context.textclass, parent_context.layout,
1754 parent_context.layout, parent_context.font);
1755 context.check_layout(os);
1756 os << "\\start_of_appendix\n";
1757 parse_text(p, os, FLAG_END, outer, context);
1758 context.check_end_layout(os);
1762 else if (known_environments.find(name) != known_environments.end()) {
1763 vector<ArgumentType> arguments = known_environments[name];
1764 // The last "argument" denotes wether we may translate the
1765 // environment contents to LyX
1766 // The default required if no argument is given makes us
1767 // compatible with the reLyXre environment.
1768 ArgumentType contents = arguments.empty() ?
1771 if (!arguments.empty())
1772 arguments.pop_back();
1773 // See comment in parse_unknown_environment()
1774 bool const specialfont =
1775 (parent_context.font != parent_context.normalfont);
1776 bool const new_layout_allowed =
1777 parent_context.new_layout_allowed;
1779 parent_context.new_layout_allowed = false;
1780 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1781 outer, parent_context);
1782 if (contents == verbatim)
1783 output_ert_inset(os, p.ertEnvironment(name),
1786 parse_text_snippet(p, os, FLAG_END, outer,
1788 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1790 parent_context.new_layout_allowed = new_layout_allowed;
1794 parse_unknown_environment(p, name, os, FLAG_END, outer,
1798 active_environments.pop_back();
1802 /// parses a comment and outputs it to \p os.
1803 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1805 LASSERT(t.cat() == catComment, return);
1806 if (!t.cs().empty()) {
1807 context.check_layout(os);
1808 output_ert_inset(os, '%' + t.cs(), context);
1809 if (p.next_token().cat() == catNewline) {
1810 // A newline after a comment line starts a new
1812 if (context.new_layout_allowed) {
1813 if(!context.atParagraphStart())
1814 // Only start a new paragraph if not already
1815 // done (we might get called recursively)
1816 context.new_paragraph(os);
1818 output_ert_inset(os, "\n", context);
1819 eat_whitespace(p, os, context, true);
1822 // "%\n" combination
1829 * Reads spaces and comments until the first non-space, non-comment token.
1830 * New paragraphs (double newlines or \\par) are handled like simple spaces
1831 * if \p eatParagraph is true.
1832 * Spaces are skipped, but comments are written to \p os.
1834 void eat_whitespace(Parser & p, ostream & os, Context & context,
1838 Token const & t = p.get_token();
1839 if (t.cat() == catComment)
1840 parse_comment(p, os, t, context);
1841 else if ((! eatParagraph && p.isParagraph()) ||
1842 (t.cat() != catSpace && t.cat() != catNewline)) {
1851 * Set a font attribute, parse text and reset the font attribute.
1852 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1853 * \param currentvalue Current value of the attribute. Is set to the new
1854 * value during parsing.
1855 * \param newvalue New value of the attribute
1857 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1858 Context & context, string const & attribute,
1859 string & currentvalue, string const & newvalue)
1861 context.check_layout(os);
1862 string const oldvalue = currentvalue;
1863 currentvalue = newvalue;
1864 os << '\n' << attribute << ' ' << newvalue << "\n";
1865 parse_text_snippet(p, os, flags, outer, context);
1866 context.check_layout(os);
1867 os << '\n' << attribute << ' ' << oldvalue << "\n";
1868 currentvalue = oldvalue;
1872 /// get the arguments of a natbib or jurabib citation command
1873 void get_cite_arguments(Parser & p, bool natbibOrder,
1874 string & before, string & after)
1876 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1878 // text before the citation
1880 // text after the citation
1881 after = p.getFullOpt();
1883 if (!after.empty()) {
1884 before = p.getFullOpt();
1885 if (natbibOrder && !before.empty())
1886 swap(before, after);
1891 /// Convert filenames with TeX macros and/or quotes to something LyX
1893 string const normalize_filename(string const & name)
1898 Token const & t = p.get_token();
1899 if (t.cat() != catEscape)
1901 else if (t.cs() == "lyxdot") {
1902 // This is used by LyX for simple dots in relative
1906 } else if (t.cs() == "space") {
1909 } else if (t.cs() == "string") {
1910 // Convert \string" to " and \string~ to ~
1911 Token const & n = p.next_token();
1912 if (n.asInput() != "\"" && n.asInput() != "~")
1917 // Strip quotes. This is a bit complicated (see latex_path()).
1918 string full = os.str();
1919 if (!full.empty() && full[0] == '"') {
1920 string base = removeExtension(full);
1921 string ext = getExtension(full);
1922 if (!base.empty() && base[base.length()-1] == '"')
1925 return addExtension(trim(base, "\""), ext);
1926 if (full[full.length()-1] == '"')
1929 return trim(full, "\"");
1935 /// Convert \p name from TeX convention (relative to master file) to LyX
1936 /// convention (relative to .lyx file) if it is relative
1937 void fix_child_filename(string & name)
1939 string const absMasterTeX = getMasterFilePath(true);
1940 bool const isabs = FileName::isAbsolute(name);
1941 // convert from "relative to .tex master" to absolute original path
1943 name = makeAbsPath(name, absMasterTeX).absFileName();
1944 bool copyfile = copyFiles();
1945 string const absParentLyX = getParentFilePath(false);
1948 // convert from absolute original path to "relative to master file"
1949 string const rel = to_utf8(makeRelPath(from_utf8(name),
1950 from_utf8(absMasterTeX)));
1951 // re-interpret "relative to .tex file" as "relative to .lyx file"
1952 // (is different if the master .lyx file resides in a
1953 // different path than the master .tex file)
1954 string const absMasterLyX = getMasterFilePath(false);
1955 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1956 // Do not copy if the new path is impossible to create. Example:
1957 // absMasterTeX = "/foo/bar/"
1958 // absMasterLyX = "/bar/"
1959 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1960 if (contains(name, "/../"))
1967 // convert from absolute original path to
1968 // "relative to .lyx file"
1969 name = to_utf8(makeRelPath(from_utf8(abs),
1970 from_utf8(absParentLyX)));
1974 // convert from absolute original path to "relative to .lyx file"
1975 name = to_utf8(makeRelPath(from_utf8(name),
1976 from_utf8(absParentLyX)));
1981 void copy_file(FileName const & src, string dstname)
1985 string const absParent = getParentFilePath(false);
1987 if (FileName::isAbsolute(dstname))
1988 dst = FileName(dstname);
1990 dst = makeAbsPath(dstname, absParent);
1991 string const absMaster = getMasterFilePath(false);
1992 FileName const srcpath = src.onlyPath();
1993 FileName const dstpath = dst.onlyPath();
1994 if (equivalent(srcpath, dstpath))
1996 if (!dstpath.isDirectory()) {
1997 if (!dstpath.createPath()) {
1998 cerr << "Warning: Could not create directory for file `"
1999 << dst.absFileName() << "´." << endl;
2003 if (dst.isReadableFile()) {
2004 if (overwriteFiles())
2005 cerr << "Warning: Overwriting existing file `"
2006 << dst.absFileName() << "´." << endl;
2008 cerr << "Warning: Not overwriting existing file `"
2009 << dst.absFileName() << "´." << endl;
2013 if (!src.copyTo(dst))
2014 cerr << "Warning: Could not copy file `" << src.absFileName()
2015 << "´ to `" << dst.absFileName() << "´." << endl;
2019 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2020 bool parse_chunk(Parser & p, ostream & os, Context & context)
2022 // check whether a chunk is possible here.
2023 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2029 // read the parameters
2030 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2031 if (!params.first) {
2036 Parser::Arg const code = p.verbatimStuff("\n@");
2041 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2042 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2046 // The last newline read is important for paragraph handling
2050 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2051 // We must have a valid layout before outputting the Chunk inset.
2052 context.check_layout(os);
2053 Context chunkcontext(true, context.textclass);
2054 chunkcontext.layout = &context.textclass.plainLayout();
2055 begin_inset(os, "Flex Chunk");
2056 os << "\nstatus open\n";
2057 if (!params.second.empty()) {
2058 chunkcontext.check_layout(os);
2059 Context paramscontext(true, context.textclass);
2060 paramscontext.layout = &context.textclass.plainLayout();
2061 begin_inset(os, "Argument 1");
2062 os << "\nstatus open\n";
2063 output_ert(os, params.second, paramscontext);
2066 output_ert(os, code.second, chunkcontext);
2074 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2075 bool is_macro(Parser & p)
2077 Token first = p.curr_token();
2078 if (first.cat() != catEscape || !p.good())
2080 if (first.cs() == "def")
2082 if (first.cs() != "global" && first.cs() != "long")
2084 Token second = p.get_token();
2086 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2087 second.cat() == catNewline || second.cat() == catComment)) {
2088 second = p.get_token();
2091 bool secondvalid = second.cat() == catEscape;
2093 bool thirdvalid = false;
2094 if (p.good() && first.cs() == "global" && secondvalid &&
2095 second.cs() == "long") {
2096 third = p.get_token();
2098 while (p.good() && !p.isParagraph() &&
2099 (third.cat() == catSpace ||
2100 third.cat() == catNewline ||
2101 third.cat() == catComment)) {
2102 third = p.get_token();
2105 thirdvalid = third.cat() == catEscape;
2107 for (int i = 0; i < pos; ++i)
2112 return (first.cs() == "global" || first.cs() == "long") &&
2113 second.cs() == "def";
2114 return first.cs() == "global" && second.cs() == "long" &&
2115 third.cs() == "def";
2119 /// Parse a macro definition (assumes that is_macro() returned true)
2120 void parse_macro(Parser & p, ostream & os, Context & context)
2122 context.check_layout(os);
2123 Token first = p.curr_token();
2126 string command = first.asInput();
2127 if (first.cs() != "def") {
2129 eat_whitespace(p, os, context, false);
2130 second = p.curr_token();
2131 command += second.asInput();
2132 if (second.cs() != "def") {
2134 eat_whitespace(p, os, context, false);
2135 third = p.curr_token();
2136 command += third.asInput();
2139 eat_whitespace(p, os, context, false);
2140 string const name = p.get_token().cs();
2141 eat_whitespace(p, os, context, false);
2147 while (p.next_token().cat() != catBegin) {
2148 if (p.next_token().cat() == catParameter) {
2153 // followed by number?
2154 if (p.next_token().cat() == catOther) {
2155 string s = p.get_token().asInput();
2157 // number = current arity + 1?
2158 if (s.size() == 1 && s[0] == arity + '0' + 1)
2163 paramtext += p.get_token().cs();
2165 paramtext += p.get_token().cs();
2170 // only output simple (i.e. compatible) macro as FormulaMacros
2171 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2173 context.check_layout(os);
2174 begin_inset(os, "FormulaMacro");
2175 os << "\n\\def" << ert;
2178 output_ert_inset(os, command + ert, context);
2182 void registerExternalTemplatePackages(string const & name)
2184 external::TemplateManager const & etm = external::TemplateManager::get();
2185 external::Template const * const et = etm.getTemplateByName(name);
2188 external::Template::Formats::const_iterator cit = et->formats.end();
2190 cit = et->formats.find("PDFLaTeX");
2191 if (cit == et->formats.end())
2192 // If the template has not specified a PDFLaTeX output,
2193 // we try the LaTeX format.
2194 cit = et->formats.find("LaTeX");
2195 if (cit == et->formats.end())
2197 vector<string>::const_iterator qit = cit->second.requirements.begin();
2198 vector<string>::const_iterator qend = cit->second.requirements.end();
2199 for (; qit != qend; ++qit)
2200 preamble.registerAutomaticallyLoadedPackage(*qit);
2203 } // anonymous namespace
2206 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2209 Layout const * newlayout = 0;
2210 InsetLayout const * newinsetlayout = 0;
2211 char const * const * where = 0;
2212 // Store the latest bibliographystyle, addcontentslineContent and
2213 // nocite{*} option (needed for bibtex inset)
2215 string contentslineContent;
2216 string bibliographystyle = "default";
2217 bool const use_natbib = isProvided("natbib");
2218 bool const use_jurabib = isProvided("jurabib");
2221 // it is impossible to determine the correct encoding for non-CJK Japanese.
2222 // Therefore write a note at the beginning of the document
2223 if (is_nonCJKJapanese) {
2224 context.check_layout(os);
2225 begin_inset(os, "Note Note\n");
2226 os << "status open\n\\begin_layout Plain Layout\n"
2227 << "\\series bold\n"
2228 << "Important information:\n"
2229 << "\\end_layout\n\n"
2230 << "\\begin_layout Plain Layout\n"
2231 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2232 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2233 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2234 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2235 << " and specify the encoding using the -e command-line switch.\n"
2236 << " In addition, you might want to double check that the desired output encoding\n"
2237 << " is correctly selected in Document > Settings > Language.\n"
2238 << "\\end_layout\n";
2240 is_nonCJKJapanese = false;
2244 Token const & t = p.get_token();
2246 debugToken(cerr, t, flags);
2249 if (flags & FLAG_ITEM) {
2250 if (t.cat() == catSpace)
2253 flags &= ~FLAG_ITEM;
2254 if (t.cat() == catBegin) {
2255 // skip the brace and collect everything to the next matching
2257 flags |= FLAG_BRACE_LAST;
2261 // handle only this single token, leave the loop if done
2262 flags |= FLAG_LEAVE;
2265 if (t.cat() != catEscape && t.character() == ']' &&
2266 (flags & FLAG_BRACK_LAST))
2268 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2271 // If there is anything between \end{env} and \begin{env} we
2272 // don't need to output a separator.
2273 if (t.cat() != catSpace && t.cat() != catNewline &&
2274 t.asInput() != "\\begin")
2280 bool const starred = p.next_token().asInput() == "*";
2281 string const starredname(starred ? (t.cs() + '*') : t.cs());
2282 if (t.cat() == catMath) {
2283 // we are inside some text mode thingy, so opening new math is allowed
2284 context.check_layout(os);
2285 begin_inset(os, "Formula ");
2286 Token const & n = p.get_token();
2287 bool const display(n.cat() == catMath && outer);
2289 // TeX's $$...$$ syntax for displayed math
2291 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2293 p.get_token(); // skip the second '$' token
2295 // simple $...$ stuff
2298 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2303 // Prevent the conversion of a line break to a
2304 // space (bug 7668). This does not change the
2305 // output, but looks ugly in LyX.
2306 eat_whitespace(p, os, context, false);
2310 else if (t.cat() == catSuper || t.cat() == catSub)
2311 cerr << "catcode " << t << " illegal in text mode\n";
2313 // Basic support for english quotes. This should be
2314 // extended to other quotes, but is not so easy (a
2315 // left english quote is the same as a right german
2317 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2318 context.check_layout(os);
2319 begin_inset(os, "Quotes ");
2325 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2326 context.check_layout(os);
2327 begin_inset(os, "Quotes ");
2334 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2335 context.check_layout(os);
2336 begin_inset(os, "Quotes ");
2343 else if (t.asInput() == "<"
2344 && p.next_token().asInput() == "<") {
2345 bool has_chunk = false;
2349 has_chunk = parse_chunk(p, os, context);
2355 context.check_layout(os);
2356 begin_inset(os, "Quotes ");
2357 //FIXME: this is a right danish quote;
2358 // why not a left french quote?
2366 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2367 check_space(p, os, context);
2369 else if (t.character() == '[' && noweb_mode &&
2370 p.next_token().character() == '[') {
2371 // These can contain underscores
2373 string const s = p.getFullOpt() + ']';
2374 if (p.next_token().character() == ']')
2377 cerr << "Warning: Inserting missing ']' in '"
2378 << s << "'." << endl;
2379 output_ert_inset(os, s, context);
2382 else if (t.cat() == catLetter) {
2383 context.check_layout(os);
2384 // Workaround for bug 4752.
2385 // FIXME: This whole code block needs to be removed
2386 // when the bug is fixed and tex2lyx produces
2387 // the updated file format.
2388 // The replacement algorithm in LyX is so stupid that
2389 // it even translates a phrase if it is part of a word.
2390 bool handled = false;
2391 for (int const * l = known_phrase_lengths; *l; ++l) {
2392 string phrase = t.cs();
2393 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2394 phrase += p.get_token().cs();
2395 if (is_known(phrase, known_coded_phrases)) {
2396 output_ert_inset(os, phrase, context);
2400 for (size_t i = 1; i < phrase.length(); ++i)
2408 else if (t.cat() == catOther ||
2409 t.cat() == catAlign ||
2410 t.cat() == catParameter) {
2411 // This translates "&" to "\\&" which may be wrong...
2412 context.check_layout(os);
2416 else if (p.isParagraph()) {
2417 if (context.new_layout_allowed)
2418 context.new_paragraph(os);
2420 output_ert_inset(os, "\\par ", context);
2421 eat_whitespace(p, os, context, true);
2424 else if (t.cat() == catActive) {
2425 context.check_layout(os);
2426 if (t.character() == '~') {
2427 if (context.layout->free_spacing)
2430 begin_inset(os, "space ~\n");
2437 else if (t.cat() == catBegin) {
2438 Token const next = p.next_token();
2439 Token const end = p.next_next_token();
2440 if (next.cat() == catEnd) {
2442 Token const prev = p.prev_token();
2444 if (p.next_token().character() == '`' ||
2445 (prev.character() == '-' &&
2446 p.next_token().character() == '-'))
2447 ; // ignore it in {}`` or -{}-
2449 output_ert_inset(os, "{}", context);
2450 } else if (next.cat() == catEscape &&
2451 is_known(next.cs(), known_quotes) &&
2452 end.cat() == catEnd) {
2453 // Something like {\textquoteright} (e.g.
2454 // from writer2latex). LyX writes
2455 // \textquoteright{}, so we may skip the
2456 // braces here for better readability.
2457 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2459 } else if (p.next_token().asInput() == "\\ascii") {
2460 // handle the \ascii characters
2461 // (the case without braces is handled later)
2462 // the code is "{\ascii\xxx}"
2463 p.get_token(); // eat \ascii
2464 string name2 = p.get_token().asInput();
2465 p.get_token(); // eat the final '}'
2466 string const name = "{\\ascii" + name2 + "}";
2470 // get the character from unicodesymbols
2471 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2472 Encodings::TEXT_CMD, termination, rem, &req);
2474 context.check_layout(os);
2477 output_ert_inset(os,
2478 to_utf8(rem), context);
2479 for (set<string>::const_iterator it = req.begin();
2480 it != req.end(); ++it)
2481 preamble.registerAutomaticallyLoadedPackage(*it);
2483 // we did not find a non-ert version
2484 output_ert_inset(os, name, context);
2486 context.check_layout(os);
2487 // special handling of font attribute changes
2488 Token const prev = p.prev_token();
2489 TeXFont const oldFont = context.font;
2490 if (next.character() == '[' ||
2491 next.character() == ']' ||
2492 next.character() == '*') {
2494 if (p.next_token().cat() == catEnd) {
2499 output_ert_inset(os, "{", context);
2500 parse_text_snippet(p, os,
2503 output_ert_inset(os, "}", context);
2505 } else if (! context.new_layout_allowed) {
2506 output_ert_inset(os, "{", context);
2507 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2509 output_ert_inset(os, "}", context);
2510 } else if (is_known(next.cs(), known_sizes)) {
2511 // next will change the size, so we must
2513 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2515 if (!context.atParagraphStart())
2517 << context.font.size << "\n";
2518 } else if (is_known(next.cs(), known_font_families)) {
2519 // next will change the font family, so we
2520 // must reset it here
2521 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2523 if (!context.atParagraphStart())
2525 << context.font.family << "\n";
2526 } else if (is_known(next.cs(), known_font_series)) {
2527 // next will change the font series, so we
2528 // must reset it here
2529 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2531 if (!context.atParagraphStart())
2533 << context.font.series << "\n";
2534 } else if (is_known(next.cs(), known_font_shapes)) {
2535 // next will change the font shape, so we
2536 // must reset it here
2537 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2539 if (!context.atParagraphStart())
2541 << context.font.shape << "\n";
2542 } else if (is_known(next.cs(), known_old_font_families) ||
2543 is_known(next.cs(), known_old_font_series) ||
2544 is_known(next.cs(), known_old_font_shapes)) {
2545 // next will change the font family, series
2546 // and shape, so we must reset it here
2547 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2549 if (!context.atParagraphStart())
2551 << context.font.family
2553 << context.font.series
2555 << context.font.shape << "\n";
2557 output_ert_inset(os, "{", context);
2558 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2560 output_ert_inset(os, "}", context);
2565 else if (t.cat() == catEnd) {
2566 if (flags & FLAG_BRACE_LAST) {
2569 cerr << "stray '}' in text\n";
2570 output_ert_inset(os, "}", context);
2573 else if (t.cat() == catComment)
2574 parse_comment(p, os, t, context);
2577 // control sequences
2580 else if (t.cs() == "(" || t.cs() == "[") {
2581 bool const simple = t.cs() == "(";
2582 context.check_layout(os);
2583 begin_inset(os, "Formula");
2584 os << " \\" << t.cs();
2585 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2586 os << '\\' << (simple ? ')' : ']');
2589 // Prevent the conversion of a line break to a
2590 // space (bug 7668). This does not change the
2591 // output, but looks ugly in LyX.
2592 eat_whitespace(p, os, context, false);
2596 else if (t.cs() == "begin")
2597 parse_environment(p, os, outer, last_env,
2600 else if (t.cs() == "end") {
2601 if (flags & FLAG_END) {
2602 // eat environment name
2603 string const name = p.getArg('{', '}');
2604 if (name != active_environment())
2605 cerr << "\\end{" + name + "} does not match \\begin{"
2606 + active_environment() + "}\n";
2609 p.error("found 'end' unexpectedly");
2612 else if (t.cs() == "item") {
2614 bool const optarg = p.hasOpt();
2616 // FIXME: This swallows comments, but we cannot use
2617 // eat_whitespace() since we must not output
2618 // anything before the item.
2619 p.skip_spaces(true);
2620 s = p.verbatimOption();
2622 p.skip_spaces(false);
2624 context.check_layout(os);
2625 if (context.has_item) {
2626 // An item in an unknown list-like environment
2627 // FIXME: Do this in check_layout()!
2628 context.has_item = false;
2630 output_ert_inset(os, "\\item", context);
2632 output_ert_inset(os, "\\item ", context);
2635 if (context.layout->labeltype != LABEL_MANUAL) {
2636 // handle option of itemize item
2637 begin_inset(os, "Argument item:1\n");
2638 os << "status open\n";
2639 os << "\n\\begin_layout Plain Layout\n";
2641 os << parse_text_snippet(p2,
2642 FLAG_BRACK_LAST, outer, context);
2643 // we must not use context.check_end_layout(os)
2644 // because that would close the outer itemize layout
2645 os << "\n\\end_layout\n";
2647 eat_whitespace(p, os, context, false);
2648 } else if (!s.empty()) {
2649 // LyX adds braces around the argument,
2650 // so we need to remove them here.
2651 if (s.size() > 2 && s[0] == '{' &&
2652 s[s.size()-1] == '}')
2653 s = s.substr(1, s.size()-2);
2654 // If the argument contains a space we
2655 // must put it into ERT: Otherwise LyX
2656 // would misinterpret the space as
2657 // item delimiter (bug 7663)
2658 if (contains(s, ' ')) {
2659 output_ert_inset(os, s, context);
2662 os << parse_text_snippet(p2,
2663 FLAG_BRACK_LAST, outer, context);
2665 // The space is needed to separate the
2666 // item from the rest of the sentence.
2668 eat_whitespace(p, os, context, false);
2673 else if (t.cs() == "bibitem") {
2675 context.check_layout(os);
2676 eat_whitespace(p, os, context, false);
2677 string label = convert_command_inset_arg(p.verbatimOption());
2678 string key = convert_command_inset_arg(p.verbatim_item());
2679 if (contains(label, '\\') || contains(key, '\\')) {
2680 // LyX can't handle LaTeX commands in labels or keys
2681 output_ert_inset(os, t.asInput() + '[' + label +
2682 "]{" + p.verbatim_item() + '}',
2685 begin_command_inset(os, "bibitem", "bibitem");
2686 os << "label \"" << label << "\"\n"
2687 "key \"" << key << "\"\n";
2692 else if (is_macro(p)) {
2693 // catch the case of \def\inputGnumericTable
2695 if (t.cs() == "def") {
2696 Token second = p.next_token();
2697 if (second.cs() == "inputGnumericTable") {
2701 Token third = p.get_token();
2703 if (third.cs() == "input") {
2707 string name = normalize_filename(p.verbatim_item());
2708 string const path = getMasterFilePath(true);
2709 // We want to preserve relative / absolute filenames,
2710 // therefore path is only used for testing
2711 // The file extension is in every case ".tex".
2712 // So we need to remove this extension and check for
2713 // the original one.
2714 name = removeExtension(name);
2715 if (!makeAbsPath(name, path).exists()) {
2716 char const * const Gnumeric_formats[] = {"gnumeric",
2718 string const Gnumeric_name =
2719 find_file(name, path, Gnumeric_formats);
2720 if (!Gnumeric_name.empty())
2721 name = Gnumeric_name;
2723 FileName const absname = makeAbsPath(name, path);
2724 if (absname.exists()) {
2725 fix_child_filename(name);
2726 copy_file(absname, name);
2728 cerr << "Warning: Could not find file '"
2729 << name << "'." << endl;
2730 context.check_layout(os);
2731 begin_inset(os, "External\n\ttemplate ");
2732 os << "GnumericSpreadsheet\n\tfilename "
2735 context.check_layout(os);
2737 // register the packages that are automatically loaded
2738 // by the Gnumeric template
2739 registerExternalTemplatePackages("GnumericSpreadsheet");
2744 parse_macro(p, os, context);
2747 else if (t.cs() == "noindent") {
2749 context.add_par_extra_stuff("\\noindent\n");
2752 else if (t.cs() == "appendix") {
2753 context.add_par_extra_stuff("\\start_of_appendix\n");
2754 // We need to start a new paragraph. Otherwise the
2755 // appendix in 'bla\appendix\chapter{' would start
2757 context.new_paragraph(os);
2758 // We need to make sure that the paragraph is
2759 // generated even if it is empty. Otherwise the
2760 // appendix in '\par\appendix\par\chapter{' would
2762 context.check_layout(os);
2763 // FIXME: This is a hack to prevent paragraph
2764 // deletion if it is empty. Handle this better!
2765 output_ert_inset(os,
2766 "%dummy comment inserted by tex2lyx to "
2767 "ensure that this paragraph is not empty",
2769 // Both measures above may generate an additional
2770 // empty paragraph, but that does not hurt, because
2771 // whitespace does not matter here.
2772 eat_whitespace(p, os, context, true);
2775 // Must catch empty dates before findLayout is called below
2776 else if (t.cs() == "date") {
2777 eat_whitespace(p, os, context, false);
2779 string const date = p.verbatim_item();
2782 preamble.suppressDate(true);
2785 preamble.suppressDate(false);
2786 if (context.new_layout_allowed &&
2787 (newlayout = findLayout(context.textclass,
2790 output_command_layout(os, p, outer,
2791 context, newlayout);
2792 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2793 if (!preamble.titleLayoutFound())
2794 preamble.titleLayoutFound(newlayout->intitle);
2795 set<string> const & req = newlayout->requires();
2796 set<string>::const_iterator it = req.begin();
2797 set<string>::const_iterator en = req.end();
2798 for (; it != en; ++it)
2799 preamble.registerAutomaticallyLoadedPackage(*it);
2801 output_ert_inset(os,
2802 "\\date{" + p.verbatim_item() + '}',
2807 // Starred section headings
2808 // Must attempt to parse "Section*" before "Section".
2809 else if ((p.next_token().asInput() == "*") &&
2810 context.new_layout_allowed &&
2811 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2814 output_command_layout(os, p, outer, context, newlayout);
2816 if (!preamble.titleLayoutFound())
2817 preamble.titleLayoutFound(newlayout->intitle);
2818 set<string> const & req = newlayout->requires();
2819 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2820 preamble.registerAutomaticallyLoadedPackage(*it);
2823 // Section headings and the like
2824 else if (context.new_layout_allowed &&
2825 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2827 output_command_layout(os, p, outer, context, newlayout);
2829 if (!preamble.titleLayoutFound())
2830 preamble.titleLayoutFound(newlayout->intitle);
2831 set<string> const & req = newlayout->requires();
2832 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2833 preamble.registerAutomaticallyLoadedPackage(*it);
2836 else if (t.cs() == "subfloat") {
2837 // the syntax is \subfloat[caption]{content}
2838 // if it is a table of figure depends on the surrounding float
2839 bool has_caption = false;
2841 // do nothing if there is no outer float
2842 if (!float_type.empty()) {
2843 context.check_layout(os);
2845 begin_inset(os, "Float " + float_type + "\n");
2847 << "\nsideways false"
2848 << "\nstatus collapsed\n\n";
2851 if (p.next_token().cat() != catEscape &&
2852 p.next_token().character() == '[') {
2853 p.get_token(); // eat '['
2854 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2858 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2859 // the caption comes always as the last
2861 // we must make sure that the caption gets a \begin_layout
2862 os << "\n\\begin_layout Plain Layout";
2864 begin_inset(os, "Caption Standard\n");
2865 Context newcontext(true, context.textclass,
2866 0, 0, context.font);
2867 newcontext.check_layout(os);
2868 os << caption << "\n";
2869 newcontext.check_end_layout(os);
2870 // We don't need really a new paragraph, but
2871 // we must make sure that the next item gets a \begin_layout.
2872 //newcontext.new_paragraph(os);
2876 // We don't need really a new paragraph, but
2877 // we must make sure that the next item gets a \begin_layout.
2879 context.new_paragraph(os);
2882 context.check_end_layout(os);
2883 // close the layout we opened
2885 os << "\n\\end_layout\n";
2887 // if the float type is not supported or there is no surrounding float
2890 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2891 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2892 "]{" + p.verbatim_item() + '}', context);
2894 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2898 else if (t.cs() == "includegraphics") {
2899 bool const clip = p.next_token().asInput() == "*";
2902 string const arg = p.getArg('[', ']');
2903 map<string, string> opts;
2904 vector<string> keys;
2905 split_map(arg, opts, keys);
2907 opts["clip"] = string();
2908 string name = normalize_filename(p.verbatim_item());
2910 string const path = getMasterFilePath(true);
2911 // We want to preserve relative / absolute filenames,
2912 // therefore path is only used for testing
2913 if (!makeAbsPath(name, path).exists()) {
2914 // The file extension is probably missing.
2915 // Now try to find it out.
2916 string const dvips_name =
2917 find_file(name, path,
2918 known_dvips_graphics_formats);
2919 string const pdftex_name =
2920 find_file(name, path,
2921 known_pdftex_graphics_formats);
2922 if (!dvips_name.empty()) {
2923 if (!pdftex_name.empty()) {
2924 cerr << "This file contains the "
2926 "\"\\includegraphics{"
2928 "However, files\n\""
2929 << dvips_name << "\" and\n\""
2930 << pdftex_name << "\"\n"
2931 "both exist, so I had to make a "
2932 "choice and took the first one.\n"
2933 "Please move the unwanted one "
2934 "someplace else and try again\n"
2935 "if my choice was wrong."
2939 } else if (!pdftex_name.empty()) {
2945 FileName const absname = makeAbsPath(name, path);
2946 if (absname.exists()) {
2947 fix_child_filename(name);
2948 copy_file(absname, name);
2950 cerr << "Warning: Could not find graphics file '"
2951 << name << "'." << endl;
2953 context.check_layout(os);
2954 begin_inset(os, "Graphics ");
2955 os << "\n\tfilename " << name << '\n';
2956 if (opts.find("width") != opts.end())
2958 << translate_len(opts["width"]) << '\n';
2959 if (opts.find("height") != opts.end())
2961 << translate_len(opts["height"]) << '\n';
2962 if (opts.find("scale") != opts.end()) {
2963 istringstream iss(opts["scale"]);
2967 os << "\tscale " << val << '\n';
2969 if (opts.find("angle") != opts.end()) {
2970 os << "\trotateAngle "
2971 << opts["angle"] << '\n';
2972 vector<string>::const_iterator a =
2973 find(keys.begin(), keys.end(), "angle");
2974 vector<string>::const_iterator s =
2975 find(keys.begin(), keys.end(), "width");
2976 if (s == keys.end())
2977 s = find(keys.begin(), keys.end(), "height");
2978 if (s == keys.end())
2979 s = find(keys.begin(), keys.end(), "scale");
2980 if (s != keys.end() && distance(s, a) > 0)
2981 os << "\tscaleBeforeRotation\n";
2983 if (opts.find("origin") != opts.end()) {
2985 string const opt = opts["origin"];
2986 if (opt.find('l') != string::npos) ss << "left";
2987 if (opt.find('r') != string::npos) ss << "right";
2988 if (opt.find('c') != string::npos) ss << "center";
2989 if (opt.find('t') != string::npos) ss << "Top";
2990 if (opt.find('b') != string::npos) ss << "Bottom";
2991 if (opt.find('B') != string::npos) ss << "Baseline";
2992 if (!ss.str().empty())
2993 os << "\trotateOrigin " << ss.str() << '\n';
2995 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2997 if (opts.find("keepaspectratio") != opts.end())
2998 os << "\tkeepAspectRatio\n";
2999 if (opts.find("clip") != opts.end())
3001 if (opts.find("draft") != opts.end())
3003 if (opts.find("bb") != opts.end())
3004 os << "\tBoundingBox "
3005 << opts["bb"] << '\n';
3006 int numberOfbbOptions = 0;
3007 if (opts.find("bbllx") != opts.end())
3008 numberOfbbOptions++;
3009 if (opts.find("bblly") != opts.end())
3010 numberOfbbOptions++;
3011 if (opts.find("bburx") != opts.end())
3012 numberOfbbOptions++;
3013 if (opts.find("bbury") != opts.end())
3014 numberOfbbOptions++;
3015 if (numberOfbbOptions == 4)
3016 os << "\tBoundingBox "
3017 << opts["bbllx"] << " " << opts["bblly"] << " "
3018 << opts["bburx"] << " " << opts["bbury"] << '\n';
3019 else if (numberOfbbOptions > 0)
3020 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3021 numberOfbbOptions = 0;
3022 if (opts.find("natwidth") != opts.end())
3023 numberOfbbOptions++;
3024 if (opts.find("natheight") != opts.end())
3025 numberOfbbOptions++;
3026 if (numberOfbbOptions == 2)
3027 os << "\tBoundingBox 0bp 0bp "
3028 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3029 else if (numberOfbbOptions > 0)
3030 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3031 ostringstream special;
3032 if (opts.find("hiresbb") != opts.end())
3033 special << "hiresbb,";
3034 if (opts.find("trim") != opts.end())
3036 if (opts.find("viewport") != opts.end())
3037 special << "viewport=" << opts["viewport"] << ',';
3038 if (opts.find("totalheight") != opts.end())
3039 special << "totalheight=" << opts["totalheight"] << ',';
3040 if (opts.find("type") != opts.end())
3041 special << "type=" << opts["type"] << ',';
3042 if (opts.find("ext") != opts.end())
3043 special << "ext=" << opts["ext"] << ',';
3044 if (opts.find("read") != opts.end())
3045 special << "read=" << opts["read"] << ',';
3046 if (opts.find("command") != opts.end())
3047 special << "command=" << opts["command"] << ',';
3048 string s_special = special.str();
3049 if (!s_special.empty()) {
3050 // We had special arguments. Remove the trailing ','.
3051 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3053 // TODO: Handle the unknown settings better.
3054 // Warn about invalid options.
3055 // Check whether some option was given twice.
3057 preamble.registerAutomaticallyLoadedPackage("graphicx");
3060 else if (t.cs() == "footnote" ||
3061 (t.cs() == "thanks" && context.layout->intitle)) {
3063 context.check_layout(os);
3064 begin_inset(os, "Foot\n");
3065 os << "status collapsed\n\n";
3066 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3070 else if (t.cs() == "marginpar") {
3072 context.check_layout(os);
3073 begin_inset(os, "Marginal\n");
3074 os << "status collapsed\n\n";
3075 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3079 else if (t.cs() == "lstinline") {
3081 parse_listings(p, os, context, true);
3084 else if (t.cs() == "ensuremath") {
3086 context.check_layout(os);
3087 string const s = p.verbatim_item();
3088 //FIXME: this never triggers in UTF8
3089 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3092 output_ert_inset(os, "\\ensuremath{" + s + "}",
3096 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3097 if (preamble.titleLayoutFound()) {
3099 skip_spaces_braces(p);
3101 output_ert_inset(os, t.asInput(), context);
3104 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3105 context.check_layout(os);
3106 begin_command_inset(os, "toc", t.cs());
3108 skip_spaces_braces(p);
3109 if (t.cs() == "lstlistoflistings")
3110 preamble.registerAutomaticallyLoadedPackage("listings");
3113 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3114 context.check_layout(os);
3115 if (t.cs() == "listoffigures")
3116 begin_inset(os, "FloatList figure\n");
3118 begin_inset(os, "FloatList table\n");
3120 skip_spaces_braces(p);
3123 else if (t.cs() == "listof") {
3124 p.skip_spaces(true);
3125 string const name = p.get_token().cs();
3126 if (context.textclass.floats().typeExist(name)) {
3127 context.check_layout(os);
3128 begin_inset(os, "FloatList ");
3131 p.get_token(); // swallow second arg
3133 output_ert_inset(os, "\\listof{" + name + "}", context);
3136 else if ((where = is_known(t.cs(), known_text_font_families)))
3137 parse_text_attributes(p, os, FLAG_ITEM, outer,
3138 context, "\\family", context.font.family,
3139 known_coded_font_families[where - known_text_font_families]);
3141 else if ((where = is_known(t.cs(), known_text_font_series)))
3142 parse_text_attributes(p, os, FLAG_ITEM, outer,
3143 context, "\\series", context.font.series,
3144 known_coded_font_series[where - known_text_font_series]);
3146 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3147 parse_text_attributes(p, os, FLAG_ITEM, outer,
3148 context, "\\shape", context.font.shape,
3149 known_coded_font_shapes[where - known_text_font_shapes]);
3151 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3152 context.check_layout(os);
3153 TeXFont oldFont = context.font;
3154 context.font.init();
3155 context.font.size = oldFont.size;
3156 os << "\n\\family " << context.font.family << "\n";
3157 os << "\n\\series " << context.font.series << "\n";
3158 os << "\n\\shape " << context.font.shape << "\n";
3159 if (t.cs() == "textnormal") {
3160 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3161 output_font_change(os, context.font, oldFont);
3162 context.font = oldFont;
3164 eat_whitespace(p, os, context, false);
3167 else if (t.cs() == "textcolor") {
3168 // scheme is \textcolor{color name}{text}
3169 string const color = p.verbatim_item();
3170 // we only support the predefined colors of the color package
3171 if (color == "black" || color == "blue" || color == "cyan"
3172 || color == "green" || color == "magenta" || color == "red"
3173 || color == "white" || color == "yellow") {
3174 context.check_layout(os);
3175 os << "\n\\color " << color << "\n";
3176 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3177 context.check_layout(os);
3178 os << "\n\\color inherit\n";
3179 preamble.registerAutomaticallyLoadedPackage("color");
3181 // for custom defined colors
3182 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3185 else if (t.cs() == "underbar" || t.cs() == "uline") {
3186 // \underbar is not 100% correct (LyX outputs \uline
3187 // of ulem.sty). The difference is that \ulem allows
3188 // line breaks, and \underbar does not.
3189 // Do NOT handle \underline.
3190 // \underbar cuts through y, g, q, p etc.,
3191 // \underline does not.
3192 context.check_layout(os);
3193 os << "\n\\bar under\n";
3194 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3195 context.check_layout(os);
3196 os << "\n\\bar default\n";
3197 preamble.registerAutomaticallyLoadedPackage("ulem");
3200 else if (t.cs() == "sout") {
3201 context.check_layout(os);
3202 os << "\n\\strikeout on\n";
3203 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3204 context.check_layout(os);
3205 os << "\n\\strikeout default\n";
3206 preamble.registerAutomaticallyLoadedPackage("ulem");
3209 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3210 t.cs() == "emph" || t.cs() == "noun") {
3211 context.check_layout(os);
3212 os << "\n\\" << t.cs() << " on\n";
3213 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3214 context.check_layout(os);
3215 os << "\n\\" << t.cs() << " default\n";
3216 if (t.cs() == "uuline" || t.cs() == "uwave")
3217 preamble.registerAutomaticallyLoadedPackage("ulem");
3220 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3221 context.check_layout(os);
3222 string name = p.getArg('{', '}');
3223 string localtime = p.getArg('{', '}');
3224 preamble.registerAuthor(name);
3225 Author const & author = preamble.getAuthor(name);
3226 // from_asctime_utc() will fail if LyX decides to output the
3227 // time in the text language.
3228 time_t ptime = from_asctime_utc(localtime);
3229 if (ptime == static_cast<time_t>(-1)) {
3230 cerr << "Warning: Could not parse time `" << localtime
3231 << "´ for change tracking, using current time instead.\n";
3232 ptime = current_time();
3234 if (t.cs() == "lyxadded")
3235 os << "\n\\change_inserted ";
3237 os << "\n\\change_deleted ";
3238 os << author.bufferId() << ' ' << ptime << '\n';
3239 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3240 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3241 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3242 LaTeXPackages::isAvailable("xcolor");
3243 // No need to test for luatex, since luatex comes in
3244 // two flavours (dvi and pdf), like latex, and those
3245 // are detected by pdflatex.
3246 if (pdflatex || xetex) {
3248 preamble.registerAutomaticallyLoadedPackage("ulem");
3249 preamble.registerAutomaticallyLoadedPackage("xcolor");
3250 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3254 preamble.registerAutomaticallyLoadedPackage("dvipost");
3255 } else if (xcolorulem) {
3256 preamble.registerAutomaticallyLoadedPackage("ulem");
3257 preamble.registerAutomaticallyLoadedPackage("xcolor");
3262 else if (t.cs() == "textipa") {
3263 context.check_layout(os);
3264 begin_inset(os, "IPA\n");
3265 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3267 preamble.registerAutomaticallyLoadedPackage("tipa");
3268 preamble.registerAutomaticallyLoadedPackage("tipx");
3271 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3272 context.check_layout(os);
3273 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3274 os << "status open\n";
3275 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3280 else if (t.cs() == "textvertline") {
3281 // FIXME: This is not correct, \textvertline is higher than |
3287 else if (t.cs() == "tone" ) {
3288 context.check_layout(os);
3289 // register the tone package
3290 preamble.registerAutomaticallyLoadedPackage("tone");
3291 string content = trimSpaceAndEol(p.verbatim_item());
3292 string command = t.asInput() + "{" + content + "}";
3293 // some tones can be detected by unicodesymbols, some need special code
3294 if (is_known(content, known_tones)) {
3295 os << "\\IPAChar " << command << "\n";
3298 // try to see whether the string is in unicodesymbols
3302 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3303 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3304 termination, rem, &req);
3308 output_ert_inset(os, to_utf8(rem), context);
3309 for (set<string>::const_iterator it = req.begin();
3310 it != req.end(); ++it)
3311 preamble.registerAutomaticallyLoadedPackage(*it);
3313 // we did not find a non-ert version
3314 output_ert_inset(os, command, context);
3317 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3318 t.cs() == "vphantom") {
3319 context.check_layout(os);
3320 if (t.cs() == "phantom")
3321 begin_inset(os, "Phantom Phantom\n");
3322 if (t.cs() == "hphantom")
3323 begin_inset(os, "Phantom HPhantom\n");
3324 if (t.cs() == "vphantom")
3325 begin_inset(os, "Phantom VPhantom\n");
3326 os << "status open\n";
3327 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3332 else if (t.cs() == "href") {
3333 context.check_layout(os);
3334 string target = convert_command_inset_arg(p.verbatim_item());
3335 string name = convert_command_inset_arg(p.verbatim_item());
3337 size_t i = target.find(':');
3338 if (i != string::npos) {
3339 type = target.substr(0, i + 1);
3340 if (type == "mailto:" || type == "file:")
3341 target = target.substr(i + 1);
3342 // handle the case that name is equal to target, except of "http://"
3343 else if (target.substr(i + 3) == name && type == "http:")
3346 begin_command_inset(os, "href", "href");
3348 os << "name \"" << name << "\"\n";
3349 os << "target \"" << target << "\"\n";
3350 if (type == "mailto:" || type == "file:")
3351 os << "type \"" << type << "\"\n";
3353 skip_spaces_braces(p);
3356 else if (t.cs() == "lyxline") {
3357 // swallow size argument (it is not used anyway)
3359 if (!context.atParagraphStart()) {
3360 // so our line is in the middle of a paragraph
3361 // we need to add a new line, lest this line
3362 // follow the other content on that line and
3363 // run off the side of the page
3364 // FIXME: This may create an empty paragraph,
3365 // but without that it would not be
3366 // possible to set noindent below.
3367 // Fortunately LaTeX does not care
3368 // about the empty paragraph.
3369 context.new_paragraph(os);
3371 if (preamble.indentParagraphs()) {
3372 // we need to unindent, lest the line be too long
3373 context.add_par_extra_stuff("\\noindent\n");
3375 context.check_layout(os);
3376 begin_command_inset(os, "line", "rule");
3377 os << "offset \"0.5ex\"\n"
3378 "width \"100line%\"\n"
3383 else if (t.cs() == "rule") {
3384 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3385 string const width = p.getArg('{', '}');
3386 string const thickness = p.getArg('{', '}');
3387 context.check_layout(os);
3388 begin_command_inset(os, "line", "rule");
3389 if (!offset.empty())
3390 os << "offset \"" << translate_len(offset) << "\"\n";
3391 os << "width \"" << translate_len(width) << "\"\n"
3392 "height \"" << translate_len(thickness) << "\"\n";
3396 else if (is_known(t.cs(), known_phrases) ||
3397 (t.cs() == "protect" &&
3398 p.next_token().cat() == catEscape &&
3399 is_known(p.next_token().cs(), known_phrases))) {
3400 // LyX sometimes puts a \protect in front, so we have to ignore it
3401 // FIXME: This needs to be changed when bug 4752 is fixed.
3403 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3405 context.check_layout(os);
3406 os << known_coded_phrases[where - known_phrases];
3407 skip_spaces_braces(p);
3410 // handle refstyle first to catch \eqref which can also occur
3411 // without refstyle. Only recognize these commands if
3412 // refstyle.sty was found in the preamble (otherwise \eqref
3413 // and user defined ref commands could be misdetected).
3414 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3415 preamble.refstyle()) {
3416 context.check_layout(os);
3417 begin_command_inset(os, "ref", "formatted");
3418 os << "reference \"";
3419 os << known_refstyle_prefixes[where - known_refstyle_commands]
3421 os << convert_command_inset_arg(p.verbatim_item())
3424 preamble.registerAutomaticallyLoadedPackage("refstyle");
3427 // if refstyle is used, we must not convert \prettyref to a
3428 // formatted reference, since that would result in a refstyle command.
3429 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3430 (t.cs() != "prettyref" || !preamble.refstyle())) {
3431 string const opt = p.getOpt();
3433 context.check_layout(os);
3434 begin_command_inset(os, "ref",
3435 known_coded_ref_commands[where - known_ref_commands]);
3436 os << "reference \""
3437 << convert_command_inset_arg(p.verbatim_item())
3440 if (t.cs() == "vref" || t.cs() == "vpageref")
3441 preamble.registerAutomaticallyLoadedPackage("varioref");
3442 else if (t.cs() == "prettyref")
3443 preamble.registerAutomaticallyLoadedPackage("prettyref");
3445 // LyX does not yet support optional arguments of ref commands
3446 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3447 p.verbatim_item() + '}', context);
3451 else if (use_natbib &&
3452 is_known(t.cs(), known_natbib_commands) &&
3453 ((t.cs() != "citefullauthor" &&
3454 t.cs() != "citeyear" &&
3455 t.cs() != "citeyearpar") ||
3456 p.next_token().asInput() != "*")) {
3457 context.check_layout(os);
3458 string command = t.cs();
3459 if (p.next_token().asInput() == "*") {
3463 if (command == "citefullauthor")
3464 // alternative name for "\\citeauthor*"
3465 command = "citeauthor*";
3467 // text before the citation
3469 // text after the citation
3471 get_cite_arguments(p, true, before, after);
3473 if (command == "cite") {
3474 // \cite without optional argument means
3475 // \citet, \cite with at least one optional
3476 // argument means \citep.
3477 if (before.empty() && after.empty())
3482 if (before.empty() && after == "[]")
3483 // avoid \citet[]{a}
3485 else if (before == "[]" && after == "[]") {
3486 // avoid \citet[][]{a}
3490 // remove the brackets around after and before
3491 if (!after.empty()) {
3493 after.erase(after.length() - 1, 1);
3494 after = convert_command_inset_arg(after);
3496 if (!before.empty()) {
3498 before.erase(before.length() - 1, 1);
3499 before = convert_command_inset_arg(before);
3501 begin_command_inset(os, "citation", command);
3502 os << "after " << '"' << after << '"' << "\n";
3503 os << "before " << '"' << before << '"' << "\n";
3505 << convert_command_inset_arg(p.verbatim_item())
3508 // Need to set the cite engine if natbib is loaded by
3509 // the document class directly
3510 if (preamble.citeEngine() == "basic")
3511 preamble.citeEngine("natbib");
3514 else if (use_jurabib &&
3515 is_known(t.cs(), known_jurabib_commands) &&
3516 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3517 context.check_layout(os);
3518 string command = t.cs();
3519 if (p.next_token().asInput() == "*") {
3523 char argumentOrder = '\0';
3524 vector<string> const options =
3525 preamble.getPackageOptions("jurabib");
3526 if (find(options.begin(), options.end(),
3527 "natbiborder") != options.end())
3528 argumentOrder = 'n';
3529 else if (find(options.begin(), options.end(),
3530 "jurabiborder") != options.end())
3531 argumentOrder = 'j';
3533 // text before the citation
3535 // text after the citation
3537 get_cite_arguments(p, argumentOrder != 'j', before, after);
3539 string const citation = p.verbatim_item();
3540 if (!before.empty() && argumentOrder == '\0') {
3541 cerr << "Warning: Assuming argument order "
3542 "of jurabib version 0.6 for\n'"
3543 << command << before << after << '{'
3544 << citation << "}'.\n"
3545 "Add 'jurabiborder' to the jurabib "
3546 "package options if you used an\n"
3547 "earlier jurabib version." << endl;
3549 if (!after.empty()) {
3551 after.erase(after.length() - 1, 1);
3553 if (!before.empty()) {
3555 before.erase(before.length() - 1, 1);
3557 begin_command_inset(os, "citation", command);
3558 os << "after " << '"' << after << '"' << "\n";
3559 os << "before " << '"' << before << '"' << "\n";
3560 os << "key " << '"' << citation << '"' << "\n";
3562 // Need to set the cite engine if jurabib is loaded by
3563 // the document class directly
3564 if (preamble.citeEngine() == "basic")
3565 preamble.citeEngine("jurabib");
3568 else if (t.cs() == "cite"
3569 || t.cs() == "nocite") {
3570 context.check_layout(os);
3571 string after = convert_command_inset_arg(p.getArg('[', ']'));
3572 string key = convert_command_inset_arg(p.verbatim_item());
3573 // store the case that it is "\nocite{*}" to use it later for
3576 begin_command_inset(os, "citation", t.cs());
3577 os << "after " << '"' << after << '"' << "\n";
3578 os << "key " << '"' << key << '"' << "\n";
3580 } else if (t.cs() == "nocite")
3584 else if (t.cs() == "index" ||
3585 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3586 context.check_layout(os);
3587 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3588 p.getArg('[', ']') : "";
3589 string const kind = arg.empty() ? "idx" : arg;
3590 begin_inset(os, "Index ");
3591 os << kind << "\nstatus collapsed\n";
3592 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3595 preamble.registerAutomaticallyLoadedPackage("splitidx");
3598 else if (t.cs() == "nomenclature") {
3599 context.check_layout(os);
3600 begin_command_inset(os, "nomenclature", "nomenclature");
3601 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3602 if (!prefix.empty())
3603 os << "prefix " << '"' << prefix << '"' << "\n";
3604 os << "symbol " << '"'
3605 << convert_command_inset_arg(p.verbatim_item());
3606 os << "\"\ndescription \""
3607 << convert_command_inset_arg(p.verbatim_item())
3610 preamble.registerAutomaticallyLoadedPackage("nomencl");
3613 else if (t.cs() == "label") {
3614 context.check_layout(os);
3615 begin_command_inset(os, "label", "label");
3617 << convert_command_inset_arg(p.verbatim_item())
3622 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3623 context.check_layout(os);
3624 string commandname = t.cs();
3626 if (p.next_token().asInput() == "*") {
3631 begin_command_inset(os, "index_print", commandname);
3632 string const indexname = p.getArg('[', ']');
3634 if (indexname.empty())
3635 os << "type \"idx\"\n";
3637 os << "type \"" << indexname << "\"\n";
3640 skip_spaces_braces(p);
3641 preamble.registerAutomaticallyLoadedPackage("makeidx");
3642 if (preamble.use_indices() == "true")
3643 preamble.registerAutomaticallyLoadedPackage("splitidx");
3646 else if (t.cs() == "printnomenclature") {
3648 string width_type = "";
3649 context.check_layout(os);
3650 begin_command_inset(os, "nomencl_print", "printnomenclature");
3651 // case of a custom width
3653 width = p.getArg('[', ']');
3654 width = translate_len(width);
3655 width_type = "custom";
3657 // case of no custom width
3658 // the case of no custom width but the width set
3659 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3660 // because the user could have set anything, not only the width
3661 // of the longest label (which would be width_type = "auto")
3662 string label = convert_command_inset_arg(p.getArg('{', '}'));
3663 if (label.empty() && width_type.empty())
3664 width_type = "none";
3665 os << "set_width \"" << width_type << "\"\n";
3666 if (width_type == "custom")
3667 os << "width \"" << width << '\"';
3669 skip_spaces_braces(p);
3670 preamble.registerAutomaticallyLoadedPackage("nomencl");
3673 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3674 context.check_layout(os);
3675 begin_inset(os, "script ");
3676 os << t.cs().substr(4) << '\n';
3677 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3679 if (t.cs() == "textsubscript")
3680 preamble.registerAutomaticallyLoadedPackage("subscript");
3683 else if ((where = is_known(t.cs(), known_quotes))) {
3684 context.check_layout(os);
3685 begin_inset(os, "Quotes ");
3686 os << known_coded_quotes[where - known_quotes];
3688 // LyX adds {} after the quote, so we have to eat
3689 // spaces here if there are any before a possible
3691 eat_whitespace(p, os, context, false);
3695 else if ((where = is_known(t.cs(), known_sizes)) &&
3696 context.new_layout_allowed) {
3697 context.check_layout(os);
3698 TeXFont const oldFont = context.font;
3699 context.font.size = known_coded_sizes[where - known_sizes];
3700 output_font_change(os, oldFont, context.font);
3701 eat_whitespace(p, os, context, false);
3704 else if ((where = is_known(t.cs(), known_font_families)) &&
3705 context.new_layout_allowed) {
3706 context.check_layout(os);
3707 TeXFont const oldFont = context.font;
3708 context.font.family =
3709 known_coded_font_families[where - known_font_families];
3710 output_font_change(os, oldFont, context.font);
3711 eat_whitespace(p, os, context, false);
3714 else if ((where = is_known(t.cs(), known_font_series)) &&
3715 context.new_layout_allowed) {
3716 context.check_layout(os);
3717 TeXFont const oldFont = context.font;
3718 context.font.series =
3719 known_coded_font_series[where - known_font_series];
3720 output_font_change(os, oldFont, context.font);
3721 eat_whitespace(p, os, context, false);
3724 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3725 context.new_layout_allowed) {
3726 context.check_layout(os);
3727 TeXFont const oldFont = context.font;
3728 context.font.shape =
3729 known_coded_font_shapes[where - known_font_shapes];
3730 output_font_change(os, oldFont, context.font);
3731 eat_whitespace(p, os, context, false);
3733 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3734 context.new_layout_allowed) {
3735 context.check_layout(os);
3736 TeXFont const oldFont = context.font;
3737 context.font.init();
3738 context.font.size = oldFont.size;
3739 context.font.family =
3740 known_coded_font_families[where - known_old_font_families];
3741 output_font_change(os, oldFont, context.font);
3742 eat_whitespace(p, os, context, false);
3745 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3746 context.new_layout_allowed) {
3747 context.check_layout(os);
3748 TeXFont const oldFont = context.font;
3749 context.font.init();
3750 context.font.size = oldFont.size;
3751 context.font.series =
3752 known_coded_font_series[where - known_old_font_series];
3753 output_font_change(os, oldFont, context.font);
3754 eat_whitespace(p, os, context, false);
3757 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3758 context.new_layout_allowed) {
3759 context.check_layout(os);
3760 TeXFont const oldFont = context.font;
3761 context.font.init();
3762 context.font.size = oldFont.size;
3763 context.font.shape =
3764 known_coded_font_shapes[where - known_old_font_shapes];
3765 output_font_change(os, oldFont, context.font);
3766 eat_whitespace(p, os, context, false);
3769 else if (t.cs() == "selectlanguage") {
3770 context.check_layout(os);
3771 // save the language for the case that a
3772 // \foreignlanguage is used
3773 context.font.language = babel2lyx(p.verbatim_item());
3774 os << "\n\\lang " << context.font.language << "\n";
3777 else if (t.cs() == "foreignlanguage") {
3778 string const lang = babel2lyx(p.verbatim_item());
3779 parse_text_attributes(p, os, FLAG_ITEM, outer,
3781 context.font.language, lang);
3784 else if (prefixIs(t.cs(), "text")
3785 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3786 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3788 // We have to output the whole command if it has an option
3789 // because LyX doesn't support this yet, see bug #8214,
3790 // only if there is a single option specifying a variant, we can handle it.
3792 string langopts = p.getOpt();
3793 // check if the option contains a variant, if yes, extract it
3794 string::size_type pos_var = langopts.find("variant");
3795 string::size_type i = langopts.find(',');
3796 string::size_type k = langopts.find('=', pos_var);
3797 if (pos_var != string::npos && i == string::npos) {
3799 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3800 lang = preamble.polyglossia2lyx(variant);
3801 parse_text_attributes(p, os, FLAG_ITEM, outer,
3803 context.font.language, lang);
3805 output_ert_inset(os, t.asInput() + langopts, context);
3807 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3808 parse_text_attributes(p, os, FLAG_ITEM, outer,
3810 context.font.language, lang);
3814 else if (t.cs() == "inputencoding") {
3815 // nothing to write here
3816 string const enc = subst(p.verbatim_item(), "\n", " ");
3817 p.setEncoding(enc, Encoding::inputenc);
3820 else if ((where = is_known(t.cs(), known_special_chars))) {
3821 context.check_layout(os);
3822 os << known_coded_special_chars[where - known_special_chars];
3823 skip_spaces_braces(p);
3826 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3827 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3828 context.check_layout(os);
3829 os << "\\SpecialChar \\" << t.cs()
3830 << p.get_token().asInput() << '\n';
3833 else if (t.cs() == "textquotedbl") {
3834 context.check_layout(os);
3839 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3840 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3841 || t.cs() == "%" || t.cs() == "-") {
3842 context.check_layout(os);
3844 os << "\\SpecialChar \\-\n";
3849 else if (t.cs() == "char") {
3850 context.check_layout(os);
3851 if (p.next_token().character() == '`') {
3853 if (p.next_token().cs() == "\"") {
3858 output_ert_inset(os, "\\char`", context);
3861 output_ert_inset(os, "\\char", context);
3865 else if (t.cs() == "verb") {
3866 context.check_layout(os);
3867 // set catcodes to verbatim early, just in case.
3868 p.setCatcodes(VERBATIM_CATCODES);
3869 string delim = p.get_token().asInput();
3870 Parser::Arg arg = p.verbatimStuff(delim);
3872 output_ert_inset(os, "\\verb" + delim
3873 + arg.second + delim, context);
3875 cerr << "invalid \\verb command. Skipping" << endl;
3878 // Problem: \= creates a tabstop inside the tabbing environment
3879 // and else an accent. In the latter case we really would want
3880 // \={o} instead of \= o.
3881 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3882 output_ert_inset(os, t.asInput(), context);
3884 else if (t.cs() == "\\") {
3885 context.check_layout(os);
3887 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3888 else if (p.next_token().asInput() == "*") {
3890 // getOpt() eats the following space if there
3891 // is no optional argument, but that is OK
3892 // here since it has no effect in the output.
3893 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3896 begin_inset(os, "Newline newline");
3901 else if (t.cs() == "newline" ||
3902 (t.cs() == "linebreak" && !p.hasOpt())) {
3903 context.check_layout(os);
3904 begin_inset(os, "Newline ");
3907 skip_spaces_braces(p);
3910 else if (t.cs() == "input" || t.cs() == "include"
3911 || t.cs() == "verbatiminput") {
3912 string name = t.cs();
3913 if (t.cs() == "verbatiminput"
3914 && p.next_token().asInput() == "*")
3915 name += p.get_token().asInput();
3916 context.check_layout(os);
3917 string filename(normalize_filename(p.getArg('{', '}')));
3918 string const path = getMasterFilePath(true);
3919 // We want to preserve relative / absolute filenames,
3920 // therefore path is only used for testing
3921 if ((t.cs() == "include" || t.cs() == "input") &&
3922 !makeAbsPath(filename, path).exists()) {
3923 // The file extension is probably missing.
3924 // Now try to find it out.
3925 string const tex_name =
3926 find_file(filename, path,
3927 known_tex_extensions);
3928 if (!tex_name.empty())
3929 filename = tex_name;
3931 bool external = false;
3933 if (makeAbsPath(filename, path).exists()) {
3934 string const abstexname =
3935 makeAbsPath(filename, path).absFileName();
3936 string const absfigname =
3937 changeExtension(abstexname, ".fig");
3938 fix_child_filename(filename);
3939 string const lyxname = changeExtension(filename,
3940 roundtripMode() ? ".lyx.lyx" : ".lyx");
3941 string const abslyxname = makeAbsPath(
3942 lyxname, getParentFilePath(false)).absFileName();
3944 if (!skipChildren())
3945 external = FileName(absfigname).exists();
3946 if (t.cs() == "input" && !skipChildren()) {
3947 string const ext = getExtension(abstexname);
3949 // Combined PS/LaTeX:
3950 // x.eps, x.pstex_t (old xfig)
3951 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3952 FileName const absepsname(
3953 changeExtension(abstexname, ".eps"));
3954 FileName const abspstexname(
3955 changeExtension(abstexname, ".pstex"));
3956 bool const xfigeps =
3957 (absepsname.exists() ||
3958 abspstexname.exists()) &&
3961 // Combined PDF/LaTeX:
3962 // x.pdf, x.pdftex_t (old xfig)
3963 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3964 FileName const abspdfname(
3965 changeExtension(abstexname, ".pdf"));
3966 bool const xfigpdf =
3967 abspdfname.exists() &&
3968 (ext == "pdftex_t" || ext == "pdf_t");
3972 // Combined PS/PDF/LaTeX:
3973 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3974 string const absbase2(
3975 removeExtension(abstexname) + "_pspdftex");
3976 FileName const abseps2name(
3977 addExtension(absbase2, ".eps"));
3978 FileName const abspdf2name(
3979 addExtension(absbase2, ".pdf"));
3980 bool const xfigboth =
3981 abspdf2name.exists() &&
3982 abseps2name.exists() && ext == "pspdftex";
3984 xfig = xfigpdf || xfigeps || xfigboth;
3985 external = external && xfig;
3988 outname = changeExtension(filename, ".fig");
3989 FileName abssrc(changeExtension(abstexname, ".fig"));
3990 copy_file(abssrc, outname);
3992 // Don't try to convert, the result
3993 // would be full of ERT.
3995 FileName abssrc(abstexname);
3996 copy_file(abssrc, outname);
3997 } else if (t.cs() != "verbatiminput" &&
3999 tex2lyx(abstexname, FileName(abslyxname),
4002 // no need to call copy_file
4003 // tex2lyx creates the file
4006 FileName abssrc(abstexname);
4007 copy_file(abssrc, outname);
4010 cerr << "Warning: Could not find included file '"
4011 << filename << "'." << endl;
4015 begin_inset(os, "External\n");
4016 os << "\ttemplate XFig\n"
4017 << "\tfilename " << outname << '\n';
4018 registerExternalTemplatePackages("XFig");
4020 begin_command_inset(os, "include", name);
4021 outname = subst(outname, "\"", "\\\"");
4022 os << "preview false\n"
4023 "filename \"" << outname << "\"\n";
4024 if (t.cs() == "verbatiminput")
4025 preamble.registerAutomaticallyLoadedPackage("verbatim");
4030 else if (t.cs() == "bibliographystyle") {
4031 // store new bibliographystyle
4032 bibliographystyle = p.verbatim_item();
4033 // If any other command than \bibliography, \addcontentsline
4034 // and \nocite{*} follows, we need to output the style
4035 // (because it might be used by that command).
4036 // Otherwise, it will automatically be output by LyX.
4039 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4040 if (t2.cat() == catBegin)
4042 if (t2.cat() != catEscape)
4044 if (t2.cs() == "nocite") {
4045 if (p.getArg('{', '}') == "*")
4047 } else if (t2.cs() == "bibliography")
4049 else if (t2.cs() == "phantomsection") {
4053 else if (t2.cs() == "addcontentsline") {
4054 // get the 3 arguments of \addcontentsline
4057 contentslineContent = p.getArg('{', '}');
4058 // if the last argument is not \refname we must output
4059 if (contentslineContent == "\\refname")
4066 output_ert_inset(os,
4067 "\\bibliographystyle{" + bibliographystyle + '}',
4072 else if (t.cs() == "phantomsection") {
4073 // we only support this if it occurs between
4074 // \bibliographystyle and \bibliography
4075 if (bibliographystyle.empty())
4076 output_ert_inset(os, "\\phantomsection", context);
4079 else if (t.cs() == "addcontentsline") {
4080 context.check_layout(os);
4081 // get the 3 arguments of \addcontentsline
4082 string const one = p.getArg('{', '}');
4083 string const two = p.getArg('{', '}');
4084 string const three = p.getArg('{', '}');
4085 // only if it is a \refname, we support if for the bibtex inset
4086 if (contentslineContent != "\\refname") {
4087 output_ert_inset(os,
4088 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4093 else if (t.cs() == "bibliography") {
4094 context.check_layout(os);
4096 begin_command_inset(os, "bibtex", "bibtex");
4097 if (!btprint.empty()) {
4098 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4099 // clear the string because the next BibTeX inset can be without the
4100 // \nocite{*} option
4103 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4104 // Do we have addcontentsline?
4105 if (contentslineContent == "\\refname") {
4106 BibOpts = "bibtotoc";
4107 // clear string because next BibTeX inset can be without addcontentsline
4108 contentslineContent.clear();
4110 // Do we have a bibliographystyle set?
4111 if (!bibliographystyle.empty()) {
4112 if (BibOpts.empty())
4113 BibOpts = bibliographystyle;
4115 BibOpts = BibOpts + ',' + bibliographystyle;
4116 // clear it because each bibtex entry has its style
4117 // and we need an empty string to handle \phantomsection
4118 bibliographystyle.clear();
4120 os << "options " << '"' << BibOpts << '"' << "\n";
4124 else if (t.cs() == "parbox") {
4125 // Test whether this is an outer box of a shaded box
4127 // swallow arguments
4128 while (p.hasOpt()) {
4130 p.skip_spaces(true);
4133 p.skip_spaces(true);
4135 if (p.next_token().cat() == catBegin)
4137 p.skip_spaces(true);
4138 Token to = p.get_token();
4139 bool shaded = false;
4140 if (to.asInput() == "\\begin") {
4141 p.skip_spaces(true);
4142 if (p.getArg('{', '}') == "shaded")
4147 parse_outer_box(p, os, FLAG_ITEM, outer,
4148 context, "parbox", "shaded");
4150 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4154 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4155 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4156 t.cs() == "shadowbox" || t.cs() == "doublebox")
4157 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4159 else if (t.cs() == "framebox") {
4160 if (p.next_token().character() == '(') {
4161 //the syntax is: \framebox(x,y)[position]{content}
4162 string arg = t.asInput();
4163 arg += p.getFullParentheseArg();
4164 arg += p.getFullOpt();
4165 eat_whitespace(p, os, context, false);
4166 output_ert_inset(os, arg + '{', context);
4167 parse_text(p, os, FLAG_ITEM, outer, context);
4168 output_ert_inset(os, "}", context);
4170 //the syntax is: \framebox[width][position]{content}
4171 string special = p.getFullOpt();
4172 special += p.getOpt();
4173 parse_outer_box(p, os, FLAG_ITEM, outer,
4174 context, t.cs(), special);
4178 //\makebox() is part of the picture environment and different from \makebox{}
4179 //\makebox{} will be parsed by parse_box
4180 else if (t.cs() == "makebox") {
4181 if (p.next_token().character() == '(') {
4182 //the syntax is: \makebox(x,y)[position]{content}
4183 string arg = t.asInput();
4184 arg += p.getFullParentheseArg();
4185 arg += p.getFullOpt();
4186 eat_whitespace(p, os, context, false);
4187 output_ert_inset(os, arg + '{', context);
4188 parse_text(p, os, FLAG_ITEM, outer, context);
4189 output_ert_inset(os, "}", context);
4191 //the syntax is: \makebox[width][position]{content}
4192 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4196 else if (t.cs() == "smallskip" ||
4197 t.cs() == "medskip" ||
4198 t.cs() == "bigskip" ||
4199 t.cs() == "vfill") {
4200 context.check_layout(os);
4201 begin_inset(os, "VSpace ");
4204 skip_spaces_braces(p);
4207 else if ((where = is_known(t.cs(), known_spaces))) {
4208 context.check_layout(os);
4209 begin_inset(os, "space ");
4210 os << '\\' << known_coded_spaces[where - known_spaces]
4213 // LaTeX swallows whitespace after all spaces except
4214 // "\\,". We have to do that here, too, because LyX
4215 // adds "{}" which would make the spaces significant.
4217 eat_whitespace(p, os, context, false);
4218 // LyX adds "{}" after all spaces except "\\ " and
4219 // "\\,", so we have to remove "{}".
4220 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4221 // remove the braces after "\\,", too.
4226 else if (t.cs() == "newpage" ||
4227 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4228 t.cs() == "clearpage" ||
4229 t.cs() == "cleardoublepage") {
4230 context.check_layout(os);
4231 begin_inset(os, "Newpage ");
4234 skip_spaces_braces(p);
4237 else if (t.cs() == "DeclareRobustCommand" ||
4238 t.cs() == "DeclareRobustCommandx" ||
4239 t.cs() == "newcommand" ||
4240 t.cs() == "newcommandx" ||
4241 t.cs() == "providecommand" ||
4242 t.cs() == "providecommandx" ||
4243 t.cs() == "renewcommand" ||
4244 t.cs() == "renewcommandx") {
4245 // DeclareRobustCommand, DeclareRobustCommandx,
4246 // providecommand and providecommandx could be handled
4247 // by parse_command(), but we need to call
4248 // add_known_command() here.
4249 string name = t.asInput();
4250 if (p.next_token().asInput() == "*") {
4251 // Starred form. Eat '*'
4255 string const command = p.verbatim_item();
4256 string const opt1 = p.getFullOpt();
4257 string const opt2 = p.getFullOpt();
4258 add_known_command(command, opt1, !opt2.empty());
4259 string const ert = name + '{' + command + '}' +
4261 '{' + p.verbatim_item() + '}';
4263 if (t.cs() == "DeclareRobustCommand" ||
4264 t.cs() == "DeclareRobustCommandx" ||
4265 t.cs() == "providecommand" ||
4266 t.cs() == "providecommandx" ||
4267 name[name.length()-1] == '*')
4268 output_ert_inset(os, ert, context);
4270 context.check_layout(os);
4271 begin_inset(os, "FormulaMacro");
4277 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4278 // let could be handled by parse_command(),
4279 // but we need to call add_known_command() here.
4280 string ert = t.asInput();
4283 if (p.next_token().cat() == catBegin) {
4284 name = p.verbatim_item();
4285 ert += '{' + name + '}';
4287 name = p.verbatim_item();
4292 if (p.next_token().cat() == catBegin) {
4293 command = p.verbatim_item();
4294 ert += '{' + command + '}';
4296 command = p.verbatim_item();
4299 // If command is known, make name known too, to parse
4300 // its arguments correctly. For this reason we also
4301 // have commands in syntax.default that are hardcoded.
4302 CommandMap::iterator it = known_commands.find(command);
4303 if (it != known_commands.end())
4304 known_commands[t.asInput()] = it->second;
4305 output_ert_inset(os, ert, context);
4308 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4311 string name = t.asInput();
4312 string const length = p.verbatim_item();
4315 bool valid = splitLatexLength(length, valstring, unit);
4316 bool known_hspace = false;
4317 bool known_vspace = false;
4318 bool known_unit = false;
4321 istringstream iss(valstring);
4324 if (t.cs()[0] == 'h') {
4325 if (unit == "\\fill") {
4330 known_hspace = true;
4333 if (unit == "\\smallskipamount") {
4335 known_vspace = true;
4336 } else if (unit == "\\medskipamount") {
4338 known_vspace = true;
4339 } else if (unit == "\\bigskipamount") {
4341 known_vspace = true;
4342 } else if (unit == "\\fill") {
4344 known_vspace = true;
4348 if (!known_hspace && !known_vspace) {
4349 switch (unitFromString(unit)) {
4365 //unitFromString(unit) fails for relative units like Length::PCW
4366 // therefore handle them separately
4367 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4368 || unit == "\\textwidth" || unit == "\\linewidth"
4369 || unit == "\\textheight" || unit == "\\paperheight")
4377 // check for glue lengths
4378 bool is_gluelength = false;
4379 string gluelength = length;
4380 string::size_type i = length.find(" minus");
4381 if (i == string::npos) {
4382 i = length.find(" plus");
4383 if (i != string::npos)
4384 is_gluelength = true;
4386 is_gluelength = true;
4387 // if yes transform "9xx minus 8yy plus 7zz"
4389 if (is_gluelength) {
4390 i = gluelength.find(" minus");
4391 if (i != string::npos)
4392 gluelength.replace(i, 7, "-");
4393 i = gluelength.find(" plus");
4394 if (i != string::npos)
4395 gluelength.replace(i, 6, "+");
4398 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4399 // Literal horizontal length or known variable
4400 context.check_layout(os);
4401 begin_inset(os, "space ");
4409 if (known_unit && !known_hspace)
4410 os << "\n\\length " << translate_len(length);
4412 os << "\n\\length " << gluelength;
4414 } else if (known_unit || known_vspace || is_gluelength) {
4415 // Literal vertical length or known variable
4416 context.check_layout(os);
4417 begin_inset(os, "VSpace ");
4420 if (known_unit && !known_vspace)
4421 os << translate_len(length);
4428 // LyX can't handle other length variables in Inset VSpace/space
4433 output_ert_inset(os, name + '{' + unit + '}', context);
4434 else if (value == -1.0)
4435 output_ert_inset(os, name + "{-" + unit + '}', context);
4437 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4439 output_ert_inset(os, name + '{' + length + '}', context);
4443 // The single '=' is meant here.
4444 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4448 context.check_layout(os);
4449 docstring const name = newinsetlayout->name();
4450 bool const caption = name.find(from_ascii("Caption:")) == 0;
4452 begin_inset(os, "Caption ");
4453 os << to_utf8(name.substr(8)) << '\n';
4455 begin_inset(os, "Flex ");
4456 os << to_utf8(name) << '\n'
4457 << "status collapsed\n";
4459 if (newinsetlayout->isPassThru()) {
4460 // set catcodes to verbatim early, just in case.
4461 p.setCatcodes(VERBATIM_CATCODES);
4462 string delim = p.get_token().asInput();
4464 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4465 //FIXME: handle error condition
4466 string const arg = p.verbatimStuff("}").second;
4467 Context newcontext(true, context.textclass);
4468 if (newinsetlayout->forcePlainLayout())
4469 newcontext.layout = &context.textclass.plainLayout();
4470 output_ert(os, arg, newcontext);
4472 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4478 else if (t.cs() == "includepdf") {
4480 string const arg = p.getArg('[', ']');
4481 map<string, string> opts;
4482 vector<string> keys;
4483 split_map(arg, opts, keys);
4484 string name = normalize_filename(p.verbatim_item());
4485 string const path = getMasterFilePath(true);
4486 // We want to preserve relative / absolute filenames,
4487 // therefore path is only used for testing
4488 if (!makeAbsPath(name, path).exists()) {
4489 // The file extension is probably missing.
4490 // Now try to find it out.
4491 char const * const pdfpages_format[] = {"pdf", 0};
4492 string const pdftex_name =
4493 find_file(name, path, pdfpages_format);
4494 if (!pdftex_name.empty()) {
4499 FileName const absname = makeAbsPath(name, path);
4500 if (absname.exists())
4502 fix_child_filename(name);
4503 copy_file(absname, name);
4505 cerr << "Warning: Could not find file '"
4506 << name << "'." << endl;
4508 context.check_layout(os);
4509 begin_inset(os, "External\n\ttemplate ");
4510 os << "PDFPages\n\tfilename "
4512 // parse the options
4513 if (opts.find("pages") != opts.end())
4514 os << "\textra LaTeX \"pages="
4515 << opts["pages"] << "\"\n";
4516 if (opts.find("angle") != opts.end())
4517 os << "\trotateAngle "
4518 << opts["angle"] << '\n';
4519 if (opts.find("origin") != opts.end()) {
4521 string const opt = opts["origin"];
4522 if (opt == "tl") ss << "topleft";
4523 if (opt == "bl") ss << "bottomleft";
4524 if (opt == "Bl") ss << "baselineleft";
4525 if (opt == "c") ss << "center";
4526 if (opt == "tc") ss << "topcenter";
4527 if (opt == "bc") ss << "bottomcenter";
4528 if (opt == "Bc") ss << "baselinecenter";
4529 if (opt == "tr") ss << "topright";
4530 if (opt == "br") ss << "bottomright";
4531 if (opt == "Br") ss << "baselineright";
4532 if (!ss.str().empty())
4533 os << "\trotateOrigin " << ss.str() << '\n';
4535 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4537 if (opts.find("width") != opts.end())
4539 << translate_len(opts["width"]) << '\n';
4540 if (opts.find("height") != opts.end())
4542 << translate_len(opts["height"]) << '\n';
4543 if (opts.find("keepaspectratio") != opts.end())
4544 os << "\tkeepAspectRatio\n";
4546 context.check_layout(os);
4547 registerExternalTemplatePackages("PDFPages");
4550 else if (t.cs() == "loadgame") {
4552 string name = normalize_filename(p.verbatim_item());
4553 string const path = getMasterFilePath(true);
4554 // We want to preserve relative / absolute filenames,
4555 // therefore path is only used for testing
4556 if (!makeAbsPath(name, path).exists()) {
4557 // The file extension is probably missing.
4558 // Now try to find it out.
4559 char const * const lyxskak_format[] = {"fen", 0};
4560 string const lyxskak_name =
4561 find_file(name, path, lyxskak_format);
4562 if (!lyxskak_name.empty())
4563 name = lyxskak_name;
4565 FileName const absname = makeAbsPath(name, path);
4566 if (absname.exists())
4568 fix_child_filename(name);
4569 copy_file(absname, name);
4571 cerr << "Warning: Could not find file '"
4572 << name << "'." << endl;
4573 context.check_layout(os);
4574 begin_inset(os, "External\n\ttemplate ");
4575 os << "ChessDiagram\n\tfilename "
4578 context.check_layout(os);
4579 // after a \loadgame follows a \showboard
4580 if (p.get_token().asInput() == "showboard")
4582 registerExternalTemplatePackages("ChessDiagram");
4586 // try to see whether the string is in unicodesymbols
4587 // Only use text mode commands, since we are in text mode here,
4588 // and math commands may be invalid (bug 6797)
4589 string name = t.asInput();
4590 // handle the dingbats and Cyrillic
4591 if (name == "\\ding" || name == "\\textcyr")
4592 name = name + '{' + p.getArg('{', '}') + '}';
4593 // handle the ifsym characters
4594 else if (name == "\\textifsymbol") {
4595 string const optif = p.getFullOpt();
4596 string const argif = p.getArg('{', '}');
4597 name = name + optif + '{' + argif + '}';
4599 // handle the \ascii characters
4600 // the case of \ascii within braces, as LyX outputs it, is already
4601 // handled for t.cat() == catBegin
4602 else if (name == "\\ascii") {
4603 // the code is "\asci\xxx"
4604 name = "{" + name + p.get_token().asInput() + "}";
4607 // handle some TIPA special characters
4608 else if (preamble.isPackageUsed("tipa")) {
4609 if (name == "\\textglobfall") {
4612 } else if (name == "\\s") {
4613 // fromLaTeXCommand() does not yet
4614 // recognize tipa short cuts
4615 name = "\\textsyllabic";
4616 } else if (name == "\\=" &&
4617 p.next_token().asInput() == "*") {
4618 // fromLaTeXCommand() does not yet
4619 // recognize tipa short cuts
4622 } else if (name == "\\textdoublevertline") {
4623 // FIXME: This is not correct,
4624 // \textvertline is higher than \textbardbl
4625 name = "\\textbardbl";
4627 } else if (name == "\\!" ) {
4628 if (p.next_token().asInput() == "b") {
4629 p.get_token(); // eat 'b'
4632 } else if (p.next_token().asInput() == "d") {
4636 } else if (p.next_token().asInput() == "g") {
4640 } else if (p.next_token().asInput() == "G") {
4642 name = "\\texthtscg";
4644 } else if (p.next_token().asInput() == "j") {
4646 name = "\\texthtbardotlessj";
4648 } else if (p.next_token().asInput() == "o") {
4650 name = "\\textbullseye";
4653 } else if (name == "\\*" ) {
4654 if (p.next_token().asInput() == "k") {
4656 name = "\\textturnk";
4658 } else if (p.next_token().asInput() == "r") {
4659 p.get_token(); // eat 'b'
4660 name = "\\textturnr";
4662 } else if (p.next_token().asInput() == "t") {
4664 name = "\\textturnt";
4666 } else if (p.next_token().asInput() == "w") {
4668 name = "\\textturnw";
4673 if ((name.size() == 2 &&
4674 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4675 p.next_token().asInput() != "*") ||
4676 is_known(name.substr(1), known_tipa_marks)) {
4677 // name is a command that corresponds to a
4678 // combining character in unicodesymbols.
4679 // Append the argument, fromLaTeXCommand()
4680 // will either convert it to a single
4681 // character or a combining sequence.
4682 name += '{' + p.verbatim_item() + '}';
4684 // now get the character from unicodesymbols
4688 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4689 Encodings::TEXT_CMD, termination, rem, &req);
4691 context.check_layout(os);
4694 output_ert_inset(os, to_utf8(rem), context);
4696 skip_spaces_braces(p);
4697 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4698 preamble.registerAutomaticallyLoadedPackage(*it);
4700 //cerr << "#: " << t << " mode: " << mode << endl;
4701 // heuristic: read up to next non-nested space
4703 string s = t.asInput();
4704 string z = p.verbatim_item();
4705 while (p.good() && z != " " && !z.empty()) {
4706 //cerr << "read: " << z << endl;
4708 z = p.verbatim_item();
4710 cerr << "found ERT: " << s << endl;
4711 output_ert_inset(os, s + ' ', context);
4714 if (t.asInput() == name &&
4715 p.next_token().asInput() == "*") {
4716 // Starred commands like \vspace*{}
4717 p.get_token(); // Eat '*'
4720 if (!parse_command(name, p, os, outer, context))
4721 output_ert_inset(os, name, context);
4725 if (flags & FLAG_LEAVE) {
4726 flags &= ~FLAG_LEAVE;
4733 string guessLanguage(Parser & p, string const & lang)
4735 typedef std::map<std::string, size_t> LangMap;
4736 // map from language names to number of characters
4739 for (char const * const * i = supported_CJK_languages; *i; i++)
4740 used[string(*i)] = 0;
4743 Token const t = p.get_token();
4744 // comments are not counted for any language
4745 if (t.cat() == catComment)
4747 // commands are not counted as well, but we need to detect
4748 // \begin{CJK} and switch encoding if needed
4749 if (t.cat() == catEscape) {
4750 if (t.cs() == "inputencoding") {
4751 string const enc = subst(p.verbatim_item(), "\n", " ");
4752 p.setEncoding(enc, Encoding::inputenc);
4755 if (t.cs() != "begin")
4758 // Non-CJK content is counted for lang.
4759 // We do not care about the real language here:
4760 // If we have more non-CJK contents than CJK contents,
4761 // we simply use the language that was specified as
4762 // babel main language.
4763 used[lang] += t.asInput().length();
4766 // Now we are starting an environment
4768 string const name = p.getArg('{', '}');
4769 if (name != "CJK") {
4773 // It is a CJK environment
4775 /* name = */ p.getArg('{', '}');
4776 string const encoding = p.getArg('{', '}');
4777 /* mapping = */ p.getArg('{', '}');
4778 string const encoding_old = p.getEncoding();
4779 char const * const * const where =
4780 is_known(encoding, supported_CJK_encodings);
4782 p.setEncoding(encoding, Encoding::CJK);
4784 p.setEncoding("UTF-8");
4785 string const text = p.ertEnvironment("CJK");
4786 p.setEncoding(encoding_old);
4789 // ignore contents in unknown CJK encoding
4792 // the language of the text
4794 supported_CJK_languages[where - supported_CJK_encodings];
4795 used[cjk] += text.length();
4797 LangMap::const_iterator use = used.begin();
4798 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4799 if (it->second > use->second)