2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, bool, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout)
59 bool const forcePlainLayout =
60 layout ? layout->forcePlainLayout() : false;
61 Context newcontext(true, context.textclass);
63 newcontext.layout = &context.textclass.plainLayout();
65 newcontext.font = context.font;
67 output_arguments(os, p, outer, false, false, newcontext,
69 parse_text(p, os, flags, outer, newcontext);
71 output_arguments(os, p, outer, false, true, newcontext,
72 layout->postcommandargs());
73 newcontext.check_end_layout(os);
79 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context const & context, string const & name)
82 InsetLayout const * layout = 0;
83 DocumentClass::InsetLayouts::const_iterator it =
84 context.textclass.insetLayouts().find(from_ascii(name));
85 if (it != context.textclass.insetLayouts().end())
86 layout = &(it->second);
87 parse_text_in_inset(p, os, flags, outer, context, layout);
90 /// parses a paragraph snippet, useful for example for \\emph{...}
91 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
94 Context newcontext(context);
95 // Don't inherit the paragraph-level extra stuff
96 newcontext.par_extra_stuff.clear();
97 parse_text(p, os, flags, outer, newcontext);
98 // Make sure that we don't create invalid .lyx files
99 context.need_layout = newcontext.need_layout;
100 context.need_end_layout = newcontext.need_end_layout;
105 * Thin wrapper around parse_text_snippet() using a string.
107 * We completely ignore \c context.need_layout and \c context.need_end_layout,
108 * because our return value is not used directly (otherwise the stream version
109 * of parse_text_snippet() could be used). That means that the caller needs
110 * to do layout management manually.
111 * This is intended to parse text that does not create any layout changes.
113 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
116 Context newcontext(context);
117 newcontext.need_layout = false;
118 newcontext.need_end_layout = false;
119 newcontext.new_layout_allowed = false;
120 // Avoid warning by Context::~Context()
121 newcontext.par_extra_stuff.clear();
123 parse_text_snippet(p, os, flags, outer, newcontext);
127 string fboxrule = "";
129 string shadow_size = "";
131 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
132 "vpageref", "prettyref", "nameref", "eqref", 0 };
134 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
135 "vpageref", "formatted", "nameref", "eqref", 0 };
137 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
138 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
139 "secref", "subref", "tabref", "thmref", 0 };
141 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
142 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
143 "sec", "sub", "tab", "thm", 0 };
147 * supported CJK encodings
148 * JIS does not work with LyX's encoding conversion
150 const char * const supported_CJK_encodings[] = {
151 "EUC-JP", "KS", "GB", "UTF8",
152 "Bg5", /*"JIS",*/ "SJIS", 0};
155 * the same as supported_CJK_encodings with their corresponding LyX language name
156 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
158 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
159 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
160 * please keep this in sync with supported_CJK_encodings line by line!
162 const char * const supported_CJK_languages[] = {
163 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
164 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
168 * The starred forms are also known except for "citefullauthor",
169 * "citeyear" and "citeyearpar".
171 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
172 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
173 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
177 * No starred form other than "cite*" known.
179 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
180 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
181 // jurabib commands not (yet) supported by LyX:
183 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
184 // "footciteauthor", "footciteyear", "footciteyearpar",
185 "citefield", "citetitle", 0 };
187 /// LaTeX names for quotes
188 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
189 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
190 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
191 "guilsinglleft", "frq", "guilsinglright", 0};
193 /// the same as known_quotes with .lyx names
194 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
195 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
196 "gld", "grd", "gls", "ers", "fls",
197 "fls", "frs", "frs", 0};
199 /// LaTeX names for font sizes
200 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
201 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
203 /// the same as known_sizes with .lyx names
204 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
205 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
207 /// LaTeX 2.09 names for font families
208 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
210 /// LaTeX names for font families
211 char const * const known_font_families[] = { "rmfamily", "sffamily",
214 /// LaTeX names for font family changing commands
215 char const * const known_text_font_families[] = { "textrm", "textsf",
218 /// The same as known_old_font_families, known_font_families and
219 /// known_text_font_families with .lyx names
220 char const * const known_coded_font_families[] = { "roman", "sans",
223 /// LaTeX 2.09 names for font series
224 char const * const known_old_font_series[] = { "bf", 0};
226 /// LaTeX names for font series
227 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
229 /// LaTeX names for font series changing commands
230 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
232 /// The same as known_old_font_series, known_font_series and
233 /// known_text_font_series with .lyx names
234 char const * const known_coded_font_series[] = { "bold", "medium", 0};
236 /// LaTeX 2.09 names for font shapes
237 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
239 /// LaTeX names for font shapes
240 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
243 /// LaTeX names for font shape changing commands
244 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
247 /// The same as known_old_font_shapes, known_font_shapes and
248 /// known_text_font_shapes with .lyx names
249 char const * const known_coded_font_shapes[] = { "italic", "slanted",
250 "smallcaps", "up", 0};
252 /// Known special characters which need skip_spaces_braces() afterwards
253 char const * const known_special_chars[] = {"ldots",
254 "lyxarrow", "textcompwordmark",
255 "slash", "textasciitilde", "textasciicircum", "textbackslash",
256 "LyX", "TeX", "LaTeXe",
259 /// special characters from known_special_chars which may have a \\protect before
260 char const * const known_special_protect_chars[] = {"LyX", "TeX",
261 "LaTeXe", "LaTeX", 0};
263 /// the same as known_special_chars with .lyx names
264 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
265 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
266 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
267 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
268 "\\SpecialChar LaTeX\n", 0};
271 * Graphics file extensions known by the dvips driver of the graphics package.
272 * These extensions are used to complete the filename of an included
273 * graphics file if it does not contain an extension.
274 * The order must be the same that latex uses to find a file, because we
275 * will use the first extension that matches.
276 * This is only an approximation for the common cases. If we would want to
277 * do it right in all cases, we would need to know which graphics driver is
278 * used and know the extensions of every driver of the graphics package.
280 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
281 "ps.gz", "eps.Z", "ps.Z", 0};
284 * Graphics file extensions known by the pdftex driver of the graphics package.
285 * \sa known_dvips_graphics_formats
287 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
291 * Known file extensions for TeX files as used by \\include.
293 char const * const known_tex_extensions[] = {"tex", 0};
295 /// spaces known by InsetSpace
296 char const * const known_spaces[] = { " ", "space", ",",
297 "thinspace", "quad", "qquad", "enspace", "enskip",
298 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
299 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
300 "upbracefill", "downbracefill", 0};
302 /// the same as known_spaces with .lyx names
303 char const * const known_coded_spaces[] = { "space{}", "space{}",
304 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
305 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
306 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
307 "upbracefill{}", "downbracefill{}", 0};
309 /// known TIPA combining diacritical marks
310 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
311 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
312 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
313 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
314 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
315 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
318 /// TIPA tones that need special handling
319 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
321 // string to store the float type to be able to determine the type of subfloats
322 string float_type = "";
325 /// splits "x=z, y=b" into a map and an ordered keyword vector
326 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
331 keys.resize(v.size());
332 for (size_t i = 0; i < v.size(); ++i) {
333 size_t const pos = v[i].find('=');
334 string const index = trimSpaceAndEol(v[i].substr(0, pos));
335 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
343 * Split a LaTeX length into value and unit.
344 * The latter can be a real unit like "pt", or a latex length variable
345 * like "\textwidth". The unit may contain additional stuff like glue
346 * lengths, but we don't care, because such lengths are ERT anyway.
347 * \returns true if \p value and \p unit are valid.
349 bool splitLatexLength(string const & len, string & value, string & unit)
353 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
354 //'4,5' is a valid LaTeX length number. Change it to '4.5'
355 string const length = subst(len, ',', '.');
356 if (i == string::npos)
359 if (len[0] == '\\') {
360 // We had something like \textwidth without a factor
366 value = trimSpaceAndEol(string(length, 0, i));
370 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
371 if (contains(len, '\\'))
372 unit = trimSpaceAndEol(string(len, i));
374 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
379 /// A simple function to translate a latex length to something LyX can
380 /// understand. Not perfect, but rather best-effort.
381 bool translate_len(string const & length, string & valstring, string & unit)
383 if (!splitLatexLength(length, valstring, unit))
385 // LyX uses percent values
387 istringstream iss(valstring);
392 string const percentval = oss.str();
394 if (unit.empty() || unit[0] != '\\')
396 string::size_type const i = unit.find(' ');
397 string const endlen = (i == string::npos) ? string() : string(unit, i);
398 if (unit == "\\textwidth") {
399 valstring = percentval;
400 unit = "text%" + endlen;
401 } else if (unit == "\\columnwidth") {
402 valstring = percentval;
403 unit = "col%" + endlen;
404 } else if (unit == "\\paperwidth") {
405 valstring = percentval;
406 unit = "page%" + endlen;
407 } else if (unit == "\\linewidth") {
408 valstring = percentval;
409 unit = "line%" + endlen;
410 } else if (unit == "\\paperheight") {
411 valstring = percentval;
412 unit = "pheight%" + endlen;
413 } else if (unit == "\\textheight") {
414 valstring = percentval;
415 unit = "theight%" + endlen;
423 string translate_len(string const & length)
427 if (translate_len(length, value, unit))
429 // If the input is invalid, return what we have.
437 * Translates a LaTeX length into \p value, \p unit and
438 * \p special parts suitable for a box inset.
439 * The difference from translate_len() is that a box inset knows about
440 * some special "units" that are stored in \p special.
442 void translate_box_len(string const & length, string & value, string & unit, string & special)
444 if (translate_len(length, value, unit)) {
445 if (unit == "\\height" || unit == "\\depth" ||
446 unit == "\\totalheight" || unit == "\\width") {
447 special = unit.substr(1);
448 // The unit is not used, but LyX requires a dummy setting
461 * Find a file with basename \p name in path \p path and an extension
464 string find_file(string const & name, string const & path,
465 char const * const * extensions)
467 for (char const * const * what = extensions; *what; ++what) {
468 string const trial = addExtension(name, *what);
469 if (makeAbsPath(trial, path).exists())
476 void begin_inset(ostream & os, string const & name)
478 os << "\n\\begin_inset " << name;
482 void begin_command_inset(ostream & os, string const & name,
483 string const & latexname)
485 begin_inset(os, "CommandInset ");
486 os << name << "\nLatexCommand " << latexname << '\n';
490 void end_inset(ostream & os)
492 os << "\n\\end_inset\n\n";
496 bool skip_braces(Parser & p)
498 if (p.next_token().cat() != catBegin)
501 if (p.next_token().cat() == catEnd) {
510 /// replace LaTeX commands in \p s from the unicodesymbols file with their
512 docstring convert_unicodesymbols(docstring s)
515 for (size_t i = 0; i < s.size();) {
524 docstring parsed = encodings.fromLaTeXCommand(s,
525 Encodings::TEXT_CMD, termination, rem, &req);
526 set<string>::const_iterator it = req.begin();
527 set<string>::const_iterator en = req.end();
528 for (; it != en; ++it)
529 preamble.registerAutomaticallyLoadedPackage(*it);
532 if (s.empty() || s[0] != '\\')
541 /// try to convert \p s to a valid InsetCommand argument
542 string convert_command_inset_arg(string s)
545 // since we don't know the input encoding we can't use from_utf8
546 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
547 // LyX cannot handle newlines in a latex command
548 return subst(s, "\n", " ");
552 void output_ert(ostream & os, string const & s, Context & context)
554 context.check_layout(os);
555 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
557 os << "\n\\backslash\n";
558 else if (*it == '\n') {
559 context.new_paragraph(os);
560 context.check_layout(os);
564 context.check_end_layout(os);
568 void output_ert_inset(ostream & os, string const & s, Context & context)
570 // We must have a valid layout before outputting the ERT inset.
571 context.check_layout(os);
572 Context newcontext(true, context.textclass);
573 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
574 if (layout.forcePlainLayout())
575 newcontext.layout = &context.textclass.plainLayout();
576 begin_inset(os, "ERT");
577 os << "\nstatus collapsed\n";
578 output_ert(os, s, newcontext);
583 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
585 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
588 if (checkModule(name, command))
589 return findLayoutWithoutModule(textclass, name, command);
594 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
596 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
599 if (checkModule(name, command))
600 return findInsetLayoutWithoutModule(textclass, name, command);
605 void eat_whitespace(Parser &, ostream &, Context &, bool);
609 * Skips whitespace and braces.
610 * This should be called after a command has been parsed that is not put into
611 * ERT, and where LyX adds "{}" if needed.
613 void skip_spaces_braces(Parser & p, bool keepws = false)
615 /* The following four examples produce the same typeset output and
616 should be handled by this function:
624 // Unfortunately we need to skip comments, too.
625 // We can't use eat_whitespace since writing them after the {}
626 // results in different output in some cases.
627 bool const skipped_spaces = p.skip_spaces(true);
628 bool const skipped_braces = skip_braces(p);
629 if (keepws && skipped_spaces && !skipped_braces)
630 // put back the space (it is better handled by check_space)
631 p.unskip_spaces(true);
635 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
636 Context & context, Layout::LaTeXArgMap const & latexargs)
639 context.check_layout(os);
644 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
645 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
646 for (; lait != laend; ++lait) {
648 eat_whitespace(p, os, context, false);
649 if (lait->second.mandatory) {
650 if (p.next_token().cat() != catBegin)
652 p.get_token(); // eat '{'
654 context.check_layout(os);
657 begin_inset(os, "Argument ");
660 os << i << "\nstatus collapsed\n\n";
661 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
664 if (p.next_token().cat() == catEscape ||
665 p.next_token().character() != '[')
667 p.get_token(); // eat '['
669 context.check_layout(os);
672 begin_inset(os, "Argument ");
675 os << i << "\nstatus collapsed\n\n";
676 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
679 eat_whitespace(p, os, context, false);
684 void output_command_layout(ostream & os, Parser & p, bool outer,
685 Context & parent_context,
686 Layout const * newlayout)
688 TeXFont const oldFont = parent_context.font;
689 // save the current font size
690 string const size = oldFont.size;
691 // reset the font size to default, because the font size switches
692 // don't affect section headings and the like
693 parent_context.font.size = Context::normalfont.size;
694 // we only need to write the font change if we have an open layout
695 if (!parent_context.atParagraphStart())
696 output_font_change(os, oldFont, parent_context.font);
697 parent_context.check_end_layout(os);
698 Context context(true, parent_context.textclass, newlayout,
699 parent_context.layout, parent_context.font);
700 if (parent_context.deeper_paragraph) {
701 // We are beginning a nested environment after a
702 // deeper paragraph inside the outer list environment.
703 // Therefore we don't need to output a "begin deeper".
704 context.need_end_deeper = true;
706 context.check_deeper(os);
707 output_arguments(os, p, outer, true, false, context,
708 context.layout->latexargs());
709 parse_text(p, os, FLAG_ITEM, outer, context);
710 output_arguments(os, p, outer, false, true, context,
711 context.layout->postcommandargs());
712 context.check_end_layout(os);
713 if (parent_context.deeper_paragraph) {
714 // We must suppress the "end deeper" because we
715 // suppressed the "begin deeper" above.
716 context.need_end_deeper = false;
718 context.check_end_deeper(os);
719 // We don't need really a new paragraph, but
720 // we must make sure that the next item gets a \begin_layout.
721 parent_context.new_paragraph(os);
722 // Set the font size to the original value. No need to output it here
723 // (Context::begin_layout() will do that if needed)
724 parent_context.font.size = size;
729 * Output a space if necessary.
730 * This function gets called for every whitespace token.
732 * We have three cases here:
733 * 1. A space must be suppressed. Example: The lyxcode case below
734 * 2. A space may be suppressed. Example: Spaces before "\par"
735 * 3. A space must not be suppressed. Example: A space between two words
737 * We currently handle only 1. and 3 and from 2. only the case of
738 * spaces before newlines as a side effect.
740 * 2. could be used to suppress as many spaces as possible. This has two effects:
741 * - Reimporting LyX generated LaTeX files changes almost no whitespace
742 * - Superflous whitespace from non LyX generated LaTeX files is removed.
743 * The drawback is that the logic inside the function becomes
744 * complicated, and that is the reason why it is not implemented.
746 void check_space(Parser & p, ostream & os, Context & context)
748 Token const next = p.next_token();
749 Token const curr = p.curr_token();
750 // A space before a single newline and vice versa must be ignored
751 // LyX emits a newline before \end{lyxcode}.
752 // This newline must be ignored,
753 // otherwise LyX will add an additional protected space.
754 if (next.cat() == catSpace ||
755 next.cat() == catNewline ||
756 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
759 context.check_layout(os);
765 * Parse all arguments of \p command
767 void parse_arguments(string const & command,
768 vector<ArgumentType> const & template_arguments,
769 Parser & p, ostream & os, bool outer, Context & context)
771 string ert = command;
772 size_t no_arguments = template_arguments.size();
773 for (size_t i = 0; i < no_arguments; ++i) {
774 switch (template_arguments[i]) {
777 // This argument contains regular LaTeX
778 output_ert_inset(os, ert + '{', context);
779 eat_whitespace(p, os, context, false);
780 if (template_arguments[i] == required)
781 parse_text(p, os, FLAG_ITEM, outer, context);
783 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
787 // This argument consists only of a single item.
788 // The presence of '{' or not must be preserved.
790 if (p.next_token().cat() == catBegin)
791 ert += '{' + p.verbatim_item() + '}';
793 ert += p.verbatim_item();
797 // This argument may contain special characters
798 ert += '{' + p.verbatim_item() + '}';
802 // true because we must not eat whitespace
803 // if an optional arg follows we must not strip the
804 // brackets from this one
805 if (i < no_arguments - 1 &&
806 template_arguments[i+1] == optional)
807 ert += p.getFullOpt(true);
809 ert += p.getOpt(true);
813 output_ert_inset(os, ert, context);
818 * Check whether \p command is a known command. If yes,
819 * handle the command with all arguments.
820 * \return true if the command was parsed, false otherwise.
822 bool parse_command(string const & command, Parser & p, ostream & os,
823 bool outer, Context & context)
825 if (known_commands.find(command) != known_commands.end()) {
826 parse_arguments(command, known_commands[command], p, os,
834 /// Parses a minipage or parbox
835 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
836 unsigned inner_flags, bool outer, Context & parent_context,
837 string const & outer_type, string const & special,
838 string inner_type, string const & frame_color,
839 string const & background_color)
843 string hor_pos = "l";
844 // We need to set the height to the LaTeX default of 1\\totalheight
845 // for the case when no height argument is given
846 string height_value = "1";
847 string height_unit = "in";
848 string height_special = "totalheight";
853 string width_special = "none";
854 string thickness = "0.4pt";
856 thickness = fboxrule;
861 separation = fboxsep;
865 if (shadow_size != "")
866 shadowsize = shadow_size;
869 string framecolor = "black";
870 string backgroundcolor = "none";
871 if (frame_color != "")
872 framecolor = frame_color;
873 if (background_color != "")
874 backgroundcolor = background_color;
875 // if there is a color box around the \begin statements have not yet been parsed
877 if (frame_color != "" || background_color != "") {
878 eat_whitespace(p, os, parent_context, false);
879 p.get_token().asInput(); // the '{'
881 if (p.next_token().asInput() == "\\begin") {
882 p.get_token().asInput();
884 inner_type = "minipage";
885 inner_flags = FLAG_END;
888 else if (p.next_token().asInput() == "\\parbox") {
889 p.get_token().asInput();
890 inner_type = "parbox";
891 inner_flags = FLAG_ITEM;
894 else if (p.next_token().asInput() == "\\makebox") {
895 p.get_token().asInput();
896 inner_type = "makebox";
897 inner_flags = FLAG_ITEM;
899 // in case there is just \colorbox{color}{text}
902 inner_type = "makebox";
903 inner_flags = FLAG_BRACE_LAST;
908 if (!inner_type.empty() && p.hasOpt()) {
909 if (inner_type != "makebox")
910 position = p.getArg('[', ']');
912 latex_width = p.getArg('[', ']');
913 translate_box_len(latex_width, width_value, width_unit, width_special);
916 if (position != "t" && position != "c" && position != "b") {
917 cerr << "invalid position " << position << " for "
918 << inner_type << endl;
922 if (inner_type != "makebox") {
923 latex_height = p.getArg('[', ']');
924 translate_box_len(latex_height, height_value, height_unit, height_special);
926 string const opt = p.getArg('[', ']');
929 if (hor_pos != "l" && hor_pos != "c" &&
930 hor_pos != "r" && hor_pos != "s") {
931 cerr << "invalid hor_pos " << hor_pos
932 << " for " << inner_type << endl;
939 inner_pos = p.getArg('[', ']');
940 if (inner_pos != "c" && inner_pos != "t" &&
941 inner_pos != "b" && inner_pos != "s") {
942 cerr << "invalid inner_pos "
943 << inner_pos << " for "
944 << inner_type << endl;
945 inner_pos = position;
949 if (inner_type == "makebox")
953 if (inner_type.empty()) {
954 if (special.empty() && outer_type != "framebox")
955 latex_width = "1\\columnwidth";
958 latex_width = p2.getArg('[', ']');
959 string const opt = p2.getArg('[', ']');
962 if (hor_pos != "l" && hor_pos != "c" &&
963 hor_pos != "r" && hor_pos != "s") {
964 cerr << "invalid hor_pos " << hor_pos
965 << " for " << outer_type << endl;
969 if (outer_type == "framebox")
973 } else if (inner_type != "makebox")
974 latex_width = p.verbatim_item();
975 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
976 // as this is LyX's standard for such cases (except for makebox)
977 // \framebox is more special and handled below
978 if (latex_width.empty() && inner_type != "makebox"
979 && outer_type != "framebox")
980 latex_width = "1\\columnwidth";
982 translate_len(latex_width, width_value, width_unit);
984 bool shadedparbox = false;
985 if (inner_type == "shaded") {
986 eat_whitespace(p, os, parent_context, false);
987 if (outer_type == "parbox") {
989 if (p.next_token().cat() == catBegin)
991 eat_whitespace(p, os, parent_context, false);
997 // If we already read the inner box we have to push the inner env
998 if (!outer_type.empty() && !inner_type.empty() &&
999 (inner_flags & FLAG_END))
1000 active_environments.push_back(inner_type);
1001 // LyX can't handle length variables
1002 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
1003 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
1004 // Look whether there is some content after the end of the
1005 // inner box, but before the end of the outer box.
1006 // If yes, we need to output ERT.
1008 if (inner_flags & FLAG_END)
1009 p.ertEnvironment(inner_type);
1012 p.skip_spaces(true);
1013 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1014 if ((outer_env && p.next_token().asInput() != "\\end") ||
1015 (!outer_env && p.next_token().cat() != catEnd)) {
1016 // something is between the end of the inner box and
1017 // the end of the outer box, so we need to use ERT.
1022 // if only \makebox{content} was used we can set its width to 1\width
1023 // because this identic and also identic to \mbox
1024 // this doesn't work for \framebox{content}, thus we have to use ERT for this
1025 if (latex_width.empty() && inner_type == "makebox" && background_color == "") {
1028 width_special = "width";
1029 } else if (latex_width.empty() && outer_type == "framebox") {
1030 width_value.clear();
1032 width_special = "none";
1036 if (!outer_type.empty()) {
1037 if (outer_flags & FLAG_END)
1038 ss << "\\begin{" << outer_type << '}';
1040 ss << '\\' << outer_type << '{';
1041 if (!special.empty())
1045 if (!inner_type.empty()) {
1046 if (inner_type != "shaded") {
1047 if (inner_flags & FLAG_END)
1048 ss << "\\begin{" << inner_type << '}';
1050 ss << '\\' << inner_type;
1052 if (!position.empty())
1053 ss << '[' << position << ']';
1054 if (!latex_height.empty())
1055 ss << '[' << latex_height << ']';
1056 if (!inner_pos.empty())
1057 ss << '[' << inner_pos << ']';
1058 ss << '{' << latex_width << '}';
1059 if (!(inner_flags & FLAG_END))
1062 if (inner_type == "shaded")
1063 ss << "\\begin{shaded}";
1064 output_ert_inset(os, ss.str(), parent_context);
1065 if (!inner_type.empty()) {
1066 parse_text(p, os, inner_flags, outer, parent_context);
1067 if (inner_flags & FLAG_END)
1068 output_ert_inset(os, "\\end{" + inner_type + '}',
1071 output_ert_inset(os, "}", parent_context);
1073 if (!outer_type.empty()) {
1074 // If we already read the inner box we have to pop
1076 if (!inner_type.empty() && (inner_flags & FLAG_END))
1077 active_environments.pop_back();
1079 // Ensure that the end of the outer box is parsed correctly:
1080 // The opening brace has been eaten by parse_outer_box()
1081 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1082 outer_flags &= ~FLAG_ITEM;
1083 outer_flags |= FLAG_BRACE_LAST;
1085 parse_text(p, os, outer_flags, outer, parent_context);
1086 if (outer_flags & FLAG_END)
1087 output_ert_inset(os, "\\end{" + outer_type + '}',
1090 output_ert_inset(os, "}", parent_context);
1093 // LyX does not like empty positions, so we have
1094 // to set them to the LaTeX default values here.
1095 if (position.empty())
1097 if (inner_pos.empty())
1098 inner_pos = position;
1099 parent_context.check_layout(os);
1100 begin_inset(os, "Box ");
1101 if (outer_type == "framed")
1103 else if (outer_type == "framebox" || outer_type == "fbox")
1105 else if (outer_type == "shadowbox")
1106 os << "Shadowbox\n";
1107 else if ((outer_type == "shaded" && inner_type.empty()) ||
1108 (outer_type == "minipage" && inner_type == "shaded") ||
1109 (outer_type == "parbox" && inner_type == "shaded")) {
1111 preamble.registerAutomaticallyLoadedPackage("color");
1112 } else if (outer_type == "doublebox")
1113 os << "Doublebox\n";
1114 else if (outer_type.empty() || outer_type == "mbox")
1115 os << "Frameless\n";
1117 os << outer_type << '\n';
1118 os << "position \"" << position << "\"\n";
1119 os << "hor_pos \"" << hor_pos << "\"\n";
1120 if (outer_type == "mbox")
1121 os << "has_inner_box 1\n";
1123 os << "has_inner_box " << !inner_type.empty() << "\n";
1124 os << "inner_pos \"" << inner_pos << "\"\n";
1125 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1127 if (outer_type == "mbox")
1128 os << "use_makebox 1\n";
1130 os << "use_makebox " << (inner_type == "makebox") << '\n';
1131 if (outer_type == "fbox" || outer_type == "mbox")
1132 os << "width \"\"\n";
1134 os << "width \"" << width_value << width_unit << "\"\n";
1135 os << "special \"" << width_special << "\"\n";
1136 os << "height \"" << height_value << height_unit << "\"\n";
1137 os << "height_special \"" << height_special << "\"\n";
1138 os << "thickness \"" << thickness << "\"\n";
1139 os << "separation \"" << separation << "\"\n";
1140 os << "shadowsize \"" << shadowsize << "\"\n";
1141 os << "framecolor \"" << framecolor << "\"\n";
1142 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1143 os << "status open\n\n";
1145 // Unfortunately we can't use parse_text_in_inset:
1146 // InsetBox::forcePlainLayout() is hard coded and does not
1147 // use the inset layout. Apart from that do we call parse_text
1148 // up to two times, but need only one check_end_layout.
1149 bool const forcePlainLayout =
1150 (!inner_type.empty() || inner_type == "makebox") &&
1151 outer_type != "shaded" && outer_type != "framed";
1152 Context context(true, parent_context.textclass);
1153 if (forcePlainLayout)
1154 context.layout = &context.textclass.plainLayout();
1156 context.font = parent_context.font;
1158 // If we have no inner box the contents will be read with the outer box
1159 if (!inner_type.empty())
1160 parse_text(p, os, inner_flags, outer, context);
1162 // Ensure that the end of the outer box is parsed correctly:
1163 // The opening brace has been eaten by parse_outer_box()
1164 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1165 outer_flags &= ~FLAG_ITEM;
1166 outer_flags |= FLAG_BRACE_LAST;
1169 // Find end of outer box, output contents if inner_type is
1170 // empty and output possible comments
1171 if (!outer_type.empty()) {
1172 // If we already read the inner box we have to pop
1174 if (!inner_type.empty() && (inner_flags & FLAG_END))
1175 active_environments.pop_back();
1176 // This does not output anything but comments if
1177 // inner_type is not empty (see use_ert)
1178 parse_text(p, os, outer_flags, outer, context);
1181 context.check_end_layout(os);
1183 #ifdef PRESERVE_LAYOUT
1184 // LyX puts a % after the end of the minipage
1185 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1187 //output_ert_inset(os, "%dummy", parent_context);
1190 parent_context.new_paragraph(os);
1192 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1193 //output_ert_inset(os, "%dummy", parent_context);
1196 // We add a protected space if something real follows
1197 if (p.good() && p.next_token().cat() != catComment) {
1198 begin_inset(os, "space ~\n");
1204 if (background_color != "") {
1205 // in this case we have to eat the the closing brace of the color box
1206 p.get_token().asInput(); // the '}'
1208 if (p.next_token().asInput() == "}"
1209 && (fboxrule != "" || fboxsep != "" || shadow_size != "")) {
1210 // in this case we assume that the closing brace is from the box settings
1211 // therefore reset these values for the next box
1216 if (shadow_size != "")
1222 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1223 Context & parent_context, string const & outer_type,
1224 string const & special)
1226 eat_whitespace(p, os, parent_context, false);
1227 if (flags & FLAG_ITEM) {
1229 if (p.next_token().cat() == catBegin)
1232 cerr << "Warning: Ignoring missing '{' after \\"
1233 << outer_type << '.' << endl;
1234 eat_whitespace(p, os, parent_context, false);
1237 unsigned int inner_flags = 0;
1239 if (outer_type == "minipage" || outer_type == "parbox") {
1240 p.skip_spaces(true);
1241 while (p.hasOpt()) {
1243 p.skip_spaces(true);
1246 p.skip_spaces(true);
1247 if (outer_type == "parbox") {
1249 if (p.next_token().cat() == catBegin)
1251 p.skip_spaces(true);
1254 if (outer_type == "shaded" || outer_type == "fbox"
1255 || outer_type == "mbox") {
1256 // These boxes never have an inner box
1258 } else if (p.next_token().asInput() == "\\parbox") {
1259 inner = p.get_token().cs();
1260 inner_flags = FLAG_ITEM;
1261 } else if (p.next_token().asInput() == "\\begin") {
1262 // Is this a minipage or shaded box?
1265 inner = p.getArg('{', '}');
1267 if (inner == "minipage" || inner == "shaded")
1268 inner_flags = FLAG_END;
1273 if (inner_flags == FLAG_END) {
1274 if (inner != "shaded")
1278 eat_whitespace(p, os, parent_context, false);
1280 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1281 outer_type, special, inner, "", "");
1283 if (inner_flags == FLAG_ITEM) {
1285 eat_whitespace(p, os, parent_context, false);
1287 parse_box(p, os, flags, inner_flags, outer, parent_context,
1288 outer_type, special, inner, "", "");
1293 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1295 parent_context.check_layout(os);
1296 begin_inset(os, "listings\n");
1298 string arg = p.verbatimOption();
1299 os << "lstparams " << '"' << arg << '"' << '\n';
1300 if (arg.find("\\color") != string::npos)
1301 preamble.registerAutomaticallyLoadedPackage("color");
1304 os << "inline true\n";
1306 os << "inline false\n";
1307 os << "status collapsed\n";
1308 Context context(true, parent_context.textclass);
1309 context.layout = &parent_context.textclass.plainLayout();
1312 // set catcodes to verbatim early, just in case.
1313 p.setCatcodes(VERBATIM_CATCODES);
1314 string delim = p.get_token().asInput();
1315 //FIXME: handler error condition
1316 s = p.verbatimStuff(delim).second;
1317 // context.new_paragraph(os);
1319 s = p.verbatimEnvironment("lstlisting");
1320 output_ert(os, s, context);
1325 /// parse an unknown environment
1326 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1327 unsigned flags, bool outer,
1328 Context & parent_context)
1330 if (name == "tabbing")
1331 // We need to remember that we have to handle '\=' specially
1332 flags |= FLAG_TABBING;
1334 // We need to translate font changes and paragraphs inside the
1335 // environment to ERT if we have a non standard font.
1336 // Otherwise things like
1337 // \large\begin{foo}\huge bar\end{foo}
1339 bool const specialfont =
1340 (parent_context.font != parent_context.normalfont);
1341 bool const new_layout_allowed = parent_context.new_layout_allowed;
1343 parent_context.new_layout_allowed = false;
1344 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1345 parse_text_snippet(p, os, flags, outer, parent_context);
1346 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1348 parent_context.new_layout_allowed = new_layout_allowed;
1352 void parse_environment(Parser & p, ostream & os, bool outer,
1353 string & last_env, Context & parent_context)
1355 Layout const * newlayout;
1356 InsetLayout const * newinsetlayout = 0;
1357 string const name = p.getArg('{', '}');
1358 const bool is_starred = suffixIs(name, '*');
1359 string const unstarred_name = rtrim(name, "*");
1360 active_environments.push_back(name);
1362 if (is_math_env(name)) {
1363 parent_context.check_layout(os);
1364 begin_inset(os, "Formula ");
1365 os << "\\begin{" << name << "}";
1366 parse_math(p, os, FLAG_END, MATH_MODE);
1367 os << "\\end{" << name << "}";
1369 if (is_display_math_env(name)) {
1370 // Prevent the conversion of a line break to a space
1371 // (bug 7668). This does not change the output, but
1372 // looks ugly in LyX.
1373 eat_whitespace(p, os, parent_context, false);
1377 else if (is_known(name, preamble.polyglossia_languages)) {
1378 // We must begin a new paragraph if not already done
1379 if (! parent_context.atParagraphStart()) {
1380 parent_context.check_end_layout(os);
1381 parent_context.new_paragraph(os);
1383 // save the language in the context so that it is
1384 // handled by parse_text
1385 parent_context.font.language = preamble.polyglossia2lyx(name);
1386 parse_text(p, os, FLAG_END, outer, parent_context);
1387 // Just in case the environment is empty
1388 parent_context.extra_stuff.erase();
1389 // We must begin a new paragraph to reset the language
1390 parent_context.new_paragraph(os);
1394 else if (unstarred_name == "tabular" || name == "longtable") {
1395 eat_whitespace(p, os, parent_context, false);
1396 string width = "0pt";
1397 if (name == "tabular*") {
1398 width = lyx::translate_len(p.getArg('{', '}'));
1399 eat_whitespace(p, os, parent_context, false);
1401 parent_context.check_layout(os);
1402 begin_inset(os, "Tabular ");
1403 handle_tabular(p, os, name, width, parent_context);
1408 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1409 eat_whitespace(p, os, parent_context, false);
1410 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1411 eat_whitespace(p, os, parent_context, false);
1412 parent_context.check_layout(os);
1413 begin_inset(os, "Float " + unstarred_name + "\n");
1414 // store the float type for subfloats
1415 // subfloats only work with figures and tables
1416 if (unstarred_name == "figure")
1417 float_type = unstarred_name;
1418 else if (unstarred_name == "table")
1419 float_type = unstarred_name;
1423 os << "placement " << opt << '\n';
1424 if (contains(opt, "H"))
1425 preamble.registerAutomaticallyLoadedPackage("float");
1427 Floating const & fl = parent_context.textclass.floats()
1428 .getType(unstarred_name);
1429 if (!fl.floattype().empty() && fl.usesFloatPkg())
1430 preamble.registerAutomaticallyLoadedPackage("float");
1433 os << "wide " << convert<string>(is_starred)
1434 << "\nsideways false"
1435 << "\nstatus open\n\n";
1436 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1438 // We don't need really a new paragraph, but
1439 // we must make sure that the next item gets a \begin_layout.
1440 parent_context.new_paragraph(os);
1442 // the float is parsed thus delete the type
1446 else if (unstarred_name == "sidewaysfigure"
1447 || unstarred_name == "sidewaystable") {
1448 eat_whitespace(p, os, parent_context, false);
1449 parent_context.check_layout(os);
1450 if (unstarred_name == "sidewaysfigure")
1451 begin_inset(os, "Float figure\n");
1453 begin_inset(os, "Float table\n");
1454 os << "wide " << convert<string>(is_starred)
1455 << "\nsideways true"
1456 << "\nstatus open\n\n";
1457 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1459 // We don't need really a new paragraph, but
1460 // we must make sure that the next item gets a \begin_layout.
1461 parent_context.new_paragraph(os);
1463 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1466 else if (name == "wrapfigure" || name == "wraptable") {
1467 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1468 eat_whitespace(p, os, parent_context, false);
1469 parent_context.check_layout(os);
1472 string overhang = "0col%";
1475 lines = p.getArg('[', ']');
1476 string const placement = p.getArg('{', '}');
1478 overhang = p.getArg('[', ']');
1479 string const width = p.getArg('{', '}');
1481 if (name == "wrapfigure")
1482 begin_inset(os, "Wrap figure\n");
1484 begin_inset(os, "Wrap table\n");
1485 os << "lines " << lines
1486 << "\nplacement " << placement
1487 << "\noverhang " << lyx::translate_len(overhang)
1488 << "\nwidth " << lyx::translate_len(width)
1489 << "\nstatus open\n\n";
1490 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1492 // We don't need really a new paragraph, but
1493 // we must make sure that the next item gets a \begin_layout.
1494 parent_context.new_paragraph(os);
1496 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1499 else if (name == "minipage") {
1500 eat_whitespace(p, os, parent_context, false);
1501 // Test whether this is an outer box of a shaded box
1503 // swallow arguments
1504 while (p.hasOpt()) {
1506 p.skip_spaces(true);
1509 p.skip_spaces(true);
1510 Token t = p.get_token();
1511 bool shaded = false;
1512 if (t.asInput() == "\\begin") {
1513 p.skip_spaces(true);
1514 if (p.getArg('{', '}') == "shaded")
1519 parse_outer_box(p, os, FLAG_END, outer,
1520 parent_context, name, "shaded");
1522 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1523 "", "", name, "", "");
1527 else if (name == "comment") {
1528 eat_whitespace(p, os, parent_context, false);
1529 parent_context.check_layout(os);
1530 begin_inset(os, "Note Comment\n");
1531 os << "status open\n";
1532 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1535 skip_braces(p); // eat {} that might by set by LyX behind comments
1536 preamble.registerAutomaticallyLoadedPackage("verbatim");
1539 else if (name == "verbatim") {
1540 // FIXME: this should go in the generic code that
1541 // handles environments defined in layout file that
1542 // have "PassThru 1". However, the code over there is
1543 // already too complicated for my taste.
1544 parent_context.new_paragraph(os);
1545 Context context(true, parent_context.textclass,
1546 &parent_context.textclass[from_ascii("Verbatim")]);
1547 string s = p.verbatimEnvironment("verbatim");
1548 output_ert(os, s, context);
1552 else if (name == "IPA") {
1553 eat_whitespace(p, os, parent_context, false);
1554 parent_context.check_layout(os);
1555 begin_inset(os, "IPA\n");
1556 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1559 preamble.registerAutomaticallyLoadedPackage("tipa");
1560 preamble.registerAutomaticallyLoadedPackage("tipx");
1563 else if (name == "CJK") {
1564 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1565 // It is impossible to decide if a CJK environment was in its own paragraph or within
1566 // a line. We therefore always assume a paragraph since the latter is a rare case.
1567 eat_whitespace(p, os, parent_context, false);
1568 parent_context.check_end_layout(os);
1569 // store the encoding to be able to reset it
1570 string const encoding_old = p.getEncoding();
1571 string const encoding = p.getArg('{', '}');
1572 // FIXME: For some reason JIS does not work. Although the text
1573 // in tests/CJK.tex is identical with the SJIS version if you
1574 // convert both snippets using the recode command line utility,
1575 // the resulting .lyx file contains some extra characters if
1576 // you set buggy_encoding to false for JIS.
1577 bool const buggy_encoding = encoding == "JIS";
1578 if (!buggy_encoding)
1579 p.setEncoding(encoding, Encoding::CJK);
1581 // FIXME: This will read garbage, since the data is not encoded in utf8.
1582 p.setEncoding("UTF-8");
1584 // LyX only supports the same mapping for all CJK
1585 // environments, so we might need to output everything as ERT
1586 string const mapping = trim(p.getArg('{', '}'));
1587 char const * const * const where =
1588 is_known(encoding, supported_CJK_encodings);
1589 if (!buggy_encoding && !preamble.fontCJKSet())
1590 preamble.fontCJK(mapping);
1591 bool knownMapping = mapping == preamble.fontCJK();
1592 if (buggy_encoding || !knownMapping || !where) {
1593 parent_context.check_layout(os);
1594 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1596 // we must parse the content as verbatim because e.g. JIS can contain
1597 // normally invalid characters
1598 // FIXME: This works only for the most simple cases.
1599 // Since TeX control characters are not parsed,
1600 // things like comments are completely wrong.
1601 string const s = p.plainEnvironment("CJK");
1602 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1604 output_ert_inset(os, "\\", parent_context);
1605 else if (*it == '$')
1606 output_ert_inset(os, "$", parent_context);
1607 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1612 output_ert_inset(os, "\\end{" + name + "}",
1616 supported_CJK_languages[where - supported_CJK_encodings];
1617 // store the language because we must reset it at the end
1618 string const lang_old = parent_context.font.language;
1619 parent_context.font.language = lang;
1620 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1621 parent_context.font.language = lang_old;
1622 parent_context.new_paragraph(os);
1624 p.setEncoding(encoding_old);
1628 else if (name == "lyxgreyedout") {
1629 eat_whitespace(p, os, parent_context, false);
1630 parent_context.check_layout(os);
1631 begin_inset(os, "Note Greyedout\n");
1632 os << "status open\n";
1633 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1636 if (!preamble.notefontcolor().empty())
1637 preamble.registerAutomaticallyLoadedPackage("color");
1640 else if (name == "btSect") {
1641 eat_whitespace(p, os, parent_context, false);
1642 parent_context.check_layout(os);
1643 begin_command_inset(os, "bibtex", "bibtex");
1644 string bibstyle = "plain";
1646 bibstyle = p.getArg('[', ']');
1647 p.skip_spaces(true);
1649 string const bibfile = p.getArg('{', '}');
1650 eat_whitespace(p, os, parent_context, false);
1651 Token t = p.get_token();
1652 if (t.asInput() == "\\btPrintCited") {
1653 p.skip_spaces(true);
1654 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1656 if (t.asInput() == "\\btPrintNotCited") {
1657 p.skip_spaces(true);
1658 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1660 if (t.asInput() == "\\btPrintAll") {
1661 p.skip_spaces(true);
1662 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1664 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1665 os << "options " << '"' << bibstyle << '"' << "\n";
1666 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1671 else if (name == "framed" || name == "shaded") {
1672 eat_whitespace(p, os, parent_context, false);
1673 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1677 else if (name == "lstlisting") {
1678 eat_whitespace(p, os, parent_context, false);
1679 parse_listings(p, os, parent_context, false);
1683 else if (!parent_context.new_layout_allowed)
1684 parse_unknown_environment(p, name, os, FLAG_END, outer,
1687 // Alignment and spacing settings
1688 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1689 // therefore are totally broken!
1690 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1691 // they are commands not environments. They are furthermore switches that
1692 // can be ended by another switches, but also by commands like \footnote or
1693 // \parbox. So the only safe way is to leave them untouched.
1694 else if (name == "center" || name == "centering" ||
1695 name == "flushleft" || name == "flushright" ||
1696 name == "singlespace" || name == "onehalfspace" ||
1697 name == "doublespace" || name == "spacing") {
1698 eat_whitespace(p, os, parent_context, false);
1699 // We must begin a new paragraph if not already done
1700 if (! parent_context.atParagraphStart()) {
1701 parent_context.check_end_layout(os);
1702 parent_context.new_paragraph(os);
1704 if (name == "flushleft")
1705 parent_context.add_extra_stuff("\\align left\n");
1706 else if (name == "flushright")
1707 parent_context.add_extra_stuff("\\align right\n");
1708 else if (name == "center" || name == "centering")
1709 parent_context.add_extra_stuff("\\align center\n");
1710 else if (name == "singlespace")
1711 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1712 else if (name == "onehalfspace") {
1713 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1714 preamble.registerAutomaticallyLoadedPackage("setspace");
1715 } else if (name == "doublespace") {
1716 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1717 preamble.registerAutomaticallyLoadedPackage("setspace");
1718 } else if (name == "spacing") {
1719 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1720 preamble.registerAutomaticallyLoadedPackage("setspace");
1722 parse_text(p, os, FLAG_END, outer, parent_context);
1723 // Just in case the environment is empty
1724 parent_context.extra_stuff.erase();
1725 // We must begin a new paragraph to reset the alignment
1726 parent_context.new_paragraph(os);
1730 // The single '=' is meant here.
1731 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1732 eat_whitespace(p, os, parent_context, false);
1733 Context context(true, parent_context.textclass, newlayout,
1734 parent_context.layout, parent_context.font);
1735 if (parent_context.deeper_paragraph) {
1736 // We are beginning a nested environment after a
1737 // deeper paragraph inside the outer list environment.
1738 // Therefore we don't need to output a "begin deeper".
1739 context.need_end_deeper = true;
1741 parent_context.check_end_layout(os);
1742 if (last_env == name) {
1743 // we need to output a separator since LyX would export
1744 // the two environments as one otherwise (bug 5716)
1745 TeX2LyXDocClass const & textclass(parent_context.textclass);
1746 Context newcontext(true, textclass,
1747 &(textclass.defaultLayout()));
1748 newcontext.check_layout(os);
1749 begin_inset(os, "Separator plain\n");
1751 newcontext.check_end_layout(os);
1753 switch (context.layout->latextype) {
1754 case LATEX_LIST_ENVIRONMENT:
1755 context.add_par_extra_stuff("\\labelwidthstring "
1756 + p.verbatim_item() + '\n');
1759 case LATEX_BIB_ENVIRONMENT:
1760 p.verbatim_item(); // swallow next arg
1766 context.check_deeper(os);
1767 // handle known optional and required arguments
1768 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1769 // It is impossible to place anything after the environment name,
1770 // but before the first \\item.
1771 if (context.layout->latextype == LATEX_ENVIRONMENT)
1772 output_arguments(os, p, outer, false, false, context,
1773 context.layout->latexargs());
1774 parse_text(p, os, FLAG_END, outer, context);
1775 if (context.layout->latextype == LATEX_ENVIRONMENT)
1776 output_arguments(os, p, outer, false, true, context,
1777 context.layout->postcommandargs());
1778 context.check_end_layout(os);
1779 if (parent_context.deeper_paragraph) {
1780 // We must suppress the "end deeper" because we
1781 // suppressed the "begin deeper" above.
1782 context.need_end_deeper = false;
1784 context.check_end_deeper(os);
1785 parent_context.new_paragraph(os);
1787 if (!preamble.titleLayoutFound())
1788 preamble.titleLayoutFound(newlayout->intitle);
1789 set<string> const & req = newlayout->requires();
1790 set<string>::const_iterator it = req.begin();
1791 set<string>::const_iterator en = req.end();
1792 for (; it != en; ++it)
1793 preamble.registerAutomaticallyLoadedPackage(*it);
1796 // The single '=' is meant here.
1797 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1798 eat_whitespace(p, os, parent_context, false);
1799 parent_context.check_layout(os);
1800 begin_inset(os, "Flex ");
1801 os << to_utf8(newinsetlayout->name()) << '\n'
1802 << "status collapsed\n";
1803 if (newinsetlayout->isPassThru()) {
1804 string const arg = p.verbatimEnvironment(name);
1805 Context context(true, parent_context.textclass,
1806 &parent_context.textclass.plainLayout(),
1807 parent_context.layout);
1808 output_ert(os, arg, parent_context);
1810 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1814 else if (name == "appendix") {
1815 // This is no good latex style, but it works and is used in some documents...
1816 eat_whitespace(p, os, parent_context, false);
1817 parent_context.check_end_layout(os);
1818 Context context(true, parent_context.textclass, parent_context.layout,
1819 parent_context.layout, parent_context.font);
1820 context.check_layout(os);
1821 os << "\\start_of_appendix\n";
1822 parse_text(p, os, FLAG_END, outer, context);
1823 context.check_end_layout(os);
1827 else if (known_environments.find(name) != known_environments.end()) {
1828 vector<ArgumentType> arguments = known_environments[name];
1829 // The last "argument" denotes wether we may translate the
1830 // environment contents to LyX
1831 // The default required if no argument is given makes us
1832 // compatible with the reLyXre environment.
1833 ArgumentType contents = arguments.empty() ?
1836 if (!arguments.empty())
1837 arguments.pop_back();
1838 // See comment in parse_unknown_environment()
1839 bool const specialfont =
1840 (parent_context.font != parent_context.normalfont);
1841 bool const new_layout_allowed =
1842 parent_context.new_layout_allowed;
1844 parent_context.new_layout_allowed = false;
1845 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1846 outer, parent_context);
1847 if (contents == verbatim)
1848 output_ert_inset(os, p.ertEnvironment(name),
1851 parse_text_snippet(p, os, FLAG_END, outer,
1853 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1855 parent_context.new_layout_allowed = new_layout_allowed;
1859 parse_unknown_environment(p, name, os, FLAG_END, outer,
1863 active_environments.pop_back();
1867 /// parses a comment and outputs it to \p os.
1868 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1870 LASSERT(t.cat() == catComment, return);
1871 if (!t.cs().empty()) {
1872 context.check_layout(os);
1873 output_ert_inset(os, '%' + t.cs(), context);
1874 if (p.next_token().cat() == catNewline) {
1875 // A newline after a comment line starts a new
1877 if (context.new_layout_allowed) {
1878 if(!context.atParagraphStart())
1879 // Only start a new paragraph if not already
1880 // done (we might get called recursively)
1881 context.new_paragraph(os);
1883 output_ert_inset(os, "\n", context);
1884 eat_whitespace(p, os, context, true);
1887 // "%\n" combination
1894 * Reads spaces and comments until the first non-space, non-comment token.
1895 * New paragraphs (double newlines or \\par) are handled like simple spaces
1896 * if \p eatParagraph is true.
1897 * Spaces are skipped, but comments are written to \p os.
1899 void eat_whitespace(Parser & p, ostream & os, Context & context,
1903 Token const & t = p.get_token();
1904 if (t.cat() == catComment)
1905 parse_comment(p, os, t, context);
1906 else if ((! eatParagraph && p.isParagraph()) ||
1907 (t.cat() != catSpace && t.cat() != catNewline)) {
1916 * Set a font attribute, parse text and reset the font attribute.
1917 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1918 * \param currentvalue Current value of the attribute. Is set to the new
1919 * value during parsing.
1920 * \param newvalue New value of the attribute
1922 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1923 Context & context, string const & attribute,
1924 string & currentvalue, string const & newvalue)
1926 context.check_layout(os);
1927 string const oldvalue = currentvalue;
1928 currentvalue = newvalue;
1929 os << '\n' << attribute << ' ' << newvalue << "\n";
1930 parse_text_snippet(p, os, flags, outer, context);
1931 context.check_layout(os);
1932 os << '\n' << attribute << ' ' << oldvalue << "\n";
1933 currentvalue = oldvalue;
1937 /// get the arguments of a natbib or jurabib citation command
1938 void get_cite_arguments(Parser & p, bool natbibOrder,
1939 string & before, string & after)
1941 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1943 // text before the citation
1945 // text after the citation
1946 after = p.getFullOpt();
1948 if (!after.empty()) {
1949 before = p.getFullOpt();
1950 if (natbibOrder && !before.empty())
1951 swap(before, after);
1956 /// Convert filenames with TeX macros and/or quotes to something LyX
1958 string const normalize_filename(string const & name)
1963 Token const & t = p.get_token();
1964 if (t.cat() != catEscape)
1966 else if (t.cs() == "lyxdot") {
1967 // This is used by LyX for simple dots in relative
1971 } else if (t.cs() == "space") {
1974 } else if (t.cs() == "string") {
1975 // Convert \string" to " and \string~ to ~
1976 Token const & n = p.next_token();
1977 if (n.asInput() != "\"" && n.asInput() != "~")
1982 // Strip quotes. This is a bit complicated (see latex_path()).
1983 string full = os.str();
1984 if (!full.empty() && full[0] == '"') {
1985 string base = removeExtension(full);
1986 string ext = getExtension(full);
1987 if (!base.empty() && base[base.length()-1] == '"')
1990 return addExtension(trim(base, "\""), ext);
1991 if (full[full.length()-1] == '"')
1994 return trim(full, "\"");
2000 /// Convert \p name from TeX convention (relative to master file) to LyX
2001 /// convention (relative to .lyx file) if it is relative
2002 void fix_child_filename(string & name)
2004 string const absMasterTeX = getMasterFilePath(true);
2005 bool const isabs = FileName::isAbsolute(name);
2006 // convert from "relative to .tex master" to absolute original path
2008 name = makeAbsPath(name, absMasterTeX).absFileName();
2009 bool copyfile = copyFiles();
2010 string const absParentLyX = getParentFilePath(false);
2013 // convert from absolute original path to "relative to master file"
2014 string const rel = to_utf8(makeRelPath(from_utf8(name),
2015 from_utf8(absMasterTeX)));
2016 // re-interpret "relative to .tex file" as "relative to .lyx file"
2017 // (is different if the master .lyx file resides in a
2018 // different path than the master .tex file)
2019 string const absMasterLyX = getMasterFilePath(false);
2020 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2021 // Do not copy if the new path is impossible to create. Example:
2022 // absMasterTeX = "/foo/bar/"
2023 // absMasterLyX = "/bar/"
2024 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2025 if (contains(name, "/../"))
2032 // convert from absolute original path to
2033 // "relative to .lyx file"
2034 name = to_utf8(makeRelPath(from_utf8(abs),
2035 from_utf8(absParentLyX)));
2039 // convert from absolute original path to "relative to .lyx file"
2040 name = to_utf8(makeRelPath(from_utf8(name),
2041 from_utf8(absParentLyX)));
2046 void copy_file(FileName const & src, string dstname)
2050 string const absParent = getParentFilePath(false);
2052 if (FileName::isAbsolute(dstname))
2053 dst = FileName(dstname);
2055 dst = makeAbsPath(dstname, absParent);
2056 string const absMaster = getMasterFilePath(false);
2057 FileName const srcpath = src.onlyPath();
2058 FileName const dstpath = dst.onlyPath();
2059 if (equivalent(srcpath, dstpath))
2061 if (!dstpath.isDirectory()) {
2062 if (!dstpath.createPath()) {
2063 cerr << "Warning: Could not create directory for file `"
2064 << dst.absFileName() << "´." << endl;
2068 if (dst.isReadableFile()) {
2069 if (overwriteFiles())
2070 cerr << "Warning: Overwriting existing file `"
2071 << dst.absFileName() << "´." << endl;
2073 cerr << "Warning: Not overwriting existing file `"
2074 << dst.absFileName() << "´." << endl;
2078 if (!src.copyTo(dst))
2079 cerr << "Warning: Could not copy file `" << src.absFileName()
2080 << "´ to `" << dst.absFileName() << "´." << endl;
2084 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2085 bool parse_chunk(Parser & p, ostream & os, Context & context)
2087 // check whether a chunk is possible here.
2088 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2094 // read the parameters
2095 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2096 if (!params.first) {
2101 Parser::Arg const code = p.verbatimStuff("\n@");
2106 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2107 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2111 // The last newline read is important for paragraph handling
2115 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2116 // We must have a valid layout before outputting the Chunk inset.
2117 context.check_layout(os);
2118 Context chunkcontext(true, context.textclass);
2119 chunkcontext.layout = &context.textclass.plainLayout();
2120 begin_inset(os, "Flex Chunk");
2121 os << "\nstatus open\n";
2122 if (!params.second.empty()) {
2123 chunkcontext.check_layout(os);
2124 Context paramscontext(true, context.textclass);
2125 paramscontext.layout = &context.textclass.plainLayout();
2126 begin_inset(os, "Argument 1");
2127 os << "\nstatus open\n";
2128 output_ert(os, params.second, paramscontext);
2131 output_ert(os, code.second, chunkcontext);
2139 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2140 bool is_macro(Parser & p)
2142 Token first = p.curr_token();
2143 if (first.cat() != catEscape || !p.good())
2145 if (first.cs() == "def")
2147 if (first.cs() != "global" && first.cs() != "long")
2149 Token second = p.get_token();
2151 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2152 second.cat() == catNewline || second.cat() == catComment)) {
2153 second = p.get_token();
2156 bool secondvalid = second.cat() == catEscape;
2158 bool thirdvalid = false;
2159 if (p.good() && first.cs() == "global" && secondvalid &&
2160 second.cs() == "long") {
2161 third = p.get_token();
2163 while (p.good() && !p.isParagraph() &&
2164 (third.cat() == catSpace ||
2165 third.cat() == catNewline ||
2166 third.cat() == catComment)) {
2167 third = p.get_token();
2170 thirdvalid = third.cat() == catEscape;
2172 for (int i = 0; i < pos; ++i)
2177 return (first.cs() == "global" || first.cs() == "long") &&
2178 second.cs() == "def";
2179 return first.cs() == "global" && second.cs() == "long" &&
2180 third.cs() == "def";
2184 /// Parse a macro definition (assumes that is_macro() returned true)
2185 void parse_macro(Parser & p, ostream & os, Context & context)
2187 context.check_layout(os);
2188 Token first = p.curr_token();
2191 string command = first.asInput();
2192 if (first.cs() != "def") {
2194 eat_whitespace(p, os, context, false);
2195 second = p.curr_token();
2196 command += second.asInput();
2197 if (second.cs() != "def") {
2199 eat_whitespace(p, os, context, false);
2200 third = p.curr_token();
2201 command += third.asInput();
2204 eat_whitespace(p, os, context, false);
2205 string const name = p.get_token().cs();
2206 eat_whitespace(p, os, context, false);
2212 while (p.next_token().cat() != catBegin) {
2213 if (p.next_token().cat() == catParameter) {
2218 // followed by number?
2219 if (p.next_token().cat() == catOther) {
2220 string s = p.get_token().asInput();
2222 // number = current arity + 1?
2223 if (s.size() == 1 && s[0] == arity + '0' + 1)
2228 paramtext += p.get_token().cs();
2230 paramtext += p.get_token().cs();
2235 // only output simple (i.e. compatible) macro as FormulaMacros
2236 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2238 context.check_layout(os);
2239 begin_inset(os, "FormulaMacro");
2240 os << "\n\\def" << ert;
2243 output_ert_inset(os, command + ert, context);
2247 void registerExternalTemplatePackages(string const & name)
2249 external::TemplateManager const & etm = external::TemplateManager::get();
2250 external::Template const * const et = etm.getTemplateByName(name);
2253 external::Template::Formats::const_iterator cit = et->formats.end();
2255 cit = et->formats.find("PDFLaTeX");
2256 if (cit == et->formats.end())
2257 // If the template has not specified a PDFLaTeX output,
2258 // we try the LaTeX format.
2259 cit = et->formats.find("LaTeX");
2260 if (cit == et->formats.end())
2262 vector<string>::const_iterator qit = cit->second.requirements.begin();
2263 vector<string>::const_iterator qend = cit->second.requirements.end();
2264 for (; qit != qend; ++qit)
2265 preamble.registerAutomaticallyLoadedPackage(*qit);
2268 } // anonymous namespace
2271 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2274 Layout const * newlayout = 0;
2275 InsetLayout const * newinsetlayout = 0;
2276 char const * const * where = 0;
2277 // Store the latest bibliographystyle, addcontentslineContent and
2278 // nocite{*} option (needed for bibtex inset)
2280 string contentslineContent;
2281 string bibliographystyle = "default";
2282 bool const use_natbib = isProvided("natbib");
2283 bool const use_jurabib = isProvided("jurabib");
2286 // it is impossible to determine the correct encoding for non-CJK Japanese.
2287 // Therefore write a note at the beginning of the document
2288 if (is_nonCJKJapanese) {
2289 context.check_layout(os);
2290 begin_inset(os, "Note Note\n");
2291 os << "status open\n\\begin_layout Plain Layout\n"
2292 << "\\series bold\n"
2293 << "Important information:\n"
2294 << "\\end_layout\n\n"
2295 << "\\begin_layout Plain Layout\n"
2296 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2297 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2298 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2299 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2300 << " and specify the encoding using the -e command-line switch.\n"
2301 << " In addition, you might want to double check that the desired output encoding\n"
2302 << " is correctly selected in Document > Settings > Language.\n"
2303 << "\\end_layout\n";
2305 is_nonCJKJapanese = false;
2309 Token const & t = p.get_token();
2311 debugToken(cerr, t, flags);
2314 if (flags & FLAG_ITEM) {
2315 if (t.cat() == catSpace)
2318 flags &= ~FLAG_ITEM;
2319 if (t.cat() == catBegin) {
2320 // skip the brace and collect everything to the next matching
2322 flags |= FLAG_BRACE_LAST;
2326 // handle only this single token, leave the loop if done
2327 flags |= FLAG_LEAVE;
2330 if (t.cat() != catEscape && t.character() == ']' &&
2331 (flags & FLAG_BRACK_LAST))
2333 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2336 // If there is anything between \end{env} and \begin{env} we
2337 // don't need to output a separator.
2338 if (t.cat() != catSpace && t.cat() != catNewline &&
2339 t.asInput() != "\\begin")
2345 bool const starred = p.next_token().asInput() == "*";
2346 string const starredname(starred ? (t.cs() + '*') : t.cs());
2347 if (t.cat() == catMath) {
2348 // we are inside some text mode thingy, so opening new math is allowed
2349 context.check_layout(os);
2350 begin_inset(os, "Formula ");
2351 Token const & n = p.get_token();
2352 bool const display(n.cat() == catMath && outer);
2354 // TeX's $$...$$ syntax for displayed math
2356 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2358 p.get_token(); // skip the second '$' token
2360 // simple $...$ stuff
2363 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2368 // Prevent the conversion of a line break to a
2369 // space (bug 7668). This does not change the
2370 // output, but looks ugly in LyX.
2371 eat_whitespace(p, os, context, false);
2375 else if (t.cat() == catSuper || t.cat() == catSub)
2376 cerr << "catcode " << t << " illegal in text mode\n";
2378 // Basic support for english quotes. This should be
2379 // extended to other quotes, but is not so easy (a
2380 // left english quote is the same as a right german
2382 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2383 context.check_layout(os);
2384 begin_inset(os, "Quotes ");
2390 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2391 context.check_layout(os);
2392 begin_inset(os, "Quotes ");
2399 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2400 context.check_layout(os);
2401 begin_inset(os, "Quotes ");
2408 else if (t.asInput() == "<"
2409 && p.next_token().asInput() == "<") {
2410 bool has_chunk = false;
2414 has_chunk = parse_chunk(p, os, context);
2420 context.check_layout(os);
2421 begin_inset(os, "Quotes ");
2422 //FIXME: this is a right danish quote;
2423 // why not a left french quote?
2431 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2432 check_space(p, os, context);
2434 else if (t.character() == '[' && noweb_mode &&
2435 p.next_token().character() == '[') {
2436 // These can contain underscores
2438 string const s = p.getFullOpt() + ']';
2439 if (p.next_token().character() == ']')
2442 cerr << "Warning: Inserting missing ']' in '"
2443 << s << "'." << endl;
2444 output_ert_inset(os, s, context);
2447 else if (t.cat() == catLetter) {
2448 context.check_layout(os);
2452 else if (t.cat() == catOther ||
2453 t.cat() == catAlign ||
2454 t.cat() == catParameter) {
2455 context.check_layout(os);
2456 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2457 context.merging_hyphens_allowed &&
2458 context.font.family != "ttfamily" &&
2459 !context.layout->pass_thru) {
2460 if (p.next_next_token().asInput() == "-") {
2462 os << to_utf8(docstring(1, 0x2014));
2466 os << to_utf8(docstring(1, 0x2013));
2469 // This translates "&" to "\\&" which may be wrong...
2473 else if (p.isParagraph()) {
2474 if (context.new_layout_allowed)
2475 context.new_paragraph(os);
2477 output_ert_inset(os, "\\par ", context);
2478 eat_whitespace(p, os, context, true);
2481 else if (t.cat() == catActive) {
2482 context.check_layout(os);
2483 if (t.character() == '~') {
2484 if (context.layout->free_spacing)
2487 begin_inset(os, "space ~\n");
2494 else if (t.cat() == catBegin) {
2495 Token const next = p.next_token();
2496 Token const end = p.next_next_token();
2497 if (next.cat() == catEnd) {
2499 Token const prev = p.prev_token();
2501 if (p.next_token().character() == '`')
2502 ; // ignore it in {}``
2504 output_ert_inset(os, "{}", context);
2505 } else if (next.cat() == catEscape &&
2506 is_known(next.cs(), known_quotes) &&
2507 end.cat() == catEnd) {
2508 // Something like {\textquoteright} (e.g.
2509 // from writer2latex). LyX writes
2510 // \textquoteright{}, so we may skip the
2511 // braces here for better readability.
2512 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2514 } else if (p.next_token().asInput() == "\\ascii") {
2515 // handle the \ascii characters
2516 // (the case without braces is handled later)
2517 // the code is "{\ascii\xxx}"
2518 p.get_token(); // eat \ascii
2519 string name2 = p.get_token().asInput();
2520 p.get_token(); // eat the final '}'
2521 string const name = "{\\ascii" + name2 + "}";
2525 // get the character from unicodesymbols
2526 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2527 Encodings::TEXT_CMD, termination, rem, &req);
2529 context.check_layout(os);
2532 output_ert_inset(os,
2533 to_utf8(rem), context);
2534 for (set<string>::const_iterator it = req.begin();
2535 it != req.end(); ++it)
2536 preamble.registerAutomaticallyLoadedPackage(*it);
2538 // we did not find a non-ert version
2539 output_ert_inset(os, name, context);
2541 context.check_layout(os);
2542 // special handling of font attribute changes
2543 Token const prev = p.prev_token();
2544 TeXFont const oldFont = context.font;
2545 if (next.character() == '[' ||
2546 next.character() == ']' ||
2547 next.character() == '*') {
2549 if (p.next_token().cat() == catEnd) {
2554 output_ert_inset(os, "{", context);
2555 parse_text_snippet(p, os,
2558 output_ert_inset(os, "}", context);
2560 } else if (! context.new_layout_allowed) {
2561 output_ert_inset(os, "{", context);
2562 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2564 output_ert_inset(os, "}", context);
2565 } else if (is_known(next.cs(), known_sizes)) {
2566 // next will change the size, so we must
2568 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2570 if (!context.atParagraphStart())
2572 << context.font.size << "\n";
2573 } else if (is_known(next.cs(), known_font_families)) {
2574 // next will change the font family, so we
2575 // must reset it here
2576 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2578 if (!context.atParagraphStart())
2580 << context.font.family << "\n";
2581 } else if (is_known(next.cs(), known_font_series)) {
2582 // next will change the font series, so we
2583 // must reset it here
2584 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2586 if (!context.atParagraphStart())
2588 << context.font.series << "\n";
2589 } else if (is_known(next.cs(), known_font_shapes)) {
2590 // next will change the font shape, so we
2591 // must reset it here
2592 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2594 if (!context.atParagraphStart())
2596 << context.font.shape << "\n";
2597 } else if (is_known(next.cs(), known_old_font_families) ||
2598 is_known(next.cs(), known_old_font_series) ||
2599 is_known(next.cs(), known_old_font_shapes)) {
2600 // next will change the font family, series
2601 // and shape, so we must reset it here
2602 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2604 if (!context.atParagraphStart())
2606 << context.font.family
2608 << context.font.series
2610 << context.font.shape << "\n";
2612 output_ert_inset(os, "{", context);
2613 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2615 output_ert_inset(os, "}", context);
2620 else if (t.cat() == catEnd) {
2621 if (flags & FLAG_BRACE_LAST) {
2624 cerr << "stray '}' in text\n";
2625 output_ert_inset(os, "}", context);
2628 else if (t.cat() == catComment)
2629 parse_comment(p, os, t, context);
2632 // control sequences
2635 else if (t.cs() == "(" || t.cs() == "[") {
2636 bool const simple = t.cs() == "(";
2637 context.check_layout(os);
2638 begin_inset(os, "Formula");
2639 os << " \\" << t.cs();
2640 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2641 os << '\\' << (simple ? ')' : ']');
2644 // Prevent the conversion of a line break to a
2645 // space (bug 7668). This does not change the
2646 // output, but looks ugly in LyX.
2647 eat_whitespace(p, os, context, false);
2651 else if (t.cs() == "begin")
2652 parse_environment(p, os, outer, last_env,
2655 else if (t.cs() == "end") {
2656 if (flags & FLAG_END) {
2657 // eat environment name
2658 string const name = p.getArg('{', '}');
2659 if (name != active_environment())
2660 cerr << "\\end{" + name + "} does not match \\begin{"
2661 + active_environment() + "}\n";
2664 p.error("found 'end' unexpectedly");
2667 else if (t.cs() == "item") {
2669 bool const optarg = p.hasOpt();
2671 // FIXME: This swallows comments, but we cannot use
2672 // eat_whitespace() since we must not output
2673 // anything before the item.
2674 p.skip_spaces(true);
2675 s = p.verbatimOption();
2677 p.skip_spaces(false);
2679 context.check_layout(os);
2680 if (context.has_item) {
2681 // An item in an unknown list-like environment
2682 // FIXME: Do this in check_layout()!
2683 context.has_item = false;
2685 output_ert_inset(os, "\\item", context);
2687 output_ert_inset(os, "\\item ", context);
2690 if (context.layout->labeltype != LABEL_MANUAL) {
2691 // handle option of itemize item
2692 begin_inset(os, "Argument item:1\n");
2693 os << "status open\n";
2694 os << "\n\\begin_layout Plain Layout\n";
2696 os << parse_text_snippet(p2,
2697 FLAG_BRACK_LAST, outer, context);
2698 // we must not use context.check_end_layout(os)
2699 // because that would close the outer itemize layout
2700 os << "\n\\end_layout\n";
2702 eat_whitespace(p, os, context, false);
2703 } else if (!s.empty()) {
2704 // LyX adds braces around the argument,
2705 // so we need to remove them here.
2706 if (s.size() > 2 && s[0] == '{' &&
2707 s[s.size()-1] == '}')
2708 s = s.substr(1, s.size()-2);
2709 // If the argument contains a space we
2710 // must put it into ERT: Otherwise LyX
2711 // would misinterpret the space as
2712 // item delimiter (bug 7663)
2713 if (contains(s, ' ')) {
2714 output_ert_inset(os, s, context);
2717 os << parse_text_snippet(p2,
2718 FLAG_BRACK_LAST, outer, context);
2720 // The space is needed to separate the
2721 // item from the rest of the sentence.
2723 eat_whitespace(p, os, context, false);
2728 else if (t.cs() == "bibitem") {
2730 context.check_layout(os);
2731 eat_whitespace(p, os, context, false);
2732 string label = convert_command_inset_arg(p.verbatimOption());
2733 string key = convert_command_inset_arg(p.verbatim_item());
2734 if (contains(label, '\\') || contains(key, '\\')) {
2735 // LyX can't handle LaTeX commands in labels or keys
2736 output_ert_inset(os, t.asInput() + '[' + label +
2737 "]{" + p.verbatim_item() + '}',
2740 begin_command_inset(os, "bibitem", "bibitem");
2741 os << "label \"" << label << "\"\n"
2742 "key \"" << key << "\"\n";
2747 else if (is_macro(p)) {
2748 // catch the case of \def\inputGnumericTable
2750 if (t.cs() == "def") {
2751 Token second = p.next_token();
2752 if (second.cs() == "inputGnumericTable") {
2756 Token third = p.get_token();
2758 if (third.cs() == "input") {
2762 string name = normalize_filename(p.verbatim_item());
2763 string const path = getMasterFilePath(true);
2764 // We want to preserve relative / absolute filenames,
2765 // therefore path is only used for testing
2766 // The file extension is in every case ".tex".
2767 // So we need to remove this extension and check for
2768 // the original one.
2769 name = removeExtension(name);
2770 if (!makeAbsPath(name, path).exists()) {
2771 char const * const Gnumeric_formats[] = {"gnumeric",
2773 string const Gnumeric_name =
2774 find_file(name, path, Gnumeric_formats);
2775 if (!Gnumeric_name.empty())
2776 name = Gnumeric_name;
2778 FileName const absname = makeAbsPath(name, path);
2779 if (absname.exists()) {
2780 fix_child_filename(name);
2781 copy_file(absname, name);
2783 cerr << "Warning: Could not find file '"
2784 << name << "'." << endl;
2785 context.check_layout(os);
2786 begin_inset(os, "External\n\ttemplate ");
2787 os << "GnumericSpreadsheet\n\tfilename "
2790 context.check_layout(os);
2792 // register the packages that are automatically loaded
2793 // by the Gnumeric template
2794 registerExternalTemplatePackages("GnumericSpreadsheet");
2799 parse_macro(p, os, context);
2802 else if (t.cs() == "noindent") {
2804 context.add_par_extra_stuff("\\noindent\n");
2807 else if (t.cs() == "appendix") {
2808 context.add_par_extra_stuff("\\start_of_appendix\n");
2809 // We need to start a new paragraph. Otherwise the
2810 // appendix in 'bla\appendix\chapter{' would start
2812 context.new_paragraph(os);
2813 // We need to make sure that the paragraph is
2814 // generated even if it is empty. Otherwise the
2815 // appendix in '\par\appendix\par\chapter{' would
2817 context.check_layout(os);
2818 // FIXME: This is a hack to prevent paragraph
2819 // deletion if it is empty. Handle this better!
2820 output_ert_inset(os,
2821 "%dummy comment inserted by tex2lyx to "
2822 "ensure that this paragraph is not empty",
2824 // Both measures above may generate an additional
2825 // empty paragraph, but that does not hurt, because
2826 // whitespace does not matter here.
2827 eat_whitespace(p, os, context, true);
2830 // Must catch empty dates before findLayout is called below
2831 else if (t.cs() == "date") {
2832 eat_whitespace(p, os, context, false);
2834 string const date = p.verbatim_item();
2837 preamble.suppressDate(true);
2840 preamble.suppressDate(false);
2841 if (context.new_layout_allowed &&
2842 (newlayout = findLayout(context.textclass,
2845 output_command_layout(os, p, outer,
2846 context, newlayout);
2847 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2848 if (!preamble.titleLayoutFound())
2849 preamble.titleLayoutFound(newlayout->intitle);
2850 set<string> const & req = newlayout->requires();
2851 set<string>::const_iterator it = req.begin();
2852 set<string>::const_iterator en = req.end();
2853 for (; it != en; ++it)
2854 preamble.registerAutomaticallyLoadedPackage(*it);
2856 output_ert_inset(os,
2857 "\\date{" + p.verbatim_item() + '}',
2862 // Starred section headings
2863 // Must attempt to parse "Section*" before "Section".
2864 else if ((p.next_token().asInput() == "*") &&
2865 context.new_layout_allowed &&
2866 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2869 output_command_layout(os, p, outer, context, newlayout);
2871 if (!preamble.titleLayoutFound())
2872 preamble.titleLayoutFound(newlayout->intitle);
2873 set<string> const & req = newlayout->requires();
2874 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2875 preamble.registerAutomaticallyLoadedPackage(*it);
2878 // Section headings and the like
2879 else if (context.new_layout_allowed &&
2880 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2882 output_command_layout(os, p, outer, context, newlayout);
2884 if (!preamble.titleLayoutFound())
2885 preamble.titleLayoutFound(newlayout->intitle);
2886 set<string> const & req = newlayout->requires();
2887 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2888 preamble.registerAutomaticallyLoadedPackage(*it);
2891 else if (t.cs() == "subfloat") {
2892 // the syntax is \subfloat[list entry][sub caption]{content}
2893 // if it is a table of figure depends on the surrounding float
2894 // FIXME: second optional argument is not parsed
2895 bool has_caption = false;
2897 // do nothing if there is no outer float
2898 if (!float_type.empty()) {
2899 context.check_layout(os);
2901 begin_inset(os, "Float " + float_type + "\n");
2903 << "\nsideways false"
2904 << "\nstatus collapsed\n\n";
2907 if (p.next_token().cat() != catEscape &&
2908 p.next_token().character() == '[') {
2909 p.get_token(); // eat '['
2910 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2914 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2915 // the caption comes always as the last
2917 // we must make sure that the caption gets a \begin_layout
2918 os << "\n\\begin_layout Plain Layout";
2920 begin_inset(os, "Caption Standard\n");
2921 Context newcontext(true, context.textclass,
2922 0, 0, context.font);
2923 newcontext.check_layout(os);
2924 os << caption << "\n";
2925 newcontext.check_end_layout(os);
2926 // We don't need really a new paragraph, but
2927 // we must make sure that the next item gets a \begin_layout.
2928 //newcontext.new_paragraph(os);
2932 // We don't need really a new paragraph, but
2933 // we must make sure that the next item gets a \begin_layout.
2935 context.new_paragraph(os);
2938 context.check_end_layout(os);
2939 // close the layout we opened
2941 os << "\n\\end_layout\n";
2943 // if the float type is not supported or there is no surrounding float
2946 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2947 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2948 "]{" + p.verbatim_item() + '}', context);
2950 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2954 else if (t.cs() == "includegraphics") {
2955 bool const clip = p.next_token().asInput() == "*";
2958 string const arg = p.getArg('[', ']');
2959 map<string, string> opts;
2960 vector<string> keys;
2961 split_map(arg, opts, keys);
2963 opts["clip"] = string();
2964 string name = normalize_filename(p.verbatim_item());
2966 string const path = getMasterFilePath(true);
2967 // We want to preserve relative / absolute filenames,
2968 // therefore path is only used for testing
2969 if (!makeAbsPath(name, path).exists()) {
2970 // The file extension is probably missing.
2971 // Now try to find it out.
2972 string const dvips_name =
2973 find_file(name, path,
2974 known_dvips_graphics_formats);
2975 string const pdftex_name =
2976 find_file(name, path,
2977 known_pdftex_graphics_formats);
2978 if (!dvips_name.empty()) {
2979 if (!pdftex_name.empty()) {
2980 cerr << "This file contains the "
2982 "\"\\includegraphics{"
2984 "However, files\n\""
2985 << dvips_name << "\" and\n\""
2986 << pdftex_name << "\"\n"
2987 "both exist, so I had to make a "
2988 "choice and took the first one.\n"
2989 "Please move the unwanted one "
2990 "someplace else and try again\n"
2991 "if my choice was wrong."
2995 } else if (!pdftex_name.empty()) {
3001 FileName const absname = makeAbsPath(name, path);
3002 if (absname.exists()) {
3003 fix_child_filename(name);
3004 copy_file(absname, name);
3006 cerr << "Warning: Could not find graphics file '"
3007 << name << "'." << endl;
3009 context.check_layout(os);
3010 begin_inset(os, "Graphics ");
3011 os << "\n\tfilename " << name << '\n';
3012 if (opts.find("width") != opts.end())
3014 << translate_len(opts["width"]) << '\n';
3015 if (opts.find("height") != opts.end())
3017 << translate_len(opts["height"]) << '\n';
3018 if (opts.find("scale") != opts.end()) {
3019 istringstream iss(opts["scale"]);
3023 os << "\tscale " << val << '\n';
3025 if (opts.find("angle") != opts.end()) {
3026 os << "\trotateAngle "
3027 << opts["angle"] << '\n';
3028 vector<string>::const_iterator a =
3029 find(keys.begin(), keys.end(), "angle");
3030 vector<string>::const_iterator s =
3031 find(keys.begin(), keys.end(), "width");
3032 if (s == keys.end())
3033 s = find(keys.begin(), keys.end(), "height");
3034 if (s == keys.end())
3035 s = find(keys.begin(), keys.end(), "scale");
3036 if (s != keys.end() && distance(s, a) > 0)
3037 os << "\tscaleBeforeRotation\n";
3039 if (opts.find("origin") != opts.end()) {
3041 string const opt = opts["origin"];
3042 if (opt.find('l') != string::npos) ss << "left";
3043 if (opt.find('r') != string::npos) ss << "right";
3044 if (opt.find('c') != string::npos) ss << "center";
3045 if (opt.find('t') != string::npos) ss << "Top";
3046 if (opt.find('b') != string::npos) ss << "Bottom";
3047 if (opt.find('B') != string::npos) ss << "Baseline";
3048 if (!ss.str().empty())
3049 os << "\trotateOrigin " << ss.str() << '\n';
3051 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3053 if (opts.find("keepaspectratio") != opts.end())
3054 os << "\tkeepAspectRatio\n";
3055 if (opts.find("clip") != opts.end())
3057 if (opts.find("draft") != opts.end())
3059 if (opts.find("bb") != opts.end())
3060 os << "\tBoundingBox "
3061 << opts["bb"] << '\n';
3062 int numberOfbbOptions = 0;
3063 if (opts.find("bbllx") != opts.end())
3064 numberOfbbOptions++;
3065 if (opts.find("bblly") != opts.end())
3066 numberOfbbOptions++;
3067 if (opts.find("bburx") != opts.end())
3068 numberOfbbOptions++;
3069 if (opts.find("bbury") != opts.end())
3070 numberOfbbOptions++;
3071 if (numberOfbbOptions == 4)
3072 os << "\tBoundingBox "
3073 << opts["bbllx"] << " " << opts["bblly"] << " "
3074 << opts["bburx"] << " " << opts["bbury"] << '\n';
3075 else if (numberOfbbOptions > 0)
3076 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3077 numberOfbbOptions = 0;
3078 if (opts.find("natwidth") != opts.end())
3079 numberOfbbOptions++;
3080 if (opts.find("natheight") != opts.end())
3081 numberOfbbOptions++;
3082 if (numberOfbbOptions == 2)
3083 os << "\tBoundingBox 0bp 0bp "
3084 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3085 else if (numberOfbbOptions > 0)
3086 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3087 ostringstream special;
3088 if (opts.find("hiresbb") != opts.end())
3089 special << "hiresbb,";
3090 if (opts.find("trim") != opts.end())
3092 if (opts.find("viewport") != opts.end())
3093 special << "viewport=" << opts["viewport"] << ',';
3094 if (opts.find("totalheight") != opts.end())
3095 special << "totalheight=" << opts["totalheight"] << ',';
3096 if (opts.find("type") != opts.end())
3097 special << "type=" << opts["type"] << ',';
3098 if (opts.find("ext") != opts.end())
3099 special << "ext=" << opts["ext"] << ',';
3100 if (opts.find("read") != opts.end())
3101 special << "read=" << opts["read"] << ',';
3102 if (opts.find("command") != opts.end())
3103 special << "command=" << opts["command"] << ',';
3104 string s_special = special.str();
3105 if (!s_special.empty()) {
3106 // We had special arguments. Remove the trailing ','.
3107 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3109 // TODO: Handle the unknown settings better.
3110 // Warn about invalid options.
3111 // Check whether some option was given twice.
3113 preamble.registerAutomaticallyLoadedPackage("graphicx");
3116 else if (t.cs() == "footnote" ||
3117 (t.cs() == "thanks" && context.layout->intitle)) {
3119 context.check_layout(os);
3120 begin_inset(os, "Foot\n");
3121 os << "status collapsed\n\n";
3122 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3126 else if (t.cs() == "marginpar") {
3128 context.check_layout(os);
3129 begin_inset(os, "Marginal\n");
3130 os << "status collapsed\n\n";
3131 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3135 else if (t.cs() == "lstinline") {
3137 parse_listings(p, os, context, true);
3140 else if (t.cs() == "ensuremath") {
3142 context.check_layout(os);
3143 string const s = p.verbatim_item();
3144 //FIXME: this never triggers in UTF8
3145 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3148 output_ert_inset(os, "\\ensuremath{" + s + "}",
3152 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3153 if (preamble.titleLayoutFound()) {
3155 skip_spaces_braces(p);
3157 output_ert_inset(os, t.asInput(), context);
3160 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3161 context.check_layout(os);
3162 begin_command_inset(os, "toc", t.cs());
3164 skip_spaces_braces(p);
3165 if (t.cs() == "lstlistoflistings")
3166 preamble.registerAutomaticallyLoadedPackage("listings");
3169 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3170 context.check_layout(os);
3171 if (t.cs() == "listoffigures")
3172 begin_inset(os, "FloatList figure\n");
3174 begin_inset(os, "FloatList table\n");
3176 skip_spaces_braces(p);
3179 else if (t.cs() == "listof") {
3180 p.skip_spaces(true);
3181 string const name = p.get_token().cs();
3182 if (context.textclass.floats().typeExist(name)) {
3183 context.check_layout(os);
3184 begin_inset(os, "FloatList ");
3187 p.get_token(); // swallow second arg
3189 output_ert_inset(os, "\\listof{" + name + "}", context);
3192 else if ((where = is_known(t.cs(), known_text_font_families)))
3193 parse_text_attributes(p, os, FLAG_ITEM, outer,
3194 context, "\\family", context.font.family,
3195 known_coded_font_families[where - known_text_font_families]);
3197 else if ((where = is_known(t.cs(), known_text_font_series)))
3198 parse_text_attributes(p, os, FLAG_ITEM, outer,
3199 context, "\\series", context.font.series,
3200 known_coded_font_series[where - known_text_font_series]);
3202 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3203 parse_text_attributes(p, os, FLAG_ITEM, outer,
3204 context, "\\shape", context.font.shape,
3205 known_coded_font_shapes[where - known_text_font_shapes]);
3207 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3208 context.check_layout(os);
3209 TeXFont oldFont = context.font;
3210 context.font.init();
3211 context.font.size = oldFont.size;
3212 os << "\n\\family " << context.font.family << "\n";
3213 os << "\n\\series " << context.font.series << "\n";
3214 os << "\n\\shape " << context.font.shape << "\n";
3215 if (t.cs() == "textnormal") {
3216 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3217 output_font_change(os, context.font, oldFont);
3218 context.font = oldFont;
3220 eat_whitespace(p, os, context, false);
3223 else if (t.cs() == "textcolor") {
3224 // scheme is \textcolor{color name}{text}
3225 string const color = p.verbatim_item();
3226 // we support the predefined colors of the color and the xcolor package
3227 if (color == "black" || color == "blue" || color == "cyan"
3228 || color == "green" || color == "magenta" || color == "red"
3229 || color == "white" || color == "yellow") {
3230 context.check_layout(os);
3231 os << "\n\\color " << color << "\n";
3232 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3233 context.check_layout(os);
3234 os << "\n\\color inherit\n";
3235 preamble.registerAutomaticallyLoadedPackage("color");
3236 } else if (color == "brown" || color == "darkgray" || color == "gray"
3237 || color == "lightgray" || color == "lime" || color == "olive"
3238 || color == "orange" || color == "pink" || color == "purple"
3239 || color == "teal" || color == "violet") {
3240 context.check_layout(os);
3241 os << "\n\\color " << color << "\n";
3242 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3243 context.check_layout(os);
3244 os << "\n\\color inherit\n";
3245 preamble.registerAutomaticallyLoadedPackage("xcolor");
3247 // for custom defined colors
3248 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3251 else if (t.cs() == "underbar" || t.cs() == "uline") {
3252 // \underbar is not 100% correct (LyX outputs \uline
3253 // of ulem.sty). The difference is that \ulem allows
3254 // line breaks, and \underbar does not.
3255 // Do NOT handle \underline.
3256 // \underbar cuts through y, g, q, p etc.,
3257 // \underline does not.
3258 context.check_layout(os);
3259 os << "\n\\bar under\n";
3260 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3261 context.check_layout(os);
3262 os << "\n\\bar default\n";
3263 preamble.registerAutomaticallyLoadedPackage("ulem");
3266 else if (t.cs() == "sout") {
3267 context.check_layout(os);
3268 os << "\n\\strikeout on\n";
3269 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3270 context.check_layout(os);
3271 os << "\n\\strikeout default\n";
3272 preamble.registerAutomaticallyLoadedPackage("ulem");
3275 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3276 t.cs() == "emph" || t.cs() == "noun") {
3277 context.check_layout(os);
3278 os << "\n\\" << t.cs() << " on\n";
3279 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3280 context.check_layout(os);
3281 os << "\n\\" << t.cs() << " default\n";
3282 if (t.cs() == "uuline" || t.cs() == "uwave")
3283 preamble.registerAutomaticallyLoadedPackage("ulem");
3286 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3287 context.check_layout(os);
3288 string name = p.getArg('{', '}');
3289 string localtime = p.getArg('{', '}');
3290 preamble.registerAuthor(name);
3291 Author const & author = preamble.getAuthor(name);
3292 // from_asctime_utc() will fail if LyX decides to output the
3293 // time in the text language.
3294 time_t ptime = from_asctime_utc(localtime);
3295 if (ptime == static_cast<time_t>(-1)) {
3296 cerr << "Warning: Could not parse time `" << localtime
3297 << "´ for change tracking, using current time instead.\n";
3298 ptime = current_time();
3300 if (t.cs() == "lyxadded")
3301 os << "\n\\change_inserted ";
3303 os << "\n\\change_deleted ";
3304 os << author.bufferId() << ' ' << ptime << '\n';
3305 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3306 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3307 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3308 LaTeXPackages::isAvailable("xcolor");
3309 // No need to test for luatex, since luatex comes in
3310 // two flavours (dvi and pdf), like latex, and those
3311 // are detected by pdflatex.
3312 if (pdflatex || xetex) {
3314 preamble.registerAutomaticallyLoadedPackage("ulem");
3315 preamble.registerAutomaticallyLoadedPackage("xcolor");
3316 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3320 preamble.registerAutomaticallyLoadedPackage("dvipost");
3321 } else if (xcolorulem) {
3322 preamble.registerAutomaticallyLoadedPackage("ulem");
3323 preamble.registerAutomaticallyLoadedPackage("xcolor");
3328 else if (t.cs() == "textipa") {
3329 context.check_layout(os);
3330 begin_inset(os, "IPA\n");
3331 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3332 context.merging_hyphens_allowed = false;
3333 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3334 context.merging_hyphens_allowed = merging_hyphens_allowed;
3336 preamble.registerAutomaticallyLoadedPackage("tipa");
3337 preamble.registerAutomaticallyLoadedPackage("tipx");
3340 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3341 context.check_layout(os);
3342 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3343 os << "status open\n";
3344 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3349 else if (t.cs() == "textvertline") {
3350 // FIXME: This is not correct, \textvertline is higher than |
3356 else if (t.cs() == "tone" ) {
3357 context.check_layout(os);
3358 // register the tone package
3359 preamble.registerAutomaticallyLoadedPackage("tone");
3360 string content = trimSpaceAndEol(p.verbatim_item());
3361 string command = t.asInput() + "{" + content + "}";
3362 // some tones can be detected by unicodesymbols, some need special code
3363 if (is_known(content, known_tones)) {
3364 os << "\\IPAChar " << command << "\n";
3367 // try to see whether the string is in unicodesymbols
3371 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3372 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3373 termination, rem, &req);
3377 output_ert_inset(os, to_utf8(rem), context);
3378 for (set<string>::const_iterator it = req.begin();
3379 it != req.end(); ++it)
3380 preamble.registerAutomaticallyLoadedPackage(*it);
3382 // we did not find a non-ert version
3383 output_ert_inset(os, command, context);
3386 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3387 t.cs() == "vphantom") {
3388 context.check_layout(os);
3389 if (t.cs() == "phantom")
3390 begin_inset(os, "Phantom Phantom\n");
3391 if (t.cs() == "hphantom")
3392 begin_inset(os, "Phantom HPhantom\n");
3393 if (t.cs() == "vphantom")
3394 begin_inset(os, "Phantom VPhantom\n");
3395 os << "status open\n";
3396 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3401 else if (t.cs() == "href") {
3402 context.check_layout(os);
3403 string target = convert_command_inset_arg(p.verbatim_item());
3404 string name = convert_command_inset_arg(p.verbatim_item());
3406 size_t i = target.find(':');
3407 if (i != string::npos) {
3408 type = target.substr(0, i + 1);
3409 if (type == "mailto:" || type == "file:")
3410 target = target.substr(i + 1);
3411 // handle the case that name is equal to target, except of "http://"
3412 else if (target.substr(i + 3) == name && type == "http:")
3415 begin_command_inset(os, "href", "href");
3417 os << "name \"" << name << "\"\n";
3418 os << "target \"" << target << "\"\n";
3419 if (type == "mailto:" || type == "file:")
3420 os << "type \"" << type << "\"\n";
3422 skip_spaces_braces(p);
3425 else if (t.cs() == "lyxline") {
3426 // swallow size argument (it is not used anyway)
3428 if (!context.atParagraphStart()) {
3429 // so our line is in the middle of a paragraph
3430 // we need to add a new line, lest this line
3431 // follow the other content on that line and
3432 // run off the side of the page
3433 // FIXME: This may create an empty paragraph,
3434 // but without that it would not be
3435 // possible to set noindent below.
3436 // Fortunately LaTeX does not care
3437 // about the empty paragraph.
3438 context.new_paragraph(os);
3440 if (preamble.indentParagraphs()) {
3441 // we need to unindent, lest the line be too long
3442 context.add_par_extra_stuff("\\noindent\n");
3444 context.check_layout(os);
3445 begin_command_inset(os, "line", "rule");
3446 os << "offset \"0.5ex\"\n"
3447 "width \"100line%\"\n"
3452 else if (t.cs() == "rule") {
3453 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3454 string const width = p.getArg('{', '}');
3455 string const thickness = p.getArg('{', '}');
3456 context.check_layout(os);
3457 begin_command_inset(os, "line", "rule");
3458 if (!offset.empty())
3459 os << "offset \"" << translate_len(offset) << "\"\n";
3460 os << "width \"" << translate_len(width) << "\"\n"
3461 "height \"" << translate_len(thickness) << "\"\n";
3465 // handle refstyle first to catch \eqref which can also occur
3466 // without refstyle. Only recognize these commands if
3467 // refstyle.sty was found in the preamble (otherwise \eqref
3468 // and user defined ref commands could be misdetected).
3469 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3470 preamble.refstyle()) {
3471 context.check_layout(os);
3472 begin_command_inset(os, "ref", "formatted");
3473 os << "reference \"";
3474 os << known_refstyle_prefixes[where - known_refstyle_commands]
3476 os << convert_command_inset_arg(p.verbatim_item())
3479 preamble.registerAutomaticallyLoadedPackage("refstyle");
3482 // if refstyle is used, we must not convert \prettyref to a
3483 // formatted reference, since that would result in a refstyle command.
3484 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3485 (t.cs() != "prettyref" || !preamble.refstyle())) {
3486 string const opt = p.getOpt();
3488 context.check_layout(os);
3489 begin_command_inset(os, "ref",
3490 known_coded_ref_commands[where - known_ref_commands]);
3491 os << "reference \""
3492 << convert_command_inset_arg(p.verbatim_item())
3495 if (t.cs() == "vref" || t.cs() == "vpageref")
3496 preamble.registerAutomaticallyLoadedPackage("varioref");
3497 else if (t.cs() == "prettyref")
3498 preamble.registerAutomaticallyLoadedPackage("prettyref");
3500 // LyX does not yet support optional arguments of ref commands
3501 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3502 p.verbatim_item() + '}', context);
3506 else if (use_natbib &&
3507 is_known(t.cs(), known_natbib_commands) &&
3508 ((t.cs() != "citefullauthor" &&
3509 t.cs() != "citeyear" &&
3510 t.cs() != "citeyearpar") ||
3511 p.next_token().asInput() != "*")) {
3512 context.check_layout(os);
3513 string command = t.cs();
3514 if (p.next_token().asInput() == "*") {
3518 if (command == "citefullauthor")
3519 // alternative name for "\\citeauthor*"
3520 command = "citeauthor*";
3522 // text before the citation
3524 // text after the citation
3526 get_cite_arguments(p, true, before, after);
3528 if (command == "cite") {
3529 // \cite without optional argument means
3530 // \citet, \cite with at least one optional
3531 // argument means \citep.
3532 if (before.empty() && after.empty())
3537 if (before.empty() && after == "[]")
3538 // avoid \citet[]{a}
3540 else if (before == "[]" && after == "[]") {
3541 // avoid \citet[][]{a}
3545 // remove the brackets around after and before
3546 if (!after.empty()) {
3548 after.erase(after.length() - 1, 1);
3549 after = convert_command_inset_arg(after);
3551 if (!before.empty()) {
3553 before.erase(before.length() - 1, 1);
3554 before = convert_command_inset_arg(before);
3556 begin_command_inset(os, "citation", command);
3557 os << "after " << '"' << after << '"' << "\n";
3558 os << "before " << '"' << before << '"' << "\n";
3560 << convert_command_inset_arg(p.verbatim_item())
3563 // Need to set the cite engine if natbib is loaded by
3564 // the document class directly
3565 if (preamble.citeEngine() == "basic")
3566 preamble.citeEngine("natbib");
3569 else if (use_jurabib &&
3570 is_known(t.cs(), known_jurabib_commands) &&
3571 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3572 context.check_layout(os);
3573 string command = t.cs();
3574 if (p.next_token().asInput() == "*") {
3578 char argumentOrder = '\0';
3579 vector<string> const options =
3580 preamble.getPackageOptions("jurabib");
3581 if (find(options.begin(), options.end(),
3582 "natbiborder") != options.end())
3583 argumentOrder = 'n';
3584 else if (find(options.begin(), options.end(),
3585 "jurabiborder") != options.end())
3586 argumentOrder = 'j';
3588 // text before the citation
3590 // text after the citation
3592 get_cite_arguments(p, argumentOrder != 'j', before, after);
3594 string const citation = p.verbatim_item();
3595 if (!before.empty() && argumentOrder == '\0') {
3596 cerr << "Warning: Assuming argument order "
3597 "of jurabib version 0.6 for\n'"
3598 << command << before << after << '{'
3599 << citation << "}'.\n"
3600 "Add 'jurabiborder' to the jurabib "
3601 "package options if you used an\n"
3602 "earlier jurabib version." << endl;
3604 if (!after.empty()) {
3606 after.erase(after.length() - 1, 1);
3608 if (!before.empty()) {
3610 before.erase(before.length() - 1, 1);
3612 begin_command_inset(os, "citation", command);
3613 os << "after " << '"' << after << '"' << "\n";
3614 os << "before " << '"' << before << '"' << "\n";
3615 os << "key " << '"' << citation << '"' << "\n";
3617 // Need to set the cite engine if jurabib is loaded by
3618 // the document class directly
3619 if (preamble.citeEngine() == "basic")
3620 preamble.citeEngine("jurabib");
3623 else if (t.cs() == "cite"
3624 || t.cs() == "nocite") {
3625 context.check_layout(os);
3626 string after = convert_command_inset_arg(p.getArg('[', ']'));
3627 string key = convert_command_inset_arg(p.verbatim_item());
3628 // store the case that it is "\nocite{*}" to use it later for
3631 begin_command_inset(os, "citation", t.cs());
3632 os << "after " << '"' << after << '"' << "\n";
3633 os << "key " << '"' << key << '"' << "\n";
3635 } else if (t.cs() == "nocite")
3639 else if (t.cs() == "index" ||
3640 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3641 context.check_layout(os);
3642 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3643 p.getArg('[', ']') : "";
3644 string const kind = arg.empty() ? "idx" : arg;
3645 begin_inset(os, "Index ");
3646 os << kind << "\nstatus collapsed\n";
3647 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3650 preamble.registerAutomaticallyLoadedPackage("splitidx");
3653 else if (t.cs() == "nomenclature") {
3654 context.check_layout(os);
3655 begin_command_inset(os, "nomenclature", "nomenclature");
3656 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3657 if (!prefix.empty())
3658 os << "prefix " << '"' << prefix << '"' << "\n";
3659 os << "symbol " << '"'
3660 << convert_command_inset_arg(p.verbatim_item());
3661 os << "\"\ndescription \""
3662 << convert_command_inset_arg(p.verbatim_item())
3665 preamble.registerAutomaticallyLoadedPackage("nomencl");
3668 else if (t.cs() == "label") {
3669 context.check_layout(os);
3670 begin_command_inset(os, "label", "label");
3672 << convert_command_inset_arg(p.verbatim_item())
3677 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3678 context.check_layout(os);
3679 string commandname = t.cs();
3681 if (p.next_token().asInput() == "*") {
3686 begin_command_inset(os, "index_print", commandname);
3687 string const indexname = p.getArg('[', ']');
3689 if (indexname.empty())
3690 os << "type \"idx\"\n";
3692 os << "type \"" << indexname << "\"\n";
3695 skip_spaces_braces(p);
3696 preamble.registerAutomaticallyLoadedPackage("makeidx");
3697 if (preamble.use_indices() == "true")
3698 preamble.registerAutomaticallyLoadedPackage("splitidx");
3701 else if (t.cs() == "printnomenclature") {
3703 string width_type = "";
3704 context.check_layout(os);
3705 begin_command_inset(os, "nomencl_print", "printnomenclature");
3706 // case of a custom width
3708 width = p.getArg('[', ']');
3709 width = translate_len(width);
3710 width_type = "custom";
3712 // case of no custom width
3713 // the case of no custom width but the width set
3714 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3715 // because the user could have set anything, not only the width
3716 // of the longest label (which would be width_type = "auto")
3717 string label = convert_command_inset_arg(p.getArg('{', '}'));
3718 if (label.empty() && width_type.empty())
3719 width_type = "none";
3720 os << "set_width \"" << width_type << "\"\n";
3721 if (width_type == "custom")
3722 os << "width \"" << width << '\"';
3724 skip_spaces_braces(p);
3725 preamble.registerAutomaticallyLoadedPackage("nomencl");
3728 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3729 context.check_layout(os);
3730 begin_inset(os, "script ");
3731 os << t.cs().substr(4) << '\n';
3732 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
3733 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3735 if (t.cs() == "textsubscript")
3736 preamble.registerAutomaticallyLoadedPackage("subscript");
3739 else if ((where = is_known(t.cs(), known_quotes))) {
3740 context.check_layout(os);
3741 begin_inset(os, "Quotes ");
3742 os << known_coded_quotes[where - known_quotes];
3744 // LyX adds {} after the quote, so we have to eat
3745 // spaces here if there are any before a possible
3747 eat_whitespace(p, os, context, false);
3751 else if ((where = is_known(t.cs(), known_sizes)) &&
3752 context.new_layout_allowed) {
3753 context.check_layout(os);
3754 TeXFont const oldFont = context.font;
3755 context.font.size = known_coded_sizes[where - known_sizes];
3756 output_font_change(os, oldFont, context.font);
3757 eat_whitespace(p, os, context, false);
3760 else if ((where = is_known(t.cs(), known_font_families)) &&
3761 context.new_layout_allowed) {
3762 context.check_layout(os);
3763 TeXFont const oldFont = context.font;
3764 context.font.family =
3765 known_coded_font_families[where - known_font_families];
3766 output_font_change(os, oldFont, context.font);
3767 eat_whitespace(p, os, context, false);
3770 else if ((where = is_known(t.cs(), known_font_series)) &&
3771 context.new_layout_allowed) {
3772 context.check_layout(os);
3773 TeXFont const oldFont = context.font;
3774 context.font.series =
3775 known_coded_font_series[where - known_font_series];
3776 output_font_change(os, oldFont, context.font);
3777 eat_whitespace(p, os, context, false);
3780 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3781 context.new_layout_allowed) {
3782 context.check_layout(os);
3783 TeXFont const oldFont = context.font;
3784 context.font.shape =
3785 known_coded_font_shapes[where - known_font_shapes];
3786 output_font_change(os, oldFont, context.font);
3787 eat_whitespace(p, os, context, false);
3789 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3790 context.new_layout_allowed) {
3791 context.check_layout(os);
3792 TeXFont const oldFont = context.font;
3793 context.font.init();
3794 context.font.size = oldFont.size;
3795 context.font.family =
3796 known_coded_font_families[where - known_old_font_families];
3797 output_font_change(os, oldFont, context.font);
3798 eat_whitespace(p, os, context, false);
3801 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3802 context.new_layout_allowed) {
3803 context.check_layout(os);
3804 TeXFont const oldFont = context.font;
3805 context.font.init();
3806 context.font.size = oldFont.size;
3807 context.font.series =
3808 known_coded_font_series[where - known_old_font_series];
3809 output_font_change(os, oldFont, context.font);
3810 eat_whitespace(p, os, context, false);
3813 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3814 context.new_layout_allowed) {
3815 context.check_layout(os);
3816 TeXFont const oldFont = context.font;
3817 context.font.init();
3818 context.font.size = oldFont.size;
3819 context.font.shape =
3820 known_coded_font_shapes[where - known_old_font_shapes];
3821 output_font_change(os, oldFont, context.font);
3822 eat_whitespace(p, os, context, false);
3825 else if (t.cs() == "selectlanguage") {
3826 context.check_layout(os);
3827 // save the language for the case that a
3828 // \foreignlanguage is used
3829 context.font.language = babel2lyx(p.verbatim_item());
3830 os << "\n\\lang " << context.font.language << "\n";
3833 else if (t.cs() == "foreignlanguage") {
3834 string const lang = babel2lyx(p.verbatim_item());
3835 parse_text_attributes(p, os, FLAG_ITEM, outer,
3837 context.font.language, lang);
3840 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
3841 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3842 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3844 // We have to output the whole command if it has an option
3845 // because LyX doesn't support this yet, see bug #8214,
3846 // only if there is a single option specifying a variant, we can handle it.
3848 string langopts = p.getOpt();
3849 // check if the option contains a variant, if yes, extract it
3850 string::size_type pos_var = langopts.find("variant");
3851 string::size_type i = langopts.find(',');
3852 string::size_type k = langopts.find('=', pos_var);
3853 if (pos_var != string::npos && i == string::npos) {
3855 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3856 lang = preamble.polyglossia2lyx(variant);
3857 parse_text_attributes(p, os, FLAG_ITEM, outer,
3859 context.font.language, lang);
3861 output_ert_inset(os, t.asInput() + langopts, context);
3863 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3864 parse_text_attributes(p, os, FLAG_ITEM, outer,
3866 context.font.language, lang);
3870 else if (t.cs() == "inputencoding") {
3871 // nothing to write here
3872 string const enc = subst(p.verbatim_item(), "\n", " ");
3873 p.setEncoding(enc, Encoding::inputenc);
3876 else if (is_known(t.cs(), known_special_chars) ||
3877 (t.cs() == "protect" &&
3878 p.next_token().cat() == catEscape &&
3879 is_known(p.next_token().cs(), known_special_protect_chars))) {
3880 // LyX sometimes puts a \protect in front, so we have to ignore it
3882 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3883 known_special_chars);
3884 context.check_layout(os);
3885 os << known_coded_special_chars[where - known_special_chars];
3886 skip_spaces_braces(p);
3889 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3890 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
3891 p.next_next_token().asInput() == "-") ||
3892 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3893 // LyX sometimes puts a \protect in front, so we have to ignore it
3894 if (t.cs() == "protect")
3896 context.check_layout(os);
3897 if (t.cs() == "nobreakdash")
3898 os << "\\SpecialChar nobreakdash\n";
3900 os << "\\SpecialChar endofsentence\n";
3904 else if (t.cs() == "textquotedbl") {
3905 context.check_layout(os);
3910 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3911 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3912 || t.cs() == "%" || t.cs() == "-") {
3913 context.check_layout(os);
3915 os << "\\SpecialChar softhyphen\n";
3920 else if (t.cs() == "char") {
3921 context.check_layout(os);
3922 if (p.next_token().character() == '`') {
3924 if (p.next_token().cs() == "\"") {
3929 output_ert_inset(os, "\\char`", context);
3932 output_ert_inset(os, "\\char", context);
3936 else if (t.cs() == "verb") {
3937 context.check_layout(os);
3938 // set catcodes to verbatim early, just in case.
3939 p.setCatcodes(VERBATIM_CATCODES);
3940 string delim = p.get_token().asInput();
3941 Parser::Arg arg = p.verbatimStuff(delim);
3943 output_ert_inset(os, "\\verb" + delim
3944 + arg.second + delim, context);
3946 cerr << "invalid \\verb command. Skipping" << endl;
3949 // Problem: \= creates a tabstop inside the tabbing environment
3950 // and else an accent. In the latter case we really would want
3951 // \={o} instead of \= o.
3952 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3953 output_ert_inset(os, t.asInput(), context);
3955 else if (t.cs() == "\\") {
3956 context.check_layout(os);
3958 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3959 else if (p.next_token().asInput() == "*") {
3961 // getOpt() eats the following space if there
3962 // is no optional argument, but that is OK
3963 // here since it has no effect in the output.
3964 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3967 begin_inset(os, "Newline newline");
3972 else if (t.cs() == "newline" ||
3973 (t.cs() == "linebreak" && !p.hasOpt())) {
3974 context.check_layout(os);
3975 begin_inset(os, "Newline ");
3978 skip_spaces_braces(p);
3981 else if (t.cs() == "input" || t.cs() == "include"
3982 || t.cs() == "verbatiminput") {
3983 string name = t.cs();
3984 if (t.cs() == "verbatiminput"
3985 && p.next_token().asInput() == "*")
3986 name += p.get_token().asInput();
3987 context.check_layout(os);
3988 string filename(normalize_filename(p.getArg('{', '}')));
3989 string const path = getMasterFilePath(true);
3990 // We want to preserve relative / absolute filenames,
3991 // therefore path is only used for testing
3992 if ((t.cs() == "include" || t.cs() == "input") &&
3993 !makeAbsPath(filename, path).exists()) {
3994 // The file extension is probably missing.
3995 // Now try to find it out.
3996 string const tex_name =
3997 find_file(filename, path,
3998 known_tex_extensions);
3999 if (!tex_name.empty())
4000 filename = tex_name;
4002 bool external = false;
4004 if (makeAbsPath(filename, path).exists()) {
4005 string const abstexname =
4006 makeAbsPath(filename, path).absFileName();
4007 string const absfigname =
4008 changeExtension(abstexname, ".fig");
4009 fix_child_filename(filename);
4010 string const lyxname = changeExtension(filename,
4011 roundtripMode() ? ".lyx.lyx" : ".lyx");
4012 string const abslyxname = makeAbsPath(
4013 lyxname, getParentFilePath(false)).absFileName();
4015 if (!skipChildren())
4016 external = FileName(absfigname).exists();
4017 if (t.cs() == "input" && !skipChildren()) {
4018 string const ext = getExtension(abstexname);
4020 // Combined PS/LaTeX:
4021 // x.eps, x.pstex_t (old xfig)
4022 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4023 FileName const absepsname(
4024 changeExtension(abstexname, ".eps"));
4025 FileName const abspstexname(
4026 changeExtension(abstexname, ".pstex"));
4027 bool const xfigeps =
4028 (absepsname.exists() ||
4029 abspstexname.exists()) &&
4032 // Combined PDF/LaTeX:
4033 // x.pdf, x.pdftex_t (old xfig)
4034 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4035 FileName const abspdfname(
4036 changeExtension(abstexname, ".pdf"));
4037 bool const xfigpdf =
4038 abspdfname.exists() &&
4039 (ext == "pdftex_t" || ext == "pdf_t");
4043 // Combined PS/PDF/LaTeX:
4044 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4045 string const absbase2(
4046 removeExtension(abstexname) + "_pspdftex");
4047 FileName const abseps2name(
4048 addExtension(absbase2, ".eps"));
4049 FileName const abspdf2name(
4050 addExtension(absbase2, ".pdf"));
4051 bool const xfigboth =
4052 abspdf2name.exists() &&
4053 abseps2name.exists() && ext == "pspdftex";
4055 xfig = xfigpdf || xfigeps || xfigboth;
4056 external = external && xfig;
4059 outname = changeExtension(filename, ".fig");
4060 FileName abssrc(changeExtension(abstexname, ".fig"));
4061 copy_file(abssrc, outname);
4063 // Don't try to convert, the result
4064 // would be full of ERT.
4066 FileName abssrc(abstexname);
4067 copy_file(abssrc, outname);
4068 } else if (t.cs() != "verbatiminput" &&
4070 tex2lyx(abstexname, FileName(abslyxname),
4073 // no need to call copy_file
4074 // tex2lyx creates the file
4077 FileName abssrc(abstexname);
4078 copy_file(abssrc, outname);
4081 cerr << "Warning: Could not find included file '"
4082 << filename << "'." << endl;
4086 begin_inset(os, "External\n");
4087 os << "\ttemplate XFig\n"
4088 << "\tfilename " << outname << '\n';
4089 registerExternalTemplatePackages("XFig");
4091 begin_command_inset(os, "include", name);
4092 outname = subst(outname, "\"", "\\\"");
4093 os << "preview false\n"
4094 "filename \"" << outname << "\"\n";
4095 if (t.cs() == "verbatiminput")
4096 preamble.registerAutomaticallyLoadedPackage("verbatim");
4101 else if (t.cs() == "bibliographystyle") {
4102 // store new bibliographystyle
4103 bibliographystyle = p.verbatim_item();
4104 // If any other command than \bibliography, \addcontentsline
4105 // and \nocite{*} follows, we need to output the style
4106 // (because it might be used by that command).
4107 // Otherwise, it will automatically be output by LyX.
4110 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4111 if (t2.cat() == catBegin)
4113 if (t2.cat() != catEscape)
4115 if (t2.cs() == "nocite") {
4116 if (p.getArg('{', '}') == "*")
4118 } else if (t2.cs() == "bibliography")
4120 else if (t2.cs() == "phantomsection") {
4124 else if (t2.cs() == "addcontentsline") {
4125 // get the 3 arguments of \addcontentsline
4128 contentslineContent = p.getArg('{', '}');
4129 // if the last argument is not \refname we must output
4130 if (contentslineContent == "\\refname")
4137 output_ert_inset(os,
4138 "\\bibliographystyle{" + bibliographystyle + '}',
4143 else if (t.cs() == "phantomsection") {
4144 // we only support this if it occurs between
4145 // \bibliographystyle and \bibliography
4146 if (bibliographystyle.empty())
4147 output_ert_inset(os, "\\phantomsection", context);
4150 else if (t.cs() == "addcontentsline") {
4151 context.check_layout(os);
4152 // get the 3 arguments of \addcontentsline
4153 string const one = p.getArg('{', '}');
4154 string const two = p.getArg('{', '}');
4155 string const three = p.getArg('{', '}');
4156 // only if it is a \refname, we support if for the bibtex inset
4157 if (contentslineContent != "\\refname") {
4158 output_ert_inset(os,
4159 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4164 else if (t.cs() == "bibliography") {
4165 context.check_layout(os);
4167 begin_command_inset(os, "bibtex", "bibtex");
4168 if (!btprint.empty()) {
4169 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4170 // clear the string because the next BibTeX inset can be without the
4171 // \nocite{*} option
4174 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4175 // Do we have addcontentsline?
4176 if (contentslineContent == "\\refname") {
4177 BibOpts = "bibtotoc";
4178 // clear string because next BibTeX inset can be without addcontentsline
4179 contentslineContent.clear();
4181 // Do we have a bibliographystyle set?
4182 if (!bibliographystyle.empty()) {
4183 if (BibOpts.empty())
4184 BibOpts = bibliographystyle;
4186 BibOpts = BibOpts + ',' + bibliographystyle;
4187 // clear it because each bibtex entry has its style
4188 // and we need an empty string to handle \phantomsection
4189 bibliographystyle.clear();
4191 os << "options " << '"' << BibOpts << '"' << "\n";
4195 else if (t.cs() == "parbox") {
4196 // Test whether this is an outer box of a shaded box
4198 // swallow arguments
4199 while (p.hasOpt()) {
4201 p.skip_spaces(true);
4204 p.skip_spaces(true);
4206 if (p.next_token().cat() == catBegin)
4208 p.skip_spaces(true);
4209 Token to = p.get_token();
4210 bool shaded = false;
4211 if (to.asInput() == "\\begin") {
4212 p.skip_spaces(true);
4213 if (p.getArg('{', '}') == "shaded")
4218 parse_outer_box(p, os, FLAG_ITEM, outer,
4219 context, "parbox", "shaded");
4221 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4222 "", "", t.cs(), "", "");
4225 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4226 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4227 t.cs() == "shadowbox" || t.cs() == "doublebox")
4228 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4230 else if (t.cs() == "colorbox") {
4231 string const backgroundcolor = p.getArg('{', '}');
4232 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4235 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4236 || t.cs() == "shadowsize") {
4237 p.skip_spaces(true);
4238 if (t.cs() == "fboxrule")
4240 if (t.cs() == "fboxsep")
4242 if (t.cs() == "shadowsize")
4244 while (p.good() && p.next_token().cat() != catSpace
4245 && p.next_token().cat() != catNewline
4246 && p.next_token().cat() != catEscape) {
4247 if (t.cs() == "fboxrule")
4248 fboxrule = fboxrule + p.get_token().asInput();
4249 if (t.cs() == "fboxsep")
4250 fboxsep = fboxsep + p.get_token().asInput();
4251 if (t.cs() == "shadowsize")
4252 shadow_size = shadow_size + p.get_token().asInput();
4256 //\framebox() is part of the picture environment and different from \framebox{}
4257 //\framebox{} will be parsed by parse_outer_box
4258 else if (t.cs() == "framebox") {
4259 if (p.next_token().character() == '(') {
4260 //the syntax is: \framebox(x,y)[position]{content}
4261 string arg = t.asInput();
4262 arg += p.getFullParentheseArg();
4263 arg += p.getFullOpt();
4264 eat_whitespace(p, os, context, false);
4265 output_ert_inset(os, arg + '{', context);
4266 parse_text(p, os, FLAG_ITEM, outer, context);
4267 output_ert_inset(os, "}", context);
4269 //the syntax is: \framebox[width][position]{content}
4270 string special = p.getFullOpt();
4271 special += p.getOpt();
4272 parse_outer_box(p, os, FLAG_ITEM, outer,
4273 context, t.cs(), special);
4277 //\makebox() is part of the picture environment and different from \makebox{}
4278 //\makebox{} will be parsed by parse_box
4279 else if (t.cs() == "makebox") {
4280 if (p.next_token().character() == '(') {
4281 //the syntax is: \makebox(x,y)[position]{content}
4282 string arg = t.asInput();
4283 arg += p.getFullParentheseArg();
4284 arg += p.getFullOpt();
4285 eat_whitespace(p, os, context, false);
4286 output_ert_inset(os, arg + '{', context);
4287 parse_text(p, os, FLAG_ITEM, outer, context);
4288 output_ert_inset(os, "}", context);
4290 //the syntax is: \makebox[width][position]{content}
4291 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4292 "", "", t.cs(), "", "");
4295 else if (t.cs() == "smallskip" ||
4296 t.cs() == "medskip" ||
4297 t.cs() == "bigskip" ||
4298 t.cs() == "vfill") {
4299 context.check_layout(os);
4300 begin_inset(os, "VSpace ");
4303 skip_spaces_braces(p);
4306 else if ((where = is_known(t.cs(), known_spaces))) {
4307 context.check_layout(os);
4308 begin_inset(os, "space ");
4309 os << '\\' << known_coded_spaces[where - known_spaces]
4312 // LaTeX swallows whitespace after all spaces except
4313 // "\\,". We have to do that here, too, because LyX
4314 // adds "{}" which would make the spaces significant.
4316 eat_whitespace(p, os, context, false);
4317 // LyX adds "{}" after all spaces except "\\ " and
4318 // "\\,", so we have to remove "{}".
4319 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4320 // remove the braces after "\\,", too.
4325 else if (t.cs() == "newpage" ||
4326 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4327 t.cs() == "clearpage" ||
4328 t.cs() == "cleardoublepage") {
4329 context.check_layout(os);
4330 begin_inset(os, "Newpage ");
4333 skip_spaces_braces(p);
4336 else if (t.cs() == "DeclareRobustCommand" ||
4337 t.cs() == "DeclareRobustCommandx" ||
4338 t.cs() == "newcommand" ||
4339 t.cs() == "newcommandx" ||
4340 t.cs() == "providecommand" ||
4341 t.cs() == "providecommandx" ||
4342 t.cs() == "renewcommand" ||
4343 t.cs() == "renewcommandx") {
4344 // DeclareRobustCommand, DeclareRobustCommandx,
4345 // providecommand and providecommandx could be handled
4346 // by parse_command(), but we need to call
4347 // add_known_command() here.
4348 string name = t.asInput();
4349 if (p.next_token().asInput() == "*") {
4350 // Starred form. Eat '*'
4354 string const command = p.verbatim_item();
4355 string const opt1 = p.getFullOpt();
4356 string const opt2 = p.getFullOpt();
4357 add_known_command(command, opt1, !opt2.empty());
4358 string const ert = name + '{' + command + '}' +
4360 '{' + p.verbatim_item() + '}';
4362 if (t.cs() == "DeclareRobustCommand" ||
4363 t.cs() == "DeclareRobustCommandx" ||
4364 t.cs() == "providecommand" ||
4365 t.cs() == "providecommandx" ||
4366 name[name.length()-1] == '*')
4367 output_ert_inset(os, ert, context);
4369 context.check_layout(os);
4370 begin_inset(os, "FormulaMacro");
4376 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4377 // let could be handled by parse_command(),
4378 // but we need to call add_known_command() here.
4379 string ert = t.asInput();
4382 if (p.next_token().cat() == catBegin) {
4383 name = p.verbatim_item();
4384 ert += '{' + name + '}';
4386 name = p.verbatim_item();
4391 if (p.next_token().cat() == catBegin) {
4392 command = p.verbatim_item();
4393 ert += '{' + command + '}';
4395 command = p.verbatim_item();
4398 // If command is known, make name known too, to parse
4399 // its arguments correctly. For this reason we also
4400 // have commands in syntax.default that are hardcoded.
4401 CommandMap::iterator it = known_commands.find(command);
4402 if (it != known_commands.end())
4403 known_commands[t.asInput()] = it->second;
4404 output_ert_inset(os, ert, context);
4407 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4410 string name = t.asInput();
4411 string const length = p.verbatim_item();
4414 bool valid = splitLatexLength(length, valstring, unit);
4415 bool known_hspace = false;
4416 bool known_vspace = false;
4417 bool known_unit = false;
4420 istringstream iss(valstring);
4423 if (t.cs()[0] == 'h') {
4424 if (unit == "\\fill") {
4429 known_hspace = true;
4432 if (unit == "\\smallskipamount") {
4434 known_vspace = true;
4435 } else if (unit == "\\medskipamount") {
4437 known_vspace = true;
4438 } else if (unit == "\\bigskipamount") {
4440 known_vspace = true;
4441 } else if (unit == "\\fill") {
4443 known_vspace = true;
4447 if (!known_hspace && !known_vspace) {
4448 switch (unitFromString(unit)) {
4464 //unitFromString(unit) fails for relative units like Length::PCW
4465 // therefore handle them separately
4466 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4467 || unit == "\\textwidth" || unit == "\\linewidth"
4468 || unit == "\\textheight" || unit == "\\paperheight")
4476 // check for glue lengths
4477 bool is_gluelength = false;
4478 string gluelength = length;
4479 string::size_type i = length.find(" minus");
4480 if (i == string::npos) {
4481 i = length.find(" plus");
4482 if (i != string::npos)
4483 is_gluelength = true;
4485 is_gluelength = true;
4486 // if yes transform "9xx minus 8yy plus 7zz"
4488 if (is_gluelength) {
4489 i = gluelength.find(" minus");
4490 if (i != string::npos)
4491 gluelength.replace(i, 7, "-");
4492 i = gluelength.find(" plus");
4493 if (i != string::npos)
4494 gluelength.replace(i, 6, "+");
4497 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4498 // Literal horizontal length or known variable
4499 context.check_layout(os);
4500 begin_inset(os, "space ");
4508 if (known_unit && !known_hspace)
4509 os << "\n\\length " << translate_len(length);
4511 os << "\n\\length " << gluelength;
4513 } else if (known_unit || known_vspace || is_gluelength) {
4514 // Literal vertical length or known variable
4515 context.check_layout(os);
4516 begin_inset(os, "VSpace ");
4519 if (known_unit && !known_vspace)
4520 os << translate_len(length);
4527 // LyX can't handle other length variables in Inset VSpace/space
4532 output_ert_inset(os, name + '{' + unit + '}', context);
4533 else if (value == -1.0)
4534 output_ert_inset(os, name + "{-" + unit + '}', context);
4536 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4538 output_ert_inset(os, name + '{' + length + '}', context);
4542 // The single '=' is meant here.
4543 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4547 context.check_layout(os);
4548 docstring const name = newinsetlayout->name();
4549 bool const caption = name.find(from_ascii("Caption:")) == 0;
4551 begin_inset(os, "Caption ");
4552 os << to_utf8(name.substr(8)) << '\n';
4554 begin_inset(os, "Flex ");
4555 os << to_utf8(name) << '\n'
4556 << "status collapsed\n";
4558 if (newinsetlayout->isPassThru()) {
4559 // set catcodes to verbatim early, just in case.
4560 p.setCatcodes(VERBATIM_CATCODES);
4561 string delim = p.get_token().asInput();
4563 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4564 //FIXME: handle error condition
4565 string const arg = p.verbatimStuff("}").second;
4566 Context newcontext(true, context.textclass);
4567 if (newinsetlayout->forcePlainLayout())
4568 newcontext.layout = &context.textclass.plainLayout();
4569 output_ert(os, arg, newcontext);
4571 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4577 else if (t.cs() == "includepdf") {
4579 string const arg = p.getArg('[', ']');
4580 map<string, string> opts;
4581 vector<string> keys;
4582 split_map(arg, opts, keys);
4583 string name = normalize_filename(p.verbatim_item());
4584 string const path = getMasterFilePath(true);
4585 // We want to preserve relative / absolute filenames,
4586 // therefore path is only used for testing
4587 if (!makeAbsPath(name, path).exists()) {
4588 // The file extension is probably missing.
4589 // Now try to find it out.
4590 char const * const pdfpages_format[] = {"pdf", 0};
4591 string const pdftex_name =
4592 find_file(name, path, pdfpages_format);
4593 if (!pdftex_name.empty()) {
4598 FileName const absname = makeAbsPath(name, path);
4599 if (absname.exists())
4601 fix_child_filename(name);
4602 copy_file(absname, name);
4604 cerr << "Warning: Could not find file '"
4605 << name << "'." << endl;
4607 context.check_layout(os);
4608 begin_inset(os, "External\n\ttemplate ");
4609 os << "PDFPages\n\tfilename "
4611 // parse the options
4612 if (opts.find("pages") != opts.end())
4613 os << "\textra LaTeX \"pages="
4614 << opts["pages"] << "\"\n";
4615 if (opts.find("angle") != opts.end())
4616 os << "\trotateAngle "
4617 << opts["angle"] << '\n';
4618 if (opts.find("origin") != opts.end()) {
4620 string const opt = opts["origin"];
4621 if (opt == "tl") ss << "topleft";
4622 if (opt == "bl") ss << "bottomleft";
4623 if (opt == "Bl") ss << "baselineleft";
4624 if (opt == "c") ss << "center";
4625 if (opt == "tc") ss << "topcenter";
4626 if (opt == "bc") ss << "bottomcenter";
4627 if (opt == "Bc") ss << "baselinecenter";
4628 if (opt == "tr") ss << "topright";
4629 if (opt == "br") ss << "bottomright";
4630 if (opt == "Br") ss << "baselineright";
4631 if (!ss.str().empty())
4632 os << "\trotateOrigin " << ss.str() << '\n';
4634 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4636 if (opts.find("width") != opts.end())
4638 << translate_len(opts["width"]) << '\n';
4639 if (opts.find("height") != opts.end())
4641 << translate_len(opts["height"]) << '\n';
4642 if (opts.find("keepaspectratio") != opts.end())
4643 os << "\tkeepAspectRatio\n";
4645 context.check_layout(os);
4646 registerExternalTemplatePackages("PDFPages");
4649 else if (t.cs() == "loadgame") {
4651 string name = normalize_filename(p.verbatim_item());
4652 string const path = getMasterFilePath(true);
4653 // We want to preserve relative / absolute filenames,
4654 // therefore path is only used for testing
4655 if (!makeAbsPath(name, path).exists()) {
4656 // The file extension is probably missing.
4657 // Now try to find it out.
4658 char const * const lyxskak_format[] = {"fen", 0};
4659 string const lyxskak_name =
4660 find_file(name, path, lyxskak_format);
4661 if (!lyxskak_name.empty())
4662 name = lyxskak_name;
4664 FileName const absname = makeAbsPath(name, path);
4665 if (absname.exists())
4667 fix_child_filename(name);
4668 copy_file(absname, name);
4670 cerr << "Warning: Could not find file '"
4671 << name << "'." << endl;
4672 context.check_layout(os);
4673 begin_inset(os, "External\n\ttemplate ");
4674 os << "ChessDiagram\n\tfilename "
4677 context.check_layout(os);
4678 // after a \loadgame follows a \showboard
4679 if (p.get_token().asInput() == "showboard")
4681 registerExternalTemplatePackages("ChessDiagram");
4685 // try to see whether the string is in unicodesymbols
4686 // Only use text mode commands, since we are in text mode here,
4687 // and math commands may be invalid (bug 6797)
4688 string name = t.asInput();
4689 // handle the dingbats, cyrillic and greek
4690 if (name == "\\ding" || name == "\\textcyr" ||
4691 (name == "\\textgreek" && !preamble.usePolyglossia()))
4692 name = name + '{' + p.getArg('{', '}') + '}';
4693 // handle the ifsym characters
4694 else if (name == "\\textifsymbol") {
4695 string const optif = p.getFullOpt();
4696 string const argif = p.getArg('{', '}');
4697 name = name + optif + '{' + argif + '}';
4699 // handle the \ascii characters
4700 // the case of \ascii within braces, as LyX outputs it, is already
4701 // handled for t.cat() == catBegin
4702 else if (name == "\\ascii") {
4703 // the code is "\asci\xxx"
4704 name = "{" + name + p.get_token().asInput() + "}";
4707 // handle some TIPA special characters
4708 else if (preamble.isPackageUsed("tipa")) {
4709 if (name == "\\textglobfall") {
4712 } else if (name == "\\s") {
4713 // fromLaTeXCommand() does not yet
4714 // recognize tipa short cuts
4715 name = "\\textsyllabic";
4716 } else if (name == "\\=" &&
4717 p.next_token().asInput() == "*") {
4718 // fromLaTeXCommand() does not yet
4719 // recognize tipa short cuts
4722 } else if (name == "\\textdoublevertline") {
4723 // FIXME: This is not correct,
4724 // \textvertline is higher than \textbardbl
4725 name = "\\textbardbl";
4727 } else if (name == "\\!" ) {
4728 if (p.next_token().asInput() == "b") {
4729 p.get_token(); // eat 'b'
4732 } else if (p.next_token().asInput() == "d") {
4736 } else if (p.next_token().asInput() == "g") {
4740 } else if (p.next_token().asInput() == "G") {
4742 name = "\\texthtscg";
4744 } else if (p.next_token().asInput() == "j") {
4746 name = "\\texthtbardotlessj";
4748 } else if (p.next_token().asInput() == "o") {
4750 name = "\\textbullseye";
4753 } else if (name == "\\*" ) {
4754 if (p.next_token().asInput() == "k") {
4756 name = "\\textturnk";
4758 } else if (p.next_token().asInput() == "r") {
4759 p.get_token(); // eat 'b'
4760 name = "\\textturnr";
4762 } else if (p.next_token().asInput() == "t") {
4764 name = "\\textturnt";
4766 } else if (p.next_token().asInput() == "w") {
4768 name = "\\textturnw";
4773 if ((name.size() == 2 &&
4774 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4775 p.next_token().asInput() != "*") ||
4776 is_known(name.substr(1), known_tipa_marks)) {
4777 // name is a command that corresponds to a
4778 // combining character in unicodesymbols.
4779 // Append the argument, fromLaTeXCommand()
4780 // will either convert it to a single
4781 // character or a combining sequence.
4782 name += '{' + p.verbatim_item() + '}';
4784 // now get the character from unicodesymbols
4788 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4789 Encodings::TEXT_CMD, termination, rem, &req);
4791 context.check_layout(os);
4794 output_ert_inset(os, to_utf8(rem), context);
4796 skip_spaces_braces(p);
4797 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4798 preamble.registerAutomaticallyLoadedPackage(*it);
4800 //cerr << "#: " << t << " mode: " << mode << endl;
4801 // heuristic: read up to next non-nested space
4803 string s = t.asInput();
4804 string z = p.verbatim_item();
4805 while (p.good() && z != " " && !z.empty()) {
4806 //cerr << "read: " << z << endl;
4808 z = p.verbatim_item();
4810 cerr << "found ERT: " << s << endl;
4811 output_ert_inset(os, s + ' ', context);
4814 if (t.asInput() == name &&
4815 p.next_token().asInput() == "*") {
4816 // Starred commands like \vspace*{}
4817 p.get_token(); // Eat '*'
4820 if (!parse_command(name, p, os, outer, context))
4821 output_ert_inset(os, name, context);
4825 if (flags & FLAG_LEAVE) {
4826 flags &= ~FLAG_LEAVE;
4833 string guessLanguage(Parser & p, string const & lang)
4835 typedef std::map<std::string, size_t> LangMap;
4836 // map from language names to number of characters
4839 for (char const * const * i = supported_CJK_languages; *i; i++)
4840 used[string(*i)] = 0;
4843 Token const t = p.get_token();
4844 // comments are not counted for any language
4845 if (t.cat() == catComment)
4847 // commands are not counted as well, but we need to detect
4848 // \begin{CJK} and switch encoding if needed
4849 if (t.cat() == catEscape) {
4850 if (t.cs() == "inputencoding") {
4851 string const enc = subst(p.verbatim_item(), "\n", " ");
4852 p.setEncoding(enc, Encoding::inputenc);
4855 if (t.cs() != "begin")
4858 // Non-CJK content is counted for lang.
4859 // We do not care about the real language here:
4860 // If we have more non-CJK contents than CJK contents,
4861 // we simply use the language that was specified as
4862 // babel main language.
4863 used[lang] += t.asInput().length();
4866 // Now we are starting an environment
4868 string const name = p.getArg('{', '}');
4869 if (name != "CJK") {
4873 // It is a CJK environment
4875 /* name = */ p.getArg('{', '}');
4876 string const encoding = p.getArg('{', '}');
4877 /* mapping = */ p.getArg('{', '}');
4878 string const encoding_old = p.getEncoding();
4879 char const * const * const where =
4880 is_known(encoding, supported_CJK_encodings);
4882 p.setEncoding(encoding, Encoding::CJK);
4884 p.setEncoding("UTF-8");
4885 string const text = p.ertEnvironment("CJK");
4886 p.setEncoding(encoding_old);
4889 // ignore contents in unknown CJK encoding
4892 // the language of the text
4894 supported_CJK_languages[where - supported_CJK_encodings];
4895 used[cjk] += text.length();
4897 LangMap::const_iterator use = used.begin();
4898 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4899 if (it->second > use->second)