2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49 Context const & context, InsetLayout const * layout)
51 bool const forcePlainLayout =
52 layout ? layout->forcePlainLayout() : false;
53 Context newcontext(true, context.textclass);
55 newcontext.layout = &context.textclass.plainLayout();
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context const & context, string const & name)
68 InsetLayout const * layout = 0;
69 DocumentClass::InsetLayouts::const_iterator it =
70 context.textclass.insetLayouts().find(from_ascii(name));
71 if (it != context.textclass.insetLayouts().end())
72 layout = &(it->second);
73 parse_text_in_inset(p, os, flags, outer, context, layout);
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context newcontext(context);
81 // Don't inherit the paragraph-level extra stuff
82 newcontext.par_extra_stuff.clear();
83 parse_text(p, os, flags, outer, newcontext);
84 // Make sure that we don't create invalid .lyx files
85 context.need_layout = newcontext.need_layout;
86 context.need_end_layout = newcontext.need_end_layout;
91 * Thin wrapper around parse_text_snippet() using a string.
93 * We completely ignore \c context.need_layout and \c context.need_end_layout,
94 * because our return value is not used directly (otherwise the stream version
95 * of parse_text_snippet() could be used). That means that the caller needs
96 * to do layout management manually.
97 * This is intended to parse text that does not create any layout changes.
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
102 Context newcontext(context);
103 newcontext.need_layout = false;
104 newcontext.need_end_layout = false;
105 newcontext.new_layout_allowed = false;
106 // Avoid warning by Context::~Context()
107 newcontext.par_extra_stuff.clear();
109 parse_text_snippet(p, os, flags, outer, newcontext);
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115 "vpageref", "prettyref", "nameref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "nameref", "eqref", 0 };
120 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
121 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
122 "secref", "subref", "tabref", "thmref", 0 };
124 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
125 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
126 "sec", "sub", "tab", "thm", 0 };
130 * supported CJK encodings
131 * JIS does not work with LyX's encoding conversion
133 const char * const supported_CJK_encodings[] = {
134 "EUC-JP", "KS", "GB", "UTF8",
135 "Bg5", /*"JIS",*/ "SJIS", 0};
138 * the same as supported_CJK_encodings with their corresponding LyX language name
139 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
141 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
142 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
143 * please keep this in sync with supported_CJK_encodings line by line!
145 const char * const supported_CJK_languages[] = {
146 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
147 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
151 * The starred forms are also known except for "citefullauthor",
152 * "citeyear" and "citeyearpar".
154 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
155 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
156 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
160 * No starred form other than "cite*" known.
162 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
163 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
164 // jurabib commands not (yet) supported by LyX:
166 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
167 // "footciteauthor", "footciteyear", "footciteyearpar",
168 "citefield", "citetitle", 0 };
170 /// LaTeX names for quotes
171 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
172 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
173 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
174 "guilsinglleft", "frq", "guilsinglright", 0};
176 /// the same as known_quotes with .lyx names
177 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
178 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
179 "gld", "grd", "gls", "ers", "fls",
180 "fls", "frs", "frs", 0};
182 /// LaTeX names for font sizes
183 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
184 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
186 /// the same as known_sizes with .lyx names
187 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
188 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
190 /// LaTeX 2.09 names for font families
191 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
193 /// LaTeX names for font families
194 char const * const known_font_families[] = { "rmfamily", "sffamily",
197 /// LaTeX names for font family changing commands
198 char const * const known_text_font_families[] = { "textrm", "textsf",
201 /// The same as known_old_font_families, known_font_families and
202 /// known_text_font_families with .lyx names
203 char const * const known_coded_font_families[] = { "roman", "sans",
206 /// LaTeX 2.09 names for font series
207 char const * const known_old_font_series[] = { "bf", 0};
209 /// LaTeX names for font series
210 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
212 /// LaTeX names for font series changing commands
213 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
215 /// The same as known_old_font_series, known_font_series and
216 /// known_text_font_series with .lyx names
217 char const * const known_coded_font_series[] = { "bold", "medium", 0};
219 /// LaTeX 2.09 names for font shapes
220 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
222 /// LaTeX names for font shapes
223 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
226 /// LaTeX names for font shape changing commands
227 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
230 /// The same as known_old_font_shapes, known_font_shapes and
231 /// known_text_font_shapes with .lyx names
232 char const * const known_coded_font_shapes[] = { "italic", "slanted",
233 "smallcaps", "up", 0};
235 /// Known special characters which need skip_spaces_braces() afterwards
236 char const * const known_special_chars[] = {"ldots",
237 "lyxarrow", "textcompwordmark",
238 "slash", "textasciitilde", "textasciicircum", "textbackslash", 0};
240 /// the same as known_special_chars with .lyx names
241 char const * const known_coded_special_chars[] = {"\\SpecialChar \\ldots{}\n",
242 "\\SpecialChar \\menuseparator\n", "\\SpecialChar \\textcompwordmark{}\n",
243 "\\SpecialChar \\slash{}\n", "~", "^", "\n\\backslash\n", 0};
246 * Graphics file extensions known by the dvips driver of the graphics package.
247 * These extensions are used to complete the filename of an included
248 * graphics file if it does not contain an extension.
249 * The order must be the same that latex uses to find a file, because we
250 * will use the first extension that matches.
251 * This is only an approximation for the common cases. If we would want to
252 * do it right in all cases, we would need to know which graphics driver is
253 * used and know the extensions of every driver of the graphics package.
255 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
256 "ps.gz", "eps.Z", "ps.Z", 0};
259 * Graphics file extensions known by the pdftex driver of the graphics package.
260 * \sa known_dvips_graphics_formats
262 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
266 * Known file extensions for TeX files as used by \\include.
268 char const * const known_tex_extensions[] = {"tex", 0};
270 /// spaces known by InsetSpace
271 char const * const known_spaces[] = { " ", "space", ",",
272 "thinspace", "quad", "qquad", "enspace", "enskip",
273 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
274 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
275 "upbracefill", "downbracefill", 0};
277 /// the same as known_spaces with .lyx names
278 char const * const known_coded_spaces[] = { "space{}", "space{}",
279 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
280 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
281 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
282 "upbracefill{}", "downbracefill{}", 0};
284 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
285 /// them in ERT. "LaTeXe" must come before "LaTeX"!
286 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
287 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
288 int const known_phrase_lengths[] = {3, 5, 7, 0};
290 /// known TIPA combining diacritical marks
291 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
292 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
293 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
294 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
295 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
296 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
299 /// TIPA tones that need special handling
300 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
302 // string to store the float type to be able to determine the type of subfloats
303 string float_type = "";
306 /// splits "x=z, y=b" into a map and an ordered keyword vector
307 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
312 keys.resize(v.size());
313 for (size_t i = 0; i < v.size(); ++i) {
314 size_t const pos = v[i].find('=');
315 string const index = trimSpaceAndEol(v[i].substr(0, pos));
316 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
324 * Split a LaTeX length into value and unit.
325 * The latter can be a real unit like "pt", or a latex length variable
326 * like "\textwidth". The unit may contain additional stuff like glue
327 * lengths, but we don't care, because such lengths are ERT anyway.
328 * \returns true if \p value and \p unit are valid.
330 bool splitLatexLength(string const & len, string & value, string & unit)
334 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
335 //'4,5' is a valid LaTeX length number. Change it to '4.5'
336 string const length = subst(len, ',', '.');
337 if (i == string::npos)
340 if (len[0] == '\\') {
341 // We had something like \textwidth without a factor
347 value = trimSpaceAndEol(string(length, 0, i));
351 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
352 if (contains(len, '\\'))
353 unit = trimSpaceAndEol(string(len, i));
355 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
360 /// A simple function to translate a latex length to something LyX can
361 /// understand. Not perfect, but rather best-effort.
362 bool translate_len(string const & length, string & valstring, string & unit)
364 if (!splitLatexLength(length, valstring, unit))
366 // LyX uses percent values
368 istringstream iss(valstring);
373 string const percentval = oss.str();
375 if (unit.empty() || unit[0] != '\\')
377 string::size_type const i = unit.find(' ');
378 string const endlen = (i == string::npos) ? string() : string(unit, i);
379 if (unit == "\\textwidth") {
380 valstring = percentval;
381 unit = "text%" + endlen;
382 } else if (unit == "\\columnwidth") {
383 valstring = percentval;
384 unit = "col%" + endlen;
385 } else if (unit == "\\paperwidth") {
386 valstring = percentval;
387 unit = "page%" + endlen;
388 } else if (unit == "\\linewidth") {
389 valstring = percentval;
390 unit = "line%" + endlen;
391 } else if (unit == "\\paperheight") {
392 valstring = percentval;
393 unit = "pheight%" + endlen;
394 } else if (unit == "\\textheight") {
395 valstring = percentval;
396 unit = "theight%" + endlen;
404 string translate_len(string const & length)
408 if (translate_len(length, value, unit))
410 // If the input is invalid, return what we have.
418 * Translates a LaTeX length into \p value, \p unit and
419 * \p special parts suitable for a box inset.
420 * The difference from translate_len() is that a box inset knows about
421 * some special "units" that are stored in \p special.
423 void translate_box_len(string const & length, string & value, string & unit, string & special)
425 if (translate_len(length, value, unit)) {
426 if (unit == "\\height" || unit == "\\depth" ||
427 unit == "\\totalheight" || unit == "\\width") {
428 special = unit.substr(1);
429 // The unit is not used, but LyX requires a dummy setting
442 * Find a file with basename \p name in path \p path and an extension
445 string find_file(string const & name, string const & path,
446 char const * const * extensions)
448 for (char const * const * what = extensions; *what; ++what) {
449 string const trial = addExtension(name, *what);
450 if (makeAbsPath(trial, path).exists())
457 void begin_inset(ostream & os, string const & name)
459 os << "\n\\begin_inset " << name;
463 void begin_command_inset(ostream & os, string const & name,
464 string const & latexname)
466 begin_inset(os, "CommandInset ");
467 os << name << "\nLatexCommand " << latexname << '\n';
471 void end_inset(ostream & os)
473 os << "\n\\end_inset\n\n";
477 bool skip_braces(Parser & p)
479 if (p.next_token().cat() != catBegin)
482 if (p.next_token().cat() == catEnd) {
491 /// replace LaTeX commands in \p s from the unicodesymbols file with their
493 docstring convert_unicodesymbols(docstring s)
496 for (size_t i = 0; i < s.size();) {
505 docstring parsed = encodings.fromLaTeXCommand(s,
506 Encodings::TEXT_CMD, termination, rem, &req);
507 set<string>::const_iterator it = req.begin();
508 set<string>::const_iterator en = req.end();
509 for (; it != en; ++it)
510 preamble.registerAutomaticallyLoadedPackage(*it);
513 if (s.empty() || s[0] != '\\')
522 /// try to convert \p s to a valid InsetCommand argument
523 string convert_command_inset_arg(string s)
526 // since we don't know the input encoding we can't use from_utf8
527 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
528 // LyX cannot handle newlines in a latex command
529 return subst(s, "\n", " ");
533 void output_ert(ostream & os, string const & s, Context & context)
535 context.check_layout(os);
536 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
538 os << "\n\\backslash\n";
539 else if (*it == '\n') {
540 context.new_paragraph(os);
541 context.check_layout(os);
545 context.check_end_layout(os);
549 void output_ert_inset(ostream & os, string const & s, Context & context)
551 // We must have a valid layout before outputting the ERT inset.
552 context.check_layout(os);
553 Context newcontext(true, context.textclass);
554 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
555 if (layout.forcePlainLayout())
556 newcontext.layout = &context.textclass.plainLayout();
557 begin_inset(os, "ERT");
558 os << "\nstatus collapsed\n";
559 output_ert(os, s, newcontext);
564 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
566 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
569 if (checkModule(name, command))
570 return findLayoutWithoutModule(textclass, name, command);
575 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
577 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
580 if (checkModule(name, command))
581 return findInsetLayoutWithoutModule(textclass, name, command);
586 void eat_whitespace(Parser &, ostream &, Context &, bool);
590 * Skips whitespace and braces.
591 * This should be called after a command has been parsed that is not put into
592 * ERT, and where LyX adds "{}" if needed.
594 void skip_spaces_braces(Parser & p, bool keepws = false)
596 /* The following four examples produce the same typeset output and
597 should be handled by this function:
605 // Unfortunately we need to skip comments, too.
606 // We can't use eat_whitespace since writing them after the {}
607 // results in different output in some cases.
608 bool const skipped_spaces = p.skip_spaces(true);
609 bool const skipped_braces = skip_braces(p);
610 if (keepws && skipped_spaces && !skipped_braces)
611 // put back the space (it is better handled by check_space)
612 p.unskip_spaces(true);
616 void output_command_layout(ostream & os, Parser & p, bool outer,
617 Context & parent_context,
618 Layout const * newlayout)
620 TeXFont const oldFont = parent_context.font;
621 // save the current font size
622 string const size = oldFont.size;
623 // reset the font size to default, because the font size switches
624 // don't affect section headings and the like
625 parent_context.font.size = Context::normalfont.size;
626 // we only need to write the font change if we have an open layout
627 if (!parent_context.atParagraphStart())
628 output_font_change(os, oldFont, parent_context.font);
629 parent_context.check_end_layout(os);
630 Context context(true, parent_context.textclass, newlayout,
631 parent_context.layout, parent_context.font);
632 if (parent_context.deeper_paragraph) {
633 // We are beginning a nested environment after a
634 // deeper paragraph inside the outer list environment.
635 // Therefore we don't need to output a "begin deeper".
636 context.need_end_deeper = true;
638 context.check_deeper(os);
639 context.check_layout(os);
641 Layout::LaTeXArgMap::const_iterator lait = context.layout->latexargs().begin();
642 Layout::LaTeXArgMap::const_iterator const laend = context.layout->latexargs().end();
643 for (; lait != laend; ++lait) {
645 eat_whitespace(p, os, context, false);
646 if (lait->second.mandatory) {
647 if (p.next_token().cat() != catBegin)
649 p.get_token(); // eat '{'
650 begin_inset(os, "Argument ");
651 os << i << "\nstatus collapsed\n\n";
652 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
655 if (p.next_token().cat() == catEscape ||
656 p.next_token().character() != '[')
658 p.get_token(); // eat '['
659 begin_inset(os, "Argument ");
660 os << i << "\nstatus collapsed\n\n";
661 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
664 eat_whitespace(p, os, context, false);
666 parse_text(p, os, FLAG_ITEM, outer, context);
667 context.check_end_layout(os);
668 if (parent_context.deeper_paragraph) {
669 // We must suppress the "end deeper" because we
670 // suppressed the "begin deeper" above.
671 context.need_end_deeper = false;
673 context.check_end_deeper(os);
674 // We don't need really a new paragraph, but
675 // we must make sure that the next item gets a \begin_layout.
676 parent_context.new_paragraph(os);
677 // Set the font size to the original value. No need to output it here
678 // (Context::begin_layout() will do that if needed)
679 parent_context.font.size = size;
684 * Output a space if necessary.
685 * This function gets called for every whitespace token.
687 * We have three cases here:
688 * 1. A space must be suppressed. Example: The lyxcode case below
689 * 2. A space may be suppressed. Example: Spaces before "\par"
690 * 3. A space must not be suppressed. Example: A space between two words
692 * We currently handle only 1. and 3 and from 2. only the case of
693 * spaces before newlines as a side effect.
695 * 2. could be used to suppress as many spaces as possible. This has two effects:
696 * - Reimporting LyX generated LaTeX files changes almost no whitespace
697 * - Superflous whitespace from non LyX generated LaTeX files is removed.
698 * The drawback is that the logic inside the function becomes
699 * complicated, and that is the reason why it is not implemented.
701 void check_space(Parser & p, ostream & os, Context & context)
703 Token const next = p.next_token();
704 Token const curr = p.curr_token();
705 // A space before a single newline and vice versa must be ignored
706 // LyX emits a newline before \end{lyxcode}.
707 // This newline must be ignored,
708 // otherwise LyX will add an additional protected space.
709 if (next.cat() == catSpace ||
710 next.cat() == catNewline ||
711 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
714 context.check_layout(os);
720 * Parse all arguments of \p command
722 void parse_arguments(string const & command,
723 vector<ArgumentType> const & template_arguments,
724 Parser & p, ostream & os, bool outer, Context & context)
726 string ert = command;
727 size_t no_arguments = template_arguments.size();
728 for (size_t i = 0; i < no_arguments; ++i) {
729 switch (template_arguments[i]) {
732 // This argument contains regular LaTeX
733 output_ert_inset(os, ert + '{', context);
734 eat_whitespace(p, os, context, false);
735 if (template_arguments[i] == required)
736 parse_text(p, os, FLAG_ITEM, outer, context);
738 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
742 // This argument consists only of a single item.
743 // The presence of '{' or not must be preserved.
745 if (p.next_token().cat() == catBegin)
746 ert += '{' + p.verbatim_item() + '}';
748 ert += p.verbatim_item();
752 // This argument may contain special characters
753 ert += '{' + p.verbatim_item() + '}';
757 // true because we must not eat whitespace
758 // if an optional arg follows we must not strip the
759 // brackets from this one
760 if (i < no_arguments - 1 &&
761 template_arguments[i+1] == optional)
762 ert += p.getFullOpt(true);
764 ert += p.getOpt(true);
768 output_ert_inset(os, ert, context);
773 * Check whether \p command is a known command. If yes,
774 * handle the command with all arguments.
775 * \return true if the command was parsed, false otherwise.
777 bool parse_command(string const & command, Parser & p, ostream & os,
778 bool outer, Context & context)
780 if (known_commands.find(command) != known_commands.end()) {
781 parse_arguments(command, known_commands[command], p, os,
789 /// Parses a minipage or parbox
790 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
791 unsigned inner_flags, bool outer, Context & parent_context,
792 string const & outer_type, string const & special,
793 string const & inner_type)
797 string hor_pos = "c";
798 // We need to set the height to the LaTeX default of 1\\totalheight
799 // for the case when no height argument is given
800 string height_value = "1";
801 string height_unit = "in";
802 string height_special = "totalheight";
807 string width_special = "none";
808 if (!inner_type.empty() && p.hasOpt()) {
809 if (inner_type != "makebox")
810 position = p.getArg('[', ']');
812 latex_width = p.getArg('[', ']');
813 translate_box_len(latex_width, width_value, width_unit, width_special);
816 if (position != "t" && position != "c" && position != "b") {
817 cerr << "invalid position " << position << " for "
818 << inner_type << endl;
822 if (inner_type != "makebox") {
823 latex_height = p.getArg('[', ']');
824 translate_box_len(latex_height, height_value, height_unit, height_special);
826 string const opt = p.getArg('[', ']');
829 if (hor_pos != "l" && hor_pos != "c" &&
830 hor_pos != "r" && hor_pos != "s") {
831 cerr << "invalid hor_pos " << hor_pos
832 << " for " << inner_type << endl;
839 inner_pos = p.getArg('[', ']');
840 if (inner_pos != "c" && inner_pos != "t" &&
841 inner_pos != "b" && inner_pos != "s") {
842 cerr << "invalid inner_pos "
843 << inner_pos << " for "
844 << inner_type << endl;
845 inner_pos = position;
850 if (inner_type.empty()) {
851 if (special.empty() && outer_type != "framebox")
852 latex_width = "1\\columnwidth";
855 latex_width = p2.getArg('[', ']');
856 string const opt = p2.getArg('[', ']');
859 if (hor_pos != "l" && hor_pos != "c" &&
860 hor_pos != "r" && hor_pos != "s") {
861 cerr << "invalid hor_pos " << hor_pos
862 << " for " << outer_type << endl;
867 } else if (inner_type != "makebox")
868 latex_width = p.verbatim_item();
869 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
870 // as this is LyX's standard for such cases (except for makebox)
871 // \framebox is more special and handled below
872 if (latex_width.empty() && inner_type != "makebox"
873 && outer_type != "framebox")
874 latex_width = "1\\columnwidth";
876 translate_len(latex_width, width_value, width_unit);
878 bool shadedparbox = false;
879 if (inner_type == "shaded") {
880 eat_whitespace(p, os, parent_context, false);
881 if (outer_type == "parbox") {
883 if (p.next_token().cat() == catBegin)
885 eat_whitespace(p, os, parent_context, false);
891 // If we already read the inner box we have to push the inner env
892 if (!outer_type.empty() && !inner_type.empty() &&
893 (inner_flags & FLAG_END))
894 active_environments.push_back(inner_type);
895 // LyX can't handle length variables
896 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
897 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
898 // Look whether there is some content after the end of the
899 // inner box, but before the end of the outer box.
900 // If yes, we need to output ERT.
902 if (inner_flags & FLAG_END)
903 p.ertEnvironment(inner_type);
907 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
908 if ((outer_env && p.next_token().asInput() != "\\end") ||
909 (!outer_env && p.next_token().cat() != catEnd)) {
910 // something is between the end of the inner box and
911 // the end of the outer box, so we need to use ERT.
916 // if only \makebox{content} was used we can set its width to 1\width
917 // because this identic and also identic to \mbox
918 // this doesn't work for \framebox{content}, thus we have to use ERT for this
919 if (latex_width.empty() && inner_type == "makebox") {
922 width_special = "width";
923 } else if (latex_width.empty() && outer_type == "framebox") {
926 width_special = "none";
930 if (!outer_type.empty()) {
931 if (outer_flags & FLAG_END)
932 ss << "\\begin{" << outer_type << '}';
934 ss << '\\' << outer_type << '{';
935 if (!special.empty())
939 if (!inner_type.empty()) {
940 if (inner_type != "shaded") {
941 if (inner_flags & FLAG_END)
942 ss << "\\begin{" << inner_type << '}';
944 ss << '\\' << inner_type;
946 if (!position.empty())
947 ss << '[' << position << ']';
948 if (!latex_height.empty())
949 ss << '[' << latex_height << ']';
950 if (!inner_pos.empty())
951 ss << '[' << inner_pos << ']';
952 ss << '{' << latex_width << '}';
953 if (!(inner_flags & FLAG_END))
956 if (inner_type == "shaded")
957 ss << "\\begin{shaded}";
958 output_ert_inset(os, ss.str(), parent_context);
959 if (!inner_type.empty()) {
960 parse_text(p, os, inner_flags, outer, parent_context);
961 if (inner_flags & FLAG_END)
962 output_ert_inset(os, "\\end{" + inner_type + '}',
965 output_ert_inset(os, "}", parent_context);
967 if (!outer_type.empty()) {
968 // If we already read the inner box we have to pop
970 if (!inner_type.empty() && (inner_flags & FLAG_END))
971 active_environments.pop_back();
973 // Ensure that the end of the outer box is parsed correctly:
974 // The opening brace has been eaten by parse_outer_box()
975 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
976 outer_flags &= ~FLAG_ITEM;
977 outer_flags |= FLAG_BRACE_LAST;
979 parse_text(p, os, outer_flags, outer, parent_context);
980 if (outer_flags & FLAG_END)
981 output_ert_inset(os, "\\end{" + outer_type + '}',
984 output_ert_inset(os, "}", parent_context);
987 // LyX does not like empty positions, so we have
988 // to set them to the LaTeX default values here.
989 if (position.empty())
991 if (inner_pos.empty())
992 inner_pos = position;
993 parent_context.check_layout(os);
994 begin_inset(os, "Box ");
995 if (outer_type == "framed")
997 else if (outer_type == "framebox" || outer_type == "fbox")
999 else if (outer_type == "shadowbox")
1000 os << "Shadowbox\n";
1001 else if ((outer_type == "shaded" && inner_type.empty()) ||
1002 (outer_type == "minipage" && inner_type == "shaded") ||
1003 (outer_type == "parbox" && inner_type == "shaded")) {
1005 preamble.registerAutomaticallyLoadedPackage("color");
1006 } else if (outer_type == "doublebox")
1007 os << "Doublebox\n";
1008 else if (outer_type.empty() || outer_type == "mbox")
1009 os << "Frameless\n";
1011 os << outer_type << '\n';
1012 os << "position \"" << position << "\"\n";
1013 os << "hor_pos \"" << hor_pos << "\"\n";
1014 if (outer_type == "mbox")
1015 os << "has_inner_box 1\n";
1017 os << "has_inner_box " << !inner_type.empty() << "\n";
1018 os << "inner_pos \"" << inner_pos << "\"\n";
1019 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1021 if (outer_type == "mbox")
1022 os << "use_makebox 1\n";
1024 os << "use_makebox " << (inner_type == "makebox") << '\n';
1025 if (outer_type == "fbox" || outer_type == "mbox")
1026 os << "width \"\"\n";
1028 os << "width \"" << width_value << width_unit << "\"\n";
1029 os << "special \"" << width_special << "\"\n";
1030 os << "height \"" << height_value << height_unit << "\"\n";
1031 os << "height_special \"" << height_special << "\"\n";
1032 os << "status open\n\n";
1034 // Unfortunately we can't use parse_text_in_inset:
1035 // InsetBox::forcePlainLayout() is hard coded and does not
1036 // use the inset layout. Apart from that do we call parse_text
1037 // up to two times, but need only one check_end_layout.
1038 bool const forcePlainLayout =
1039 (!inner_type.empty() || inner_type == "makebox") &&
1040 outer_type != "shaded" && outer_type != "framed";
1041 Context context(true, parent_context.textclass);
1042 if (forcePlainLayout)
1043 context.layout = &context.textclass.plainLayout();
1045 context.font = parent_context.font;
1047 // If we have no inner box the contents will be read with the outer box
1048 if (!inner_type.empty())
1049 parse_text(p, os, inner_flags, outer, context);
1051 // Ensure that the end of the outer box is parsed correctly:
1052 // The opening brace has been eaten by parse_outer_box()
1053 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1054 outer_flags &= ~FLAG_ITEM;
1055 outer_flags |= FLAG_BRACE_LAST;
1058 // Find end of outer box, output contents if inner_type is
1059 // empty and output possible comments
1060 if (!outer_type.empty()) {
1061 // If we already read the inner box we have to pop
1063 if (!inner_type.empty() && (inner_flags & FLAG_END))
1064 active_environments.pop_back();
1065 // This does not output anything but comments if
1066 // inner_type is not empty (see use_ert)
1067 parse_text(p, os, outer_flags, outer, context);
1070 context.check_end_layout(os);
1072 #ifdef PRESERVE_LAYOUT
1073 // LyX puts a % after the end of the minipage
1074 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1076 //output_ert_inset(os, "%dummy", parent_context);
1079 parent_context.new_paragraph(os);
1081 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1082 //output_ert_inset(os, "%dummy", parent_context);
1085 // We add a protected space if something real follows
1086 if (p.good() && p.next_token().cat() != catComment) {
1087 begin_inset(os, "space ~\n");
1096 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1097 Context & parent_context, string const & outer_type,
1098 string const & special)
1100 eat_whitespace(p, os, parent_context, false);
1101 if (flags & FLAG_ITEM) {
1103 if (p.next_token().cat() == catBegin)
1106 cerr << "Warning: Ignoring missing '{' after \\"
1107 << outer_type << '.' << endl;
1108 eat_whitespace(p, os, parent_context, false);
1111 unsigned int inner_flags = 0;
1113 if (outer_type == "minipage" || outer_type == "parbox") {
1114 p.skip_spaces(true);
1115 while (p.hasOpt()) {
1117 p.skip_spaces(true);
1120 p.skip_spaces(true);
1121 if (outer_type == "parbox") {
1123 if (p.next_token().cat() == catBegin)
1125 p.skip_spaces(true);
1128 if (outer_type == "shaded" || outer_type == "fbox"
1129 || outer_type == "mbox") {
1130 // These boxes never have an inner box
1132 } else if (p.next_token().asInput() == "\\parbox") {
1133 inner = p.get_token().cs();
1134 inner_flags = FLAG_ITEM;
1135 } else if (p.next_token().asInput() == "\\begin") {
1136 // Is this a minipage or shaded box?
1139 inner = p.getArg('{', '}');
1141 if (inner == "minipage" || inner == "shaded")
1142 inner_flags = FLAG_END;
1147 if (inner_flags == FLAG_END) {
1148 if (inner != "shaded")
1152 eat_whitespace(p, os, parent_context, false);
1154 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1155 outer_type, special, inner);
1157 if (inner_flags == FLAG_ITEM) {
1159 eat_whitespace(p, os, parent_context, false);
1161 parse_box(p, os, flags, inner_flags, outer, parent_context,
1162 outer_type, special, inner);
1167 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1169 parent_context.check_layout(os);
1170 begin_inset(os, "listings\n");
1172 string arg = p.verbatimOption();
1173 os << "lstparams " << '"' << arg << '"' << '\n';
1174 if (arg.find("\\color") != string::npos)
1175 preamble.registerAutomaticallyLoadedPackage("color");
1178 os << "inline true\n";
1180 os << "inline false\n";
1181 os << "status collapsed\n";
1182 Context context(true, parent_context.textclass);
1183 context.layout = &parent_context.textclass.plainLayout();
1186 // set catcodes to verbatim early, just in case.
1187 p.setCatcodes(VERBATIM_CATCODES);
1188 string delim = p.get_token().asInput();
1189 //FIXME: handler error condition
1190 s = p.verbatimStuff(delim).second;
1191 // context.new_paragraph(os);
1193 s = p.verbatimEnvironment("lstlisting");
1194 output_ert(os, s, context);
1199 /// parse an unknown environment
1200 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1201 unsigned flags, bool outer,
1202 Context & parent_context)
1204 if (name == "tabbing")
1205 // We need to remember that we have to handle '\=' specially
1206 flags |= FLAG_TABBING;
1208 // We need to translate font changes and paragraphs inside the
1209 // environment to ERT if we have a non standard font.
1210 // Otherwise things like
1211 // \large\begin{foo}\huge bar\end{foo}
1213 bool const specialfont =
1214 (parent_context.font != parent_context.normalfont);
1215 bool const new_layout_allowed = parent_context.new_layout_allowed;
1217 parent_context.new_layout_allowed = false;
1218 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1219 parse_text_snippet(p, os, flags, outer, parent_context);
1220 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1222 parent_context.new_layout_allowed = new_layout_allowed;
1226 void parse_environment(Parser & p, ostream & os, bool outer,
1227 string & last_env, Context & parent_context)
1229 Layout const * newlayout;
1230 InsetLayout const * newinsetlayout = 0;
1231 string const name = p.getArg('{', '}');
1232 const bool is_starred = suffixIs(name, '*');
1233 string const unstarred_name = rtrim(name, "*");
1234 active_environments.push_back(name);
1236 if (is_math_env(name)) {
1237 parent_context.check_layout(os);
1238 begin_inset(os, "Formula ");
1239 os << "\\begin{" << name << "}";
1240 parse_math(p, os, FLAG_END, MATH_MODE);
1241 os << "\\end{" << name << "}";
1243 if (is_display_math_env(name)) {
1244 // Prevent the conversion of a line break to a space
1245 // (bug 7668). This does not change the output, but
1246 // looks ugly in LyX.
1247 eat_whitespace(p, os, parent_context, false);
1251 else if (is_known(name, preamble.polyglossia_languages)) {
1252 // We must begin a new paragraph if not already done
1253 if (! parent_context.atParagraphStart()) {
1254 parent_context.check_end_layout(os);
1255 parent_context.new_paragraph(os);
1257 // save the language in the context so that it is
1258 // handled by parse_text
1259 parent_context.font.language = preamble.polyglossia2lyx(name);
1260 parse_text(p, os, FLAG_END, outer, parent_context);
1261 // Just in case the environment is empty
1262 parent_context.extra_stuff.erase();
1263 // We must begin a new paragraph to reset the language
1264 parent_context.new_paragraph(os);
1268 else if (unstarred_name == "tabular" || name == "longtable") {
1269 eat_whitespace(p, os, parent_context, false);
1270 string width = "0pt";
1271 if (name == "tabular*") {
1272 width = lyx::translate_len(p.getArg('{', '}'));
1273 eat_whitespace(p, os, parent_context, false);
1275 parent_context.check_layout(os);
1276 begin_inset(os, "Tabular ");
1277 handle_tabular(p, os, name, width, parent_context);
1282 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1283 eat_whitespace(p, os, parent_context, false);
1284 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1285 eat_whitespace(p, os, parent_context, false);
1286 parent_context.check_layout(os);
1287 begin_inset(os, "Float " + unstarred_name + "\n");
1288 // store the float type for subfloats
1289 // subfloats only work with figures and tables
1290 if (unstarred_name == "figure")
1291 float_type = unstarred_name;
1292 else if (unstarred_name == "table")
1293 float_type = unstarred_name;
1297 os << "placement " << opt << '\n';
1298 if (contains(opt, "H"))
1299 preamble.registerAutomaticallyLoadedPackage("float");
1301 Floating const & fl = parent_context.textclass.floats()
1302 .getType(unstarred_name);
1303 if (!fl.floattype().empty() && fl.usesFloatPkg())
1304 preamble.registerAutomaticallyLoadedPackage("float");
1307 os << "wide " << convert<string>(is_starred)
1308 << "\nsideways false"
1309 << "\nstatus open\n\n";
1310 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1312 // We don't need really a new paragraph, but
1313 // we must make sure that the next item gets a \begin_layout.
1314 parent_context.new_paragraph(os);
1316 // the float is parsed thus delete the type
1320 else if (unstarred_name == "sidewaysfigure"
1321 || unstarred_name == "sidewaystable") {
1322 eat_whitespace(p, os, parent_context, false);
1323 parent_context.check_layout(os);
1324 if (unstarred_name == "sidewaysfigure")
1325 begin_inset(os, "Float figure\n");
1327 begin_inset(os, "Float table\n");
1328 os << "wide " << convert<string>(is_starred)
1329 << "\nsideways true"
1330 << "\nstatus open\n\n";
1331 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1333 // We don't need really a new paragraph, but
1334 // we must make sure that the next item gets a \begin_layout.
1335 parent_context.new_paragraph(os);
1337 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1340 else if (name == "wrapfigure" || name == "wraptable") {
1341 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1342 eat_whitespace(p, os, parent_context, false);
1343 parent_context.check_layout(os);
1346 string overhang = "0col%";
1349 lines = p.getArg('[', ']');
1350 string const placement = p.getArg('{', '}');
1352 overhang = p.getArg('[', ']');
1353 string const width = p.getArg('{', '}');
1355 if (name == "wrapfigure")
1356 begin_inset(os, "Wrap figure\n");
1358 begin_inset(os, "Wrap table\n");
1359 os << "lines " << lines
1360 << "\nplacement " << placement
1361 << "\noverhang " << lyx::translate_len(overhang)
1362 << "\nwidth " << lyx::translate_len(width)
1363 << "\nstatus open\n\n";
1364 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1366 // We don't need really a new paragraph, but
1367 // we must make sure that the next item gets a \begin_layout.
1368 parent_context.new_paragraph(os);
1370 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1373 else if (name == "minipage") {
1374 eat_whitespace(p, os, parent_context, false);
1375 // Test whether this is an outer box of a shaded box
1377 // swallow arguments
1378 while (p.hasOpt()) {
1380 p.skip_spaces(true);
1383 p.skip_spaces(true);
1384 Token t = p.get_token();
1385 bool shaded = false;
1386 if (t.asInput() == "\\begin") {
1387 p.skip_spaces(true);
1388 if (p.getArg('{', '}') == "shaded")
1393 parse_outer_box(p, os, FLAG_END, outer,
1394 parent_context, name, "shaded");
1396 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1401 else if (name == "comment") {
1402 eat_whitespace(p, os, parent_context, false);
1403 parent_context.check_layout(os);
1404 begin_inset(os, "Note Comment\n");
1405 os << "status open\n";
1406 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1409 skip_braces(p); // eat {} that might by set by LyX behind comments
1410 preamble.registerAutomaticallyLoadedPackage("verbatim");
1413 else if (name == "verbatim") {
1414 // FIXME: this should go in the generic code that
1415 // handles environments defined in layout file that
1416 // have "PassThru 1". However, the code over there is
1417 // already too complicated for my taste.
1418 parent_context.new_paragraph(os);
1419 Context context(true, parent_context.textclass,
1420 &parent_context.textclass[from_ascii("Verbatim")]);
1421 string s = p.verbatimEnvironment("verbatim");
1422 output_ert(os, s, context);
1426 else if (name == "IPA") {
1427 eat_whitespace(p, os, parent_context, false);
1428 parent_context.check_layout(os);
1429 begin_inset(os, "IPA\n");
1430 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1433 preamble.registerAutomaticallyLoadedPackage("tipa");
1434 preamble.registerAutomaticallyLoadedPackage("tipx");
1437 else if (name == "CJK") {
1438 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1439 // It is impossible to decide if a CJK environment was in its own paragraph or within
1440 // a line. We therefore always assume a paragraph since the latter is a rare case.
1441 eat_whitespace(p, os, parent_context, false);
1442 parent_context.check_end_layout(os);
1443 // store the encoding to be able to reset it
1444 string const encoding_old = p.getEncoding();
1445 string const encoding = p.getArg('{', '}');
1446 // FIXME: For some reason JIS does not work. Although the text
1447 // in tests/CJK.tex is identical with the SJIS version if you
1448 // convert both snippets using the recode command line utility,
1449 // the resulting .lyx file contains some extra characters if
1450 // you set buggy_encoding to false for JIS.
1451 bool const buggy_encoding = encoding == "JIS";
1452 if (!buggy_encoding)
1453 p.setEncoding(encoding, Encoding::CJK);
1455 // FIXME: This will read garbage, since the data is not encoded in utf8.
1456 p.setEncoding("UTF-8");
1458 // LyX only supports the same mapping for all CJK
1459 // environments, so we might need to output everything as ERT
1460 string const mapping = trim(p.getArg('{', '}'));
1461 char const * const * const where =
1462 is_known(encoding, supported_CJK_encodings);
1463 if (!buggy_encoding && !preamble.fontCJKSet())
1464 preamble.fontCJK(mapping);
1465 bool knownMapping = mapping == preamble.fontCJK();
1466 if (buggy_encoding || !knownMapping || !where) {
1467 parent_context.check_layout(os);
1468 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1470 // we must parse the content as verbatim because e.g. JIS can contain
1471 // normally invalid characters
1472 // FIXME: This works only for the most simple cases.
1473 // Since TeX control characters are not parsed,
1474 // things like comments are completely wrong.
1475 string const s = p.plainEnvironment("CJK");
1476 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1478 output_ert_inset(os, "\\", parent_context);
1479 else if (*it == '$')
1480 output_ert_inset(os, "$", parent_context);
1481 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1486 output_ert_inset(os, "\\end{" + name + "}",
1490 supported_CJK_languages[where - supported_CJK_encodings];
1491 // store the language because we must reset it at the end
1492 string const lang_old = parent_context.font.language;
1493 parent_context.font.language = lang;
1494 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1495 parent_context.font.language = lang_old;
1496 parent_context.new_paragraph(os);
1498 p.setEncoding(encoding_old);
1502 else if (name == "lyxgreyedout") {
1503 eat_whitespace(p, os, parent_context, false);
1504 parent_context.check_layout(os);
1505 begin_inset(os, "Note Greyedout\n");
1506 os << "status open\n";
1507 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1510 if (!preamble.notefontcolor().empty())
1511 preamble.registerAutomaticallyLoadedPackage("color");
1514 else if (name == "btSect") {
1515 eat_whitespace(p, os, parent_context, false);
1516 parent_context.check_layout(os);
1517 begin_command_inset(os, "bibtex", "bibtex");
1518 string bibstyle = "plain";
1520 bibstyle = p.getArg('[', ']');
1521 p.skip_spaces(true);
1523 string const bibfile = p.getArg('{', '}');
1524 eat_whitespace(p, os, parent_context, false);
1525 Token t = p.get_token();
1526 if (t.asInput() == "\\btPrintCited") {
1527 p.skip_spaces(true);
1528 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1530 if (t.asInput() == "\\btPrintNotCited") {
1531 p.skip_spaces(true);
1532 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1534 if (t.asInput() == "\\btPrintAll") {
1535 p.skip_spaces(true);
1536 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1538 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1539 os << "options " << '"' << bibstyle << '"' << "\n";
1540 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1545 else if (name == "framed" || name == "shaded") {
1546 eat_whitespace(p, os, parent_context, false);
1547 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1551 else if (name == "lstlisting") {
1552 eat_whitespace(p, os, parent_context, false);
1553 parse_listings(p, os, parent_context, false);
1557 else if (!parent_context.new_layout_allowed)
1558 parse_unknown_environment(p, name, os, FLAG_END, outer,
1561 // Alignment and spacing settings
1562 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1563 // therefore are totally broken!
1564 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1565 // they are commands not environments. They are furthermore switches that
1566 // can be ended by another switches, but also by commands like \footnote or
1567 // \parbox. So the only safe way is to leave them untouched.
1568 else if (name == "center" || name == "centering" ||
1569 name == "flushleft" || name == "flushright" ||
1570 name == "singlespace" || name == "onehalfspace" ||
1571 name == "doublespace" || name == "spacing") {
1572 eat_whitespace(p, os, parent_context, false);
1573 // We must begin a new paragraph if not already done
1574 if (! parent_context.atParagraphStart()) {
1575 parent_context.check_end_layout(os);
1576 parent_context.new_paragraph(os);
1578 if (name == "flushleft")
1579 parent_context.add_extra_stuff("\\align left\n");
1580 else if (name == "flushright")
1581 parent_context.add_extra_stuff("\\align right\n");
1582 else if (name == "center" || name == "centering")
1583 parent_context.add_extra_stuff("\\align center\n");
1584 else if (name == "singlespace")
1585 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1586 else if (name == "onehalfspace") {
1587 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1588 preamble.registerAutomaticallyLoadedPackage("setspace");
1589 } else if (name == "doublespace") {
1590 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1591 preamble.registerAutomaticallyLoadedPackage("setspace");
1592 } else if (name == "spacing") {
1593 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1594 preamble.registerAutomaticallyLoadedPackage("setspace");
1596 parse_text(p, os, FLAG_END, outer, parent_context);
1597 // Just in case the environment is empty
1598 parent_context.extra_stuff.erase();
1599 // We must begin a new paragraph to reset the alignment
1600 parent_context.new_paragraph(os);
1604 // The single '=' is meant here.
1605 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1606 eat_whitespace(p, os, parent_context, false);
1607 Context context(true, parent_context.textclass, newlayout,
1608 parent_context.layout, parent_context.font);
1609 if (parent_context.deeper_paragraph) {
1610 // We are beginning a nested environment after a
1611 // deeper paragraph inside the outer list environment.
1612 // Therefore we don't need to output a "begin deeper".
1613 context.need_end_deeper = true;
1615 parent_context.check_end_layout(os);
1616 if (last_env == name) {
1617 // we need to output a separator since LyX would export
1618 // the two environments as one otherwise (bug 5716)
1619 TeX2LyXDocClass const & textclass(parent_context.textclass);
1620 Context newcontext(true, textclass,
1621 &(textclass.defaultLayout()));
1622 newcontext.check_layout(os);
1623 begin_inset(os, "Separator plain\n");
1625 newcontext.check_end_layout(os);
1627 switch (context.layout->latextype) {
1628 case LATEX_LIST_ENVIRONMENT:
1629 context.add_par_extra_stuff("\\labelwidthstring "
1630 + p.verbatim_item() + '\n');
1633 case LATEX_BIB_ENVIRONMENT:
1634 p.verbatim_item(); // swallow next arg
1640 context.check_deeper(os);
1641 // handle known optional and required arguments
1642 // FIXME: Since format 446, layouts do not require anymore all optional
1643 // arguments before the required ones. Needs to be implemented!
1644 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1645 // It is impossible to place anything after the environment name,
1646 // but before the first \\item.
1647 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1648 bool need_layout = true;
1650 while (optargs < context.layout->optArgs()) {
1651 eat_whitespace(p, os, context, false);
1652 if (p.next_token().cat() == catEscape ||
1653 p.next_token().character() != '[')
1655 p.get_token(); // eat '['
1657 context.check_layout(os);
1658 need_layout = false;
1660 // FIXME: Just a workaround. InsetArgument::updateBuffer
1661 // will compute a proper ID for all "999" Arguments
1662 // (which is also what lyx2lyx produces).
1663 // However, tex2lyx should be able to output proper IDs
1665 begin_inset(os, "Argument 999\n");
1666 os << "status collapsed\n\n";
1667 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1669 eat_whitespace(p, os, context, false);
1673 while (reqargs < context.layout->requiredArgs()) {
1674 eat_whitespace(p, os, context, false);
1675 if (p.next_token().cat() != catBegin)
1677 p.get_token(); // eat '{'
1679 context.check_layout(os);
1680 need_layout = false;
1682 // FIXME: Just a workaround. InsetArgument::updateBuffer
1683 // will compute a proper ID for all "999" Arguments
1684 // (which is also what lyx2lyx produces).
1685 // However, tex2lyx should be able to output proper IDs
1687 begin_inset(os, "Argument 999\n");
1688 os << "status collapsed\n\n";
1689 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1691 eat_whitespace(p, os, context, false);
1695 parse_text(p, os, FLAG_END, outer, context);
1696 context.check_end_layout(os);
1697 if (parent_context.deeper_paragraph) {
1698 // We must suppress the "end deeper" because we
1699 // suppressed the "begin deeper" above.
1700 context.need_end_deeper = false;
1702 context.check_end_deeper(os);
1703 parent_context.new_paragraph(os);
1705 if (!preamble.titleLayoutFound())
1706 preamble.titleLayoutFound(newlayout->intitle);
1707 set<string> const & req = newlayout->requires();
1708 set<string>::const_iterator it = req.begin();
1709 set<string>::const_iterator en = req.end();
1710 for (; it != en; ++it)
1711 preamble.registerAutomaticallyLoadedPackage(*it);
1714 // The single '=' is meant here.
1715 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1716 eat_whitespace(p, os, parent_context, false);
1717 parent_context.check_layout(os);
1718 begin_inset(os, "Flex ");
1719 os << to_utf8(newinsetlayout->name()) << '\n'
1720 << "status collapsed\n";
1721 if (newinsetlayout->isPassThru()) {
1722 string const arg = p.verbatimEnvironment(name);
1723 Context context(true, parent_context.textclass,
1724 &parent_context.textclass.plainLayout(),
1725 parent_context.layout);
1726 output_ert(os, arg, parent_context);
1728 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1732 else if (name == "appendix") {
1733 // This is no good latex style, but it works and is used in some documents...
1734 eat_whitespace(p, os, parent_context, false);
1735 parent_context.check_end_layout(os);
1736 Context context(true, parent_context.textclass, parent_context.layout,
1737 parent_context.layout, parent_context.font);
1738 context.check_layout(os);
1739 os << "\\start_of_appendix\n";
1740 parse_text(p, os, FLAG_END, outer, context);
1741 context.check_end_layout(os);
1745 else if (known_environments.find(name) != known_environments.end()) {
1746 vector<ArgumentType> arguments = known_environments[name];
1747 // The last "argument" denotes wether we may translate the
1748 // environment contents to LyX
1749 // The default required if no argument is given makes us
1750 // compatible with the reLyXre environment.
1751 ArgumentType contents = arguments.empty() ?
1754 if (!arguments.empty())
1755 arguments.pop_back();
1756 // See comment in parse_unknown_environment()
1757 bool const specialfont =
1758 (parent_context.font != parent_context.normalfont);
1759 bool const new_layout_allowed =
1760 parent_context.new_layout_allowed;
1762 parent_context.new_layout_allowed = false;
1763 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1764 outer, parent_context);
1765 if (contents == verbatim)
1766 output_ert_inset(os, p.ertEnvironment(name),
1769 parse_text_snippet(p, os, FLAG_END, outer,
1771 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1773 parent_context.new_layout_allowed = new_layout_allowed;
1777 parse_unknown_environment(p, name, os, FLAG_END, outer,
1781 active_environments.pop_back();
1785 /// parses a comment and outputs it to \p os.
1786 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1788 LASSERT(t.cat() == catComment, return);
1789 if (!t.cs().empty()) {
1790 context.check_layout(os);
1791 output_ert_inset(os, '%' + t.cs(), context);
1792 if (p.next_token().cat() == catNewline) {
1793 // A newline after a comment line starts a new
1795 if (context.new_layout_allowed) {
1796 if(!context.atParagraphStart())
1797 // Only start a new paragraph if not already
1798 // done (we might get called recursively)
1799 context.new_paragraph(os);
1801 output_ert_inset(os, "\n", context);
1802 eat_whitespace(p, os, context, true);
1805 // "%\n" combination
1812 * Reads spaces and comments until the first non-space, non-comment token.
1813 * New paragraphs (double newlines or \\par) are handled like simple spaces
1814 * if \p eatParagraph is true.
1815 * Spaces are skipped, but comments are written to \p os.
1817 void eat_whitespace(Parser & p, ostream & os, Context & context,
1821 Token const & t = p.get_token();
1822 if (t.cat() == catComment)
1823 parse_comment(p, os, t, context);
1824 else if ((! eatParagraph && p.isParagraph()) ||
1825 (t.cat() != catSpace && t.cat() != catNewline)) {
1834 * Set a font attribute, parse text and reset the font attribute.
1835 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1836 * \param currentvalue Current value of the attribute. Is set to the new
1837 * value during parsing.
1838 * \param newvalue New value of the attribute
1840 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1841 Context & context, string const & attribute,
1842 string & currentvalue, string const & newvalue)
1844 context.check_layout(os);
1845 string const oldvalue = currentvalue;
1846 currentvalue = newvalue;
1847 os << '\n' << attribute << ' ' << newvalue << "\n";
1848 parse_text_snippet(p, os, flags, outer, context);
1849 context.check_layout(os);
1850 os << '\n' << attribute << ' ' << oldvalue << "\n";
1851 currentvalue = oldvalue;
1855 /// get the arguments of a natbib or jurabib citation command
1856 void get_cite_arguments(Parser & p, bool natbibOrder,
1857 string & before, string & after)
1859 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1861 // text before the citation
1863 // text after the citation
1864 after = p.getFullOpt();
1866 if (!after.empty()) {
1867 before = p.getFullOpt();
1868 if (natbibOrder && !before.empty())
1869 swap(before, after);
1874 /// Convert filenames with TeX macros and/or quotes to something LyX
1876 string const normalize_filename(string const & name)
1881 Token const & t = p.get_token();
1882 if (t.cat() != catEscape)
1884 else if (t.cs() == "lyxdot") {
1885 // This is used by LyX for simple dots in relative
1889 } else if (t.cs() == "space") {
1892 } else if (t.cs() == "string") {
1893 // Convert \string" to " and \string~ to ~
1894 Token const & n = p.next_token();
1895 if (n.asInput() != "\"" && n.asInput() != "~")
1900 // Strip quotes. This is a bit complicated (see latex_path()).
1901 string full = os.str();
1902 if (!full.empty() && full[0] == '"') {
1903 string base = removeExtension(full);
1904 string ext = getExtension(full);
1905 if (!base.empty() && base[base.length()-1] == '"')
1908 return addExtension(trim(base, "\""), ext);
1909 if (full[full.length()-1] == '"')
1912 return trim(full, "\"");
1918 /// Convert \p name from TeX convention (relative to master file) to LyX
1919 /// convention (relative to .lyx file) if it is relative
1920 void fix_child_filename(string & name)
1922 string const absMasterTeX = getMasterFilePath(true);
1923 bool const isabs = FileName::isAbsolute(name);
1924 // convert from "relative to .tex master" to absolute original path
1926 name = makeAbsPath(name, absMasterTeX).absFileName();
1927 bool copyfile = copyFiles();
1928 string const absParentLyX = getParentFilePath(false);
1931 // convert from absolute original path to "relative to master file"
1932 string const rel = to_utf8(makeRelPath(from_utf8(name),
1933 from_utf8(absMasterTeX)));
1934 // re-interpret "relative to .tex file" as "relative to .lyx file"
1935 // (is different if the master .lyx file resides in a
1936 // different path than the master .tex file)
1937 string const absMasterLyX = getMasterFilePath(false);
1938 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1939 // Do not copy if the new path is impossible to create. Example:
1940 // absMasterTeX = "/foo/bar/"
1941 // absMasterLyX = "/bar/"
1942 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1943 if (contains(name, "/../"))
1950 // convert from absolute original path to
1951 // "relative to .lyx file"
1952 name = to_utf8(makeRelPath(from_utf8(abs),
1953 from_utf8(absParentLyX)));
1957 // convert from absolute original path to "relative to .lyx file"
1958 name = to_utf8(makeRelPath(from_utf8(name),
1959 from_utf8(absParentLyX)));
1964 void copy_file(FileName const & src, string dstname)
1968 string const absParent = getParentFilePath(false);
1970 if (FileName::isAbsolute(dstname))
1971 dst = FileName(dstname);
1973 dst = makeAbsPath(dstname, absParent);
1974 string const absMaster = getMasterFilePath(false);
1975 FileName const srcpath = src.onlyPath();
1976 FileName const dstpath = dst.onlyPath();
1977 if (equivalent(srcpath, dstpath))
1979 if (!dstpath.isDirectory()) {
1980 if (!dstpath.createPath()) {
1981 cerr << "Warning: Could not create directory for file `"
1982 << dst.absFileName() << "´." << endl;
1986 if (dst.isReadableFile()) {
1987 if (overwriteFiles())
1988 cerr << "Warning: Overwriting existing file `"
1989 << dst.absFileName() << "´." << endl;
1991 cerr << "Warning: Not overwriting existing file `"
1992 << dst.absFileName() << "´." << endl;
1996 if (!src.copyTo(dst))
1997 cerr << "Warning: Could not copy file `" << src.absFileName()
1998 << "´ to `" << dst.absFileName() << "´." << endl;
2002 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2003 bool parse_chunk(Parser & p, ostream & os, Context & context)
2005 // check whether a chunk is possible here.
2006 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2012 // read the parameters
2013 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2014 if (!params.first) {
2019 Parser::Arg const code = p.verbatimStuff("\n@");
2024 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2025 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2029 // The last newline read is important for paragraph handling
2033 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2034 // We must have a valid layout before outputting the Chunk inset.
2035 context.check_layout(os);
2036 Context chunkcontext(true, context.textclass);
2037 chunkcontext.layout = &context.textclass.plainLayout();
2038 begin_inset(os, "Flex Chunk");
2039 os << "\nstatus open\n";
2040 if (!params.second.empty()) {
2041 chunkcontext.check_layout(os);
2042 Context paramscontext(true, context.textclass);
2043 paramscontext.layout = &context.textclass.plainLayout();
2044 begin_inset(os, "Argument 1");
2045 os << "\nstatus open\n";
2046 output_ert(os, params.second, paramscontext);
2049 output_ert(os, code.second, chunkcontext);
2057 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2058 bool is_macro(Parser & p)
2060 Token first = p.curr_token();
2061 if (first.cat() != catEscape || !p.good())
2063 if (first.cs() == "def")
2065 if (first.cs() != "global" && first.cs() != "long")
2067 Token second = p.get_token();
2069 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2070 second.cat() == catNewline || second.cat() == catComment)) {
2071 second = p.get_token();
2074 bool secondvalid = second.cat() == catEscape;
2076 bool thirdvalid = false;
2077 if (p.good() && first.cs() == "global" && secondvalid &&
2078 second.cs() == "long") {
2079 third = p.get_token();
2081 while (p.good() && !p.isParagraph() &&
2082 (third.cat() == catSpace ||
2083 third.cat() == catNewline ||
2084 third.cat() == catComment)) {
2085 third = p.get_token();
2088 thirdvalid = third.cat() == catEscape;
2090 for (int i = 0; i < pos; ++i)
2095 return (first.cs() == "global" || first.cs() == "long") &&
2096 second.cs() == "def";
2097 return first.cs() == "global" && second.cs() == "long" &&
2098 third.cs() == "def";
2102 /// Parse a macro definition (assumes that is_macro() returned true)
2103 void parse_macro(Parser & p, ostream & os, Context & context)
2105 context.check_layout(os);
2106 Token first = p.curr_token();
2109 string command = first.asInput();
2110 if (first.cs() != "def") {
2112 eat_whitespace(p, os, context, false);
2113 second = p.curr_token();
2114 command += second.asInput();
2115 if (second.cs() != "def") {
2117 eat_whitespace(p, os, context, false);
2118 third = p.curr_token();
2119 command += third.asInput();
2122 eat_whitespace(p, os, context, false);
2123 string const name = p.get_token().cs();
2124 eat_whitespace(p, os, context, false);
2130 while (p.next_token().cat() != catBegin) {
2131 if (p.next_token().cat() == catParameter) {
2136 // followed by number?
2137 if (p.next_token().cat() == catOther) {
2138 string s = p.get_token().asInput();
2140 // number = current arity + 1?
2141 if (s.size() == 1 && s[0] == arity + '0' + 1)
2146 paramtext += p.get_token().cs();
2148 paramtext += p.get_token().cs();
2153 // only output simple (i.e. compatible) macro as FormulaMacros
2154 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2156 context.check_layout(os);
2157 begin_inset(os, "FormulaMacro");
2158 os << "\n\\def" << ert;
2161 output_ert_inset(os, command + ert, context);
2165 void registerExternalTemplatePackages(string const & name)
2167 external::TemplateManager const & etm = external::TemplateManager::get();
2168 external::Template const * const et = etm.getTemplateByName(name);
2171 external::Template::Formats::const_iterator cit = et->formats.end();
2173 cit = et->formats.find("PDFLaTeX");
2174 if (cit == et->formats.end())
2175 // If the template has not specified a PDFLaTeX output,
2176 // we try the LaTeX format.
2177 cit = et->formats.find("LaTeX");
2178 if (cit == et->formats.end())
2180 vector<string>::const_iterator qit = cit->second.requirements.begin();
2181 vector<string>::const_iterator qend = cit->second.requirements.end();
2182 for (; qit != qend; ++qit)
2183 preamble.registerAutomaticallyLoadedPackage(*qit);
2186 } // anonymous namespace
2189 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2192 Layout const * newlayout = 0;
2193 InsetLayout const * newinsetlayout = 0;
2194 char const * const * where = 0;
2195 // Store the latest bibliographystyle, addcontentslineContent and
2196 // nocite{*} option (needed for bibtex inset)
2198 string contentslineContent;
2199 string bibliographystyle = "default";
2200 bool const use_natbib = isProvided("natbib");
2201 bool const use_jurabib = isProvided("jurabib");
2204 // it is impossible to determine the correct encoding for non-CJK Japanese.
2205 // Therefore write a note at the beginning of the document
2206 if (is_nonCJKJapanese) {
2207 context.check_layout(os);
2208 begin_inset(os, "Note Note\n");
2209 os << "status open\n\\begin_layout Plain Layout\n"
2210 << "\\series bold\n"
2211 << "Important information:\n"
2212 << "\\end_layout\n\n"
2213 << "\\begin_layout Plain Layout\n"
2214 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2215 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2216 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2217 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2218 << " and specify the encoding using the -e command-line switch.\n"
2219 << " In addition, you might want to double check that the desired output encoding\n"
2220 << " is correctly selected in Document > Settings > Language.\n"
2221 << "\\end_layout\n";
2223 is_nonCJKJapanese = false;
2227 Token const & t = p.get_token();
2229 debugToken(cerr, t, flags);
2232 if (flags & FLAG_ITEM) {
2233 if (t.cat() == catSpace)
2236 flags &= ~FLAG_ITEM;
2237 if (t.cat() == catBegin) {
2238 // skip the brace and collect everything to the next matching
2240 flags |= FLAG_BRACE_LAST;
2244 // handle only this single token, leave the loop if done
2245 flags |= FLAG_LEAVE;
2248 if (t.cat() != catEscape && t.character() == ']' &&
2249 (flags & FLAG_BRACK_LAST))
2251 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2254 // If there is anything between \end{env} and \begin{env} we
2255 // don't need to output a separator.
2256 if (t.cat() != catSpace && t.cat() != catNewline &&
2257 t.asInput() != "\\begin")
2263 bool const starred = p.next_token().asInput() == "*";
2264 string const starredname(starred ? (t.cs() + '*') : t.cs());
2265 if (t.cat() == catMath) {
2266 // we are inside some text mode thingy, so opening new math is allowed
2267 context.check_layout(os);
2268 begin_inset(os, "Formula ");
2269 Token const & n = p.get_token();
2270 bool const display(n.cat() == catMath && outer);
2272 // TeX's $$...$$ syntax for displayed math
2274 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2276 p.get_token(); // skip the second '$' token
2278 // simple $...$ stuff
2281 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2286 // Prevent the conversion of a line break to a
2287 // space (bug 7668). This does not change the
2288 // output, but looks ugly in LyX.
2289 eat_whitespace(p, os, context, false);
2293 else if (t.cat() == catSuper || t.cat() == catSub)
2294 cerr << "catcode " << t << " illegal in text mode\n";
2296 // Basic support for english quotes. This should be
2297 // extended to other quotes, but is not so easy (a
2298 // left english quote is the same as a right german
2300 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2301 context.check_layout(os);
2302 begin_inset(os, "Quotes ");
2308 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2309 context.check_layout(os);
2310 begin_inset(os, "Quotes ");
2317 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2318 context.check_layout(os);
2319 begin_inset(os, "Quotes ");
2326 else if (t.asInput() == "<"
2327 && p.next_token().asInput() == "<") {
2328 bool has_chunk = false;
2332 has_chunk = parse_chunk(p, os, context);
2338 context.check_layout(os);
2339 begin_inset(os, "Quotes ");
2340 //FIXME: this is a right danish quote;
2341 // why not a left french quote?
2349 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2350 check_space(p, os, context);
2352 else if (t.character() == '[' && noweb_mode &&
2353 p.next_token().character() == '[') {
2354 // These can contain underscores
2356 string const s = p.getFullOpt() + ']';
2357 if (p.next_token().character() == ']')
2360 cerr << "Warning: Inserting missing ']' in '"
2361 << s << "'." << endl;
2362 output_ert_inset(os, s, context);
2365 else if (t.cat() == catLetter) {
2366 context.check_layout(os);
2367 // Workaround for bug 4752.
2368 // FIXME: This whole code block needs to be removed
2369 // when the bug is fixed and tex2lyx produces
2370 // the updated file format.
2371 // The replacement algorithm in LyX is so stupid that
2372 // it even translates a phrase if it is part of a word.
2373 bool handled = false;
2374 for (int const * l = known_phrase_lengths; *l; ++l) {
2375 string phrase = t.cs();
2376 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2377 phrase += p.get_token().cs();
2378 if (is_known(phrase, known_coded_phrases)) {
2379 output_ert_inset(os, phrase, context);
2383 for (size_t i = 1; i < phrase.length(); ++i)
2391 else if (t.cat() == catOther ||
2392 t.cat() == catAlign ||
2393 t.cat() == catParameter) {
2394 // This translates "&" to "\\&" which may be wrong...
2395 context.check_layout(os);
2399 else if (p.isParagraph()) {
2400 if (context.new_layout_allowed)
2401 context.new_paragraph(os);
2403 output_ert_inset(os, "\\par ", context);
2404 eat_whitespace(p, os, context, true);
2407 else if (t.cat() == catActive) {
2408 context.check_layout(os);
2409 if (t.character() == '~') {
2410 if (context.layout->free_spacing)
2413 begin_inset(os, "space ~\n");
2420 else if (t.cat() == catBegin) {
2421 Token const next = p.next_token();
2422 Token const end = p.next_next_token();
2423 if (next.cat() == catEnd) {
2425 Token const prev = p.prev_token();
2427 if (p.next_token().character() == '`' ||
2428 (prev.character() == '-' &&
2429 p.next_token().character() == '-'))
2430 ; // ignore it in {}`` or -{}-
2432 output_ert_inset(os, "{}", context);
2433 } else if (next.cat() == catEscape &&
2434 is_known(next.cs(), known_quotes) &&
2435 end.cat() == catEnd) {
2436 // Something like {\textquoteright} (e.g.
2437 // from writer2latex). LyX writes
2438 // \textquoteright{}, so we may skip the
2439 // braces here for better readability.
2440 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2442 } else if (p.next_token().asInput() == "\\ascii") {
2443 // handle the \ascii characters
2444 // (the case without braces is handled later)
2445 // the code is "{\ascii\xxx}"
2446 p.get_token(); // eat \ascii
2447 string name2 = p.get_token().asInput();
2448 p.get_token(); // eat the final '}'
2449 string const name = "{\\ascii" + name2 + "}";
2453 // get the character from unicodesymbols
2454 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2455 Encodings::TEXT_CMD, termination, rem, &req);
2457 context.check_layout(os);
2460 output_ert_inset(os,
2461 to_utf8(rem), context);
2462 for (set<string>::const_iterator it = req.begin();
2463 it != req.end(); ++it)
2464 preamble.registerAutomaticallyLoadedPackage(*it);
2466 // we did not find a non-ert version
2467 output_ert_inset(os, name, context);
2469 context.check_layout(os);
2470 // special handling of font attribute changes
2471 Token const prev = p.prev_token();
2472 TeXFont const oldFont = context.font;
2473 if (next.character() == '[' ||
2474 next.character() == ']' ||
2475 next.character() == '*') {
2477 if (p.next_token().cat() == catEnd) {
2482 output_ert_inset(os, "{", context);
2483 parse_text_snippet(p, os,
2486 output_ert_inset(os, "}", context);
2488 } else if (! context.new_layout_allowed) {
2489 output_ert_inset(os, "{", context);
2490 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2492 output_ert_inset(os, "}", context);
2493 } else if (is_known(next.cs(), known_sizes)) {
2494 // next will change the size, so we must
2496 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2498 if (!context.atParagraphStart())
2500 << context.font.size << "\n";
2501 } else if (is_known(next.cs(), known_font_families)) {
2502 // next will change the font family, so we
2503 // must reset it here
2504 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2506 if (!context.atParagraphStart())
2508 << context.font.family << "\n";
2509 } else if (is_known(next.cs(), known_font_series)) {
2510 // next will change the font series, so we
2511 // must reset it here
2512 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2514 if (!context.atParagraphStart())
2516 << context.font.series << "\n";
2517 } else if (is_known(next.cs(), known_font_shapes)) {
2518 // next will change the font shape, so we
2519 // must reset it here
2520 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2522 if (!context.atParagraphStart())
2524 << context.font.shape << "\n";
2525 } else if (is_known(next.cs(), known_old_font_families) ||
2526 is_known(next.cs(), known_old_font_series) ||
2527 is_known(next.cs(), known_old_font_shapes)) {
2528 // next will change the font family, series
2529 // and shape, so we must reset it here
2530 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2532 if (!context.atParagraphStart())
2534 << context.font.family
2536 << context.font.series
2538 << context.font.shape << "\n";
2540 output_ert_inset(os, "{", context);
2541 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2543 output_ert_inset(os, "}", context);
2548 else if (t.cat() == catEnd) {
2549 if (flags & FLAG_BRACE_LAST) {
2552 cerr << "stray '}' in text\n";
2553 output_ert_inset(os, "}", context);
2556 else if (t.cat() == catComment)
2557 parse_comment(p, os, t, context);
2560 // control sequences
2563 else if (t.cs() == "(" || t.cs() == "[") {
2564 bool const simple = t.cs() == "(";
2565 context.check_layout(os);
2566 begin_inset(os, "Formula");
2567 os << " \\" << t.cs();
2568 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2569 os << '\\' << (simple ? ')' : ']');
2572 // Prevent the conversion of a line break to a
2573 // space (bug 7668). This does not change the
2574 // output, but looks ugly in LyX.
2575 eat_whitespace(p, os, context, false);
2579 else if (t.cs() == "begin")
2580 parse_environment(p, os, outer, last_env,
2583 else if (t.cs() == "end") {
2584 if (flags & FLAG_END) {
2585 // eat environment name
2586 string const name = p.getArg('{', '}');
2587 if (name != active_environment())
2588 cerr << "\\end{" + name + "} does not match \\begin{"
2589 + active_environment() + "}\n";
2592 p.error("found 'end' unexpectedly");
2595 else if (t.cs() == "item") {
2597 bool const optarg = p.hasOpt();
2599 // FIXME: This swallows comments, but we cannot use
2600 // eat_whitespace() since we must not output
2601 // anything before the item.
2602 p.skip_spaces(true);
2603 s = p.verbatimOption();
2605 p.skip_spaces(false);
2607 context.check_layout(os);
2608 if (context.has_item) {
2609 // An item in an unknown list-like environment
2610 // FIXME: Do this in check_layout()!
2611 context.has_item = false;
2613 output_ert_inset(os, "\\item", context);
2615 output_ert_inset(os, "\\item ", context);
2618 if (context.layout->labeltype != LABEL_MANUAL) {
2619 // handle option of itemize item
2620 begin_inset(os, "Argument item:1\n");
2621 os << "status open\n";
2622 os << "\n\\begin_layout Plain Layout\n";
2624 os << parse_text_snippet(p2,
2625 FLAG_BRACK_LAST, outer, context);
2626 // we must not use context.check_end_layout(os)
2627 // because that would close the outer itemize layout
2628 os << "\n\\end_layout\n";
2630 eat_whitespace(p, os, context, false);
2631 } else if (!s.empty()) {
2632 // LyX adds braces around the argument,
2633 // so we need to remove them here.
2634 if (s.size() > 2 && s[0] == '{' &&
2635 s[s.size()-1] == '}')
2636 s = s.substr(1, s.size()-2);
2637 // If the argument contains a space we
2638 // must put it into ERT: Otherwise LyX
2639 // would misinterpret the space as
2640 // item delimiter (bug 7663)
2641 if (contains(s, ' ')) {
2642 output_ert_inset(os, s, context);
2645 os << parse_text_snippet(p2,
2646 FLAG_BRACK_LAST, outer, context);
2648 // The space is needed to separate the
2649 // item from the rest of the sentence.
2651 eat_whitespace(p, os, context, false);
2656 else if (t.cs() == "bibitem") {
2658 context.check_layout(os);
2659 eat_whitespace(p, os, context, false);
2660 string label = convert_command_inset_arg(p.verbatimOption());
2661 string key = convert_command_inset_arg(p.verbatim_item());
2662 if (contains(label, '\\') || contains(key, '\\')) {
2663 // LyX can't handle LaTeX commands in labels or keys
2664 output_ert_inset(os, t.asInput() + '[' + label +
2665 "]{" + p.verbatim_item() + '}',
2668 begin_command_inset(os, "bibitem", "bibitem");
2669 os << "label \"" << label << "\"\n"
2670 "key \"" << key << "\"\n";
2675 else if (is_macro(p)) {
2676 // catch the case of \def\inputGnumericTable
2678 if (t.cs() == "def") {
2679 Token second = p.next_token();
2680 if (second.cs() == "inputGnumericTable") {
2684 Token third = p.get_token();
2686 if (third.cs() == "input") {
2690 string name = normalize_filename(p.verbatim_item());
2691 string const path = getMasterFilePath(true);
2692 // We want to preserve relative / absolute filenames,
2693 // therefore path is only used for testing
2694 // The file extension is in every case ".tex".
2695 // So we need to remove this extension and check for
2696 // the original one.
2697 name = removeExtension(name);
2698 if (!makeAbsPath(name, path).exists()) {
2699 char const * const Gnumeric_formats[] = {"gnumeric",
2701 string const Gnumeric_name =
2702 find_file(name, path, Gnumeric_formats);
2703 if (!Gnumeric_name.empty())
2704 name = Gnumeric_name;
2706 FileName const absname = makeAbsPath(name, path);
2707 if (absname.exists()) {
2708 fix_child_filename(name);
2709 copy_file(absname, name);
2711 cerr << "Warning: Could not find file '"
2712 << name << "'." << endl;
2713 context.check_layout(os);
2714 begin_inset(os, "External\n\ttemplate ");
2715 os << "GnumericSpreadsheet\n\tfilename "
2718 context.check_layout(os);
2720 // register the packages that are automatically loaded
2721 // by the Gnumeric template
2722 registerExternalTemplatePackages("GnumericSpreadsheet");
2727 parse_macro(p, os, context);
2730 else if (t.cs() == "noindent") {
2732 context.add_par_extra_stuff("\\noindent\n");
2735 else if (t.cs() == "appendix") {
2736 context.add_par_extra_stuff("\\start_of_appendix\n");
2737 // We need to start a new paragraph. Otherwise the
2738 // appendix in 'bla\appendix\chapter{' would start
2740 context.new_paragraph(os);
2741 // We need to make sure that the paragraph is
2742 // generated even if it is empty. Otherwise the
2743 // appendix in '\par\appendix\par\chapter{' would
2745 context.check_layout(os);
2746 // FIXME: This is a hack to prevent paragraph
2747 // deletion if it is empty. Handle this better!
2748 output_ert_inset(os,
2749 "%dummy comment inserted by tex2lyx to "
2750 "ensure that this paragraph is not empty",
2752 // Both measures above may generate an additional
2753 // empty paragraph, but that does not hurt, because
2754 // whitespace does not matter here.
2755 eat_whitespace(p, os, context, true);
2758 // Must catch empty dates before findLayout is called below
2759 else if (t.cs() == "date") {
2760 eat_whitespace(p, os, context, false);
2762 string const date = p.verbatim_item();
2765 preamble.suppressDate(true);
2768 preamble.suppressDate(false);
2769 if (context.new_layout_allowed &&
2770 (newlayout = findLayout(context.textclass,
2773 output_command_layout(os, p, outer,
2774 context, newlayout);
2775 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2776 if (!preamble.titleLayoutFound())
2777 preamble.titleLayoutFound(newlayout->intitle);
2778 set<string> const & req = newlayout->requires();
2779 set<string>::const_iterator it = req.begin();
2780 set<string>::const_iterator en = req.end();
2781 for (; it != en; ++it)
2782 preamble.registerAutomaticallyLoadedPackage(*it);
2784 output_ert_inset(os,
2785 "\\date{" + p.verbatim_item() + '}',
2790 // Starred section headings
2791 // Must attempt to parse "Section*" before "Section".
2792 else if ((p.next_token().asInput() == "*") &&
2793 context.new_layout_allowed &&
2794 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2797 output_command_layout(os, p, outer, context, newlayout);
2799 if (!preamble.titleLayoutFound())
2800 preamble.titleLayoutFound(newlayout->intitle);
2801 set<string> const & req = newlayout->requires();
2802 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2803 preamble.registerAutomaticallyLoadedPackage(*it);
2806 // Section headings and the like
2807 else if (context.new_layout_allowed &&
2808 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2810 output_command_layout(os, p, outer, context, newlayout);
2812 if (!preamble.titleLayoutFound())
2813 preamble.titleLayoutFound(newlayout->intitle);
2814 set<string> const & req = newlayout->requires();
2815 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2816 preamble.registerAutomaticallyLoadedPackage(*it);
2819 else if (t.cs() == "caption" || t.cs() == "captionabove" ||
2820 t.cs() == "captionbelow") {
2824 context.check_layout(os);
2826 if (starred && t.cs() == "caption")
2827 begin_inset(os, "Caption LongTableNoNumber\n");
2828 else if (t.cs() == "caption")
2829 begin_inset(os, "Caption Standard\n");
2830 else if (t.cs() == "captionabove")
2831 begin_inset(os, "Caption Above\n");
2832 else if (t.cs() == "captionbelow")
2833 begin_inset(os, "Caption Below\n");
2834 os << "status collapsed\n";
2835 Context newcontext(true, context.textclass, 0, 0, context.font);
2836 newcontext.check_layout(os);
2837 // FIXME InsetArgument is now properly implemented in InsetLayout
2838 // (for captions, but also for others)
2839 if (p.next_token().cat() != catEscape &&
2840 p.next_token().character() == '[') {
2841 p.get_token(); // eat '['
2842 begin_inset(os, "Argument 1\n");
2843 os << "status collapsed\n";
2844 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2846 eat_whitespace(p, os, context, false);
2848 parse_text(p, os, FLAG_ITEM, outer, context);
2849 context.check_end_layout(os);
2850 // We don't need really a new paragraph, but
2851 // we must make sure that the next item gets a \begin_layout.
2852 context.new_paragraph(os);
2855 newcontext.check_end_layout(os);
2858 else if (t.cs() == "subfloat") {
2859 // the syntax is \subfloat[caption]{content}
2860 // if it is a table of figure depends on the surrounding float
2861 bool has_caption = false;
2863 // do nothing if there is no outer float
2864 if (!float_type.empty()) {
2865 context.check_layout(os);
2867 begin_inset(os, "Float " + float_type + "\n");
2869 << "\nsideways false"
2870 << "\nstatus collapsed\n\n";
2873 if (p.next_token().cat() != catEscape &&
2874 p.next_token().character() == '[') {
2875 p.get_token(); // eat '['
2876 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2880 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2881 // the caption comes always as the last
2883 // we must make sure that the caption gets a \begin_layout
2884 os << "\n\\begin_layout Plain Layout";
2886 begin_inset(os, "Caption Standard\n");
2887 Context newcontext(true, context.textclass,
2888 0, 0, context.font);
2889 newcontext.check_layout(os);
2890 os << caption << "\n";
2891 newcontext.check_end_layout(os);
2892 // We don't need really a new paragraph, but
2893 // we must make sure that the next item gets a \begin_layout.
2894 //newcontext.new_paragraph(os);
2898 // We don't need really a new paragraph, but
2899 // we must make sure that the next item gets a \begin_layout.
2901 context.new_paragraph(os);
2904 context.check_end_layout(os);
2905 // close the layout we opened
2907 os << "\n\\end_layout\n";
2909 // if the float type is not supported or there is no surrounding float
2912 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2913 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2914 "]{" + p.verbatim_item() + '}', context);
2916 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2920 else if (t.cs() == "includegraphics") {
2921 bool const clip = p.next_token().asInput() == "*";
2924 string const arg = p.getArg('[', ']');
2925 map<string, string> opts;
2926 vector<string> keys;
2927 split_map(arg, opts, keys);
2929 opts["clip"] = string();
2930 string name = normalize_filename(p.verbatim_item());
2932 string const path = getMasterFilePath(true);
2933 // We want to preserve relative / absolute filenames,
2934 // therefore path is only used for testing
2935 if (!makeAbsPath(name, path).exists()) {
2936 // The file extension is probably missing.
2937 // Now try to find it out.
2938 string const dvips_name =
2939 find_file(name, path,
2940 known_dvips_graphics_formats);
2941 string const pdftex_name =
2942 find_file(name, path,
2943 known_pdftex_graphics_formats);
2944 if (!dvips_name.empty()) {
2945 if (!pdftex_name.empty()) {
2946 cerr << "This file contains the "
2948 "\"\\includegraphics{"
2950 "However, files\n\""
2951 << dvips_name << "\" and\n\""
2952 << pdftex_name << "\"\n"
2953 "both exist, so I had to make a "
2954 "choice and took the first one.\n"
2955 "Please move the unwanted one "
2956 "someplace else and try again\n"
2957 "if my choice was wrong."
2961 } else if (!pdftex_name.empty()) {
2967 FileName const absname = makeAbsPath(name, path);
2968 if (absname.exists()) {
2969 fix_child_filename(name);
2970 copy_file(absname, name);
2972 cerr << "Warning: Could not find graphics file '"
2973 << name << "'." << endl;
2975 context.check_layout(os);
2976 begin_inset(os, "Graphics ");
2977 os << "\n\tfilename " << name << '\n';
2978 if (opts.find("width") != opts.end())
2980 << translate_len(opts["width"]) << '\n';
2981 if (opts.find("height") != opts.end())
2983 << translate_len(opts["height"]) << '\n';
2984 if (opts.find("scale") != opts.end()) {
2985 istringstream iss(opts["scale"]);
2989 os << "\tscale " << val << '\n';
2991 if (opts.find("angle") != opts.end()) {
2992 os << "\trotateAngle "
2993 << opts["angle"] << '\n';
2994 vector<string>::const_iterator a =
2995 find(keys.begin(), keys.end(), "angle");
2996 vector<string>::const_iterator s =
2997 find(keys.begin(), keys.end(), "width");
2998 if (s == keys.end())
2999 s = find(keys.begin(), keys.end(), "height");
3000 if (s == keys.end())
3001 s = find(keys.begin(), keys.end(), "scale");
3002 if (s != keys.end() && distance(s, a) > 0)
3003 os << "\tscaleBeforeRotation\n";
3005 if (opts.find("origin") != opts.end()) {
3007 string const opt = opts["origin"];
3008 if (opt.find('l') != string::npos) ss << "left";
3009 if (opt.find('r') != string::npos) ss << "right";
3010 if (opt.find('c') != string::npos) ss << "center";
3011 if (opt.find('t') != string::npos) ss << "Top";
3012 if (opt.find('b') != string::npos) ss << "Bottom";
3013 if (opt.find('B') != string::npos) ss << "Baseline";
3014 if (!ss.str().empty())
3015 os << "\trotateOrigin " << ss.str() << '\n';
3017 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3019 if (opts.find("keepaspectratio") != opts.end())
3020 os << "\tkeepAspectRatio\n";
3021 if (opts.find("clip") != opts.end())
3023 if (opts.find("draft") != opts.end())
3025 if (opts.find("bb") != opts.end())
3026 os << "\tBoundingBox "
3027 << opts["bb"] << '\n';
3028 int numberOfbbOptions = 0;
3029 if (opts.find("bbllx") != opts.end())
3030 numberOfbbOptions++;
3031 if (opts.find("bblly") != opts.end())
3032 numberOfbbOptions++;
3033 if (opts.find("bburx") != opts.end())
3034 numberOfbbOptions++;
3035 if (opts.find("bbury") != opts.end())
3036 numberOfbbOptions++;
3037 if (numberOfbbOptions == 4)
3038 os << "\tBoundingBox "
3039 << opts["bbllx"] << " " << opts["bblly"] << " "
3040 << opts["bburx"] << " " << opts["bbury"] << '\n';
3041 else if (numberOfbbOptions > 0)
3042 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3043 numberOfbbOptions = 0;
3044 if (opts.find("natwidth") != opts.end())
3045 numberOfbbOptions++;
3046 if (opts.find("natheight") != opts.end())
3047 numberOfbbOptions++;
3048 if (numberOfbbOptions == 2)
3049 os << "\tBoundingBox 0bp 0bp "
3050 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3051 else if (numberOfbbOptions > 0)
3052 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3053 ostringstream special;
3054 if (opts.find("hiresbb") != opts.end())
3055 special << "hiresbb,";
3056 if (opts.find("trim") != opts.end())
3058 if (opts.find("viewport") != opts.end())
3059 special << "viewport=" << opts["viewport"] << ',';
3060 if (opts.find("totalheight") != opts.end())
3061 special << "totalheight=" << opts["totalheight"] << ',';
3062 if (opts.find("type") != opts.end())
3063 special << "type=" << opts["type"] << ',';
3064 if (opts.find("ext") != opts.end())
3065 special << "ext=" << opts["ext"] << ',';
3066 if (opts.find("read") != opts.end())
3067 special << "read=" << opts["read"] << ',';
3068 if (opts.find("command") != opts.end())
3069 special << "command=" << opts["command"] << ',';
3070 string s_special = special.str();
3071 if (!s_special.empty()) {
3072 // We had special arguments. Remove the trailing ','.
3073 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3075 // TODO: Handle the unknown settings better.
3076 // Warn about invalid options.
3077 // Check whether some option was given twice.
3079 preamble.registerAutomaticallyLoadedPackage("graphicx");
3082 else if (t.cs() == "footnote" ||
3083 (t.cs() == "thanks" && context.layout->intitle)) {
3085 context.check_layout(os);
3086 begin_inset(os, "Foot\n");
3087 os << "status collapsed\n\n";
3088 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3092 else if (t.cs() == "marginpar") {
3094 context.check_layout(os);
3095 begin_inset(os, "Marginal\n");
3096 os << "status collapsed\n\n";
3097 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3101 else if (t.cs() == "lstinline") {
3103 parse_listings(p, os, context, true);
3106 else if (t.cs() == "ensuremath") {
3108 context.check_layout(os);
3109 string const s = p.verbatim_item();
3110 //FIXME: this never triggers in UTF8
3111 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3114 output_ert_inset(os, "\\ensuremath{" + s + "}",
3118 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3119 if (preamble.titleLayoutFound()) {
3121 skip_spaces_braces(p);
3123 output_ert_inset(os, t.asInput(), context);
3126 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3127 context.check_layout(os);
3128 begin_command_inset(os, "toc", t.cs());
3130 skip_spaces_braces(p);
3131 if (t.cs() == "lstlistoflistings")
3132 preamble.registerAutomaticallyLoadedPackage("listings");
3135 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3136 context.check_layout(os);
3137 if (t.cs() == "listoffigures")
3138 begin_inset(os, "FloatList figure\n");
3140 begin_inset(os, "FloatList table\n");
3142 skip_spaces_braces(p);
3145 else if (t.cs() == "listof") {
3146 p.skip_spaces(true);
3147 string const name = p.get_token().cs();
3148 if (context.textclass.floats().typeExist(name)) {
3149 context.check_layout(os);
3150 begin_inset(os, "FloatList ");
3153 p.get_token(); // swallow second arg
3155 output_ert_inset(os, "\\listof{" + name + "}", context);
3158 else if ((where = is_known(t.cs(), known_text_font_families)))
3159 parse_text_attributes(p, os, FLAG_ITEM, outer,
3160 context, "\\family", context.font.family,
3161 known_coded_font_families[where - known_text_font_families]);
3163 else if ((where = is_known(t.cs(), known_text_font_series)))
3164 parse_text_attributes(p, os, FLAG_ITEM, outer,
3165 context, "\\series", context.font.series,
3166 known_coded_font_series[where - known_text_font_series]);
3168 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3169 parse_text_attributes(p, os, FLAG_ITEM, outer,
3170 context, "\\shape", context.font.shape,
3171 known_coded_font_shapes[where - known_text_font_shapes]);
3173 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3174 context.check_layout(os);
3175 TeXFont oldFont = context.font;
3176 context.font.init();
3177 context.font.size = oldFont.size;
3178 os << "\n\\family " << context.font.family << "\n";
3179 os << "\n\\series " << context.font.series << "\n";
3180 os << "\n\\shape " << context.font.shape << "\n";
3181 if (t.cs() == "textnormal") {
3182 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3183 output_font_change(os, context.font, oldFont);
3184 context.font = oldFont;
3186 eat_whitespace(p, os, context, false);
3189 else if (t.cs() == "textcolor") {
3190 // scheme is \textcolor{color name}{text}
3191 string const color = p.verbatim_item();
3192 // we only support the predefined colors of the color package
3193 if (color == "black" || color == "blue" || color == "cyan"
3194 || color == "green" || color == "magenta" || color == "red"
3195 || color == "white" || color == "yellow") {
3196 context.check_layout(os);
3197 os << "\n\\color " << color << "\n";
3198 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3199 context.check_layout(os);
3200 os << "\n\\color inherit\n";
3201 preamble.registerAutomaticallyLoadedPackage("color");
3203 // for custom defined colors
3204 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3207 else if (t.cs() == "underbar" || t.cs() == "uline") {
3208 // \underbar is not 100% correct (LyX outputs \uline
3209 // of ulem.sty). The difference is that \ulem allows
3210 // line breaks, and \underbar does not.
3211 // Do NOT handle \underline.
3212 // \underbar cuts through y, g, q, p etc.,
3213 // \underline does not.
3214 context.check_layout(os);
3215 os << "\n\\bar under\n";
3216 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3217 context.check_layout(os);
3218 os << "\n\\bar default\n";
3219 preamble.registerAutomaticallyLoadedPackage("ulem");
3222 else if (t.cs() == "sout") {
3223 context.check_layout(os);
3224 os << "\n\\strikeout on\n";
3225 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3226 context.check_layout(os);
3227 os << "\n\\strikeout default\n";
3228 preamble.registerAutomaticallyLoadedPackage("ulem");
3231 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3232 t.cs() == "emph" || t.cs() == "noun") {
3233 context.check_layout(os);
3234 os << "\n\\" << t.cs() << " on\n";
3235 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3236 context.check_layout(os);
3237 os << "\n\\" << t.cs() << " default\n";
3238 if (t.cs() == "uuline" || t.cs() == "uwave")
3239 preamble.registerAutomaticallyLoadedPackage("ulem");
3242 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3243 context.check_layout(os);
3244 string name = p.getArg('{', '}');
3245 string localtime = p.getArg('{', '}');
3246 preamble.registerAuthor(name);
3247 Author const & author = preamble.getAuthor(name);
3248 // from_asctime_utc() will fail if LyX decides to output the
3249 // time in the text language.
3250 time_t ptime = from_asctime_utc(localtime);
3251 if (ptime == static_cast<time_t>(-1)) {
3252 cerr << "Warning: Could not parse time `" << localtime
3253 << "´ for change tracking, using current time instead.\n";
3254 ptime = current_time();
3256 if (t.cs() == "lyxadded")
3257 os << "\n\\change_inserted ";
3259 os << "\n\\change_deleted ";
3260 os << author.bufferId() << ' ' << ptime << '\n';
3261 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3262 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3263 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3264 LaTeXPackages::isAvailable("xcolor");
3265 // No need to test for luatex, since luatex comes in
3266 // two flavours (dvi and pdf), like latex, and those
3267 // are detected by pdflatex.
3268 if (pdflatex || xetex) {
3270 preamble.registerAutomaticallyLoadedPackage("ulem");
3271 preamble.registerAutomaticallyLoadedPackage("xcolor");
3272 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3276 preamble.registerAutomaticallyLoadedPackage("dvipost");
3277 } else if (xcolorulem) {
3278 preamble.registerAutomaticallyLoadedPackage("ulem");
3279 preamble.registerAutomaticallyLoadedPackage("xcolor");
3284 else if (t.cs() == "textipa") {
3285 context.check_layout(os);
3286 begin_inset(os, "IPA\n");
3287 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3289 preamble.registerAutomaticallyLoadedPackage("tipa");
3290 preamble.registerAutomaticallyLoadedPackage("tipx");
3293 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3294 context.check_layout(os);
3295 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3296 os << "status open\n";
3297 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3302 else if (t.cs() == "textvertline") {
3303 // FIXME: This is not correct, \textvertline is higher than |
3309 else if (t.cs() == "tone" ) {
3310 context.check_layout(os);
3311 // register the tone package
3312 preamble.registerAutomaticallyLoadedPackage("tone");
3313 string content = trimSpaceAndEol(p.verbatim_item());
3314 string command = t.asInput() + "{" + content + "}";
3315 // some tones can be detected by unicodesymbols, some need special code
3316 if (is_known(content, known_tones)) {
3317 os << "\\IPAChar " << command << "\n";
3320 // try to see whether the string is in unicodesymbols
3324 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3325 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3326 termination, rem, &req);
3330 output_ert_inset(os, to_utf8(rem), context);
3331 for (set<string>::const_iterator it = req.begin();
3332 it != req.end(); ++it)
3333 preamble.registerAutomaticallyLoadedPackage(*it);
3335 // we did not find a non-ert version
3336 output_ert_inset(os, command, context);
3339 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3340 t.cs() == "vphantom") {
3341 context.check_layout(os);
3342 if (t.cs() == "phantom")
3343 begin_inset(os, "Phantom Phantom\n");
3344 if (t.cs() == "hphantom")
3345 begin_inset(os, "Phantom HPhantom\n");
3346 if (t.cs() == "vphantom")
3347 begin_inset(os, "Phantom VPhantom\n");
3348 os << "status open\n";
3349 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3354 else if (t.cs() == "href") {
3355 context.check_layout(os);
3356 string target = convert_command_inset_arg(p.verbatim_item());
3357 string name = convert_command_inset_arg(p.verbatim_item());
3359 size_t i = target.find(':');
3360 if (i != string::npos) {
3361 type = target.substr(0, i + 1);
3362 if (type == "mailto:" || type == "file:")
3363 target = target.substr(i + 1);
3364 // handle the case that name is equal to target, except of "http://"
3365 else if (target.substr(i + 3) == name && type == "http:")
3368 begin_command_inset(os, "href", "href");
3370 os << "name \"" << name << "\"\n";
3371 os << "target \"" << target << "\"\n";
3372 if (type == "mailto:" || type == "file:")
3373 os << "type \"" << type << "\"\n";
3375 skip_spaces_braces(p);
3378 else if (t.cs() == "lyxline") {
3379 // swallow size argument (it is not used anyway)
3381 if (!context.atParagraphStart()) {
3382 // so our line is in the middle of a paragraph
3383 // we need to add a new line, lest this line
3384 // follow the other content on that line and
3385 // run off the side of the page
3386 // FIXME: This may create an empty paragraph,
3387 // but without that it would not be
3388 // possible to set noindent below.
3389 // Fortunately LaTeX does not care
3390 // about the empty paragraph.
3391 context.new_paragraph(os);
3393 if (preamble.indentParagraphs()) {
3394 // we need to unindent, lest the line be too long
3395 context.add_par_extra_stuff("\\noindent\n");
3397 context.check_layout(os);
3398 begin_command_inset(os, "line", "rule");
3399 os << "offset \"0.5ex\"\n"
3400 "width \"100line%\"\n"
3405 else if (t.cs() == "rule") {
3406 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3407 string const width = p.getArg('{', '}');
3408 string const thickness = p.getArg('{', '}');
3409 context.check_layout(os);
3410 begin_command_inset(os, "line", "rule");
3411 if (!offset.empty())
3412 os << "offset \"" << translate_len(offset) << "\"\n";
3413 os << "width \"" << translate_len(width) << "\"\n"
3414 "height \"" << translate_len(thickness) << "\"\n";
3418 else if (is_known(t.cs(), known_phrases) ||
3419 (t.cs() == "protect" &&
3420 p.next_token().cat() == catEscape &&
3421 is_known(p.next_token().cs(), known_phrases))) {
3422 // LyX sometimes puts a \protect in front, so we have to ignore it
3423 // FIXME: This needs to be changed when bug 4752 is fixed.
3425 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3427 context.check_layout(os);
3428 os << known_coded_phrases[where - known_phrases];
3429 skip_spaces_braces(p);
3432 // handle refstyle first to catch \eqref which can also occur
3433 // without refstyle. Only recognize these commands if
3434 // refstyle.sty was found in the preamble (otherwise \eqref
3435 // and user defined ref commands could be misdetected).
3436 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3437 preamble.refstyle()) {
3438 context.check_layout(os);
3439 begin_command_inset(os, "ref", "formatted");
3440 os << "reference \"";
3441 os << known_refstyle_prefixes[where - known_refstyle_commands]
3443 os << convert_command_inset_arg(p.verbatim_item())
3446 preamble.registerAutomaticallyLoadedPackage("refstyle");
3449 // if refstyle is used, we must not convert \prettyref to a
3450 // formatted reference, since that would result in a refstyle command.
3451 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3452 (t.cs() != "prettyref" || !preamble.refstyle())) {
3453 string const opt = p.getOpt();
3455 context.check_layout(os);
3456 begin_command_inset(os, "ref",
3457 known_coded_ref_commands[where - known_ref_commands]);
3458 os << "reference \""
3459 << convert_command_inset_arg(p.verbatim_item())
3462 if (t.cs() == "vref" || t.cs() == "vpageref")
3463 preamble.registerAutomaticallyLoadedPackage("varioref");
3464 else if (t.cs() == "prettyref")
3465 preamble.registerAutomaticallyLoadedPackage("prettyref");
3467 // LyX does not yet support optional arguments of ref commands
3468 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3469 p.verbatim_item() + '}', context);
3473 else if (use_natbib &&
3474 is_known(t.cs(), known_natbib_commands) &&
3475 ((t.cs() != "citefullauthor" &&
3476 t.cs() != "citeyear" &&
3477 t.cs() != "citeyearpar") ||
3478 p.next_token().asInput() != "*")) {
3479 context.check_layout(os);
3480 string command = t.cs();
3481 if (p.next_token().asInput() == "*") {
3485 if (command == "citefullauthor")
3486 // alternative name for "\\citeauthor*"
3487 command = "citeauthor*";
3489 // text before the citation
3491 // text after the citation
3493 get_cite_arguments(p, true, before, after);
3495 if (command == "cite") {
3496 // \cite without optional argument means
3497 // \citet, \cite with at least one optional
3498 // argument means \citep.
3499 if (before.empty() && after.empty())
3504 if (before.empty() && after == "[]")
3505 // avoid \citet[]{a}
3507 else if (before == "[]" && after == "[]") {
3508 // avoid \citet[][]{a}
3512 // remove the brackets around after and before
3513 if (!after.empty()) {
3515 after.erase(after.length() - 1, 1);
3516 after = convert_command_inset_arg(after);
3518 if (!before.empty()) {
3520 before.erase(before.length() - 1, 1);
3521 before = convert_command_inset_arg(before);
3523 begin_command_inset(os, "citation", command);
3524 os << "after " << '"' << after << '"' << "\n";
3525 os << "before " << '"' << before << '"' << "\n";
3527 << convert_command_inset_arg(p.verbatim_item())
3530 // Need to set the cite engine if natbib is loaded by
3531 // the document class directly
3532 if (preamble.citeEngine() == "basic")
3533 preamble.citeEngine("natbib");
3536 else if (use_jurabib &&
3537 is_known(t.cs(), known_jurabib_commands) &&
3538 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3539 context.check_layout(os);
3540 string command = t.cs();
3541 if (p.next_token().asInput() == "*") {
3545 char argumentOrder = '\0';
3546 vector<string> const options =
3547 preamble.getPackageOptions("jurabib");
3548 if (find(options.begin(), options.end(),
3549 "natbiborder") != options.end())
3550 argumentOrder = 'n';
3551 else if (find(options.begin(), options.end(),
3552 "jurabiborder") != options.end())
3553 argumentOrder = 'j';
3555 // text before the citation
3557 // text after the citation
3559 get_cite_arguments(p, argumentOrder != 'j', before, after);
3561 string const citation = p.verbatim_item();
3562 if (!before.empty() && argumentOrder == '\0') {
3563 cerr << "Warning: Assuming argument order "
3564 "of jurabib version 0.6 for\n'"
3565 << command << before << after << '{'
3566 << citation << "}'.\n"
3567 "Add 'jurabiborder' to the jurabib "
3568 "package options if you used an\n"
3569 "earlier jurabib version." << endl;
3571 if (!after.empty()) {
3573 after.erase(after.length() - 1, 1);
3575 if (!before.empty()) {
3577 before.erase(before.length() - 1, 1);
3579 begin_command_inset(os, "citation", command);
3580 os << "after " << '"' << after << '"' << "\n";
3581 os << "before " << '"' << before << '"' << "\n";
3582 os << "key " << '"' << citation << '"' << "\n";
3584 // Need to set the cite engine if jurabib is loaded by
3585 // the document class directly
3586 if (preamble.citeEngine() == "basic")
3587 preamble.citeEngine("jurabib");
3590 else if (t.cs() == "cite"
3591 || t.cs() == "nocite") {
3592 context.check_layout(os);
3593 string after = convert_command_inset_arg(p.getArg('[', ']'));
3594 string key = convert_command_inset_arg(p.verbatim_item());
3595 // store the case that it is "\nocite{*}" to use it later for
3598 begin_command_inset(os, "citation", t.cs());
3599 os << "after " << '"' << after << '"' << "\n";
3600 os << "key " << '"' << key << '"' << "\n";
3602 } else if (t.cs() == "nocite")
3606 else if (t.cs() == "index" ||
3607 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3608 context.check_layout(os);
3609 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3610 p.getArg('[', ']') : "";
3611 string const kind = arg.empty() ? "idx" : arg;
3612 begin_inset(os, "Index ");
3613 os << kind << "\nstatus collapsed\n";
3614 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3617 preamble.registerAutomaticallyLoadedPackage("splitidx");
3620 else if (t.cs() == "nomenclature") {
3621 context.check_layout(os);
3622 begin_command_inset(os, "nomenclature", "nomenclature");
3623 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3624 if (!prefix.empty())
3625 os << "prefix " << '"' << prefix << '"' << "\n";
3626 os << "symbol " << '"'
3627 << convert_command_inset_arg(p.verbatim_item());
3628 os << "\"\ndescription \""
3629 << convert_command_inset_arg(p.verbatim_item())
3632 preamble.registerAutomaticallyLoadedPackage("nomencl");
3635 else if (t.cs() == "label") {
3636 context.check_layout(os);
3637 begin_command_inset(os, "label", "label");
3639 << convert_command_inset_arg(p.verbatim_item())
3644 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3645 context.check_layout(os);
3646 string commandname = t.cs();
3648 if (p.next_token().asInput() == "*") {
3653 begin_command_inset(os, "index_print", commandname);
3654 string const indexname = p.getArg('[', ']');
3656 if (indexname.empty())
3657 os << "type \"idx\"\n";
3659 os << "type \"" << indexname << "\"\n";
3662 skip_spaces_braces(p);
3663 preamble.registerAutomaticallyLoadedPackage("makeidx");
3664 if (preamble.use_indices() == "true")
3665 preamble.registerAutomaticallyLoadedPackage("splitidx");
3668 else if (t.cs() == "printnomenclature") {
3670 string width_type = "";
3671 context.check_layout(os);
3672 begin_command_inset(os, "nomencl_print", "printnomenclature");
3673 // case of a custom width
3675 width = p.getArg('[', ']');
3676 width = translate_len(width);
3677 width_type = "custom";
3679 // case of no custom width
3680 // the case of no custom width but the width set
3681 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3682 // because the user could have set anything, not only the width
3683 // of the longest label (which would be width_type = "auto")
3684 string label = convert_command_inset_arg(p.getArg('{', '}'));
3685 if (label.empty() && width_type.empty())
3686 width_type = "none";
3687 os << "set_width \"" << width_type << "\"\n";
3688 if (width_type == "custom")
3689 os << "width \"" << width << '\"';
3691 skip_spaces_braces(p);
3692 preamble.registerAutomaticallyLoadedPackage("nomencl");
3695 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3696 context.check_layout(os);
3697 begin_inset(os, "script ");
3698 os << t.cs().substr(4) << '\n';
3699 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3701 if (t.cs() == "textsubscript")
3702 preamble.registerAutomaticallyLoadedPackage("subscript");
3705 else if ((where = is_known(t.cs(), known_quotes))) {
3706 context.check_layout(os);
3707 begin_inset(os, "Quotes ");
3708 os << known_coded_quotes[where - known_quotes];
3710 // LyX adds {} after the quote, so we have to eat
3711 // spaces here if there are any before a possible
3713 eat_whitespace(p, os, context, false);
3717 else if ((where = is_known(t.cs(), known_sizes)) &&
3718 context.new_layout_allowed) {
3719 context.check_layout(os);
3720 TeXFont const oldFont = context.font;
3721 context.font.size = known_coded_sizes[where - known_sizes];
3722 output_font_change(os, oldFont, context.font);
3723 eat_whitespace(p, os, context, false);
3726 else if ((where = is_known(t.cs(), known_font_families)) &&
3727 context.new_layout_allowed) {
3728 context.check_layout(os);
3729 TeXFont const oldFont = context.font;
3730 context.font.family =
3731 known_coded_font_families[where - known_font_families];
3732 output_font_change(os, oldFont, context.font);
3733 eat_whitespace(p, os, context, false);
3736 else if ((where = is_known(t.cs(), known_font_series)) &&
3737 context.new_layout_allowed) {
3738 context.check_layout(os);
3739 TeXFont const oldFont = context.font;
3740 context.font.series =
3741 known_coded_font_series[where - known_font_series];
3742 output_font_change(os, oldFont, context.font);
3743 eat_whitespace(p, os, context, false);
3746 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3747 context.new_layout_allowed) {
3748 context.check_layout(os);
3749 TeXFont const oldFont = context.font;
3750 context.font.shape =
3751 known_coded_font_shapes[where - known_font_shapes];
3752 output_font_change(os, oldFont, context.font);
3753 eat_whitespace(p, os, context, false);
3755 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3756 context.new_layout_allowed) {
3757 context.check_layout(os);
3758 TeXFont const oldFont = context.font;
3759 context.font.init();
3760 context.font.size = oldFont.size;
3761 context.font.family =
3762 known_coded_font_families[where - known_old_font_families];
3763 output_font_change(os, oldFont, context.font);
3764 eat_whitespace(p, os, context, false);
3767 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3768 context.new_layout_allowed) {
3769 context.check_layout(os);
3770 TeXFont const oldFont = context.font;
3771 context.font.init();
3772 context.font.size = oldFont.size;
3773 context.font.series =
3774 known_coded_font_series[where - known_old_font_series];
3775 output_font_change(os, oldFont, context.font);
3776 eat_whitespace(p, os, context, false);
3779 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3780 context.new_layout_allowed) {
3781 context.check_layout(os);
3782 TeXFont const oldFont = context.font;
3783 context.font.init();
3784 context.font.size = oldFont.size;
3785 context.font.shape =
3786 known_coded_font_shapes[where - known_old_font_shapes];
3787 output_font_change(os, oldFont, context.font);
3788 eat_whitespace(p, os, context, false);
3791 else if (t.cs() == "selectlanguage") {
3792 context.check_layout(os);
3793 // save the language for the case that a
3794 // \foreignlanguage is used
3795 context.font.language = babel2lyx(p.verbatim_item());
3796 os << "\n\\lang " << context.font.language << "\n";
3799 else if (t.cs() == "foreignlanguage") {
3800 string const lang = babel2lyx(p.verbatim_item());
3801 parse_text_attributes(p, os, FLAG_ITEM, outer,
3803 context.font.language, lang);
3806 else if (prefixIs(t.cs(), "text")
3807 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3808 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3810 // We have to output the whole command if it has an option
3811 // because LyX doesn't support this yet, see bug #8214,
3812 // only if there is a single option specifying a variant, we can handle it.
3814 string langopts = p.getOpt();
3815 // check if the option contains a variant, if yes, extract it
3816 string::size_type pos_var = langopts.find("variant");
3817 string::size_type i = langopts.find(',');
3818 string::size_type k = langopts.find('=', pos_var);
3819 if (pos_var != string::npos && i == string::npos) {
3821 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3822 lang = preamble.polyglossia2lyx(variant);
3823 parse_text_attributes(p, os, FLAG_ITEM, outer,
3825 context.font.language, lang);
3827 output_ert_inset(os, t.asInput() + langopts, context);
3829 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3830 parse_text_attributes(p, os, FLAG_ITEM, outer,
3832 context.font.language, lang);
3836 else if (t.cs() == "inputencoding") {
3837 // nothing to write here
3838 string const enc = subst(p.verbatim_item(), "\n", " ");
3839 p.setEncoding(enc, Encoding::inputenc);
3842 else if ((where = is_known(t.cs(), known_special_chars))) {
3843 context.check_layout(os);
3844 os << known_coded_special_chars[where - known_special_chars];
3845 skip_spaces_braces(p);
3848 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3849 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3850 context.check_layout(os);
3851 os << "\\SpecialChar \\" << t.cs()
3852 << p.get_token().asInput() << '\n';
3855 else if (t.cs() == "textquotedbl") {
3856 context.check_layout(os);
3861 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3862 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3863 || t.cs() == "%" || t.cs() == "-") {
3864 context.check_layout(os);
3866 os << "\\SpecialChar \\-\n";
3871 else if (t.cs() == "char") {
3872 context.check_layout(os);
3873 if (p.next_token().character() == '`') {
3875 if (p.next_token().cs() == "\"") {
3880 output_ert_inset(os, "\\char`", context);
3883 output_ert_inset(os, "\\char", context);
3887 else if (t.cs() == "verb") {
3888 context.check_layout(os);
3889 // set catcodes to verbatim early, just in case.
3890 p.setCatcodes(VERBATIM_CATCODES);
3891 string delim = p.get_token().asInput();
3892 Parser::Arg arg = p.verbatimStuff(delim);
3894 output_ert_inset(os, "\\verb" + delim
3895 + arg.second + delim, context);
3897 cerr << "invalid \\verb command. Skipping" << endl;
3900 // Problem: \= creates a tabstop inside the tabbing environment
3901 // and else an accent. In the latter case we really would want
3902 // \={o} instead of \= o.
3903 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3904 output_ert_inset(os, t.asInput(), context);
3906 else if (t.cs() == "\\") {
3907 context.check_layout(os);
3909 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3910 else if (p.next_token().asInput() == "*") {
3912 // getOpt() eats the following space if there
3913 // is no optional argument, but that is OK
3914 // here since it has no effect in the output.
3915 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3918 begin_inset(os, "Newline newline");
3923 else if (t.cs() == "newline" ||
3924 (t.cs() == "linebreak" && !p.hasOpt())) {
3925 context.check_layout(os);
3926 begin_inset(os, "Newline ");
3929 skip_spaces_braces(p);
3932 else if (t.cs() == "input" || t.cs() == "include"
3933 || t.cs() == "verbatiminput") {
3934 string name = t.cs();
3935 if (t.cs() == "verbatiminput"
3936 && p.next_token().asInput() == "*")
3937 name += p.get_token().asInput();
3938 context.check_layout(os);
3939 string filename(normalize_filename(p.getArg('{', '}')));
3940 string const path = getMasterFilePath(true);
3941 // We want to preserve relative / absolute filenames,
3942 // therefore path is only used for testing
3943 if ((t.cs() == "include" || t.cs() == "input") &&
3944 !makeAbsPath(filename, path).exists()) {
3945 // The file extension is probably missing.
3946 // Now try to find it out.
3947 string const tex_name =
3948 find_file(filename, path,
3949 known_tex_extensions);
3950 if (!tex_name.empty())
3951 filename = tex_name;
3953 bool external = false;
3955 if (makeAbsPath(filename, path).exists()) {
3956 string const abstexname =
3957 makeAbsPath(filename, path).absFileName();
3958 string const absfigname =
3959 changeExtension(abstexname, ".fig");
3960 fix_child_filename(filename);
3961 string const lyxname = changeExtension(filename,
3962 roundtripMode() ? ".lyx.lyx" : ".lyx");
3963 string const abslyxname = makeAbsPath(
3964 lyxname, getParentFilePath(false)).absFileName();
3966 if (!skipChildren())
3967 external = FileName(absfigname).exists();
3968 if (t.cs() == "input" && !skipChildren()) {
3969 string const ext = getExtension(abstexname);
3971 // Combined PS/LaTeX:
3972 // x.eps, x.pstex_t (old xfig)
3973 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3974 FileName const absepsname(
3975 changeExtension(abstexname, ".eps"));
3976 FileName const abspstexname(
3977 changeExtension(abstexname, ".pstex"));
3978 bool const xfigeps =
3979 (absepsname.exists() ||
3980 abspstexname.exists()) &&
3983 // Combined PDF/LaTeX:
3984 // x.pdf, x.pdftex_t (old xfig)
3985 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3986 FileName const abspdfname(
3987 changeExtension(abstexname, ".pdf"));
3988 bool const xfigpdf =
3989 abspdfname.exists() &&
3990 (ext == "pdftex_t" || ext == "pdf_t");
3994 // Combined PS/PDF/LaTeX:
3995 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3996 string const absbase2(
3997 removeExtension(abstexname) + "_pspdftex");
3998 FileName const abseps2name(
3999 addExtension(absbase2, ".eps"));
4000 FileName const abspdf2name(
4001 addExtension(absbase2, ".pdf"));
4002 bool const xfigboth =
4003 abspdf2name.exists() &&
4004 abseps2name.exists() && ext == "pspdftex";
4006 xfig = xfigpdf || xfigeps || xfigboth;
4007 external = external && xfig;
4010 outname = changeExtension(filename, ".fig");
4011 FileName abssrc(changeExtension(abstexname, ".fig"));
4012 copy_file(abssrc, outname);
4014 // Don't try to convert, the result
4015 // would be full of ERT.
4017 FileName abssrc(abstexname);
4018 copy_file(abssrc, outname);
4019 } else if (t.cs() != "verbatiminput" &&
4021 tex2lyx(abstexname, FileName(abslyxname),
4024 // no need to call copy_file
4025 // tex2lyx creates the file
4028 FileName abssrc(abstexname);
4029 copy_file(abssrc, outname);
4032 cerr << "Warning: Could not find included file '"
4033 << filename << "'." << endl;
4037 begin_inset(os, "External\n");
4038 os << "\ttemplate XFig\n"
4039 << "\tfilename " << outname << '\n';
4040 registerExternalTemplatePackages("XFig");
4042 begin_command_inset(os, "include", name);
4043 outname = subst(outname, "\"", "\\\"");
4044 os << "preview false\n"
4045 "filename \"" << outname << "\"\n";
4046 if (t.cs() == "verbatiminput")
4047 preamble.registerAutomaticallyLoadedPackage("verbatim");
4052 else if (t.cs() == "bibliographystyle") {
4053 // store new bibliographystyle
4054 bibliographystyle = p.verbatim_item();
4055 // If any other command than \bibliography, \addcontentsline
4056 // and \nocite{*} follows, we need to output the style
4057 // (because it might be used by that command).
4058 // Otherwise, it will automatically be output by LyX.
4061 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4062 if (t2.cat() == catBegin)
4064 if (t2.cat() != catEscape)
4066 if (t2.cs() == "nocite") {
4067 if (p.getArg('{', '}') == "*")
4069 } else if (t2.cs() == "bibliography")
4071 else if (t2.cs() == "phantomsection") {
4075 else if (t2.cs() == "addcontentsline") {
4076 // get the 3 arguments of \addcontentsline
4079 contentslineContent = p.getArg('{', '}');
4080 // if the last argument is not \refname we must output
4081 if (contentslineContent == "\\refname")
4088 output_ert_inset(os,
4089 "\\bibliographystyle{" + bibliographystyle + '}',
4094 else if (t.cs() == "phantomsection") {
4095 // we only support this if it occurs between
4096 // \bibliographystyle and \bibliography
4097 if (bibliographystyle.empty())
4098 output_ert_inset(os, "\\phantomsection", context);
4101 else if (t.cs() == "addcontentsline") {
4102 context.check_layout(os);
4103 // get the 3 arguments of \addcontentsline
4104 string const one = p.getArg('{', '}');
4105 string const two = p.getArg('{', '}');
4106 string const three = p.getArg('{', '}');
4107 // only if it is a \refname, we support if for the bibtex inset
4108 if (contentslineContent != "\\refname") {
4109 output_ert_inset(os,
4110 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4115 else if (t.cs() == "bibliography") {
4116 context.check_layout(os);
4118 begin_command_inset(os, "bibtex", "bibtex");
4119 if (!btprint.empty()) {
4120 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4121 // clear the string because the next BibTeX inset can be without the
4122 // \nocite{*} option
4125 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4126 // Do we have addcontentsline?
4127 if (contentslineContent == "\\refname") {
4128 BibOpts = "bibtotoc";
4129 // clear string because next BibTeX inset can be without addcontentsline
4130 contentslineContent.clear();
4132 // Do we have a bibliographystyle set?
4133 if (!bibliographystyle.empty()) {
4134 if (BibOpts.empty())
4135 BibOpts = bibliographystyle;
4137 BibOpts = BibOpts + ',' + bibliographystyle;
4138 // clear it because each bibtex entry has its style
4139 // and we need an empty string to handle \phantomsection
4140 bibliographystyle.clear();
4142 os << "options " << '"' << BibOpts << '"' << "\n";
4146 else if (t.cs() == "parbox") {
4147 // Test whether this is an outer box of a shaded box
4149 // swallow arguments
4150 while (p.hasOpt()) {
4152 p.skip_spaces(true);
4155 p.skip_spaces(true);
4157 if (p.next_token().cat() == catBegin)
4159 p.skip_spaces(true);
4160 Token to = p.get_token();
4161 bool shaded = false;
4162 if (to.asInput() == "\\begin") {
4163 p.skip_spaces(true);
4164 if (p.getArg('{', '}') == "shaded")
4169 parse_outer_box(p, os, FLAG_ITEM, outer,
4170 context, "parbox", "shaded");
4172 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4176 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4177 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4178 t.cs() == "shadowbox" || t.cs() == "doublebox")
4179 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4181 else if (t.cs() == "framebox") {
4182 if (p.next_token().character() == '(') {
4183 //the syntax is: \framebox(x,y)[position]{content}
4184 string arg = t.asInput();
4185 arg += p.getFullParentheseArg();
4186 arg += p.getFullOpt();
4187 eat_whitespace(p, os, context, false);
4188 output_ert_inset(os, arg + '{', context);
4189 parse_text(p, os, FLAG_ITEM, outer, context);
4190 output_ert_inset(os, "}", context);
4192 //the syntax is: \framebox[width][position]{content}
4193 string special = p.getFullOpt();
4194 special += p.getOpt();
4195 parse_outer_box(p, os, FLAG_ITEM, outer,
4196 context, t.cs(), special);
4200 //\makebox() is part of the picture environment and different from \makebox{}
4201 //\makebox{} will be parsed by parse_box
4202 else if (t.cs() == "makebox") {
4203 if (p.next_token().character() == '(') {
4204 //the syntax is: \makebox(x,y)[position]{content}
4205 string arg = t.asInput();
4206 arg += p.getFullParentheseArg();
4207 arg += p.getFullOpt();
4208 eat_whitespace(p, os, context, false);
4209 output_ert_inset(os, arg + '{', context);
4210 parse_text(p, os, FLAG_ITEM, outer, context);
4211 output_ert_inset(os, "}", context);
4213 //the syntax is: \makebox[width][position]{content}
4214 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4218 else if (t.cs() == "smallskip" ||
4219 t.cs() == "medskip" ||
4220 t.cs() == "bigskip" ||
4221 t.cs() == "vfill") {
4222 context.check_layout(os);
4223 begin_inset(os, "VSpace ");
4226 skip_spaces_braces(p);
4229 else if ((where = is_known(t.cs(), known_spaces))) {
4230 context.check_layout(os);
4231 begin_inset(os, "space ");
4232 os << '\\' << known_coded_spaces[where - known_spaces]
4235 // LaTeX swallows whitespace after all spaces except
4236 // "\\,". We have to do that here, too, because LyX
4237 // adds "{}" which would make the spaces significant.
4239 eat_whitespace(p, os, context, false);
4240 // LyX adds "{}" after all spaces except "\\ " and
4241 // "\\,", so we have to remove "{}".
4242 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4243 // remove the braces after "\\,", too.
4248 else if (t.cs() == "newpage" ||
4249 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4250 t.cs() == "clearpage" ||
4251 t.cs() == "cleardoublepage") {
4252 context.check_layout(os);
4253 begin_inset(os, "Newpage ");
4256 skip_spaces_braces(p);
4259 else if (t.cs() == "DeclareRobustCommand" ||
4260 t.cs() == "DeclareRobustCommandx" ||
4261 t.cs() == "newcommand" ||
4262 t.cs() == "newcommandx" ||
4263 t.cs() == "providecommand" ||
4264 t.cs() == "providecommandx" ||
4265 t.cs() == "renewcommand" ||
4266 t.cs() == "renewcommandx") {
4267 // DeclareRobustCommand, DeclareRobustCommandx,
4268 // providecommand and providecommandx could be handled
4269 // by parse_command(), but we need to call
4270 // add_known_command() here.
4271 string name = t.asInput();
4272 if (p.next_token().asInput() == "*") {
4273 // Starred form. Eat '*'
4277 string const command = p.verbatim_item();
4278 string const opt1 = p.getFullOpt();
4279 string const opt2 = p.getFullOpt();
4280 add_known_command(command, opt1, !opt2.empty());
4281 string const ert = name + '{' + command + '}' +
4283 '{' + p.verbatim_item() + '}';
4285 if (t.cs() == "DeclareRobustCommand" ||
4286 t.cs() == "DeclareRobustCommandx" ||
4287 t.cs() == "providecommand" ||
4288 t.cs() == "providecommandx" ||
4289 name[name.length()-1] == '*')
4290 output_ert_inset(os, ert, context);
4292 context.check_layout(os);
4293 begin_inset(os, "FormulaMacro");
4299 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4300 // let could be handled by parse_command(),
4301 // but we need to call add_known_command() here.
4302 string ert = t.asInput();
4305 if (p.next_token().cat() == catBegin) {
4306 name = p.verbatim_item();
4307 ert += '{' + name + '}';
4309 name = p.verbatim_item();
4314 if (p.next_token().cat() == catBegin) {
4315 command = p.verbatim_item();
4316 ert += '{' + command + '}';
4318 command = p.verbatim_item();
4321 // If command is known, make name known too, to parse
4322 // its arguments correctly. For this reason we also
4323 // have commands in syntax.default that are hardcoded.
4324 CommandMap::iterator it = known_commands.find(command);
4325 if (it != known_commands.end())
4326 known_commands[t.asInput()] = it->second;
4327 output_ert_inset(os, ert, context);
4330 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4333 string name = t.asInput();
4334 string const length = p.verbatim_item();
4337 bool valid = splitLatexLength(length, valstring, unit);
4338 bool known_hspace = false;
4339 bool known_vspace = false;
4340 bool known_unit = false;
4343 istringstream iss(valstring);
4346 if (t.cs()[0] == 'h') {
4347 if (unit == "\\fill") {
4352 known_hspace = true;
4355 if (unit == "\\smallskipamount") {
4357 known_vspace = true;
4358 } else if (unit == "\\medskipamount") {
4360 known_vspace = true;
4361 } else if (unit == "\\bigskipamount") {
4363 known_vspace = true;
4364 } else if (unit == "\\fill") {
4366 known_vspace = true;
4370 if (!known_hspace && !known_vspace) {
4371 switch (unitFromString(unit)) {
4387 //unitFromString(unit) fails for relative units like Length::PCW
4388 // therefore handle them separately
4389 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4390 || unit == "\\textwidth" || unit == "\\linewidth"
4391 || unit == "\\textheight" || unit == "\\paperheight")
4399 // check for glue lengths
4400 bool is_gluelength = false;
4401 string gluelength = length;
4402 string::size_type i = length.find(" minus");
4403 if (i == string::npos) {
4404 i = length.find(" plus");
4405 if (i != string::npos)
4406 is_gluelength = true;
4408 is_gluelength = true;
4409 // if yes transform "9xx minus 8yy plus 7zz"
4411 if (is_gluelength) {
4412 i = gluelength.find(" minus");
4413 if (i != string::npos)
4414 gluelength.replace(i, 7, "-");
4415 i = gluelength.find(" plus");
4416 if (i != string::npos)
4417 gluelength.replace(i, 6, "+");
4420 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4421 // Literal horizontal length or known variable
4422 context.check_layout(os);
4423 begin_inset(os, "space ");
4431 if (known_unit && !known_hspace)
4432 os << "\n\\length " << translate_len(length);
4434 os << "\n\\length " << gluelength;
4436 } else if (known_unit || known_vspace || is_gluelength) {
4437 // Literal vertical length or known variable
4438 context.check_layout(os);
4439 begin_inset(os, "VSpace ");
4442 if (known_unit && !known_vspace)
4443 os << translate_len(length);
4450 // LyX can't handle other length variables in Inset VSpace/space
4455 output_ert_inset(os, name + '{' + unit + '}', context);
4456 else if (value == -1.0)
4457 output_ert_inset(os, name + "{-" + unit + '}', context);
4459 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4461 output_ert_inset(os, name + '{' + length + '}', context);
4465 // The single '=' is meant here.
4466 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4470 context.check_layout(os);
4471 begin_inset(os, "Flex ");
4472 os << to_utf8(newinsetlayout->name()) << '\n'
4473 << "status collapsed\n";
4474 if (newinsetlayout->isPassThru()) {
4475 // set catcodes to verbatim early, just in case.
4476 p.setCatcodes(VERBATIM_CATCODES);
4477 string delim = p.get_token().asInput();
4479 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4480 //FIXME: handle error condition
4481 string const arg = p.verbatimStuff("}").second;
4482 Context newcontext(true, context.textclass);
4483 if (newinsetlayout->forcePlainLayout())
4484 newcontext.layout = &context.textclass.plainLayout();
4485 output_ert(os, arg, newcontext);
4487 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4491 else if (t.cs() == "includepdf") {
4493 string const arg = p.getArg('[', ']');
4494 map<string, string> opts;
4495 vector<string> keys;
4496 split_map(arg, opts, keys);
4497 string name = normalize_filename(p.verbatim_item());
4498 string const path = getMasterFilePath(true);
4499 // We want to preserve relative / absolute filenames,
4500 // therefore path is only used for testing
4501 if (!makeAbsPath(name, path).exists()) {
4502 // The file extension is probably missing.
4503 // Now try to find it out.
4504 char const * const pdfpages_format[] = {"pdf", 0};
4505 string const pdftex_name =
4506 find_file(name, path, pdfpages_format);
4507 if (!pdftex_name.empty()) {
4512 FileName const absname = makeAbsPath(name, path);
4513 if (absname.exists())
4515 fix_child_filename(name);
4516 copy_file(absname, name);
4518 cerr << "Warning: Could not find file '"
4519 << name << "'." << endl;
4521 context.check_layout(os);
4522 begin_inset(os, "External\n\ttemplate ");
4523 os << "PDFPages\n\tfilename "
4525 // parse the options
4526 if (opts.find("pages") != opts.end())
4527 os << "\textra LaTeX \"pages="
4528 << opts["pages"] << "\"\n";
4529 if (opts.find("angle") != opts.end())
4530 os << "\trotateAngle "
4531 << opts["angle"] << '\n';
4532 if (opts.find("origin") != opts.end()) {
4534 string const opt = opts["origin"];
4535 if (opt == "tl") ss << "topleft";
4536 if (opt == "bl") ss << "bottomleft";
4537 if (opt == "Bl") ss << "baselineleft";
4538 if (opt == "c") ss << "center";
4539 if (opt == "tc") ss << "topcenter";
4540 if (opt == "bc") ss << "bottomcenter";
4541 if (opt == "Bc") ss << "baselinecenter";
4542 if (opt == "tr") ss << "topright";
4543 if (opt == "br") ss << "bottomright";
4544 if (opt == "Br") ss << "baselineright";
4545 if (!ss.str().empty())
4546 os << "\trotateOrigin " << ss.str() << '\n';
4548 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4550 if (opts.find("width") != opts.end())
4552 << translate_len(opts["width"]) << '\n';
4553 if (opts.find("height") != opts.end())
4555 << translate_len(opts["height"]) << '\n';
4556 if (opts.find("keepaspectratio") != opts.end())
4557 os << "\tkeepAspectRatio\n";
4559 context.check_layout(os);
4560 registerExternalTemplatePackages("PDFPages");
4563 else if (t.cs() == "loadgame") {
4565 string name = normalize_filename(p.verbatim_item());
4566 string const path = getMasterFilePath(true);
4567 // We want to preserve relative / absolute filenames,
4568 // therefore path is only used for testing
4569 if (!makeAbsPath(name, path).exists()) {
4570 // The file extension is probably missing.
4571 // Now try to find it out.
4572 char const * const lyxskak_format[] = {"fen", 0};
4573 string const lyxskak_name =
4574 find_file(name, path, lyxskak_format);
4575 if (!lyxskak_name.empty())
4576 name = lyxskak_name;
4578 FileName const absname = makeAbsPath(name, path);
4579 if (absname.exists())
4581 fix_child_filename(name);
4582 copy_file(absname, name);
4584 cerr << "Warning: Could not find file '"
4585 << name << "'." << endl;
4586 context.check_layout(os);
4587 begin_inset(os, "External\n\ttemplate ");
4588 os << "ChessDiagram\n\tfilename "
4591 context.check_layout(os);
4592 // after a \loadgame follows a \showboard
4593 if (p.get_token().asInput() == "showboard")
4595 registerExternalTemplatePackages("ChessDiagram");
4599 // try to see whether the string is in unicodesymbols
4600 // Only use text mode commands, since we are in text mode here,
4601 // and math commands may be invalid (bug 6797)
4602 string name = t.asInput();
4603 // handle the dingbats and Cyrillic
4604 if (name == "\\ding" || name == "\\textcyr")
4605 name = name + '{' + p.getArg('{', '}') + '}';
4606 // handle the ifsym characters
4607 else if (name == "\\textifsymbol") {
4608 string const optif = p.getFullOpt();
4609 string const argif = p.getArg('{', '}');
4610 name = name + optif + '{' + argif + '}';
4612 // handle the \ascii characters
4613 // the case of \ascii within braces, as LyX outputs it, is already
4614 // handled for t.cat() == catBegin
4615 else if (name == "\\ascii") {
4616 // the code is "\asci\xxx"
4617 name = "{" + name + p.get_token().asInput() + "}";
4620 // handle some TIPA special characters
4621 else if (preamble.isPackageUsed("tipa")) {
4622 if (name == "\\textglobfall") {
4625 } else if (name == "\\s") {
4626 // fromLaTeXCommand() does not yet
4627 // recognize tipa short cuts
4628 name = "\\textsyllabic";
4629 } else if (name == "\\=" &&
4630 p.next_token().asInput() == "*") {
4631 // fromLaTeXCommand() does not yet
4632 // recognize tipa short cuts
4635 } else if (name == "\\textdoublevertline") {
4636 // FIXME: This is not correct,
4637 // \textvertline is higher than \textbardbl
4638 name = "\\textbardbl";
4640 } else if (name == "\\!" ) {
4641 if (p.next_token().asInput() == "b") {
4642 p.get_token(); // eat 'b'
4645 } else if (p.next_token().asInput() == "d") {
4649 } else if (p.next_token().asInput() == "g") {
4653 } else if (p.next_token().asInput() == "G") {
4655 name = "\\texthtscg";
4657 } else if (p.next_token().asInput() == "j") {
4659 name = "\\texthtbardotlessj";
4661 } else if (p.next_token().asInput() == "o") {
4663 name = "\\textbullseye";
4666 } else if (name == "\\*" ) {
4667 if (p.next_token().asInput() == "k") {
4669 name = "\\textturnk";
4671 } else if (p.next_token().asInput() == "r") {
4672 p.get_token(); // eat 'b'
4673 name = "\\textturnr";
4675 } else if (p.next_token().asInput() == "t") {
4677 name = "\\textturnt";
4679 } else if (p.next_token().asInput() == "w") {
4681 name = "\\textturnw";
4686 if ((name.size() == 2 &&
4687 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4688 p.next_token().asInput() != "*") ||
4689 is_known(name.substr(1), known_tipa_marks)) {
4690 // name is a command that corresponds to a
4691 // combining character in unicodesymbols.
4692 // Append the argument, fromLaTeXCommand()
4693 // will either convert it to a single
4694 // character or a combining sequence.
4695 name += '{' + p.verbatim_item() + '}';
4697 // now get the character from unicodesymbols
4701 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4702 Encodings::TEXT_CMD, termination, rem, &req);
4704 context.check_layout(os);
4707 output_ert_inset(os, to_utf8(rem), context);
4709 skip_spaces_braces(p);
4710 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4711 preamble.registerAutomaticallyLoadedPackage(*it);
4713 //cerr << "#: " << t << " mode: " << mode << endl;
4714 // heuristic: read up to next non-nested space
4716 string s = t.asInput();
4717 string z = p.verbatim_item();
4718 while (p.good() && z != " " && !z.empty()) {
4719 //cerr << "read: " << z << endl;
4721 z = p.verbatim_item();
4723 cerr << "found ERT: " << s << endl;
4724 output_ert_inset(os, s + ' ', context);
4727 if (t.asInput() == name &&
4728 p.next_token().asInput() == "*") {
4729 // Starred commands like \vspace*{}
4730 p.get_token(); // Eat '*'
4733 if (!parse_command(name, p, os, outer, context))
4734 output_ert_inset(os, name, context);
4738 if (flags & FLAG_LEAVE) {
4739 flags &= ~FLAG_LEAVE;
4746 string guessLanguage(Parser & p, string const & lang)
4748 typedef std::map<std::string, size_t> LangMap;
4749 // map from language names to number of characters
4752 for (char const * const * i = supported_CJK_languages; *i; i++)
4753 used[string(*i)] = 0;
4756 Token const t = p.get_token();
4757 // comments are not counted for any language
4758 if (t.cat() == catComment)
4760 // commands are not counted as well, but we need to detect
4761 // \begin{CJK} and switch encoding if needed
4762 if (t.cat() == catEscape) {
4763 if (t.cs() == "inputencoding") {
4764 string const enc = subst(p.verbatim_item(), "\n", " ");
4765 p.setEncoding(enc, Encoding::inputenc);
4768 if (t.cs() != "begin")
4771 // Non-CJK content is counted for lang.
4772 // We do not care about the real language here:
4773 // If we have more non-CJK contents than CJK contents,
4774 // we simply use the language that was specified as
4775 // babel main language.
4776 used[lang] += t.asInput().length();
4779 // Now we are starting an environment
4781 string const name = p.getArg('{', '}');
4782 if (name != "CJK") {
4786 // It is a CJK environment
4788 /* name = */ p.getArg('{', '}');
4789 string const encoding = p.getArg('{', '}');
4790 /* mapping = */ p.getArg('{', '}');
4791 string const encoding_old = p.getEncoding();
4792 char const * const * const where =
4793 is_known(encoding, supported_CJK_encodings);
4795 p.setEncoding(encoding, Encoding::CJK);
4797 p.setEncoding("UTF-8");
4798 string const text = p.ertEnvironment("CJK");
4799 p.setEncoding(encoding_old);
4802 // ignore contents in unknown CJK encoding
4805 // the language of the text
4807 supported_CJK_languages[where - supported_CJK_encodings];
4808 used[cjk] += text.length();
4810 LangMap::const_iterator use = used.begin();
4811 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4812 if (it->second > use->second)