2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout)
59 bool const forcePlainLayout =
60 layout ? layout->forcePlainLayout() : false;
61 Context newcontext(true, context.textclass);
63 newcontext.layout = &context.textclass.plainLayout();
65 newcontext.font = context.font;
67 output_arguments(os, p, outer, false, 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, bool need_layout,
627 Context & context, Layout::LaTeXArgMap const & latexargs)
630 context.check_layout(os);
635 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
636 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
637 for (; lait != laend; ++lait) {
639 eat_whitespace(p, os, context, false);
640 if (lait->second.mandatory) {
641 if (p.next_token().cat() != catBegin)
643 p.get_token(); // eat '{'
645 context.check_layout(os);
648 begin_inset(os, "Argument ");
649 os << i << "\nstatus collapsed\n\n";
650 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
653 if (p.next_token().cat() == catEscape ||
654 p.next_token().character() != '[')
656 p.get_token(); // eat '['
658 context.check_layout(os);
661 begin_inset(os, "Argument ");
662 os << i << "\nstatus collapsed\n\n";
663 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
666 eat_whitespace(p, os, context, false);
671 void output_command_layout(ostream & os, Parser & p, bool outer,
672 Context & parent_context,
673 Layout const * newlayout)
675 TeXFont const oldFont = parent_context.font;
676 // save the current font size
677 string const size = oldFont.size;
678 // reset the font size to default, because the font size switches
679 // don't affect section headings and the like
680 parent_context.font.size = Context::normalfont.size;
681 // we only need to write the font change if we have an open layout
682 if (!parent_context.atParagraphStart())
683 output_font_change(os, oldFont, parent_context.font);
684 parent_context.check_end_layout(os);
685 Context context(true, parent_context.textclass, newlayout,
686 parent_context.layout, parent_context.font);
687 if (parent_context.deeper_paragraph) {
688 // We are beginning a nested environment after a
689 // deeper paragraph inside the outer list environment.
690 // Therefore we don't need to output a "begin deeper".
691 context.need_end_deeper = true;
693 context.check_deeper(os);
694 output_arguments(os, p, outer, true, context, context.layout->latexargs());
695 parse_text(p, os, FLAG_ITEM, outer, context);
696 context.check_end_layout(os);
697 if (parent_context.deeper_paragraph) {
698 // We must suppress the "end deeper" because we
699 // suppressed the "begin deeper" above.
700 context.need_end_deeper = false;
702 context.check_end_deeper(os);
703 // We don't need really a new paragraph, but
704 // we must make sure that the next item gets a \begin_layout.
705 parent_context.new_paragraph(os);
706 // Set the font size to the original value. No need to output it here
707 // (Context::begin_layout() will do that if needed)
708 parent_context.font.size = size;
713 * Output a space if necessary.
714 * This function gets called for every whitespace token.
716 * We have three cases here:
717 * 1. A space must be suppressed. Example: The lyxcode case below
718 * 2. A space may be suppressed. Example: Spaces before "\par"
719 * 3. A space must not be suppressed. Example: A space between two words
721 * We currently handle only 1. and 3 and from 2. only the case of
722 * spaces before newlines as a side effect.
724 * 2. could be used to suppress as many spaces as possible. This has two effects:
725 * - Reimporting LyX generated LaTeX files changes almost no whitespace
726 * - Superflous whitespace from non LyX generated LaTeX files is removed.
727 * The drawback is that the logic inside the function becomes
728 * complicated, and that is the reason why it is not implemented.
730 void check_space(Parser & p, ostream & os, Context & context)
732 Token const next = p.next_token();
733 Token const curr = p.curr_token();
734 // A space before a single newline and vice versa must be ignored
735 // LyX emits a newline before \end{lyxcode}.
736 // This newline must be ignored,
737 // otherwise LyX will add an additional protected space.
738 if (next.cat() == catSpace ||
739 next.cat() == catNewline ||
740 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
743 context.check_layout(os);
749 * Parse all arguments of \p command
751 void parse_arguments(string const & command,
752 vector<ArgumentType> const & template_arguments,
753 Parser & p, ostream & os, bool outer, Context & context)
755 string ert = command;
756 size_t no_arguments = template_arguments.size();
757 for (size_t i = 0; i < no_arguments; ++i) {
758 switch (template_arguments[i]) {
761 // This argument contains regular LaTeX
762 output_ert_inset(os, ert + '{', context);
763 eat_whitespace(p, os, context, false);
764 if (template_arguments[i] == required)
765 parse_text(p, os, FLAG_ITEM, outer, context);
767 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
771 // This argument consists only of a single item.
772 // The presence of '{' or not must be preserved.
774 if (p.next_token().cat() == catBegin)
775 ert += '{' + p.verbatim_item() + '}';
777 ert += p.verbatim_item();
781 // This argument may contain special characters
782 ert += '{' + p.verbatim_item() + '}';
786 // true because we must not eat whitespace
787 // if an optional arg follows we must not strip the
788 // brackets from this one
789 if (i < no_arguments - 1 &&
790 template_arguments[i+1] == optional)
791 ert += p.getFullOpt(true);
793 ert += p.getOpt(true);
797 output_ert_inset(os, ert, context);
802 * Check whether \p command is a known command. If yes,
803 * handle the command with all arguments.
804 * \return true if the command was parsed, false otherwise.
806 bool parse_command(string const & command, Parser & p, ostream & os,
807 bool outer, Context & context)
809 if (known_commands.find(command) != known_commands.end()) {
810 parse_arguments(command, known_commands[command], p, os,
818 /// Parses a minipage or parbox
819 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
820 unsigned inner_flags, bool outer, Context & parent_context,
821 string const & outer_type, string const & special,
822 string const & inner_type)
826 string hor_pos = "c";
827 // We need to set the height to the LaTeX default of 1\\totalheight
828 // for the case when no height argument is given
829 string height_value = "1";
830 string height_unit = "in";
831 string height_special = "totalheight";
836 string width_special = "none";
837 if (!inner_type.empty() && p.hasOpt()) {
838 if (inner_type != "makebox")
839 position = p.getArg('[', ']');
841 latex_width = p.getArg('[', ']');
842 translate_box_len(latex_width, width_value, width_unit, width_special);
845 if (position != "t" && position != "c" && position != "b") {
846 cerr << "invalid position " << position << " for "
847 << inner_type << endl;
851 if (inner_type != "makebox") {
852 latex_height = p.getArg('[', ']');
853 translate_box_len(latex_height, height_value, height_unit, height_special);
855 string const opt = p.getArg('[', ']');
858 if (hor_pos != "l" && hor_pos != "c" &&
859 hor_pos != "r" && hor_pos != "s") {
860 cerr << "invalid hor_pos " << hor_pos
861 << " for " << inner_type << endl;
868 inner_pos = p.getArg('[', ']');
869 if (inner_pos != "c" && inner_pos != "t" &&
870 inner_pos != "b" && inner_pos != "s") {
871 cerr << "invalid inner_pos "
872 << inner_pos << " for "
873 << inner_type << endl;
874 inner_pos = position;
879 if (inner_type.empty()) {
880 if (special.empty() && outer_type != "framebox")
881 latex_width = "1\\columnwidth";
884 latex_width = p2.getArg('[', ']');
885 string const opt = p2.getArg('[', ']');
888 if (hor_pos != "l" && hor_pos != "c" &&
889 hor_pos != "r" && hor_pos != "s") {
890 cerr << "invalid hor_pos " << hor_pos
891 << " for " << outer_type << endl;
896 } else if (inner_type != "makebox")
897 latex_width = p.verbatim_item();
898 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
899 // as this is LyX's standard for such cases (except for makebox)
900 // \framebox is more special and handled below
901 if (latex_width.empty() && inner_type != "makebox"
902 && outer_type != "framebox")
903 latex_width = "1\\columnwidth";
905 translate_len(latex_width, width_value, width_unit);
907 bool shadedparbox = false;
908 if (inner_type == "shaded") {
909 eat_whitespace(p, os, parent_context, false);
910 if (outer_type == "parbox") {
912 if (p.next_token().cat() == catBegin)
914 eat_whitespace(p, os, parent_context, false);
920 // If we already read the inner box we have to push the inner env
921 if (!outer_type.empty() && !inner_type.empty() &&
922 (inner_flags & FLAG_END))
923 active_environments.push_back(inner_type);
924 // LyX can't handle length variables
925 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
926 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
927 // Look whether there is some content after the end of the
928 // inner box, but before the end of the outer box.
929 // If yes, we need to output ERT.
931 if (inner_flags & FLAG_END)
932 p.ertEnvironment(inner_type);
936 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
937 if ((outer_env && p.next_token().asInput() != "\\end") ||
938 (!outer_env && p.next_token().cat() != catEnd)) {
939 // something is between the end of the inner box and
940 // the end of the outer box, so we need to use ERT.
945 // if only \makebox{content} was used we can set its width to 1\width
946 // because this identic and also identic to \mbox
947 // this doesn't work for \framebox{content}, thus we have to use ERT for this
948 if (latex_width.empty() && inner_type == "makebox") {
951 width_special = "width";
952 } else if (latex_width.empty() && outer_type == "framebox") {
955 width_special = "none";
959 if (!outer_type.empty()) {
960 if (outer_flags & FLAG_END)
961 ss << "\\begin{" << outer_type << '}';
963 ss << '\\' << outer_type << '{';
964 if (!special.empty())
968 if (!inner_type.empty()) {
969 if (inner_type != "shaded") {
970 if (inner_flags & FLAG_END)
971 ss << "\\begin{" << inner_type << '}';
973 ss << '\\' << inner_type;
975 if (!position.empty())
976 ss << '[' << position << ']';
977 if (!latex_height.empty())
978 ss << '[' << latex_height << ']';
979 if (!inner_pos.empty())
980 ss << '[' << inner_pos << ']';
981 ss << '{' << latex_width << '}';
982 if (!(inner_flags & FLAG_END))
985 if (inner_type == "shaded")
986 ss << "\\begin{shaded}";
987 output_ert_inset(os, ss.str(), parent_context);
988 if (!inner_type.empty()) {
989 parse_text(p, os, inner_flags, outer, parent_context);
990 if (inner_flags & FLAG_END)
991 output_ert_inset(os, "\\end{" + inner_type + '}',
994 output_ert_inset(os, "}", parent_context);
996 if (!outer_type.empty()) {
997 // If we already read the inner box we have to pop
999 if (!inner_type.empty() && (inner_flags & FLAG_END))
1000 active_environments.pop_back();
1002 // Ensure that the end of the outer box is parsed correctly:
1003 // The opening brace has been eaten by parse_outer_box()
1004 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1005 outer_flags &= ~FLAG_ITEM;
1006 outer_flags |= FLAG_BRACE_LAST;
1008 parse_text(p, os, outer_flags, outer, parent_context);
1009 if (outer_flags & FLAG_END)
1010 output_ert_inset(os, "\\end{" + outer_type + '}',
1013 output_ert_inset(os, "}", parent_context);
1016 // LyX does not like empty positions, so we have
1017 // to set them to the LaTeX default values here.
1018 if (position.empty())
1020 if (inner_pos.empty())
1021 inner_pos = position;
1022 parent_context.check_layout(os);
1023 begin_inset(os, "Box ");
1024 if (outer_type == "framed")
1026 else if (outer_type == "framebox" || outer_type == "fbox")
1028 else if (outer_type == "shadowbox")
1029 os << "Shadowbox\n";
1030 else if ((outer_type == "shaded" && inner_type.empty()) ||
1031 (outer_type == "minipage" && inner_type == "shaded") ||
1032 (outer_type == "parbox" && inner_type == "shaded")) {
1034 preamble.registerAutomaticallyLoadedPackage("color");
1035 } else if (outer_type == "doublebox")
1036 os << "Doublebox\n";
1037 else if (outer_type.empty() || outer_type == "mbox")
1038 os << "Frameless\n";
1040 os << outer_type << '\n';
1041 os << "position \"" << position << "\"\n";
1042 os << "hor_pos \"" << hor_pos << "\"\n";
1043 if (outer_type == "mbox")
1044 os << "has_inner_box 1\n";
1046 os << "has_inner_box " << !inner_type.empty() << "\n";
1047 os << "inner_pos \"" << inner_pos << "\"\n";
1048 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1050 if (outer_type == "mbox")
1051 os << "use_makebox 1\n";
1053 os << "use_makebox " << (inner_type == "makebox") << '\n';
1054 if (outer_type == "fbox" || outer_type == "mbox")
1055 os << "width \"\"\n";
1057 os << "width \"" << width_value << width_unit << "\"\n";
1058 os << "special \"" << width_special << "\"\n";
1059 os << "height \"" << height_value << height_unit << "\"\n";
1060 os << "height_special \"" << height_special << "\"\n";
1061 os << "status open\n\n";
1063 // Unfortunately we can't use parse_text_in_inset:
1064 // InsetBox::forcePlainLayout() is hard coded and does not
1065 // use the inset layout. Apart from that do we call parse_text
1066 // up to two times, but need only one check_end_layout.
1067 bool const forcePlainLayout =
1068 (!inner_type.empty() || inner_type == "makebox") &&
1069 outer_type != "shaded" && outer_type != "framed";
1070 Context context(true, parent_context.textclass);
1071 if (forcePlainLayout)
1072 context.layout = &context.textclass.plainLayout();
1074 context.font = parent_context.font;
1076 // If we have no inner box the contents will be read with the outer box
1077 if (!inner_type.empty())
1078 parse_text(p, os, inner_flags, outer, context);
1080 // Ensure that the end of the outer box is parsed correctly:
1081 // The opening brace has been eaten by parse_outer_box()
1082 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1083 outer_flags &= ~FLAG_ITEM;
1084 outer_flags |= FLAG_BRACE_LAST;
1087 // Find end of outer box, output contents if inner_type is
1088 // empty and output possible comments
1089 if (!outer_type.empty()) {
1090 // If we already read the inner box we have to pop
1092 if (!inner_type.empty() && (inner_flags & FLAG_END))
1093 active_environments.pop_back();
1094 // This does not output anything but comments if
1095 // inner_type is not empty (see use_ert)
1096 parse_text(p, os, outer_flags, outer, context);
1099 context.check_end_layout(os);
1101 #ifdef PRESERVE_LAYOUT
1102 // LyX puts a % after the end of the minipage
1103 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1105 //output_ert_inset(os, "%dummy", parent_context);
1108 parent_context.new_paragraph(os);
1110 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1111 //output_ert_inset(os, "%dummy", parent_context);
1114 // We add a protected space if something real follows
1115 if (p.good() && p.next_token().cat() != catComment) {
1116 begin_inset(os, "space ~\n");
1125 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1126 Context & parent_context, string const & outer_type,
1127 string const & special)
1129 eat_whitespace(p, os, parent_context, false);
1130 if (flags & FLAG_ITEM) {
1132 if (p.next_token().cat() == catBegin)
1135 cerr << "Warning: Ignoring missing '{' after \\"
1136 << outer_type << '.' << endl;
1137 eat_whitespace(p, os, parent_context, false);
1140 unsigned int inner_flags = 0;
1142 if (outer_type == "minipage" || outer_type == "parbox") {
1143 p.skip_spaces(true);
1144 while (p.hasOpt()) {
1146 p.skip_spaces(true);
1149 p.skip_spaces(true);
1150 if (outer_type == "parbox") {
1152 if (p.next_token().cat() == catBegin)
1154 p.skip_spaces(true);
1157 if (outer_type == "shaded" || outer_type == "fbox"
1158 || outer_type == "mbox") {
1159 // These boxes never have an inner box
1161 } else if (p.next_token().asInput() == "\\parbox") {
1162 inner = p.get_token().cs();
1163 inner_flags = FLAG_ITEM;
1164 } else if (p.next_token().asInput() == "\\begin") {
1165 // Is this a minipage or shaded box?
1168 inner = p.getArg('{', '}');
1170 if (inner == "minipage" || inner == "shaded")
1171 inner_flags = FLAG_END;
1176 if (inner_flags == FLAG_END) {
1177 if (inner != "shaded")
1181 eat_whitespace(p, os, parent_context, false);
1183 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1184 outer_type, special, inner);
1186 if (inner_flags == FLAG_ITEM) {
1188 eat_whitespace(p, os, parent_context, false);
1190 parse_box(p, os, flags, inner_flags, outer, parent_context,
1191 outer_type, special, inner);
1196 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1198 parent_context.check_layout(os);
1199 begin_inset(os, "listings\n");
1201 string arg = p.verbatimOption();
1202 os << "lstparams " << '"' << arg << '"' << '\n';
1203 if (arg.find("\\color") != string::npos)
1204 preamble.registerAutomaticallyLoadedPackage("color");
1207 os << "inline true\n";
1209 os << "inline false\n";
1210 os << "status collapsed\n";
1211 Context context(true, parent_context.textclass);
1212 context.layout = &parent_context.textclass.plainLayout();
1215 // set catcodes to verbatim early, just in case.
1216 p.setCatcodes(VERBATIM_CATCODES);
1217 string delim = p.get_token().asInput();
1218 //FIXME: handler error condition
1219 s = p.verbatimStuff(delim).second;
1220 // context.new_paragraph(os);
1222 s = p.verbatimEnvironment("lstlisting");
1223 output_ert(os, s, context);
1228 /// parse an unknown environment
1229 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1230 unsigned flags, bool outer,
1231 Context & parent_context)
1233 if (name == "tabbing")
1234 // We need to remember that we have to handle '\=' specially
1235 flags |= FLAG_TABBING;
1237 // We need to translate font changes and paragraphs inside the
1238 // environment to ERT if we have a non standard font.
1239 // Otherwise things like
1240 // \large\begin{foo}\huge bar\end{foo}
1242 bool const specialfont =
1243 (parent_context.font != parent_context.normalfont);
1244 bool const new_layout_allowed = parent_context.new_layout_allowed;
1246 parent_context.new_layout_allowed = false;
1247 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1248 parse_text_snippet(p, os, flags, outer, parent_context);
1249 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1251 parent_context.new_layout_allowed = new_layout_allowed;
1255 void parse_environment(Parser & p, ostream & os, bool outer,
1256 string & last_env, Context & parent_context)
1258 Layout const * newlayout;
1259 InsetLayout const * newinsetlayout = 0;
1260 string const name = p.getArg('{', '}');
1261 const bool is_starred = suffixIs(name, '*');
1262 string const unstarred_name = rtrim(name, "*");
1263 active_environments.push_back(name);
1265 if (is_math_env(name)) {
1266 parent_context.check_layout(os);
1267 begin_inset(os, "Formula ");
1268 os << "\\begin{" << name << "}";
1269 parse_math(p, os, FLAG_END, MATH_MODE);
1270 os << "\\end{" << name << "}";
1272 if (is_display_math_env(name)) {
1273 // Prevent the conversion of a line break to a space
1274 // (bug 7668). This does not change the output, but
1275 // looks ugly in LyX.
1276 eat_whitespace(p, os, parent_context, false);
1280 else if (is_known(name, preamble.polyglossia_languages)) {
1281 // We must begin a new paragraph if not already done
1282 if (! parent_context.atParagraphStart()) {
1283 parent_context.check_end_layout(os);
1284 parent_context.new_paragraph(os);
1286 // save the language in the context so that it is
1287 // handled by parse_text
1288 parent_context.font.language = preamble.polyglossia2lyx(name);
1289 parse_text(p, os, FLAG_END, outer, parent_context);
1290 // Just in case the environment is empty
1291 parent_context.extra_stuff.erase();
1292 // We must begin a new paragraph to reset the language
1293 parent_context.new_paragraph(os);
1297 else if (unstarred_name == "tabular" || name == "longtable") {
1298 eat_whitespace(p, os, parent_context, false);
1299 string width = "0pt";
1300 if (name == "tabular*") {
1301 width = lyx::translate_len(p.getArg('{', '}'));
1302 eat_whitespace(p, os, parent_context, false);
1304 parent_context.check_layout(os);
1305 begin_inset(os, "Tabular ");
1306 handle_tabular(p, os, name, width, parent_context);
1311 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1312 eat_whitespace(p, os, parent_context, false);
1313 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1314 eat_whitespace(p, os, parent_context, false);
1315 parent_context.check_layout(os);
1316 begin_inset(os, "Float " + unstarred_name + "\n");
1317 // store the float type for subfloats
1318 // subfloats only work with figures and tables
1319 if (unstarred_name == "figure")
1320 float_type = unstarred_name;
1321 else if (unstarred_name == "table")
1322 float_type = unstarred_name;
1326 os << "placement " << opt << '\n';
1327 if (contains(opt, "H"))
1328 preamble.registerAutomaticallyLoadedPackage("float");
1330 Floating const & fl = parent_context.textclass.floats()
1331 .getType(unstarred_name);
1332 if (!fl.floattype().empty() && fl.usesFloatPkg())
1333 preamble.registerAutomaticallyLoadedPackage("float");
1336 os << "wide " << convert<string>(is_starred)
1337 << "\nsideways false"
1338 << "\nstatus open\n\n";
1339 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1341 // We don't need really a new paragraph, but
1342 // we must make sure that the next item gets a \begin_layout.
1343 parent_context.new_paragraph(os);
1345 // the float is parsed thus delete the type
1349 else if (unstarred_name == "sidewaysfigure"
1350 || unstarred_name == "sidewaystable") {
1351 eat_whitespace(p, os, parent_context, false);
1352 parent_context.check_layout(os);
1353 if (unstarred_name == "sidewaysfigure")
1354 begin_inset(os, "Float figure\n");
1356 begin_inset(os, "Float table\n");
1357 os << "wide " << convert<string>(is_starred)
1358 << "\nsideways true"
1359 << "\nstatus open\n\n";
1360 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1362 // We don't need really a new paragraph, but
1363 // we must make sure that the next item gets a \begin_layout.
1364 parent_context.new_paragraph(os);
1366 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1369 else if (name == "wrapfigure" || name == "wraptable") {
1370 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1371 eat_whitespace(p, os, parent_context, false);
1372 parent_context.check_layout(os);
1375 string overhang = "0col%";
1378 lines = p.getArg('[', ']');
1379 string const placement = p.getArg('{', '}');
1381 overhang = p.getArg('[', ']');
1382 string const width = p.getArg('{', '}');
1384 if (name == "wrapfigure")
1385 begin_inset(os, "Wrap figure\n");
1387 begin_inset(os, "Wrap table\n");
1388 os << "lines " << lines
1389 << "\nplacement " << placement
1390 << "\noverhang " << lyx::translate_len(overhang)
1391 << "\nwidth " << lyx::translate_len(width)
1392 << "\nstatus open\n\n";
1393 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1395 // We don't need really a new paragraph, but
1396 // we must make sure that the next item gets a \begin_layout.
1397 parent_context.new_paragraph(os);
1399 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1402 else if (name == "minipage") {
1403 eat_whitespace(p, os, parent_context, false);
1404 // Test whether this is an outer box of a shaded box
1406 // swallow arguments
1407 while (p.hasOpt()) {
1409 p.skip_spaces(true);
1412 p.skip_spaces(true);
1413 Token t = p.get_token();
1414 bool shaded = false;
1415 if (t.asInput() == "\\begin") {
1416 p.skip_spaces(true);
1417 if (p.getArg('{', '}') == "shaded")
1422 parse_outer_box(p, os, FLAG_END, outer,
1423 parent_context, name, "shaded");
1425 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1430 else if (name == "comment") {
1431 eat_whitespace(p, os, parent_context, false);
1432 parent_context.check_layout(os);
1433 begin_inset(os, "Note Comment\n");
1434 os << "status open\n";
1435 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1438 skip_braces(p); // eat {} that might by set by LyX behind comments
1439 preamble.registerAutomaticallyLoadedPackage("verbatim");
1442 else if (name == "verbatim") {
1443 // FIXME: this should go in the generic code that
1444 // handles environments defined in layout file that
1445 // have "PassThru 1". However, the code over there is
1446 // already too complicated for my taste.
1447 parent_context.new_paragraph(os);
1448 Context context(true, parent_context.textclass,
1449 &parent_context.textclass[from_ascii("Verbatim")]);
1450 string s = p.verbatimEnvironment("verbatim");
1451 output_ert(os, s, context);
1455 else if (name == "IPA") {
1456 eat_whitespace(p, os, parent_context, false);
1457 parent_context.check_layout(os);
1458 begin_inset(os, "IPA\n");
1459 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1462 preamble.registerAutomaticallyLoadedPackage("tipa");
1463 preamble.registerAutomaticallyLoadedPackage("tipx");
1466 else if (name == "CJK") {
1467 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1468 // It is impossible to decide if a CJK environment was in its own paragraph or within
1469 // a line. We therefore always assume a paragraph since the latter is a rare case.
1470 eat_whitespace(p, os, parent_context, false);
1471 parent_context.check_end_layout(os);
1472 // store the encoding to be able to reset it
1473 string const encoding_old = p.getEncoding();
1474 string const encoding = p.getArg('{', '}');
1475 // FIXME: For some reason JIS does not work. Although the text
1476 // in tests/CJK.tex is identical with the SJIS version if you
1477 // convert both snippets using the recode command line utility,
1478 // the resulting .lyx file contains some extra characters if
1479 // you set buggy_encoding to false for JIS.
1480 bool const buggy_encoding = encoding == "JIS";
1481 if (!buggy_encoding)
1482 p.setEncoding(encoding, Encoding::CJK);
1484 // FIXME: This will read garbage, since the data is not encoded in utf8.
1485 p.setEncoding("UTF-8");
1487 // LyX only supports the same mapping for all CJK
1488 // environments, so we might need to output everything as ERT
1489 string const mapping = trim(p.getArg('{', '}'));
1490 char const * const * const where =
1491 is_known(encoding, supported_CJK_encodings);
1492 if (!buggy_encoding && !preamble.fontCJKSet())
1493 preamble.fontCJK(mapping);
1494 bool knownMapping = mapping == preamble.fontCJK();
1495 if (buggy_encoding || !knownMapping || !where) {
1496 parent_context.check_layout(os);
1497 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1499 // we must parse the content as verbatim because e.g. JIS can contain
1500 // normally invalid characters
1501 // FIXME: This works only for the most simple cases.
1502 // Since TeX control characters are not parsed,
1503 // things like comments are completely wrong.
1504 string const s = p.plainEnvironment("CJK");
1505 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1507 output_ert_inset(os, "\\", parent_context);
1508 else if (*it == '$')
1509 output_ert_inset(os, "$", parent_context);
1510 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1515 output_ert_inset(os, "\\end{" + name + "}",
1519 supported_CJK_languages[where - supported_CJK_encodings];
1520 // store the language because we must reset it at the end
1521 string const lang_old = parent_context.font.language;
1522 parent_context.font.language = lang;
1523 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1524 parent_context.font.language = lang_old;
1525 parent_context.new_paragraph(os);
1527 p.setEncoding(encoding_old);
1531 else if (name == "lyxgreyedout") {
1532 eat_whitespace(p, os, parent_context, false);
1533 parent_context.check_layout(os);
1534 begin_inset(os, "Note Greyedout\n");
1535 os << "status open\n";
1536 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1539 if (!preamble.notefontcolor().empty())
1540 preamble.registerAutomaticallyLoadedPackage("color");
1543 else if (name == "btSect") {
1544 eat_whitespace(p, os, parent_context, false);
1545 parent_context.check_layout(os);
1546 begin_command_inset(os, "bibtex", "bibtex");
1547 string bibstyle = "plain";
1549 bibstyle = p.getArg('[', ']');
1550 p.skip_spaces(true);
1552 string const bibfile = p.getArg('{', '}');
1553 eat_whitespace(p, os, parent_context, false);
1554 Token t = p.get_token();
1555 if (t.asInput() == "\\btPrintCited") {
1556 p.skip_spaces(true);
1557 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1559 if (t.asInput() == "\\btPrintNotCited") {
1560 p.skip_spaces(true);
1561 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1563 if (t.asInput() == "\\btPrintAll") {
1564 p.skip_spaces(true);
1565 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1567 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1568 os << "options " << '"' << bibstyle << '"' << "\n";
1569 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1574 else if (name == "framed" || name == "shaded") {
1575 eat_whitespace(p, os, parent_context, false);
1576 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1580 else if (name == "lstlisting") {
1581 eat_whitespace(p, os, parent_context, false);
1582 parse_listings(p, os, parent_context, false);
1586 else if (!parent_context.new_layout_allowed)
1587 parse_unknown_environment(p, name, os, FLAG_END, outer,
1590 // Alignment and spacing settings
1591 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1592 // therefore are totally broken!
1593 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1594 // they are commands not environments. They are furthermore switches that
1595 // can be ended by another switches, but also by commands like \footnote or
1596 // \parbox. So the only safe way is to leave them untouched.
1597 else if (name == "center" || name == "centering" ||
1598 name == "flushleft" || name == "flushright" ||
1599 name == "singlespace" || name == "onehalfspace" ||
1600 name == "doublespace" || name == "spacing") {
1601 eat_whitespace(p, os, parent_context, false);
1602 // We must begin a new paragraph if not already done
1603 if (! parent_context.atParagraphStart()) {
1604 parent_context.check_end_layout(os);
1605 parent_context.new_paragraph(os);
1607 if (name == "flushleft")
1608 parent_context.add_extra_stuff("\\align left\n");
1609 else if (name == "flushright")
1610 parent_context.add_extra_stuff("\\align right\n");
1611 else if (name == "center" || name == "centering")
1612 parent_context.add_extra_stuff("\\align center\n");
1613 else if (name == "singlespace")
1614 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1615 else if (name == "onehalfspace") {
1616 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1617 preamble.registerAutomaticallyLoadedPackage("setspace");
1618 } else if (name == "doublespace") {
1619 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1620 preamble.registerAutomaticallyLoadedPackage("setspace");
1621 } else if (name == "spacing") {
1622 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1623 preamble.registerAutomaticallyLoadedPackage("setspace");
1625 parse_text(p, os, FLAG_END, outer, parent_context);
1626 // Just in case the environment is empty
1627 parent_context.extra_stuff.erase();
1628 // We must begin a new paragraph to reset the alignment
1629 parent_context.new_paragraph(os);
1633 // The single '=' is meant here.
1634 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1635 eat_whitespace(p, os, parent_context, false);
1636 Context context(true, parent_context.textclass, newlayout,
1637 parent_context.layout, parent_context.font);
1638 if (parent_context.deeper_paragraph) {
1639 // We are beginning a nested environment after a
1640 // deeper paragraph inside the outer list environment.
1641 // Therefore we don't need to output a "begin deeper".
1642 context.need_end_deeper = true;
1644 parent_context.check_end_layout(os);
1645 if (last_env == name) {
1646 // we need to output a separator since LyX would export
1647 // the two environments as one otherwise (bug 5716)
1648 TeX2LyXDocClass const & textclass(parent_context.textclass);
1649 Context newcontext(true, textclass,
1650 &(textclass.defaultLayout()));
1651 newcontext.check_layout(os);
1652 begin_inset(os, "Separator plain\n");
1654 newcontext.check_end_layout(os);
1656 switch (context.layout->latextype) {
1657 case LATEX_LIST_ENVIRONMENT:
1658 context.add_par_extra_stuff("\\labelwidthstring "
1659 + p.verbatim_item() + '\n');
1662 case LATEX_BIB_ENVIRONMENT:
1663 p.verbatim_item(); // swallow next arg
1669 context.check_deeper(os);
1670 // handle known optional and required arguments
1671 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1672 // It is impossible to place anything after the environment name,
1673 // but before the first \\item.
1674 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1675 output_arguments(os, p, outer, false, context, context.layout->latexargs());
1677 parse_text(p, os, FLAG_END, outer, context);
1678 context.check_end_layout(os);
1679 if (parent_context.deeper_paragraph) {
1680 // We must suppress the "end deeper" because we
1681 // suppressed the "begin deeper" above.
1682 context.need_end_deeper = false;
1684 context.check_end_deeper(os);
1685 parent_context.new_paragraph(os);
1687 if (!preamble.titleLayoutFound())
1688 preamble.titleLayoutFound(newlayout->intitle);
1689 set<string> const & req = newlayout->requires();
1690 set<string>::const_iterator it = req.begin();
1691 set<string>::const_iterator en = req.end();
1692 for (; it != en; ++it)
1693 preamble.registerAutomaticallyLoadedPackage(*it);
1696 // The single '=' is meant here.
1697 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1698 eat_whitespace(p, os, parent_context, false);
1699 parent_context.check_layout(os);
1700 begin_inset(os, "Flex ");
1701 os << to_utf8(newinsetlayout->name()) << '\n'
1702 << "status collapsed\n";
1703 if (newinsetlayout->isPassThru()) {
1704 string const arg = p.verbatimEnvironment(name);
1705 Context context(true, parent_context.textclass,
1706 &parent_context.textclass.plainLayout(),
1707 parent_context.layout);
1708 output_ert(os, arg, parent_context);
1710 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1714 else if (name == "appendix") {
1715 // This is no good latex style, but it works and is used in some documents...
1716 eat_whitespace(p, os, parent_context, false);
1717 parent_context.check_end_layout(os);
1718 Context context(true, parent_context.textclass, parent_context.layout,
1719 parent_context.layout, parent_context.font);
1720 context.check_layout(os);
1721 os << "\\start_of_appendix\n";
1722 parse_text(p, os, FLAG_END, outer, context);
1723 context.check_end_layout(os);
1727 else if (known_environments.find(name) != known_environments.end()) {
1728 vector<ArgumentType> arguments = known_environments[name];
1729 // The last "argument" denotes wether we may translate the
1730 // environment contents to LyX
1731 // The default required if no argument is given makes us
1732 // compatible with the reLyXre environment.
1733 ArgumentType contents = arguments.empty() ?
1736 if (!arguments.empty())
1737 arguments.pop_back();
1738 // See comment in parse_unknown_environment()
1739 bool const specialfont =
1740 (parent_context.font != parent_context.normalfont);
1741 bool const new_layout_allowed =
1742 parent_context.new_layout_allowed;
1744 parent_context.new_layout_allowed = false;
1745 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1746 outer, parent_context);
1747 if (contents == verbatim)
1748 output_ert_inset(os, p.ertEnvironment(name),
1751 parse_text_snippet(p, os, FLAG_END, outer,
1753 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1755 parent_context.new_layout_allowed = new_layout_allowed;
1759 parse_unknown_environment(p, name, os, FLAG_END, outer,
1763 active_environments.pop_back();
1767 /// parses a comment and outputs it to \p os.
1768 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1770 LASSERT(t.cat() == catComment, return);
1771 if (!t.cs().empty()) {
1772 context.check_layout(os);
1773 output_ert_inset(os, '%' + t.cs(), context);
1774 if (p.next_token().cat() == catNewline) {
1775 // A newline after a comment line starts a new
1777 if (context.new_layout_allowed) {
1778 if(!context.atParagraphStart())
1779 // Only start a new paragraph if not already
1780 // done (we might get called recursively)
1781 context.new_paragraph(os);
1783 output_ert_inset(os, "\n", context);
1784 eat_whitespace(p, os, context, true);
1787 // "%\n" combination
1794 * Reads spaces and comments until the first non-space, non-comment token.
1795 * New paragraphs (double newlines or \\par) are handled like simple spaces
1796 * if \p eatParagraph is true.
1797 * Spaces are skipped, but comments are written to \p os.
1799 void eat_whitespace(Parser & p, ostream & os, Context & context,
1803 Token const & t = p.get_token();
1804 if (t.cat() == catComment)
1805 parse_comment(p, os, t, context);
1806 else if ((! eatParagraph && p.isParagraph()) ||
1807 (t.cat() != catSpace && t.cat() != catNewline)) {
1816 * Set a font attribute, parse text and reset the font attribute.
1817 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1818 * \param currentvalue Current value of the attribute. Is set to the new
1819 * value during parsing.
1820 * \param newvalue New value of the attribute
1822 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1823 Context & context, string const & attribute,
1824 string & currentvalue, string const & newvalue)
1826 context.check_layout(os);
1827 string const oldvalue = currentvalue;
1828 currentvalue = newvalue;
1829 os << '\n' << attribute << ' ' << newvalue << "\n";
1830 parse_text_snippet(p, os, flags, outer, context);
1831 context.check_layout(os);
1832 os << '\n' << attribute << ' ' << oldvalue << "\n";
1833 currentvalue = oldvalue;
1837 /// get the arguments of a natbib or jurabib citation command
1838 void get_cite_arguments(Parser & p, bool natbibOrder,
1839 string & before, string & after)
1841 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1843 // text before the citation
1845 // text after the citation
1846 after = p.getFullOpt();
1848 if (!after.empty()) {
1849 before = p.getFullOpt();
1850 if (natbibOrder && !before.empty())
1851 swap(before, after);
1856 /// Convert filenames with TeX macros and/or quotes to something LyX
1858 string const normalize_filename(string const & name)
1863 Token const & t = p.get_token();
1864 if (t.cat() != catEscape)
1866 else if (t.cs() == "lyxdot") {
1867 // This is used by LyX for simple dots in relative
1871 } else if (t.cs() == "space") {
1874 } else if (t.cs() == "string") {
1875 // Convert \string" to " and \string~ to ~
1876 Token const & n = p.next_token();
1877 if (n.asInput() != "\"" && n.asInput() != "~")
1882 // Strip quotes. This is a bit complicated (see latex_path()).
1883 string full = os.str();
1884 if (!full.empty() && full[0] == '"') {
1885 string base = removeExtension(full);
1886 string ext = getExtension(full);
1887 if (!base.empty() && base[base.length()-1] == '"')
1890 return addExtension(trim(base, "\""), ext);
1891 if (full[full.length()-1] == '"')
1894 return trim(full, "\"");
1900 /// Convert \p name from TeX convention (relative to master file) to LyX
1901 /// convention (relative to .lyx file) if it is relative
1902 void fix_child_filename(string & name)
1904 string const absMasterTeX = getMasterFilePath(true);
1905 bool const isabs = FileName::isAbsolute(name);
1906 // convert from "relative to .tex master" to absolute original path
1908 name = makeAbsPath(name, absMasterTeX).absFileName();
1909 bool copyfile = copyFiles();
1910 string const absParentLyX = getParentFilePath(false);
1913 // convert from absolute original path to "relative to master file"
1914 string const rel = to_utf8(makeRelPath(from_utf8(name),
1915 from_utf8(absMasterTeX)));
1916 // re-interpret "relative to .tex file" as "relative to .lyx file"
1917 // (is different if the master .lyx file resides in a
1918 // different path than the master .tex file)
1919 string const absMasterLyX = getMasterFilePath(false);
1920 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1921 // Do not copy if the new path is impossible to create. Example:
1922 // absMasterTeX = "/foo/bar/"
1923 // absMasterLyX = "/bar/"
1924 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1925 if (contains(name, "/../"))
1932 // convert from absolute original path to
1933 // "relative to .lyx file"
1934 name = to_utf8(makeRelPath(from_utf8(abs),
1935 from_utf8(absParentLyX)));
1939 // convert from absolute original path to "relative to .lyx file"
1940 name = to_utf8(makeRelPath(from_utf8(name),
1941 from_utf8(absParentLyX)));
1946 void copy_file(FileName const & src, string dstname)
1950 string const absParent = getParentFilePath(false);
1952 if (FileName::isAbsolute(dstname))
1953 dst = FileName(dstname);
1955 dst = makeAbsPath(dstname, absParent);
1956 string const absMaster = getMasterFilePath(false);
1957 FileName const srcpath = src.onlyPath();
1958 FileName const dstpath = dst.onlyPath();
1959 if (equivalent(srcpath, dstpath))
1961 if (!dstpath.isDirectory()) {
1962 if (!dstpath.createPath()) {
1963 cerr << "Warning: Could not create directory for file `"
1964 << dst.absFileName() << "´." << endl;
1968 if (dst.isReadableFile()) {
1969 if (overwriteFiles())
1970 cerr << "Warning: Overwriting existing file `"
1971 << dst.absFileName() << "´." << endl;
1973 cerr << "Warning: Not overwriting existing file `"
1974 << dst.absFileName() << "´." << endl;
1978 if (!src.copyTo(dst))
1979 cerr << "Warning: Could not copy file `" << src.absFileName()
1980 << "´ to `" << dst.absFileName() << "´." << endl;
1984 /// Parse a literate Chunk section. The initial "<<" is already parsed.
1985 bool parse_chunk(Parser & p, ostream & os, Context & context)
1987 // check whether a chunk is possible here.
1988 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
1994 // read the parameters
1995 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
1996 if (!params.first) {
2001 Parser::Arg const code = p.verbatimStuff("\n@");
2006 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2007 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2011 // The last newline read is important for paragraph handling
2015 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2016 // We must have a valid layout before outputting the Chunk inset.
2017 context.check_layout(os);
2018 Context chunkcontext(true, context.textclass);
2019 chunkcontext.layout = &context.textclass.plainLayout();
2020 begin_inset(os, "Flex Chunk");
2021 os << "\nstatus open\n";
2022 if (!params.second.empty()) {
2023 chunkcontext.check_layout(os);
2024 Context paramscontext(true, context.textclass);
2025 paramscontext.layout = &context.textclass.plainLayout();
2026 begin_inset(os, "Argument 1");
2027 os << "\nstatus open\n";
2028 output_ert(os, params.second, paramscontext);
2031 output_ert(os, code.second, chunkcontext);
2039 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2040 bool is_macro(Parser & p)
2042 Token first = p.curr_token();
2043 if (first.cat() != catEscape || !p.good())
2045 if (first.cs() == "def")
2047 if (first.cs() != "global" && first.cs() != "long")
2049 Token second = p.get_token();
2051 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2052 second.cat() == catNewline || second.cat() == catComment)) {
2053 second = p.get_token();
2056 bool secondvalid = second.cat() == catEscape;
2058 bool thirdvalid = false;
2059 if (p.good() && first.cs() == "global" && secondvalid &&
2060 second.cs() == "long") {
2061 third = p.get_token();
2063 while (p.good() && !p.isParagraph() &&
2064 (third.cat() == catSpace ||
2065 third.cat() == catNewline ||
2066 third.cat() == catComment)) {
2067 third = p.get_token();
2070 thirdvalid = third.cat() == catEscape;
2072 for (int i = 0; i < pos; ++i)
2077 return (first.cs() == "global" || first.cs() == "long") &&
2078 second.cs() == "def";
2079 return first.cs() == "global" && second.cs() == "long" &&
2080 third.cs() == "def";
2084 /// Parse a macro definition (assumes that is_macro() returned true)
2085 void parse_macro(Parser & p, ostream & os, Context & context)
2087 context.check_layout(os);
2088 Token first = p.curr_token();
2091 string command = first.asInput();
2092 if (first.cs() != "def") {
2094 eat_whitespace(p, os, context, false);
2095 second = p.curr_token();
2096 command += second.asInput();
2097 if (second.cs() != "def") {
2099 eat_whitespace(p, os, context, false);
2100 third = p.curr_token();
2101 command += third.asInput();
2104 eat_whitespace(p, os, context, false);
2105 string const name = p.get_token().cs();
2106 eat_whitespace(p, os, context, false);
2112 while (p.next_token().cat() != catBegin) {
2113 if (p.next_token().cat() == catParameter) {
2118 // followed by number?
2119 if (p.next_token().cat() == catOther) {
2120 string s = p.get_token().asInput();
2122 // number = current arity + 1?
2123 if (s.size() == 1 && s[0] == arity + '0' + 1)
2128 paramtext += p.get_token().cs();
2130 paramtext += p.get_token().cs();
2135 // only output simple (i.e. compatible) macro as FormulaMacros
2136 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2138 context.check_layout(os);
2139 begin_inset(os, "FormulaMacro");
2140 os << "\n\\def" << ert;
2143 output_ert_inset(os, command + ert, context);
2147 void registerExternalTemplatePackages(string const & name)
2149 external::TemplateManager const & etm = external::TemplateManager::get();
2150 external::Template const * const et = etm.getTemplateByName(name);
2153 external::Template::Formats::const_iterator cit = et->formats.end();
2155 cit = et->formats.find("PDFLaTeX");
2156 if (cit == et->formats.end())
2157 // If the template has not specified a PDFLaTeX output,
2158 // we try the LaTeX format.
2159 cit = et->formats.find("LaTeX");
2160 if (cit == et->formats.end())
2162 vector<string>::const_iterator qit = cit->second.requirements.begin();
2163 vector<string>::const_iterator qend = cit->second.requirements.end();
2164 for (; qit != qend; ++qit)
2165 preamble.registerAutomaticallyLoadedPackage(*qit);
2168 } // anonymous namespace
2171 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2174 Layout const * newlayout = 0;
2175 InsetLayout const * newinsetlayout = 0;
2176 char const * const * where = 0;
2177 // Store the latest bibliographystyle, addcontentslineContent and
2178 // nocite{*} option (needed for bibtex inset)
2180 string contentslineContent;
2181 string bibliographystyle = "default";
2182 bool const use_natbib = isProvided("natbib");
2183 bool const use_jurabib = isProvided("jurabib");
2186 // it is impossible to determine the correct encoding for non-CJK Japanese.
2187 // Therefore write a note at the beginning of the document
2188 if (is_nonCJKJapanese) {
2189 context.check_layout(os);
2190 begin_inset(os, "Note Note\n");
2191 os << "status open\n\\begin_layout Plain Layout\n"
2192 << "\\series bold\n"
2193 << "Important information:\n"
2194 << "\\end_layout\n\n"
2195 << "\\begin_layout Plain Layout\n"
2196 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2197 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2198 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2199 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2200 << " and specify the encoding using the -e command-line switch.\n"
2201 << " In addition, you might want to double check that the desired output encoding\n"
2202 << " is correctly selected in Document > Settings > Language.\n"
2203 << "\\end_layout\n";
2205 is_nonCJKJapanese = false;
2209 Token const & t = p.get_token();
2211 debugToken(cerr, t, flags);
2214 if (flags & FLAG_ITEM) {
2215 if (t.cat() == catSpace)
2218 flags &= ~FLAG_ITEM;
2219 if (t.cat() == catBegin) {
2220 // skip the brace and collect everything to the next matching
2222 flags |= FLAG_BRACE_LAST;
2226 // handle only this single token, leave the loop if done
2227 flags |= FLAG_LEAVE;
2230 if (t.cat() != catEscape && t.character() == ']' &&
2231 (flags & FLAG_BRACK_LAST))
2233 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2236 // If there is anything between \end{env} and \begin{env} we
2237 // don't need to output a separator.
2238 if (t.cat() != catSpace && t.cat() != catNewline &&
2239 t.asInput() != "\\begin")
2245 bool const starred = p.next_token().asInput() == "*";
2246 string const starredname(starred ? (t.cs() + '*') : t.cs());
2247 if (t.cat() == catMath) {
2248 // we are inside some text mode thingy, so opening new math is allowed
2249 context.check_layout(os);
2250 begin_inset(os, "Formula ");
2251 Token const & n = p.get_token();
2252 bool const display(n.cat() == catMath && outer);
2254 // TeX's $$...$$ syntax for displayed math
2256 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2258 p.get_token(); // skip the second '$' token
2260 // simple $...$ stuff
2263 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2268 // Prevent the conversion of a line break to a
2269 // space (bug 7668). This does not change the
2270 // output, but looks ugly in LyX.
2271 eat_whitespace(p, os, context, false);
2275 else if (t.cat() == catSuper || t.cat() == catSub)
2276 cerr << "catcode " << t << " illegal in text mode\n";
2278 // Basic support for english quotes. This should be
2279 // extended to other quotes, but is not so easy (a
2280 // left english quote is the same as a right german
2282 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2283 context.check_layout(os);
2284 begin_inset(os, "Quotes ");
2290 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2291 context.check_layout(os);
2292 begin_inset(os, "Quotes ");
2299 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2300 context.check_layout(os);
2301 begin_inset(os, "Quotes ");
2308 else if (t.asInput() == "<"
2309 && p.next_token().asInput() == "<") {
2310 bool has_chunk = false;
2314 has_chunk = parse_chunk(p, os, context);
2320 context.check_layout(os);
2321 begin_inset(os, "Quotes ");
2322 //FIXME: this is a right danish quote;
2323 // why not a left french quote?
2331 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2332 check_space(p, os, context);
2334 else if (t.character() == '[' && noweb_mode &&
2335 p.next_token().character() == '[') {
2336 // These can contain underscores
2338 string const s = p.getFullOpt() + ']';
2339 if (p.next_token().character() == ']')
2342 cerr << "Warning: Inserting missing ']' in '"
2343 << s << "'." << endl;
2344 output_ert_inset(os, s, context);
2347 else if (t.cat() == catLetter) {
2348 context.check_layout(os);
2349 // Workaround for bug 4752.
2350 // FIXME: This whole code block needs to be removed
2351 // when the bug is fixed and tex2lyx produces
2352 // the updated file format.
2353 // The replacement algorithm in LyX is so stupid that
2354 // it even translates a phrase if it is part of a word.
2355 bool handled = false;
2356 for (int const * l = known_phrase_lengths; *l; ++l) {
2357 string phrase = t.cs();
2358 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2359 phrase += p.get_token().cs();
2360 if (is_known(phrase, known_coded_phrases)) {
2361 output_ert_inset(os, phrase, context);
2365 for (size_t i = 1; i < phrase.length(); ++i)
2373 else if (t.cat() == catOther ||
2374 t.cat() == catAlign ||
2375 t.cat() == catParameter) {
2376 // This translates "&" to "\\&" which may be wrong...
2377 context.check_layout(os);
2381 else if (p.isParagraph()) {
2382 if (context.new_layout_allowed)
2383 context.new_paragraph(os);
2385 output_ert_inset(os, "\\par ", context);
2386 eat_whitespace(p, os, context, true);
2389 else if (t.cat() == catActive) {
2390 context.check_layout(os);
2391 if (t.character() == '~') {
2392 if (context.layout->free_spacing)
2395 begin_inset(os, "space ~\n");
2402 else if (t.cat() == catBegin) {
2403 Token const next = p.next_token();
2404 Token const end = p.next_next_token();
2405 if (next.cat() == catEnd) {
2407 Token const prev = p.prev_token();
2409 if (p.next_token().character() == '`' ||
2410 (prev.character() == '-' &&
2411 p.next_token().character() == '-'))
2412 ; // ignore it in {}`` or -{}-
2414 output_ert_inset(os, "{}", context);
2415 } else if (next.cat() == catEscape &&
2416 is_known(next.cs(), known_quotes) &&
2417 end.cat() == catEnd) {
2418 // Something like {\textquoteright} (e.g.
2419 // from writer2latex). LyX writes
2420 // \textquoteright{}, so we may skip the
2421 // braces here for better readability.
2422 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2424 } else if (p.next_token().asInput() == "\\ascii") {
2425 // handle the \ascii characters
2426 // (the case without braces is handled later)
2427 // the code is "{\ascii\xxx}"
2428 p.get_token(); // eat \ascii
2429 string name2 = p.get_token().asInput();
2430 p.get_token(); // eat the final '}'
2431 string const name = "{\\ascii" + name2 + "}";
2435 // get the character from unicodesymbols
2436 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2437 Encodings::TEXT_CMD, termination, rem, &req);
2439 context.check_layout(os);
2442 output_ert_inset(os,
2443 to_utf8(rem), context);
2444 for (set<string>::const_iterator it = req.begin();
2445 it != req.end(); ++it)
2446 preamble.registerAutomaticallyLoadedPackage(*it);
2448 // we did not find a non-ert version
2449 output_ert_inset(os, name, context);
2451 context.check_layout(os);
2452 // special handling of font attribute changes
2453 Token const prev = p.prev_token();
2454 TeXFont const oldFont = context.font;
2455 if (next.character() == '[' ||
2456 next.character() == ']' ||
2457 next.character() == '*') {
2459 if (p.next_token().cat() == catEnd) {
2464 output_ert_inset(os, "{", context);
2465 parse_text_snippet(p, os,
2468 output_ert_inset(os, "}", context);
2470 } else if (! context.new_layout_allowed) {
2471 output_ert_inset(os, "{", context);
2472 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2474 output_ert_inset(os, "}", context);
2475 } else if (is_known(next.cs(), known_sizes)) {
2476 // next will change the size, so we must
2478 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2480 if (!context.atParagraphStart())
2482 << context.font.size << "\n";
2483 } else if (is_known(next.cs(), known_font_families)) {
2484 // next will change the font family, so we
2485 // must reset it here
2486 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2488 if (!context.atParagraphStart())
2490 << context.font.family << "\n";
2491 } else if (is_known(next.cs(), known_font_series)) {
2492 // next will change the font series, so we
2493 // must reset it here
2494 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2496 if (!context.atParagraphStart())
2498 << context.font.series << "\n";
2499 } else if (is_known(next.cs(), known_font_shapes)) {
2500 // next will change the font shape, so we
2501 // must reset it here
2502 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2504 if (!context.atParagraphStart())
2506 << context.font.shape << "\n";
2507 } else if (is_known(next.cs(), known_old_font_families) ||
2508 is_known(next.cs(), known_old_font_series) ||
2509 is_known(next.cs(), known_old_font_shapes)) {
2510 // next will change the font family, series
2511 // and shape, so we must reset it here
2512 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2514 if (!context.atParagraphStart())
2516 << context.font.family
2518 << context.font.series
2520 << context.font.shape << "\n";
2522 output_ert_inset(os, "{", context);
2523 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2525 output_ert_inset(os, "}", context);
2530 else if (t.cat() == catEnd) {
2531 if (flags & FLAG_BRACE_LAST) {
2534 cerr << "stray '}' in text\n";
2535 output_ert_inset(os, "}", context);
2538 else if (t.cat() == catComment)
2539 parse_comment(p, os, t, context);
2542 // control sequences
2545 else if (t.cs() == "(" || t.cs() == "[") {
2546 bool const simple = t.cs() == "(";
2547 context.check_layout(os);
2548 begin_inset(os, "Formula");
2549 os << " \\" << t.cs();
2550 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2551 os << '\\' << (simple ? ')' : ']');
2554 // Prevent the conversion of a line break to a
2555 // space (bug 7668). This does not change the
2556 // output, but looks ugly in LyX.
2557 eat_whitespace(p, os, context, false);
2561 else if (t.cs() == "begin")
2562 parse_environment(p, os, outer, last_env,
2565 else if (t.cs() == "end") {
2566 if (flags & FLAG_END) {
2567 // eat environment name
2568 string const name = p.getArg('{', '}');
2569 if (name != active_environment())
2570 cerr << "\\end{" + name + "} does not match \\begin{"
2571 + active_environment() + "}\n";
2574 p.error("found 'end' unexpectedly");
2577 else if (t.cs() == "item") {
2579 bool const optarg = p.hasOpt();
2581 // FIXME: This swallows comments, but we cannot use
2582 // eat_whitespace() since we must not output
2583 // anything before the item.
2584 p.skip_spaces(true);
2585 s = p.verbatimOption();
2587 p.skip_spaces(false);
2589 context.check_layout(os);
2590 if (context.has_item) {
2591 // An item in an unknown list-like environment
2592 // FIXME: Do this in check_layout()!
2593 context.has_item = false;
2595 output_ert_inset(os, "\\item", context);
2597 output_ert_inset(os, "\\item ", context);
2600 if (context.layout->labeltype != LABEL_MANUAL) {
2601 // handle option of itemize item
2602 begin_inset(os, "Argument item:1\n");
2603 os << "status open\n";
2604 os << "\n\\begin_layout Plain Layout\n";
2606 os << parse_text_snippet(p2,
2607 FLAG_BRACK_LAST, outer, context);
2608 // we must not use context.check_end_layout(os)
2609 // because that would close the outer itemize layout
2610 os << "\n\\end_layout\n";
2612 eat_whitespace(p, os, context, false);
2613 } else if (!s.empty()) {
2614 // LyX adds braces around the argument,
2615 // so we need to remove them here.
2616 if (s.size() > 2 && s[0] == '{' &&
2617 s[s.size()-1] == '}')
2618 s = s.substr(1, s.size()-2);
2619 // If the argument contains a space we
2620 // must put it into ERT: Otherwise LyX
2621 // would misinterpret the space as
2622 // item delimiter (bug 7663)
2623 if (contains(s, ' ')) {
2624 output_ert_inset(os, s, context);
2627 os << parse_text_snippet(p2,
2628 FLAG_BRACK_LAST, outer, context);
2630 // The space is needed to separate the
2631 // item from the rest of the sentence.
2633 eat_whitespace(p, os, context, false);
2638 else if (t.cs() == "bibitem") {
2640 context.check_layout(os);
2641 eat_whitespace(p, os, context, false);
2642 string label = convert_command_inset_arg(p.verbatimOption());
2643 string key = convert_command_inset_arg(p.verbatim_item());
2644 if (contains(label, '\\') || contains(key, '\\')) {
2645 // LyX can't handle LaTeX commands in labels or keys
2646 output_ert_inset(os, t.asInput() + '[' + label +
2647 "]{" + p.verbatim_item() + '}',
2650 begin_command_inset(os, "bibitem", "bibitem");
2651 os << "label \"" << label << "\"\n"
2652 "key \"" << key << "\"\n";
2657 else if (is_macro(p)) {
2658 // catch the case of \def\inputGnumericTable
2660 if (t.cs() == "def") {
2661 Token second = p.next_token();
2662 if (second.cs() == "inputGnumericTable") {
2666 Token third = p.get_token();
2668 if (third.cs() == "input") {
2672 string name = normalize_filename(p.verbatim_item());
2673 string const path = getMasterFilePath(true);
2674 // We want to preserve relative / absolute filenames,
2675 // therefore path is only used for testing
2676 // The file extension is in every case ".tex".
2677 // So we need to remove this extension and check for
2678 // the original one.
2679 name = removeExtension(name);
2680 if (!makeAbsPath(name, path).exists()) {
2681 char const * const Gnumeric_formats[] = {"gnumeric",
2683 string const Gnumeric_name =
2684 find_file(name, path, Gnumeric_formats);
2685 if (!Gnumeric_name.empty())
2686 name = Gnumeric_name;
2688 FileName const absname = makeAbsPath(name, path);
2689 if (absname.exists()) {
2690 fix_child_filename(name);
2691 copy_file(absname, name);
2693 cerr << "Warning: Could not find file '"
2694 << name << "'." << endl;
2695 context.check_layout(os);
2696 begin_inset(os, "External\n\ttemplate ");
2697 os << "GnumericSpreadsheet\n\tfilename "
2700 context.check_layout(os);
2702 // register the packages that are automatically loaded
2703 // by the Gnumeric template
2704 registerExternalTemplatePackages("GnumericSpreadsheet");
2709 parse_macro(p, os, context);
2712 else if (t.cs() == "noindent") {
2714 context.add_par_extra_stuff("\\noindent\n");
2717 else if (t.cs() == "appendix") {
2718 context.add_par_extra_stuff("\\start_of_appendix\n");
2719 // We need to start a new paragraph. Otherwise the
2720 // appendix in 'bla\appendix\chapter{' would start
2722 context.new_paragraph(os);
2723 // We need to make sure that the paragraph is
2724 // generated even if it is empty. Otherwise the
2725 // appendix in '\par\appendix\par\chapter{' would
2727 context.check_layout(os);
2728 // FIXME: This is a hack to prevent paragraph
2729 // deletion if it is empty. Handle this better!
2730 output_ert_inset(os,
2731 "%dummy comment inserted by tex2lyx to "
2732 "ensure that this paragraph is not empty",
2734 // Both measures above may generate an additional
2735 // empty paragraph, but that does not hurt, because
2736 // whitespace does not matter here.
2737 eat_whitespace(p, os, context, true);
2740 // Must catch empty dates before findLayout is called below
2741 else if (t.cs() == "date") {
2742 eat_whitespace(p, os, context, false);
2744 string const date = p.verbatim_item();
2747 preamble.suppressDate(true);
2750 preamble.suppressDate(false);
2751 if (context.new_layout_allowed &&
2752 (newlayout = findLayout(context.textclass,
2755 output_command_layout(os, p, outer,
2756 context, newlayout);
2757 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2758 if (!preamble.titleLayoutFound())
2759 preamble.titleLayoutFound(newlayout->intitle);
2760 set<string> const & req = newlayout->requires();
2761 set<string>::const_iterator it = req.begin();
2762 set<string>::const_iterator en = req.end();
2763 for (; it != en; ++it)
2764 preamble.registerAutomaticallyLoadedPackage(*it);
2766 output_ert_inset(os,
2767 "\\date{" + p.verbatim_item() + '}',
2772 // Starred section headings
2773 // Must attempt to parse "Section*" before "Section".
2774 else if ((p.next_token().asInput() == "*") &&
2775 context.new_layout_allowed &&
2776 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2779 output_command_layout(os, p, outer, context, newlayout);
2781 if (!preamble.titleLayoutFound())
2782 preamble.titleLayoutFound(newlayout->intitle);
2783 set<string> const & req = newlayout->requires();
2784 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2785 preamble.registerAutomaticallyLoadedPackage(*it);
2788 // Section headings and the like
2789 else if (context.new_layout_allowed &&
2790 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2792 output_command_layout(os, p, outer, context, newlayout);
2794 if (!preamble.titleLayoutFound())
2795 preamble.titleLayoutFound(newlayout->intitle);
2796 set<string> const & req = newlayout->requires();
2797 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2798 preamble.registerAutomaticallyLoadedPackage(*it);
2801 else if (t.cs() == "subfloat") {
2802 // the syntax is \subfloat[caption]{content}
2803 // if it is a table of figure depends on the surrounding float
2804 bool has_caption = false;
2806 // do nothing if there is no outer float
2807 if (!float_type.empty()) {
2808 context.check_layout(os);
2810 begin_inset(os, "Float " + float_type + "\n");
2812 << "\nsideways false"
2813 << "\nstatus collapsed\n\n";
2816 if (p.next_token().cat() != catEscape &&
2817 p.next_token().character() == '[') {
2818 p.get_token(); // eat '['
2819 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2823 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2824 // the caption comes always as the last
2826 // we must make sure that the caption gets a \begin_layout
2827 os << "\n\\begin_layout Plain Layout";
2829 begin_inset(os, "Caption Standard\n");
2830 Context newcontext(true, context.textclass,
2831 0, 0, context.font);
2832 newcontext.check_layout(os);
2833 os << caption << "\n";
2834 newcontext.check_end_layout(os);
2835 // We don't need really a new paragraph, but
2836 // we must make sure that the next item gets a \begin_layout.
2837 //newcontext.new_paragraph(os);
2841 // We don't need really a new paragraph, but
2842 // we must make sure that the next item gets a \begin_layout.
2844 context.new_paragraph(os);
2847 context.check_end_layout(os);
2848 // close the layout we opened
2850 os << "\n\\end_layout\n";
2852 // if the float type is not supported or there is no surrounding float
2855 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2856 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2857 "]{" + p.verbatim_item() + '}', context);
2859 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2863 else if (t.cs() == "includegraphics") {
2864 bool const clip = p.next_token().asInput() == "*";
2867 string const arg = p.getArg('[', ']');
2868 map<string, string> opts;
2869 vector<string> keys;
2870 split_map(arg, opts, keys);
2872 opts["clip"] = string();
2873 string name = normalize_filename(p.verbatim_item());
2875 string const path = getMasterFilePath(true);
2876 // We want to preserve relative / absolute filenames,
2877 // therefore path is only used for testing
2878 if (!makeAbsPath(name, path).exists()) {
2879 // The file extension is probably missing.
2880 // Now try to find it out.
2881 string const dvips_name =
2882 find_file(name, path,
2883 known_dvips_graphics_formats);
2884 string const pdftex_name =
2885 find_file(name, path,
2886 known_pdftex_graphics_formats);
2887 if (!dvips_name.empty()) {
2888 if (!pdftex_name.empty()) {
2889 cerr << "This file contains the "
2891 "\"\\includegraphics{"
2893 "However, files\n\""
2894 << dvips_name << "\" and\n\""
2895 << pdftex_name << "\"\n"
2896 "both exist, so I had to make a "
2897 "choice and took the first one.\n"
2898 "Please move the unwanted one "
2899 "someplace else and try again\n"
2900 "if my choice was wrong."
2904 } else if (!pdftex_name.empty()) {
2910 FileName const absname = makeAbsPath(name, path);
2911 if (absname.exists()) {
2912 fix_child_filename(name);
2913 copy_file(absname, name);
2915 cerr << "Warning: Could not find graphics file '"
2916 << name << "'." << endl;
2918 context.check_layout(os);
2919 begin_inset(os, "Graphics ");
2920 os << "\n\tfilename " << name << '\n';
2921 if (opts.find("width") != opts.end())
2923 << translate_len(opts["width"]) << '\n';
2924 if (opts.find("height") != opts.end())
2926 << translate_len(opts["height"]) << '\n';
2927 if (opts.find("scale") != opts.end()) {
2928 istringstream iss(opts["scale"]);
2932 os << "\tscale " << val << '\n';
2934 if (opts.find("angle") != opts.end()) {
2935 os << "\trotateAngle "
2936 << opts["angle"] << '\n';
2937 vector<string>::const_iterator a =
2938 find(keys.begin(), keys.end(), "angle");
2939 vector<string>::const_iterator s =
2940 find(keys.begin(), keys.end(), "width");
2941 if (s == keys.end())
2942 s = find(keys.begin(), keys.end(), "height");
2943 if (s == keys.end())
2944 s = find(keys.begin(), keys.end(), "scale");
2945 if (s != keys.end() && distance(s, a) > 0)
2946 os << "\tscaleBeforeRotation\n";
2948 if (opts.find("origin") != opts.end()) {
2950 string const opt = opts["origin"];
2951 if (opt.find('l') != string::npos) ss << "left";
2952 if (opt.find('r') != string::npos) ss << "right";
2953 if (opt.find('c') != string::npos) ss << "center";
2954 if (opt.find('t') != string::npos) ss << "Top";
2955 if (opt.find('b') != string::npos) ss << "Bottom";
2956 if (opt.find('B') != string::npos) ss << "Baseline";
2957 if (!ss.str().empty())
2958 os << "\trotateOrigin " << ss.str() << '\n';
2960 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2962 if (opts.find("keepaspectratio") != opts.end())
2963 os << "\tkeepAspectRatio\n";
2964 if (opts.find("clip") != opts.end())
2966 if (opts.find("draft") != opts.end())
2968 if (opts.find("bb") != opts.end())
2969 os << "\tBoundingBox "
2970 << opts["bb"] << '\n';
2971 int numberOfbbOptions = 0;
2972 if (opts.find("bbllx") != opts.end())
2973 numberOfbbOptions++;
2974 if (opts.find("bblly") != opts.end())
2975 numberOfbbOptions++;
2976 if (opts.find("bburx") != opts.end())
2977 numberOfbbOptions++;
2978 if (opts.find("bbury") != opts.end())
2979 numberOfbbOptions++;
2980 if (numberOfbbOptions == 4)
2981 os << "\tBoundingBox "
2982 << opts["bbllx"] << " " << opts["bblly"] << " "
2983 << opts["bburx"] << " " << opts["bbury"] << '\n';
2984 else if (numberOfbbOptions > 0)
2985 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2986 numberOfbbOptions = 0;
2987 if (opts.find("natwidth") != opts.end())
2988 numberOfbbOptions++;
2989 if (opts.find("natheight") != opts.end())
2990 numberOfbbOptions++;
2991 if (numberOfbbOptions == 2)
2992 os << "\tBoundingBox 0bp 0bp "
2993 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2994 else if (numberOfbbOptions > 0)
2995 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2996 ostringstream special;
2997 if (opts.find("hiresbb") != opts.end())
2998 special << "hiresbb,";
2999 if (opts.find("trim") != opts.end())
3001 if (opts.find("viewport") != opts.end())
3002 special << "viewport=" << opts["viewport"] << ',';
3003 if (opts.find("totalheight") != opts.end())
3004 special << "totalheight=" << opts["totalheight"] << ',';
3005 if (opts.find("type") != opts.end())
3006 special << "type=" << opts["type"] << ',';
3007 if (opts.find("ext") != opts.end())
3008 special << "ext=" << opts["ext"] << ',';
3009 if (opts.find("read") != opts.end())
3010 special << "read=" << opts["read"] << ',';
3011 if (opts.find("command") != opts.end())
3012 special << "command=" << opts["command"] << ',';
3013 string s_special = special.str();
3014 if (!s_special.empty()) {
3015 // We had special arguments. Remove the trailing ','.
3016 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3018 // TODO: Handle the unknown settings better.
3019 // Warn about invalid options.
3020 // Check whether some option was given twice.
3022 preamble.registerAutomaticallyLoadedPackage("graphicx");
3025 else if (t.cs() == "footnote" ||
3026 (t.cs() == "thanks" && context.layout->intitle)) {
3028 context.check_layout(os);
3029 begin_inset(os, "Foot\n");
3030 os << "status collapsed\n\n";
3031 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3035 else if (t.cs() == "marginpar") {
3037 context.check_layout(os);
3038 begin_inset(os, "Marginal\n");
3039 os << "status collapsed\n\n";
3040 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3044 else if (t.cs() == "lstinline") {
3046 parse_listings(p, os, context, true);
3049 else if (t.cs() == "ensuremath") {
3051 context.check_layout(os);
3052 string const s = p.verbatim_item();
3053 //FIXME: this never triggers in UTF8
3054 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3057 output_ert_inset(os, "\\ensuremath{" + s + "}",
3061 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3062 if (preamble.titleLayoutFound()) {
3064 skip_spaces_braces(p);
3066 output_ert_inset(os, t.asInput(), context);
3069 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3070 context.check_layout(os);
3071 begin_command_inset(os, "toc", t.cs());
3073 skip_spaces_braces(p);
3074 if (t.cs() == "lstlistoflistings")
3075 preamble.registerAutomaticallyLoadedPackage("listings");
3078 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3079 context.check_layout(os);
3080 if (t.cs() == "listoffigures")
3081 begin_inset(os, "FloatList figure\n");
3083 begin_inset(os, "FloatList table\n");
3085 skip_spaces_braces(p);
3088 else if (t.cs() == "listof") {
3089 p.skip_spaces(true);
3090 string const name = p.get_token().cs();
3091 if (context.textclass.floats().typeExist(name)) {
3092 context.check_layout(os);
3093 begin_inset(os, "FloatList ");
3096 p.get_token(); // swallow second arg
3098 output_ert_inset(os, "\\listof{" + name + "}", context);
3101 else if ((where = is_known(t.cs(), known_text_font_families)))
3102 parse_text_attributes(p, os, FLAG_ITEM, outer,
3103 context, "\\family", context.font.family,
3104 known_coded_font_families[where - known_text_font_families]);
3106 else if ((where = is_known(t.cs(), known_text_font_series)))
3107 parse_text_attributes(p, os, FLAG_ITEM, outer,
3108 context, "\\series", context.font.series,
3109 known_coded_font_series[where - known_text_font_series]);
3111 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3112 parse_text_attributes(p, os, FLAG_ITEM, outer,
3113 context, "\\shape", context.font.shape,
3114 known_coded_font_shapes[where - known_text_font_shapes]);
3116 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3117 context.check_layout(os);
3118 TeXFont oldFont = context.font;
3119 context.font.init();
3120 context.font.size = oldFont.size;
3121 os << "\n\\family " << context.font.family << "\n";
3122 os << "\n\\series " << context.font.series << "\n";
3123 os << "\n\\shape " << context.font.shape << "\n";
3124 if (t.cs() == "textnormal") {
3125 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3126 output_font_change(os, context.font, oldFont);
3127 context.font = oldFont;
3129 eat_whitespace(p, os, context, false);
3132 else if (t.cs() == "textcolor") {
3133 // scheme is \textcolor{color name}{text}
3134 string const color = p.verbatim_item();
3135 // we only support the predefined colors of the color package
3136 if (color == "black" || color == "blue" || color == "cyan"
3137 || color == "green" || color == "magenta" || color == "red"
3138 || color == "white" || color == "yellow") {
3139 context.check_layout(os);
3140 os << "\n\\color " << color << "\n";
3141 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3142 context.check_layout(os);
3143 os << "\n\\color inherit\n";
3144 preamble.registerAutomaticallyLoadedPackage("color");
3146 // for custom defined colors
3147 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3150 else if (t.cs() == "underbar" || t.cs() == "uline") {
3151 // \underbar is not 100% correct (LyX outputs \uline
3152 // of ulem.sty). The difference is that \ulem allows
3153 // line breaks, and \underbar does not.
3154 // Do NOT handle \underline.
3155 // \underbar cuts through y, g, q, p etc.,
3156 // \underline does not.
3157 context.check_layout(os);
3158 os << "\n\\bar under\n";
3159 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3160 context.check_layout(os);
3161 os << "\n\\bar default\n";
3162 preamble.registerAutomaticallyLoadedPackage("ulem");
3165 else if (t.cs() == "sout") {
3166 context.check_layout(os);
3167 os << "\n\\strikeout on\n";
3168 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3169 context.check_layout(os);
3170 os << "\n\\strikeout default\n";
3171 preamble.registerAutomaticallyLoadedPackage("ulem");
3174 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3175 t.cs() == "emph" || t.cs() == "noun") {
3176 context.check_layout(os);
3177 os << "\n\\" << t.cs() << " on\n";
3178 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3179 context.check_layout(os);
3180 os << "\n\\" << t.cs() << " default\n";
3181 if (t.cs() == "uuline" || t.cs() == "uwave")
3182 preamble.registerAutomaticallyLoadedPackage("ulem");
3185 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3186 context.check_layout(os);
3187 string name = p.getArg('{', '}');
3188 string localtime = p.getArg('{', '}');
3189 preamble.registerAuthor(name);
3190 Author const & author = preamble.getAuthor(name);
3191 // from_asctime_utc() will fail if LyX decides to output the
3192 // time in the text language.
3193 time_t ptime = from_asctime_utc(localtime);
3194 if (ptime == static_cast<time_t>(-1)) {
3195 cerr << "Warning: Could not parse time `" << localtime
3196 << "´ for change tracking, using current time instead.\n";
3197 ptime = current_time();
3199 if (t.cs() == "lyxadded")
3200 os << "\n\\change_inserted ";
3202 os << "\n\\change_deleted ";
3203 os << author.bufferId() << ' ' << ptime << '\n';
3204 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3205 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3206 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3207 LaTeXPackages::isAvailable("xcolor");
3208 // No need to test for luatex, since luatex comes in
3209 // two flavours (dvi and pdf), like latex, and those
3210 // are detected by pdflatex.
3211 if (pdflatex || xetex) {
3213 preamble.registerAutomaticallyLoadedPackage("ulem");
3214 preamble.registerAutomaticallyLoadedPackage("xcolor");
3215 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3219 preamble.registerAutomaticallyLoadedPackage("dvipost");
3220 } else if (xcolorulem) {
3221 preamble.registerAutomaticallyLoadedPackage("ulem");
3222 preamble.registerAutomaticallyLoadedPackage("xcolor");
3227 else if (t.cs() == "textipa") {
3228 context.check_layout(os);
3229 begin_inset(os, "IPA\n");
3230 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3232 preamble.registerAutomaticallyLoadedPackage("tipa");
3233 preamble.registerAutomaticallyLoadedPackage("tipx");
3236 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3237 context.check_layout(os);
3238 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3239 os << "status open\n";
3240 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3245 else if (t.cs() == "textvertline") {
3246 // FIXME: This is not correct, \textvertline is higher than |
3252 else if (t.cs() == "tone" ) {
3253 context.check_layout(os);
3254 // register the tone package
3255 preamble.registerAutomaticallyLoadedPackage("tone");
3256 string content = trimSpaceAndEol(p.verbatim_item());
3257 string command = t.asInput() + "{" + content + "}";
3258 // some tones can be detected by unicodesymbols, some need special code
3259 if (is_known(content, known_tones)) {
3260 os << "\\IPAChar " << command << "\n";
3263 // try to see whether the string is in unicodesymbols
3267 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3268 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3269 termination, rem, &req);
3273 output_ert_inset(os, to_utf8(rem), context);
3274 for (set<string>::const_iterator it = req.begin();
3275 it != req.end(); ++it)
3276 preamble.registerAutomaticallyLoadedPackage(*it);
3278 // we did not find a non-ert version
3279 output_ert_inset(os, command, context);
3282 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3283 t.cs() == "vphantom") {
3284 context.check_layout(os);
3285 if (t.cs() == "phantom")
3286 begin_inset(os, "Phantom Phantom\n");
3287 if (t.cs() == "hphantom")
3288 begin_inset(os, "Phantom HPhantom\n");
3289 if (t.cs() == "vphantom")
3290 begin_inset(os, "Phantom VPhantom\n");
3291 os << "status open\n";
3292 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3297 else if (t.cs() == "href") {
3298 context.check_layout(os);
3299 string target = convert_command_inset_arg(p.verbatim_item());
3300 string name = convert_command_inset_arg(p.verbatim_item());
3302 size_t i = target.find(':');
3303 if (i != string::npos) {
3304 type = target.substr(0, i + 1);
3305 if (type == "mailto:" || type == "file:")
3306 target = target.substr(i + 1);
3307 // handle the case that name is equal to target, except of "http://"
3308 else if (target.substr(i + 3) == name && type == "http:")
3311 begin_command_inset(os, "href", "href");
3313 os << "name \"" << name << "\"\n";
3314 os << "target \"" << target << "\"\n";
3315 if (type == "mailto:" || type == "file:")
3316 os << "type \"" << type << "\"\n";
3318 skip_spaces_braces(p);
3321 else if (t.cs() == "lyxline") {
3322 // swallow size argument (it is not used anyway)
3324 if (!context.atParagraphStart()) {
3325 // so our line is in the middle of a paragraph
3326 // we need to add a new line, lest this line
3327 // follow the other content on that line and
3328 // run off the side of the page
3329 // FIXME: This may create an empty paragraph,
3330 // but without that it would not be
3331 // possible to set noindent below.
3332 // Fortunately LaTeX does not care
3333 // about the empty paragraph.
3334 context.new_paragraph(os);
3336 if (preamble.indentParagraphs()) {
3337 // we need to unindent, lest the line be too long
3338 context.add_par_extra_stuff("\\noindent\n");
3340 context.check_layout(os);
3341 begin_command_inset(os, "line", "rule");
3342 os << "offset \"0.5ex\"\n"
3343 "width \"100line%\"\n"
3348 else if (t.cs() == "rule") {
3349 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3350 string const width = p.getArg('{', '}');
3351 string const thickness = p.getArg('{', '}');
3352 context.check_layout(os);
3353 begin_command_inset(os, "line", "rule");
3354 if (!offset.empty())
3355 os << "offset \"" << translate_len(offset) << "\"\n";
3356 os << "width \"" << translate_len(width) << "\"\n"
3357 "height \"" << translate_len(thickness) << "\"\n";
3361 else if (is_known(t.cs(), known_phrases) ||
3362 (t.cs() == "protect" &&
3363 p.next_token().cat() == catEscape &&
3364 is_known(p.next_token().cs(), known_phrases))) {
3365 // LyX sometimes puts a \protect in front, so we have to ignore it
3366 // FIXME: This needs to be changed when bug 4752 is fixed.
3368 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3370 context.check_layout(os);
3371 os << known_coded_phrases[where - known_phrases];
3372 skip_spaces_braces(p);
3375 // handle refstyle first to catch \eqref which can also occur
3376 // without refstyle. Only recognize these commands if
3377 // refstyle.sty was found in the preamble (otherwise \eqref
3378 // and user defined ref commands could be misdetected).
3379 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3380 preamble.refstyle()) {
3381 context.check_layout(os);
3382 begin_command_inset(os, "ref", "formatted");
3383 os << "reference \"";
3384 os << known_refstyle_prefixes[where - known_refstyle_commands]
3386 os << convert_command_inset_arg(p.verbatim_item())
3389 preamble.registerAutomaticallyLoadedPackage("refstyle");
3392 // if refstyle is used, we must not convert \prettyref to a
3393 // formatted reference, since that would result in a refstyle command.
3394 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3395 (t.cs() != "prettyref" || !preamble.refstyle())) {
3396 string const opt = p.getOpt();
3398 context.check_layout(os);
3399 begin_command_inset(os, "ref",
3400 known_coded_ref_commands[where - known_ref_commands]);
3401 os << "reference \""
3402 << convert_command_inset_arg(p.verbatim_item())
3405 if (t.cs() == "vref" || t.cs() == "vpageref")
3406 preamble.registerAutomaticallyLoadedPackage("varioref");
3407 else if (t.cs() == "prettyref")
3408 preamble.registerAutomaticallyLoadedPackage("prettyref");
3410 // LyX does not yet support optional arguments of ref commands
3411 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3412 p.verbatim_item() + '}', context);
3416 else if (use_natbib &&
3417 is_known(t.cs(), known_natbib_commands) &&
3418 ((t.cs() != "citefullauthor" &&
3419 t.cs() != "citeyear" &&
3420 t.cs() != "citeyearpar") ||
3421 p.next_token().asInput() != "*")) {
3422 context.check_layout(os);
3423 string command = t.cs();
3424 if (p.next_token().asInput() == "*") {
3428 if (command == "citefullauthor")
3429 // alternative name for "\\citeauthor*"
3430 command = "citeauthor*";
3432 // text before the citation
3434 // text after the citation
3436 get_cite_arguments(p, true, before, after);
3438 if (command == "cite") {
3439 // \cite without optional argument means
3440 // \citet, \cite with at least one optional
3441 // argument means \citep.
3442 if (before.empty() && after.empty())
3447 if (before.empty() && after == "[]")
3448 // avoid \citet[]{a}
3450 else if (before == "[]" && after == "[]") {
3451 // avoid \citet[][]{a}
3455 // remove the brackets around after and before
3456 if (!after.empty()) {
3458 after.erase(after.length() - 1, 1);
3459 after = convert_command_inset_arg(after);
3461 if (!before.empty()) {
3463 before.erase(before.length() - 1, 1);
3464 before = convert_command_inset_arg(before);
3466 begin_command_inset(os, "citation", command);
3467 os << "after " << '"' << after << '"' << "\n";
3468 os << "before " << '"' << before << '"' << "\n";
3470 << convert_command_inset_arg(p.verbatim_item())
3473 // Need to set the cite engine if natbib is loaded by
3474 // the document class directly
3475 if (preamble.citeEngine() == "basic")
3476 preamble.citeEngine("natbib");
3479 else if (use_jurabib &&
3480 is_known(t.cs(), known_jurabib_commands) &&
3481 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3482 context.check_layout(os);
3483 string command = t.cs();
3484 if (p.next_token().asInput() == "*") {
3488 char argumentOrder = '\0';
3489 vector<string> const options =
3490 preamble.getPackageOptions("jurabib");
3491 if (find(options.begin(), options.end(),
3492 "natbiborder") != options.end())
3493 argumentOrder = 'n';
3494 else if (find(options.begin(), options.end(),
3495 "jurabiborder") != options.end())
3496 argumentOrder = 'j';
3498 // text before the citation
3500 // text after the citation
3502 get_cite_arguments(p, argumentOrder != 'j', before, after);
3504 string const citation = p.verbatim_item();
3505 if (!before.empty() && argumentOrder == '\0') {
3506 cerr << "Warning: Assuming argument order "
3507 "of jurabib version 0.6 for\n'"
3508 << command << before << after << '{'
3509 << citation << "}'.\n"
3510 "Add 'jurabiborder' to the jurabib "
3511 "package options if you used an\n"
3512 "earlier jurabib version." << endl;
3514 if (!after.empty()) {
3516 after.erase(after.length() - 1, 1);
3518 if (!before.empty()) {
3520 before.erase(before.length() - 1, 1);
3522 begin_command_inset(os, "citation", command);
3523 os << "after " << '"' << after << '"' << "\n";
3524 os << "before " << '"' << before << '"' << "\n";
3525 os << "key " << '"' << citation << '"' << "\n";
3527 // Need to set the cite engine if jurabib is loaded by
3528 // the document class directly
3529 if (preamble.citeEngine() == "basic")
3530 preamble.citeEngine("jurabib");
3533 else if (t.cs() == "cite"
3534 || t.cs() == "nocite") {
3535 context.check_layout(os);
3536 string after = convert_command_inset_arg(p.getArg('[', ']'));
3537 string key = convert_command_inset_arg(p.verbatim_item());
3538 // store the case that it is "\nocite{*}" to use it later for
3541 begin_command_inset(os, "citation", t.cs());
3542 os << "after " << '"' << after << '"' << "\n";
3543 os << "key " << '"' << key << '"' << "\n";
3545 } else if (t.cs() == "nocite")
3549 else if (t.cs() == "index" ||
3550 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3551 context.check_layout(os);
3552 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3553 p.getArg('[', ']') : "";
3554 string const kind = arg.empty() ? "idx" : arg;
3555 begin_inset(os, "Index ");
3556 os << kind << "\nstatus collapsed\n";
3557 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3560 preamble.registerAutomaticallyLoadedPackage("splitidx");
3563 else if (t.cs() == "nomenclature") {
3564 context.check_layout(os);
3565 begin_command_inset(os, "nomenclature", "nomenclature");
3566 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3567 if (!prefix.empty())
3568 os << "prefix " << '"' << prefix << '"' << "\n";
3569 os << "symbol " << '"'
3570 << convert_command_inset_arg(p.verbatim_item());
3571 os << "\"\ndescription \""
3572 << convert_command_inset_arg(p.verbatim_item())
3575 preamble.registerAutomaticallyLoadedPackage("nomencl");
3578 else if (t.cs() == "label") {
3579 context.check_layout(os);
3580 begin_command_inset(os, "label", "label");
3582 << convert_command_inset_arg(p.verbatim_item())
3587 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3588 context.check_layout(os);
3589 string commandname = t.cs();
3591 if (p.next_token().asInput() == "*") {
3596 begin_command_inset(os, "index_print", commandname);
3597 string const indexname = p.getArg('[', ']');
3599 if (indexname.empty())
3600 os << "type \"idx\"\n";
3602 os << "type \"" << indexname << "\"\n";
3605 skip_spaces_braces(p);
3606 preamble.registerAutomaticallyLoadedPackage("makeidx");
3607 if (preamble.use_indices() == "true")
3608 preamble.registerAutomaticallyLoadedPackage("splitidx");
3611 else if (t.cs() == "printnomenclature") {
3613 string width_type = "";
3614 context.check_layout(os);
3615 begin_command_inset(os, "nomencl_print", "printnomenclature");
3616 // case of a custom width
3618 width = p.getArg('[', ']');
3619 width = translate_len(width);
3620 width_type = "custom";
3622 // case of no custom width
3623 // the case of no custom width but the width set
3624 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3625 // because the user could have set anything, not only the width
3626 // of the longest label (which would be width_type = "auto")
3627 string label = convert_command_inset_arg(p.getArg('{', '}'));
3628 if (label.empty() && width_type.empty())
3629 width_type = "none";
3630 os << "set_width \"" << width_type << "\"\n";
3631 if (width_type == "custom")
3632 os << "width \"" << width << '\"';
3634 skip_spaces_braces(p);
3635 preamble.registerAutomaticallyLoadedPackage("nomencl");
3638 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3639 context.check_layout(os);
3640 begin_inset(os, "script ");
3641 os << t.cs().substr(4) << '\n';
3642 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3644 if (t.cs() == "textsubscript")
3645 preamble.registerAutomaticallyLoadedPackage("subscript");
3648 else if ((where = is_known(t.cs(), known_quotes))) {
3649 context.check_layout(os);
3650 begin_inset(os, "Quotes ");
3651 os << known_coded_quotes[where - known_quotes];
3653 // LyX adds {} after the quote, so we have to eat
3654 // spaces here if there are any before a possible
3656 eat_whitespace(p, os, context, false);
3660 else if ((where = is_known(t.cs(), known_sizes)) &&
3661 context.new_layout_allowed) {
3662 context.check_layout(os);
3663 TeXFont const oldFont = context.font;
3664 context.font.size = known_coded_sizes[where - known_sizes];
3665 output_font_change(os, oldFont, context.font);
3666 eat_whitespace(p, os, context, false);
3669 else if ((where = is_known(t.cs(), known_font_families)) &&
3670 context.new_layout_allowed) {
3671 context.check_layout(os);
3672 TeXFont const oldFont = context.font;
3673 context.font.family =
3674 known_coded_font_families[where - known_font_families];
3675 output_font_change(os, oldFont, context.font);
3676 eat_whitespace(p, os, context, false);
3679 else if ((where = is_known(t.cs(), known_font_series)) &&
3680 context.new_layout_allowed) {
3681 context.check_layout(os);
3682 TeXFont const oldFont = context.font;
3683 context.font.series =
3684 known_coded_font_series[where - known_font_series];
3685 output_font_change(os, oldFont, context.font);
3686 eat_whitespace(p, os, context, false);
3689 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3690 context.new_layout_allowed) {
3691 context.check_layout(os);
3692 TeXFont const oldFont = context.font;
3693 context.font.shape =
3694 known_coded_font_shapes[where - known_font_shapes];
3695 output_font_change(os, oldFont, context.font);
3696 eat_whitespace(p, os, context, false);
3698 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3699 context.new_layout_allowed) {
3700 context.check_layout(os);
3701 TeXFont const oldFont = context.font;
3702 context.font.init();
3703 context.font.size = oldFont.size;
3704 context.font.family =
3705 known_coded_font_families[where - known_old_font_families];
3706 output_font_change(os, oldFont, context.font);
3707 eat_whitespace(p, os, context, false);
3710 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3711 context.new_layout_allowed) {
3712 context.check_layout(os);
3713 TeXFont const oldFont = context.font;
3714 context.font.init();
3715 context.font.size = oldFont.size;
3716 context.font.series =
3717 known_coded_font_series[where - known_old_font_series];
3718 output_font_change(os, oldFont, context.font);
3719 eat_whitespace(p, os, context, false);
3722 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3723 context.new_layout_allowed) {
3724 context.check_layout(os);
3725 TeXFont const oldFont = context.font;
3726 context.font.init();
3727 context.font.size = oldFont.size;
3728 context.font.shape =
3729 known_coded_font_shapes[where - known_old_font_shapes];
3730 output_font_change(os, oldFont, context.font);
3731 eat_whitespace(p, os, context, false);
3734 else if (t.cs() == "selectlanguage") {
3735 context.check_layout(os);
3736 // save the language for the case that a
3737 // \foreignlanguage is used
3738 context.font.language = babel2lyx(p.verbatim_item());
3739 os << "\n\\lang " << context.font.language << "\n";
3742 else if (t.cs() == "foreignlanguage") {
3743 string const lang = babel2lyx(p.verbatim_item());
3744 parse_text_attributes(p, os, FLAG_ITEM, outer,
3746 context.font.language, lang);
3749 else if (prefixIs(t.cs(), "text")
3750 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3751 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3753 // We have to output the whole command if it has an option
3754 // because LyX doesn't support this yet, see bug #8214,
3755 // only if there is a single option specifying a variant, we can handle it.
3757 string langopts = p.getOpt();
3758 // check if the option contains a variant, if yes, extract it
3759 string::size_type pos_var = langopts.find("variant");
3760 string::size_type i = langopts.find(',');
3761 string::size_type k = langopts.find('=', pos_var);
3762 if (pos_var != string::npos && i == string::npos) {
3764 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3765 lang = preamble.polyglossia2lyx(variant);
3766 parse_text_attributes(p, os, FLAG_ITEM, outer,
3768 context.font.language, lang);
3770 output_ert_inset(os, t.asInput() + langopts, context);
3772 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3773 parse_text_attributes(p, os, FLAG_ITEM, outer,
3775 context.font.language, lang);
3779 else if (t.cs() == "inputencoding") {
3780 // nothing to write here
3781 string const enc = subst(p.verbatim_item(), "\n", " ");
3782 p.setEncoding(enc, Encoding::inputenc);
3785 else if ((where = is_known(t.cs(), known_special_chars))) {
3786 context.check_layout(os);
3787 os << known_coded_special_chars[where - known_special_chars];
3788 skip_spaces_braces(p);
3791 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3792 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3793 context.check_layout(os);
3794 os << "\\SpecialChar \\" << t.cs()
3795 << p.get_token().asInput() << '\n';
3798 else if (t.cs() == "textquotedbl") {
3799 context.check_layout(os);
3804 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3805 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3806 || t.cs() == "%" || t.cs() == "-") {
3807 context.check_layout(os);
3809 os << "\\SpecialChar \\-\n";
3814 else if (t.cs() == "char") {
3815 context.check_layout(os);
3816 if (p.next_token().character() == '`') {
3818 if (p.next_token().cs() == "\"") {
3823 output_ert_inset(os, "\\char`", context);
3826 output_ert_inset(os, "\\char", context);
3830 else if (t.cs() == "verb") {
3831 context.check_layout(os);
3832 // set catcodes to verbatim early, just in case.
3833 p.setCatcodes(VERBATIM_CATCODES);
3834 string delim = p.get_token().asInput();
3835 Parser::Arg arg = p.verbatimStuff(delim);
3837 output_ert_inset(os, "\\verb" + delim
3838 + arg.second + delim, context);
3840 cerr << "invalid \\verb command. Skipping" << endl;
3843 // Problem: \= creates a tabstop inside the tabbing environment
3844 // and else an accent. In the latter case we really would want
3845 // \={o} instead of \= o.
3846 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3847 output_ert_inset(os, t.asInput(), context);
3849 else if (t.cs() == "\\") {
3850 context.check_layout(os);
3852 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3853 else if (p.next_token().asInput() == "*") {
3855 // getOpt() eats the following space if there
3856 // is no optional argument, but that is OK
3857 // here since it has no effect in the output.
3858 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3861 begin_inset(os, "Newline newline");
3866 else if (t.cs() == "newline" ||
3867 (t.cs() == "linebreak" && !p.hasOpt())) {
3868 context.check_layout(os);
3869 begin_inset(os, "Newline ");
3872 skip_spaces_braces(p);
3875 else if (t.cs() == "input" || t.cs() == "include"
3876 || t.cs() == "verbatiminput") {
3877 string name = t.cs();
3878 if (t.cs() == "verbatiminput"
3879 && p.next_token().asInput() == "*")
3880 name += p.get_token().asInput();
3881 context.check_layout(os);
3882 string filename(normalize_filename(p.getArg('{', '}')));
3883 string const path = getMasterFilePath(true);
3884 // We want to preserve relative / absolute filenames,
3885 // therefore path is only used for testing
3886 if ((t.cs() == "include" || t.cs() == "input") &&
3887 !makeAbsPath(filename, path).exists()) {
3888 // The file extension is probably missing.
3889 // Now try to find it out.
3890 string const tex_name =
3891 find_file(filename, path,
3892 known_tex_extensions);
3893 if (!tex_name.empty())
3894 filename = tex_name;
3896 bool external = false;
3898 if (makeAbsPath(filename, path).exists()) {
3899 string const abstexname =
3900 makeAbsPath(filename, path).absFileName();
3901 string const absfigname =
3902 changeExtension(abstexname, ".fig");
3903 fix_child_filename(filename);
3904 string const lyxname = changeExtension(filename,
3905 roundtripMode() ? ".lyx.lyx" : ".lyx");
3906 string const abslyxname = makeAbsPath(
3907 lyxname, getParentFilePath(false)).absFileName();
3909 if (!skipChildren())
3910 external = FileName(absfigname).exists();
3911 if (t.cs() == "input" && !skipChildren()) {
3912 string const ext = getExtension(abstexname);
3914 // Combined PS/LaTeX:
3915 // x.eps, x.pstex_t (old xfig)
3916 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3917 FileName const absepsname(
3918 changeExtension(abstexname, ".eps"));
3919 FileName const abspstexname(
3920 changeExtension(abstexname, ".pstex"));
3921 bool const xfigeps =
3922 (absepsname.exists() ||
3923 abspstexname.exists()) &&
3926 // Combined PDF/LaTeX:
3927 // x.pdf, x.pdftex_t (old xfig)
3928 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3929 FileName const abspdfname(
3930 changeExtension(abstexname, ".pdf"));
3931 bool const xfigpdf =
3932 abspdfname.exists() &&
3933 (ext == "pdftex_t" || ext == "pdf_t");
3937 // Combined PS/PDF/LaTeX:
3938 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3939 string const absbase2(
3940 removeExtension(abstexname) + "_pspdftex");
3941 FileName const abseps2name(
3942 addExtension(absbase2, ".eps"));
3943 FileName const abspdf2name(
3944 addExtension(absbase2, ".pdf"));
3945 bool const xfigboth =
3946 abspdf2name.exists() &&
3947 abseps2name.exists() && ext == "pspdftex";
3949 xfig = xfigpdf || xfigeps || xfigboth;
3950 external = external && xfig;
3953 outname = changeExtension(filename, ".fig");
3954 FileName abssrc(changeExtension(abstexname, ".fig"));
3955 copy_file(abssrc, outname);
3957 // Don't try to convert, the result
3958 // would be full of ERT.
3960 FileName abssrc(abstexname);
3961 copy_file(abssrc, outname);
3962 } else if (t.cs() != "verbatiminput" &&
3964 tex2lyx(abstexname, FileName(abslyxname),
3967 // no need to call copy_file
3968 // tex2lyx creates the file
3971 FileName abssrc(abstexname);
3972 copy_file(abssrc, outname);
3975 cerr << "Warning: Could not find included file '"
3976 << filename << "'." << endl;
3980 begin_inset(os, "External\n");
3981 os << "\ttemplate XFig\n"
3982 << "\tfilename " << outname << '\n';
3983 registerExternalTemplatePackages("XFig");
3985 begin_command_inset(os, "include", name);
3986 outname = subst(outname, "\"", "\\\"");
3987 os << "preview false\n"
3988 "filename \"" << outname << "\"\n";
3989 if (t.cs() == "verbatiminput")
3990 preamble.registerAutomaticallyLoadedPackage("verbatim");
3995 else if (t.cs() == "bibliographystyle") {
3996 // store new bibliographystyle
3997 bibliographystyle = p.verbatim_item();
3998 // If any other command than \bibliography, \addcontentsline
3999 // and \nocite{*} follows, we need to output the style
4000 // (because it might be used by that command).
4001 // Otherwise, it will automatically be output by LyX.
4004 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4005 if (t2.cat() == catBegin)
4007 if (t2.cat() != catEscape)
4009 if (t2.cs() == "nocite") {
4010 if (p.getArg('{', '}') == "*")
4012 } else if (t2.cs() == "bibliography")
4014 else if (t2.cs() == "phantomsection") {
4018 else if (t2.cs() == "addcontentsline") {
4019 // get the 3 arguments of \addcontentsline
4022 contentslineContent = p.getArg('{', '}');
4023 // if the last argument is not \refname we must output
4024 if (contentslineContent == "\\refname")
4031 output_ert_inset(os,
4032 "\\bibliographystyle{" + bibliographystyle + '}',
4037 else if (t.cs() == "phantomsection") {
4038 // we only support this if it occurs between
4039 // \bibliographystyle and \bibliography
4040 if (bibliographystyle.empty())
4041 output_ert_inset(os, "\\phantomsection", context);
4044 else if (t.cs() == "addcontentsline") {
4045 context.check_layout(os);
4046 // get the 3 arguments of \addcontentsline
4047 string const one = p.getArg('{', '}');
4048 string const two = p.getArg('{', '}');
4049 string const three = p.getArg('{', '}');
4050 // only if it is a \refname, we support if for the bibtex inset
4051 if (contentslineContent != "\\refname") {
4052 output_ert_inset(os,
4053 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4058 else if (t.cs() == "bibliography") {
4059 context.check_layout(os);
4061 begin_command_inset(os, "bibtex", "bibtex");
4062 if (!btprint.empty()) {
4063 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4064 // clear the string because the next BibTeX inset can be without the
4065 // \nocite{*} option
4068 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4069 // Do we have addcontentsline?
4070 if (contentslineContent == "\\refname") {
4071 BibOpts = "bibtotoc";
4072 // clear string because next BibTeX inset can be without addcontentsline
4073 contentslineContent.clear();
4075 // Do we have a bibliographystyle set?
4076 if (!bibliographystyle.empty()) {
4077 if (BibOpts.empty())
4078 BibOpts = bibliographystyle;
4080 BibOpts = BibOpts + ',' + bibliographystyle;
4081 // clear it because each bibtex entry has its style
4082 // and we need an empty string to handle \phantomsection
4083 bibliographystyle.clear();
4085 os << "options " << '"' << BibOpts << '"' << "\n";
4089 else if (t.cs() == "parbox") {
4090 // Test whether this is an outer box of a shaded box
4092 // swallow arguments
4093 while (p.hasOpt()) {
4095 p.skip_spaces(true);
4098 p.skip_spaces(true);
4100 if (p.next_token().cat() == catBegin)
4102 p.skip_spaces(true);
4103 Token to = p.get_token();
4104 bool shaded = false;
4105 if (to.asInput() == "\\begin") {
4106 p.skip_spaces(true);
4107 if (p.getArg('{', '}') == "shaded")
4112 parse_outer_box(p, os, FLAG_ITEM, outer,
4113 context, "parbox", "shaded");
4115 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4119 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4120 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4121 t.cs() == "shadowbox" || t.cs() == "doublebox")
4122 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4124 else if (t.cs() == "framebox") {
4125 if (p.next_token().character() == '(') {
4126 //the syntax is: \framebox(x,y)[position]{content}
4127 string arg = t.asInput();
4128 arg += p.getFullParentheseArg();
4129 arg += p.getFullOpt();
4130 eat_whitespace(p, os, context, false);
4131 output_ert_inset(os, arg + '{', context);
4132 parse_text(p, os, FLAG_ITEM, outer, context);
4133 output_ert_inset(os, "}", context);
4135 //the syntax is: \framebox[width][position]{content}
4136 string special = p.getFullOpt();
4137 special += p.getOpt();
4138 parse_outer_box(p, os, FLAG_ITEM, outer,
4139 context, t.cs(), special);
4143 //\makebox() is part of the picture environment and different from \makebox{}
4144 //\makebox{} will be parsed by parse_box
4145 else if (t.cs() == "makebox") {
4146 if (p.next_token().character() == '(') {
4147 //the syntax is: \makebox(x,y)[position]{content}
4148 string arg = t.asInput();
4149 arg += p.getFullParentheseArg();
4150 arg += p.getFullOpt();
4151 eat_whitespace(p, os, context, false);
4152 output_ert_inset(os, arg + '{', context);
4153 parse_text(p, os, FLAG_ITEM, outer, context);
4154 output_ert_inset(os, "}", context);
4156 //the syntax is: \makebox[width][position]{content}
4157 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4161 else if (t.cs() == "smallskip" ||
4162 t.cs() == "medskip" ||
4163 t.cs() == "bigskip" ||
4164 t.cs() == "vfill") {
4165 context.check_layout(os);
4166 begin_inset(os, "VSpace ");
4169 skip_spaces_braces(p);
4172 else if ((where = is_known(t.cs(), known_spaces))) {
4173 context.check_layout(os);
4174 begin_inset(os, "space ");
4175 os << '\\' << known_coded_spaces[where - known_spaces]
4178 // LaTeX swallows whitespace after all spaces except
4179 // "\\,". We have to do that here, too, because LyX
4180 // adds "{}" which would make the spaces significant.
4182 eat_whitespace(p, os, context, false);
4183 // LyX adds "{}" after all spaces except "\\ " and
4184 // "\\,", so we have to remove "{}".
4185 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4186 // remove the braces after "\\,", too.
4191 else if (t.cs() == "newpage" ||
4192 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4193 t.cs() == "clearpage" ||
4194 t.cs() == "cleardoublepage") {
4195 context.check_layout(os);
4196 begin_inset(os, "Newpage ");
4199 skip_spaces_braces(p);
4202 else if (t.cs() == "DeclareRobustCommand" ||
4203 t.cs() == "DeclareRobustCommandx" ||
4204 t.cs() == "newcommand" ||
4205 t.cs() == "newcommandx" ||
4206 t.cs() == "providecommand" ||
4207 t.cs() == "providecommandx" ||
4208 t.cs() == "renewcommand" ||
4209 t.cs() == "renewcommandx") {
4210 // DeclareRobustCommand, DeclareRobustCommandx,
4211 // providecommand and providecommandx could be handled
4212 // by parse_command(), but we need to call
4213 // add_known_command() here.
4214 string name = t.asInput();
4215 if (p.next_token().asInput() == "*") {
4216 // Starred form. Eat '*'
4220 string const command = p.verbatim_item();
4221 string const opt1 = p.getFullOpt();
4222 string const opt2 = p.getFullOpt();
4223 add_known_command(command, opt1, !opt2.empty());
4224 string const ert = name + '{' + command + '}' +
4226 '{' + p.verbatim_item() + '}';
4228 if (t.cs() == "DeclareRobustCommand" ||
4229 t.cs() == "DeclareRobustCommandx" ||
4230 t.cs() == "providecommand" ||
4231 t.cs() == "providecommandx" ||
4232 name[name.length()-1] == '*')
4233 output_ert_inset(os, ert, context);
4235 context.check_layout(os);
4236 begin_inset(os, "FormulaMacro");
4242 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4243 // let could be handled by parse_command(),
4244 // but we need to call add_known_command() here.
4245 string ert = t.asInput();
4248 if (p.next_token().cat() == catBegin) {
4249 name = p.verbatim_item();
4250 ert += '{' + name + '}';
4252 name = p.verbatim_item();
4257 if (p.next_token().cat() == catBegin) {
4258 command = p.verbatim_item();
4259 ert += '{' + command + '}';
4261 command = p.verbatim_item();
4264 // If command is known, make name known too, to parse
4265 // its arguments correctly. For this reason we also
4266 // have commands in syntax.default that are hardcoded.
4267 CommandMap::iterator it = known_commands.find(command);
4268 if (it != known_commands.end())
4269 known_commands[t.asInput()] = it->second;
4270 output_ert_inset(os, ert, context);
4273 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4276 string name = t.asInput();
4277 string const length = p.verbatim_item();
4280 bool valid = splitLatexLength(length, valstring, unit);
4281 bool known_hspace = false;
4282 bool known_vspace = false;
4283 bool known_unit = false;
4286 istringstream iss(valstring);
4289 if (t.cs()[0] == 'h') {
4290 if (unit == "\\fill") {
4295 known_hspace = true;
4298 if (unit == "\\smallskipamount") {
4300 known_vspace = true;
4301 } else if (unit == "\\medskipamount") {
4303 known_vspace = true;
4304 } else if (unit == "\\bigskipamount") {
4306 known_vspace = true;
4307 } else if (unit == "\\fill") {
4309 known_vspace = true;
4313 if (!known_hspace && !known_vspace) {
4314 switch (unitFromString(unit)) {
4330 //unitFromString(unit) fails for relative units like Length::PCW
4331 // therefore handle them separately
4332 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4333 || unit == "\\textwidth" || unit == "\\linewidth"
4334 || unit == "\\textheight" || unit == "\\paperheight")
4342 // check for glue lengths
4343 bool is_gluelength = false;
4344 string gluelength = length;
4345 string::size_type i = length.find(" minus");
4346 if (i == string::npos) {
4347 i = length.find(" plus");
4348 if (i != string::npos)
4349 is_gluelength = true;
4351 is_gluelength = true;
4352 // if yes transform "9xx minus 8yy plus 7zz"
4354 if (is_gluelength) {
4355 i = gluelength.find(" minus");
4356 if (i != string::npos)
4357 gluelength.replace(i, 7, "-");
4358 i = gluelength.find(" plus");
4359 if (i != string::npos)
4360 gluelength.replace(i, 6, "+");
4363 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4364 // Literal horizontal length or known variable
4365 context.check_layout(os);
4366 begin_inset(os, "space ");
4374 if (known_unit && !known_hspace)
4375 os << "\n\\length " << translate_len(length);
4377 os << "\n\\length " << gluelength;
4379 } else if (known_unit || known_vspace || is_gluelength) {
4380 // Literal vertical length or known variable
4381 context.check_layout(os);
4382 begin_inset(os, "VSpace ");
4385 if (known_unit && !known_vspace)
4386 os << translate_len(length);
4393 // LyX can't handle other length variables in Inset VSpace/space
4398 output_ert_inset(os, name + '{' + unit + '}', context);
4399 else if (value == -1.0)
4400 output_ert_inset(os, name + "{-" + unit + '}', context);
4402 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4404 output_ert_inset(os, name + '{' + length + '}', context);
4408 // The single '=' is meant here.
4409 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4413 context.check_layout(os);
4414 docstring const name = newinsetlayout->name();
4415 bool const caption = name.find(from_ascii("Caption:")) == 0;
4417 begin_inset(os, "Caption ");
4418 os << to_utf8(name.substr(8)) << '\n';
4420 begin_inset(os, "Flex ");
4421 os << to_utf8(name) << '\n'
4422 << "status collapsed\n";
4424 if (newinsetlayout->isPassThru()) {
4425 // set catcodes to verbatim early, just in case.
4426 p.setCatcodes(VERBATIM_CATCODES);
4427 string delim = p.get_token().asInput();
4429 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4430 //FIXME: handle error condition
4431 string const arg = p.verbatimStuff("}").second;
4432 Context newcontext(true, context.textclass);
4433 if (newinsetlayout->forcePlainLayout())
4434 newcontext.layout = &context.textclass.plainLayout();
4435 output_ert(os, arg, newcontext);
4437 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4443 else if (t.cs() == "includepdf") {
4445 string const arg = p.getArg('[', ']');
4446 map<string, string> opts;
4447 vector<string> keys;
4448 split_map(arg, opts, keys);
4449 string name = normalize_filename(p.verbatim_item());
4450 string const path = getMasterFilePath(true);
4451 // We want to preserve relative / absolute filenames,
4452 // therefore path is only used for testing
4453 if (!makeAbsPath(name, path).exists()) {
4454 // The file extension is probably missing.
4455 // Now try to find it out.
4456 char const * const pdfpages_format[] = {"pdf", 0};
4457 string const pdftex_name =
4458 find_file(name, path, pdfpages_format);
4459 if (!pdftex_name.empty()) {
4464 FileName const absname = makeAbsPath(name, path);
4465 if (absname.exists())
4467 fix_child_filename(name);
4468 copy_file(absname, name);
4470 cerr << "Warning: Could not find file '"
4471 << name << "'." << endl;
4473 context.check_layout(os);
4474 begin_inset(os, "External\n\ttemplate ");
4475 os << "PDFPages\n\tfilename "
4477 // parse the options
4478 if (opts.find("pages") != opts.end())
4479 os << "\textra LaTeX \"pages="
4480 << opts["pages"] << "\"\n";
4481 if (opts.find("angle") != opts.end())
4482 os << "\trotateAngle "
4483 << opts["angle"] << '\n';
4484 if (opts.find("origin") != opts.end()) {
4486 string const opt = opts["origin"];
4487 if (opt == "tl") ss << "topleft";
4488 if (opt == "bl") ss << "bottomleft";
4489 if (opt == "Bl") ss << "baselineleft";
4490 if (opt == "c") ss << "center";
4491 if (opt == "tc") ss << "topcenter";
4492 if (opt == "bc") ss << "bottomcenter";
4493 if (opt == "Bc") ss << "baselinecenter";
4494 if (opt == "tr") ss << "topright";
4495 if (opt == "br") ss << "bottomright";
4496 if (opt == "Br") ss << "baselineright";
4497 if (!ss.str().empty())
4498 os << "\trotateOrigin " << ss.str() << '\n';
4500 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4502 if (opts.find("width") != opts.end())
4504 << translate_len(opts["width"]) << '\n';
4505 if (opts.find("height") != opts.end())
4507 << translate_len(opts["height"]) << '\n';
4508 if (opts.find("keepaspectratio") != opts.end())
4509 os << "\tkeepAspectRatio\n";
4511 context.check_layout(os);
4512 registerExternalTemplatePackages("PDFPages");
4515 else if (t.cs() == "loadgame") {
4517 string name = normalize_filename(p.verbatim_item());
4518 string const path = getMasterFilePath(true);
4519 // We want to preserve relative / absolute filenames,
4520 // therefore path is only used for testing
4521 if (!makeAbsPath(name, path).exists()) {
4522 // The file extension is probably missing.
4523 // Now try to find it out.
4524 char const * const lyxskak_format[] = {"fen", 0};
4525 string const lyxskak_name =
4526 find_file(name, path, lyxskak_format);
4527 if (!lyxskak_name.empty())
4528 name = lyxskak_name;
4530 FileName const absname = makeAbsPath(name, path);
4531 if (absname.exists())
4533 fix_child_filename(name);
4534 copy_file(absname, name);
4536 cerr << "Warning: Could not find file '"
4537 << name << "'." << endl;
4538 context.check_layout(os);
4539 begin_inset(os, "External\n\ttemplate ");
4540 os << "ChessDiagram\n\tfilename "
4543 context.check_layout(os);
4544 // after a \loadgame follows a \showboard
4545 if (p.get_token().asInput() == "showboard")
4547 registerExternalTemplatePackages("ChessDiagram");
4551 // try to see whether the string is in unicodesymbols
4552 // Only use text mode commands, since we are in text mode here,
4553 // and math commands may be invalid (bug 6797)
4554 string name = t.asInput();
4555 // handle the dingbats and Cyrillic
4556 if (name == "\\ding" || name == "\\textcyr")
4557 name = name + '{' + p.getArg('{', '}') + '}';
4558 // handle the ifsym characters
4559 else if (name == "\\textifsymbol") {
4560 string const optif = p.getFullOpt();
4561 string const argif = p.getArg('{', '}');
4562 name = name + optif + '{' + argif + '}';
4564 // handle the \ascii characters
4565 // the case of \ascii within braces, as LyX outputs it, is already
4566 // handled for t.cat() == catBegin
4567 else if (name == "\\ascii") {
4568 // the code is "\asci\xxx"
4569 name = "{" + name + p.get_token().asInput() + "}";
4572 // handle some TIPA special characters
4573 else if (preamble.isPackageUsed("tipa")) {
4574 if (name == "\\textglobfall") {
4577 } else if (name == "\\s") {
4578 // fromLaTeXCommand() does not yet
4579 // recognize tipa short cuts
4580 name = "\\textsyllabic";
4581 } else if (name == "\\=" &&
4582 p.next_token().asInput() == "*") {
4583 // fromLaTeXCommand() does not yet
4584 // recognize tipa short cuts
4587 } else if (name == "\\textdoublevertline") {
4588 // FIXME: This is not correct,
4589 // \textvertline is higher than \textbardbl
4590 name = "\\textbardbl";
4592 } else if (name == "\\!" ) {
4593 if (p.next_token().asInput() == "b") {
4594 p.get_token(); // eat 'b'
4597 } else if (p.next_token().asInput() == "d") {
4601 } else if (p.next_token().asInput() == "g") {
4605 } else if (p.next_token().asInput() == "G") {
4607 name = "\\texthtscg";
4609 } else if (p.next_token().asInput() == "j") {
4611 name = "\\texthtbardotlessj";
4613 } else if (p.next_token().asInput() == "o") {
4615 name = "\\textbullseye";
4618 } else if (name == "\\*" ) {
4619 if (p.next_token().asInput() == "k") {
4621 name = "\\textturnk";
4623 } else if (p.next_token().asInput() == "r") {
4624 p.get_token(); // eat 'b'
4625 name = "\\textturnr";
4627 } else if (p.next_token().asInput() == "t") {
4629 name = "\\textturnt";
4631 } else if (p.next_token().asInput() == "w") {
4633 name = "\\textturnw";
4638 if ((name.size() == 2 &&
4639 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4640 p.next_token().asInput() != "*") ||
4641 is_known(name.substr(1), known_tipa_marks)) {
4642 // name is a command that corresponds to a
4643 // combining character in unicodesymbols.
4644 // Append the argument, fromLaTeXCommand()
4645 // will either convert it to a single
4646 // character or a combining sequence.
4647 name += '{' + p.verbatim_item() + '}';
4649 // now get the character from unicodesymbols
4653 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4654 Encodings::TEXT_CMD, termination, rem, &req);
4656 context.check_layout(os);
4659 output_ert_inset(os, to_utf8(rem), context);
4661 skip_spaces_braces(p);
4662 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4663 preamble.registerAutomaticallyLoadedPackage(*it);
4665 //cerr << "#: " << t << " mode: " << mode << endl;
4666 // heuristic: read up to next non-nested space
4668 string s = t.asInput();
4669 string z = p.verbatim_item();
4670 while (p.good() && z != " " && !z.empty()) {
4671 //cerr << "read: " << z << endl;
4673 z = p.verbatim_item();
4675 cerr << "found ERT: " << s << endl;
4676 output_ert_inset(os, s + ' ', context);
4679 if (t.asInput() == name &&
4680 p.next_token().asInput() == "*") {
4681 // Starred commands like \vspace*{}
4682 p.get_token(); // Eat '*'
4685 if (!parse_command(name, p, os, outer, context))
4686 output_ert_inset(os, name, context);
4690 if (flags & FLAG_LEAVE) {
4691 flags &= ~FLAG_LEAVE;
4698 string guessLanguage(Parser & p, string const & lang)
4700 typedef std::map<std::string, size_t> LangMap;
4701 // map from language names to number of characters
4704 for (char const * const * i = supported_CJK_languages; *i; i++)
4705 used[string(*i)] = 0;
4708 Token const t = p.get_token();
4709 // comments are not counted for any language
4710 if (t.cat() == catComment)
4712 // commands are not counted as well, but we need to detect
4713 // \begin{CJK} and switch encoding if needed
4714 if (t.cat() == catEscape) {
4715 if (t.cs() == "inputencoding") {
4716 string const enc = subst(p.verbatim_item(), "\n", " ");
4717 p.setEncoding(enc, Encoding::inputenc);
4720 if (t.cs() != "begin")
4723 // Non-CJK content is counted for lang.
4724 // We do not care about the real language here:
4725 // If we have more non-CJK contents than CJK contents,
4726 // we simply use the language that was specified as
4727 // babel main language.
4728 used[lang] += t.asInput().length();
4731 // Now we are starting an environment
4733 string const name = p.getArg('{', '}');
4734 if (name != "CJK") {
4738 // It is a CJK environment
4740 /* name = */ p.getArg('{', '}');
4741 string const encoding = p.getArg('{', '}');
4742 /* mapping = */ p.getArg('{', '}');
4743 string const encoding_old = p.getEncoding();
4744 char const * const * const where =
4745 is_known(encoding, supported_CJK_encodings);
4747 p.setEncoding(encoding, Encoding::CJK);
4749 p.setEncoding("UTF-8");
4750 string const text = p.ertEnvironment("CJK");
4751 p.setEncoding(encoding_old);
4754 // ignore contents in unknown CJK encoding
4757 // the language of the text
4759 supported_CJK_languages[where - supported_CJK_encodings];
4760 used[cjk] += text.length();
4762 LangMap::const_iterator use = used.begin();
4763 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4764 if (it->second > use->second)