2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49 Context const & context, InsetLayout const * layout)
51 bool const forcePlainLayout =
52 layout ? layout->forcePlainLayout() : false;
53 Context newcontext(true, context.textclass);
55 newcontext.layout = &context.textclass.plainLayout();
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context const & context, string const & name)
68 InsetLayout const * layout = 0;
69 DocumentClass::InsetLayouts::const_iterator it =
70 context.textclass.insetLayouts().find(from_ascii(name));
71 if (it != context.textclass.insetLayouts().end())
72 layout = &(it->second);
73 parse_text_in_inset(p, os, flags, outer, context, layout);
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context newcontext(context);
81 // Don't inherit the paragraph-level extra stuff
82 newcontext.par_extra_stuff.clear();
83 parse_text(p, os, flags, outer, newcontext);
84 // Make sure that we don't create invalid .lyx files
85 context.need_layout = newcontext.need_layout;
86 context.need_end_layout = newcontext.need_end_layout;
91 * Thin wrapper around parse_text_snippet() using a string.
93 * We completely ignore \c context.need_layout and \c context.need_end_layout,
94 * because our return value is not used directly (otherwise the stream version
95 * of parse_text_snippet() could be used). That means that the caller needs
96 * to do layout management manually.
97 * This is intended to parse text that does not create any layout changes.
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
102 Context newcontext(context);
103 newcontext.need_layout = false;
104 newcontext.need_end_layout = false;
105 newcontext.new_layout_allowed = false;
106 // Avoid warning by Context::~Context()
107 newcontext.par_extra_stuff.clear();
109 parse_text_snippet(p, os, flags, outer, newcontext);
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115 "vpageref", "prettyref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "eqref", 0 };
121 * supported CJK encodings
122 * JIS does not work with LyX's encoding conversion
124 const char * const supported_CJK_encodings[] = {
125 "EUC-JP", "KS", "GB", "UTF8",
126 "Bg5", /*"JIS",*/ "SJIS", 0};
129 * the same as supported_CJK_encodings with their corresponding LyX language name
130 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
132 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
133 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
134 * please keep this in sync with supported_CJK_encodings line by line!
136 const char * const supported_CJK_languages[] = {
137 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
138 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
142 * The starred forms are also known except for "citefullauthor",
143 * "citeyear" and "citeyearpar".
145 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
146 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
147 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
151 * No starred form other than "cite*" known.
153 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
154 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
155 // jurabib commands not (yet) supported by LyX:
157 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
158 // "footciteauthor", "footciteyear", "footciteyearpar",
159 "citefield", "citetitle", 0 };
161 /// LaTeX names for quotes
162 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
163 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
164 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
165 "guilsinglleft", "frq", "guilsinglright", 0};
167 /// the same as known_quotes with .lyx names
168 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
169 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
170 "gld", "grd", "gls", "ers", "fls",
171 "fls", "frs", "frs", 0};
173 /// LaTeX names for font sizes
174 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
175 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
177 /// the same as known_sizes with .lyx names
178 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
179 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
181 /// LaTeX 2.09 names for font families
182 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
184 /// LaTeX names for font families
185 char const * const known_font_families[] = { "rmfamily", "sffamily",
188 /// LaTeX names for font family changing commands
189 char const * const known_text_font_families[] = { "textrm", "textsf",
192 /// The same as known_old_font_families, known_font_families and
193 /// known_text_font_families with .lyx names
194 char const * const known_coded_font_families[] = { "roman", "sans",
197 /// LaTeX 2.09 names for font series
198 char const * const known_old_font_series[] = { "bf", 0};
200 /// LaTeX names for font series
201 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
203 /// LaTeX names for font series changing commands
204 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
206 /// The same as known_old_font_series, known_font_series and
207 /// known_text_font_series with .lyx names
208 char const * const known_coded_font_series[] = { "bold", "medium", 0};
210 /// LaTeX 2.09 names for font shapes
211 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
213 /// LaTeX names for font shapes
214 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
217 /// LaTeX names for font shape changing commands
218 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
221 /// The same as known_old_font_shapes, known_font_shapes and
222 /// known_text_font_shapes with .lyx names
223 char const * const known_coded_font_shapes[] = { "italic", "slanted",
224 "smallcaps", "up", 0};
226 /// Known special characters which need skip_spaces_braces() afterwards
227 char const * const known_special_chars[] = {"ldots", "lyxarrow",
228 "textcompwordmark", "slash", 0};
230 /// the same as known_special_chars with .lyx names
231 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
232 "textcompwordmark{}", "slash{}", 0};
235 * Graphics file extensions known by the dvips driver of the graphics package.
236 * These extensions are used to complete the filename of an included
237 * graphics file if it does not contain an extension.
238 * The order must be the same that latex uses to find a file, because we
239 * will use the first extension that matches.
240 * This is only an approximation for the common cases. If we would want to
241 * do it right in all cases, we would need to know which graphics driver is
242 * used and know the extensions of every driver of the graphics package.
244 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
245 "ps.gz", "eps.Z", "ps.Z", 0};
248 * Graphics file extensions known by the pdftex driver of the graphics package.
249 * \sa known_dvips_graphics_formats
251 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
255 * Known file extensions for TeX files as used by \\include.
257 char const * const known_tex_extensions[] = {"tex", 0};
259 /// spaces known by InsetSpace
260 char const * const known_spaces[] = { " ", "space", ",",
261 "thinspace", "quad", "qquad", "enspace", "enskip",
262 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
263 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
264 "upbracefill", "downbracefill", 0};
266 /// the same as known_spaces with .lyx names
267 char const * const known_coded_spaces[] = { "space{}", "space{}",
268 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
269 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
270 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
271 "upbracefill{}", "downbracefill{}", 0};
273 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
274 /// them in ERT. "LaTeXe" must come before "LaTeX"!
275 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
276 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
277 int const known_phrase_lengths[] = {3, 5, 7, 0};
279 // string to store the float type to be able to determine the type of subfloats
280 string float_type = "";
283 /// splits "x=z, y=b" into a map and an ordered keyword vector
284 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
289 keys.resize(v.size());
290 for (size_t i = 0; i < v.size(); ++i) {
291 size_t const pos = v[i].find('=');
292 string const index = trimSpaceAndEol(v[i].substr(0, pos));
293 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
301 * Split a LaTeX length into value and unit.
302 * The latter can be a real unit like "pt", or a latex length variable
303 * like "\textwidth". The unit may contain additional stuff like glue
304 * lengths, but we don't care, because such lengths are ERT anyway.
305 * \returns true if \p value and \p unit are valid.
307 bool splitLatexLength(string const & len, string & value, string & unit)
311 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
312 //'4,5' is a valid LaTeX length number. Change it to '4.5'
313 string const length = subst(len, ',', '.');
314 if (i == string::npos)
317 if (len[0] == '\\') {
318 // We had something like \textwidth without a factor
324 value = trimSpaceAndEol(string(length, 0, i));
328 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
329 if (contains(len, '\\'))
330 unit = trimSpaceAndEol(string(len, i));
332 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
337 /// A simple function to translate a latex length to something LyX can
338 /// understand. Not perfect, but rather best-effort.
339 bool translate_len(string const & length, string & valstring, string & unit)
341 if (!splitLatexLength(length, valstring, unit))
343 // LyX uses percent values
345 istringstream iss(valstring);
350 string const percentval = oss.str();
352 if (unit.empty() || unit[0] != '\\')
354 string::size_type const i = unit.find(' ');
355 string const endlen = (i == string::npos) ? string() : string(unit, i);
356 if (unit == "\\textwidth") {
357 valstring = percentval;
358 unit = "text%" + endlen;
359 } else if (unit == "\\columnwidth") {
360 valstring = percentval;
361 unit = "col%" + endlen;
362 } else if (unit == "\\paperwidth") {
363 valstring = percentval;
364 unit = "page%" + endlen;
365 } else if (unit == "\\linewidth") {
366 valstring = percentval;
367 unit = "line%" + endlen;
368 } else if (unit == "\\paperheight") {
369 valstring = percentval;
370 unit = "pheight%" + endlen;
371 } else if (unit == "\\textheight") {
372 valstring = percentval;
373 unit = "theight%" + endlen;
381 string translate_len(string const & length)
385 if (translate_len(length, value, unit))
387 // If the input is invalid, return what we have.
395 * Translates a LaTeX length into \p value, \p unit and
396 * \p special parts suitable for a box inset.
397 * The difference from translate_len() is that a box inset knows about
398 * some special "units" that are stored in \p special.
400 void translate_box_len(string const & length, string & value, string & unit, string & special)
402 if (translate_len(length, value, unit)) {
403 if (unit == "\\height" || unit == "\\depth" ||
404 unit == "\\totalheight" || unit == "\\width") {
405 special = unit.substr(1);
406 // The unit is not used, but LyX requires a dummy setting
419 * Find a file with basename \p name in path \p path and an extension
422 string find_file(string const & name, string const & path,
423 char const * const * extensions)
425 for (char const * const * what = extensions; *what; ++what) {
426 string const trial = addExtension(name, *what);
427 if (makeAbsPath(trial, path).exists())
434 void begin_inset(ostream & os, string const & name)
436 os << "\n\\begin_inset " << name;
440 void begin_command_inset(ostream & os, string const & name,
441 string const & latexname)
443 begin_inset(os, "CommandInset ");
444 os << name << "\nLatexCommand " << latexname << '\n';
448 void end_inset(ostream & os)
450 os << "\n\\end_inset\n\n";
454 bool skip_braces(Parser & p)
456 if (p.next_token().cat() != catBegin)
459 if (p.next_token().cat() == catEnd) {
468 /// replace LaTeX commands in \p s from the unicodesymbols file with their
470 docstring convert_unicodesymbols(docstring s)
473 for (size_t i = 0; i < s.size();) {
482 docstring parsed = encodings.fromLaTeXCommand(s,
483 Encodings::TEXT_CMD, termination, rem, &req);
484 set<string>::const_iterator it = req.begin();
485 set<string>::const_iterator en = req.end();
486 for (; it != en; ++it)
487 preamble.registerAutomaticallyLoadedPackage(*it);
490 if (s.empty() || s[0] != '\\')
499 /// try to convert \p s to a valid InsetCommand argument
500 string convert_command_inset_arg(string s)
503 // since we don't know the input encoding we can't use from_utf8
504 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
505 // LyX cannot handle newlines in a latex command
506 return subst(s, "\n", " ");
510 void handle_backslash(ostream & os, string const & s)
512 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
514 os << "\n\\backslash\n";
521 void handle_ert(ostream & os, string const & s, Context & context)
523 // We must have a valid layout before outputting the ERT inset.
524 context.check_layout(os);
525 Context newcontext(true, context.textclass);
526 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
527 if (layout.forcePlainLayout())
528 newcontext.layout = &context.textclass.plainLayout();
529 begin_inset(os, "ERT");
530 os << "\nstatus collapsed\n";
531 newcontext.check_layout(os);
532 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
534 os << "\n\\backslash\n";
535 else if (*it == '\n') {
536 newcontext.new_paragraph(os);
537 newcontext.check_layout(os);
541 newcontext.check_end_layout(os);
546 void handle_comment(ostream & os, string const & s, Context & context)
548 // TODO: Handle this better
549 Context newcontext(true, context.textclass);
550 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
551 if (layout.forcePlainLayout())
552 newcontext.layout = &context.textclass.plainLayout();
553 begin_inset(os, "ERT");
554 os << "\nstatus collapsed\n";
555 newcontext.check_layout(os);
556 handle_backslash(os, s);
557 // make sure that our comment is the last thing on the line
558 newcontext.new_paragraph(os);
559 newcontext.check_layout(os);
560 newcontext.check_end_layout(os);
565 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
567 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
570 if (checkModule(name, command))
571 return findLayoutWithoutModule(textclass, name, command);
576 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
578 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
581 if (checkModule(name, command))
582 return findInsetLayoutWithoutModule(textclass, name, command);
587 void eat_whitespace(Parser &, ostream &, Context &, bool);
591 * Skips whitespace and braces.
592 * This should be called after a command has been parsed that is not put into
593 * ERT, and where LyX adds "{}" if needed.
595 void skip_spaces_braces(Parser & p, bool keepws = false)
597 /* The following four examples produce the same typeset output and
598 should be handled by this function:
606 // Unfortunately we need to skip comments, too.
607 // We can't use eat_whitespace since writing them after the {}
608 // results in different output in some cases.
609 bool const skipped_spaces = p.skip_spaces(true);
610 bool const skipped_braces = skip_braces(p);
611 if (keepws && skipped_spaces && !skipped_braces)
612 // put back the space (it is better handled by check_space)
613 p.unskip_spaces(true);
617 void output_command_layout(ostream & os, Parser & p, bool outer,
618 Context & parent_context,
619 Layout const * newlayout)
621 TeXFont const oldFont = parent_context.font;
622 // save the current font size
623 string const size = oldFont.size;
624 // reset the font size to default, because the font size switches
625 // don't affect section headings and the like
626 parent_context.font.size = Context::normalfont.size;
627 // we only need to write the font change if we have an open layout
628 if (!parent_context.atParagraphStart())
629 output_font_change(os, oldFont, parent_context.font);
630 parent_context.check_end_layout(os);
631 Context context(true, parent_context.textclass, newlayout,
632 parent_context.layout, parent_context.font);
633 if (parent_context.deeper_paragraph) {
634 // We are beginning a nested environment after a
635 // deeper paragraph inside the outer list environment.
636 // Therefore we don't need to output a "begin deeper".
637 context.need_end_deeper = true;
639 context.check_deeper(os);
640 context.check_layout(os);
641 // FIXME: Adjust to format 446!
642 // Since format 446, layouts do not require anymore all optional
643 // arguments before the required ones. Needs to be implemented!
645 while (optargs < context.layout->optArgs()) {
646 eat_whitespace(p, os, context, false);
647 if (p.next_token().cat() == catEscape ||
648 p.next_token().character() != '[')
650 p.get_token(); // eat '['
651 // FIXME: Just a workaround. InsetArgument::updateBuffer
652 // will compute a proper ID for all "999" Arguments
653 // (which is also what lyx2lyx produces).
654 // However, tex2lyx should be able to output proper IDs
656 begin_inset(os, "Argument 999\n");
657 os << "status collapsed\n\n";
658 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
660 eat_whitespace(p, os, context, false);
664 while (reqargs < context.layout->requiredArgs()) {
665 eat_whitespace(p, os, context, false);
666 if (p.next_token().cat() != catBegin)
668 p.get_token(); // eat '{'
669 // FIXME: Just a workaround. InsetArgument::updateBuffer
670 // will compute a proper ID for all "999" Arguments
671 // (which is also what lyx2lyx produces).
672 // However, tex2lyx should be able to output proper IDs
674 begin_inset(os, "Argument 999\n");
675 os << "status collapsed\n\n";
676 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
678 eat_whitespace(p, os, context, false);
681 parse_text(p, os, FLAG_ITEM, outer, context);
682 context.check_end_layout(os);
683 if (parent_context.deeper_paragraph) {
684 // We must suppress the "end deeper" because we
685 // suppressed the "begin deeper" above.
686 context.need_end_deeper = false;
688 context.check_end_deeper(os);
689 // We don't need really a new paragraph, but
690 // we must make sure that the next item gets a \begin_layout.
691 parent_context.new_paragraph(os);
692 // Set the font size to the original value. No need to output it here
693 // (Context::begin_layout() will do that if needed)
694 parent_context.font.size = size;
699 * Output a space if necessary.
700 * This function gets called for every whitespace token.
702 * We have three cases here:
703 * 1. A space must be suppressed. Example: The lyxcode case below
704 * 2. A space may be suppressed. Example: Spaces before "\par"
705 * 3. A space must not be suppressed. Example: A space between two words
707 * We currently handle only 1. and 3 and from 2. only the case of
708 * spaces before newlines as a side effect.
710 * 2. could be used to suppress as many spaces as possible. This has two effects:
711 * - Reimporting LyX generated LaTeX files changes almost no whitespace
712 * - Superflous whitespace from non LyX generated LaTeX files is removed.
713 * The drawback is that the logic inside the function becomes
714 * complicated, and that is the reason why it is not implemented.
716 void check_space(Parser & p, ostream & os, Context & context)
718 Token const next = p.next_token();
719 Token const curr = p.curr_token();
720 // A space before a single newline and vice versa must be ignored
721 // LyX emits a newline before \end{lyxcode}.
722 // This newline must be ignored,
723 // otherwise LyX will add an additional protected space.
724 if (next.cat() == catSpace ||
725 next.cat() == catNewline ||
726 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
729 context.check_layout(os);
735 * Parse all arguments of \p command
737 void parse_arguments(string const & command,
738 vector<ArgumentType> const & template_arguments,
739 Parser & p, ostream & os, bool outer, Context & context)
741 string ert = command;
742 size_t no_arguments = template_arguments.size();
743 for (size_t i = 0; i < no_arguments; ++i) {
744 switch (template_arguments[i]) {
747 // This argument contains regular LaTeX
748 handle_ert(os, ert + '{', context);
749 eat_whitespace(p, os, context, false);
750 if (template_arguments[i] == required)
751 parse_text(p, os, FLAG_ITEM, outer, context);
753 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
757 // This argument consists only of a single item.
758 // The presence of '{' or not must be preserved.
760 if (p.next_token().cat() == catBegin)
761 ert += '{' + p.verbatim_item() + '}';
763 ert += p.verbatim_item();
767 // This argument may contain special characters
768 ert += '{' + p.verbatim_item() + '}';
772 // true because we must not eat whitespace
773 // if an optional arg follows we must not strip the
774 // brackets from this one
775 if (i < no_arguments - 1 &&
776 template_arguments[i+1] == optional)
777 ert += p.getFullOpt(true);
779 ert += p.getOpt(true);
783 handle_ert(os, ert, context);
788 * Check whether \p command is a known command. If yes,
789 * handle the command with all arguments.
790 * \return true if the command was parsed, false otherwise.
792 bool parse_command(string const & command, Parser & p, ostream & os,
793 bool outer, Context & context)
795 if (known_commands.find(command) != known_commands.end()) {
796 parse_arguments(command, known_commands[command], p, os,
804 /// Parses a minipage or parbox
805 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
806 unsigned inner_flags, bool outer, Context & parent_context,
807 string const & outer_type, string const & special,
808 string const & inner_type)
812 string hor_pos = "c";
813 // We need to set the height to the LaTeX default of 1\\totalheight
814 // for the case when no height argument is given
815 string height_value = "1";
816 string height_unit = "in";
817 string height_special = "totalheight";
822 string width_special = "none";
823 if (!inner_type.empty() && p.hasOpt()) {
824 if (inner_type != "makebox")
825 position = p.getArg('[', ']');
827 latex_width = p.getArg('[', ']');
828 translate_box_len(latex_width, width_value, width_unit, width_special);
831 if (position != "t" && position != "c" && position != "b") {
832 cerr << "invalid position " << position << " for "
833 << inner_type << endl;
837 if (inner_type != "makebox") {
838 latex_height = p.getArg('[', ']');
839 translate_box_len(latex_height, height_value, height_unit, height_special);
841 string const opt = p.getArg('[', ']');
844 if (hor_pos != "l" && hor_pos != "c" &&
845 hor_pos != "r" && hor_pos != "s") {
846 cerr << "invalid hor_pos " << hor_pos
847 << " for " << inner_type << endl;
854 inner_pos = p.getArg('[', ']');
855 if (inner_pos != "c" && inner_pos != "t" &&
856 inner_pos != "b" && inner_pos != "s") {
857 cerr << "invalid inner_pos "
858 << inner_pos << " for "
859 << inner_type << endl;
860 inner_pos = position;
865 if (inner_type.empty()) {
866 if (special.empty() && outer_type != "framebox")
867 latex_width = "1\\columnwidth";
870 latex_width = p2.getArg('[', ']');
871 string const opt = p2.getArg('[', ']');
874 if (hor_pos != "l" && hor_pos != "c" &&
875 hor_pos != "r" && hor_pos != "s") {
876 cerr << "invalid hor_pos " << hor_pos
877 << " for " << outer_type << endl;
882 } else if (inner_type != "makebox")
883 latex_width = p.verbatim_item();
884 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
885 // as this is LyX's standard for such cases (except for makebox)
886 // \framebox is more special and handled below
887 if (latex_width.empty() && inner_type != "makebox"
888 && outer_type != "framebox")
889 latex_width = "1\\columnwidth";
891 translate_len(latex_width, width_value, width_unit);
893 bool shadedparbox = false;
894 if (inner_type == "shaded") {
895 eat_whitespace(p, os, parent_context, false);
896 if (outer_type == "parbox") {
898 if (p.next_token().cat() == catBegin)
900 eat_whitespace(p, os, parent_context, false);
906 // If we already read the inner box we have to push the inner env
907 if (!outer_type.empty() && !inner_type.empty() &&
908 (inner_flags & FLAG_END))
909 active_environments.push_back(inner_type);
910 // LyX can't handle length variables
911 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
912 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
913 // Look whether there is some content after the end of the
914 // inner box, but before the end of the outer box.
915 // If yes, we need to output ERT.
917 if (inner_flags & FLAG_END)
918 p.verbatimEnvironment(inner_type);
922 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
923 if ((outer_env && p.next_token().asInput() != "\\end") ||
924 (!outer_env && p.next_token().cat() != catEnd)) {
925 // something is between the end of the inner box and
926 // the end of the outer box, so we need to use ERT.
931 // if only \makebox{content} was used we can set its width to 1\width
932 // because this identic and also identic to \mbox
933 // this doesn't work for \framebox{content}, thus we have to use ERT for this
934 if (latex_width.empty() && inner_type == "makebox") {
937 width_special = "width";
938 } else if (latex_width.empty() && outer_type == "framebox") {
943 if (!outer_type.empty()) {
944 if (outer_flags & FLAG_END)
945 ss << "\\begin{" << outer_type << '}';
947 ss << '\\' << outer_type << '{';
948 if (!special.empty())
952 if (!inner_type.empty()) {
953 if (inner_type != "shaded") {
954 if (inner_flags & FLAG_END)
955 ss << "\\begin{" << inner_type << '}';
957 ss << '\\' << inner_type;
959 if (!position.empty())
960 ss << '[' << position << ']';
961 if (!latex_height.empty())
962 ss << '[' << latex_height << ']';
963 if (!inner_pos.empty())
964 ss << '[' << inner_pos << ']';
965 ss << '{' << latex_width << '}';
966 if (!(inner_flags & FLAG_END))
969 if (inner_type == "shaded")
970 ss << "\\begin{shaded}";
971 handle_ert(os, ss.str(), parent_context);
972 if (!inner_type.empty()) {
973 parse_text(p, os, inner_flags, outer, parent_context);
974 if (inner_flags & FLAG_END)
975 handle_ert(os, "\\end{" + inner_type + '}',
978 handle_ert(os, "}", parent_context);
980 if (!outer_type.empty()) {
981 // If we already read the inner box we have to pop
983 if (!inner_type.empty() && (inner_flags & FLAG_END))
984 active_environments.pop_back();
986 // Ensure that the end of the outer box is parsed correctly:
987 // The opening brace has been eaten by parse_outer_box()
988 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
989 outer_flags &= ~FLAG_ITEM;
990 outer_flags |= FLAG_BRACE_LAST;
992 parse_text(p, os, outer_flags, outer, parent_context);
993 if (outer_flags & FLAG_END)
994 handle_ert(os, "\\end{" + outer_type + '}',
996 else if (inner_type.empty() && outer_type == "framebox")
997 // in this case it is already closed later
1000 handle_ert(os, "}", parent_context);
1003 // LyX does not like empty positions, so we have
1004 // to set them to the LaTeX default values here.
1005 if (position.empty())
1007 if (inner_pos.empty())
1008 inner_pos = position;
1009 parent_context.check_layout(os);
1010 begin_inset(os, "Box ");
1011 if (outer_type == "framed")
1013 else if (outer_type == "framebox")
1015 else if (outer_type == "shadowbox")
1016 os << "Shadowbox\n";
1017 else if ((outer_type == "shaded" && inner_type.empty()) ||
1018 (outer_type == "minipage" && inner_type == "shaded") ||
1019 (outer_type == "parbox" && inner_type == "shaded")) {
1021 preamble.registerAutomaticallyLoadedPackage("color");
1022 } else if (outer_type == "doublebox")
1023 os << "Doublebox\n";
1024 else if (outer_type.empty())
1025 os << "Frameless\n";
1027 os << outer_type << '\n';
1028 os << "position \"" << position << "\"\n";
1029 os << "hor_pos \"" << hor_pos << "\"\n";
1030 os << "has_inner_box " << !inner_type.empty() << "\n";
1031 os << "inner_pos \"" << inner_pos << "\"\n";
1032 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1034 os << "use_makebox " << (inner_type == "makebox") << '\n';
1035 os << "width \"" << width_value << width_unit << "\"\n";
1036 os << "special \"" << width_special << "\"\n";
1037 os << "height \"" << height_value << height_unit << "\"\n";
1038 os << "height_special \"" << height_special << "\"\n";
1039 os << "status open\n\n";
1041 // Unfortunately we can't use parse_text_in_inset:
1042 // InsetBox::forcePlainLayout() is hard coded and does not
1043 // use the inset layout. Apart from that do we call parse_text
1044 // up to two times, but need only one check_end_layout.
1045 bool const forcePlainLayout =
1046 (!inner_type.empty() || inner_type == "makebox") &&
1047 outer_type != "shaded" && outer_type != "framed";
1048 Context context(true, parent_context.textclass);
1049 if (forcePlainLayout)
1050 context.layout = &context.textclass.plainLayout();
1052 context.font = parent_context.font;
1054 // If we have no inner box the contents will be read with the outer box
1055 if (!inner_type.empty())
1056 parse_text(p, os, inner_flags, outer, context);
1058 // Ensure that the end of the outer box is parsed correctly:
1059 // The opening brace has been eaten by parse_outer_box()
1060 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1061 outer_flags &= ~FLAG_ITEM;
1062 outer_flags |= FLAG_BRACE_LAST;
1065 // Find end of outer box, output contents if inner_type is
1066 // empty and output possible comments
1067 if (!outer_type.empty()) {
1068 // If we already read the inner box we have to pop
1070 if (!inner_type.empty() && (inner_flags & FLAG_END))
1071 active_environments.pop_back();
1072 // This does not output anything but comments if
1073 // inner_type is not empty (see use_ert)
1074 parse_text(p, os, outer_flags, outer, context);
1077 context.check_end_layout(os);
1079 #ifdef PRESERVE_LAYOUT
1080 // LyX puts a % after the end of the minipage
1081 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1083 //handle_comment(os, "%dummy", parent_context);
1086 parent_context.new_paragraph(os);
1088 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1089 //handle_comment(os, "%dummy", parent_context);
1092 // We add a protected space if something real follows
1093 if (p.good() && p.next_token().cat() != catComment) {
1094 begin_inset(os, "space ~\n");
1103 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1104 Context & parent_context, string const & outer_type,
1105 string const & special)
1107 eat_whitespace(p, os, parent_context, false);
1108 if (flags & FLAG_ITEM) {
1110 if (p.next_token().cat() == catBegin)
1113 cerr << "Warning: Ignoring missing '{' after \\"
1114 << outer_type << '.' << endl;
1115 eat_whitespace(p, os, parent_context, false);
1118 unsigned int inner_flags = 0;
1120 if (outer_type == "minipage" || outer_type == "parbox") {
1121 p.skip_spaces(true);
1122 while (p.hasOpt()) {
1124 p.skip_spaces(true);
1127 p.skip_spaces(true);
1128 if (outer_type == "parbox") {
1130 if (p.next_token().cat() == catBegin)
1132 p.skip_spaces(true);
1135 if (outer_type == "shaded") {
1136 // These boxes never have an inner box
1138 } else if (p.next_token().asInput() == "\\parbox") {
1139 inner = p.get_token().cs();
1140 inner_flags = FLAG_ITEM;
1141 } else if (p.next_token().asInput() == "\\begin") {
1142 // Is this a minipage or shaded box?
1145 inner = p.getArg('{', '}');
1147 if (inner == "minipage" || inner == "shaded")
1148 inner_flags = FLAG_END;
1153 if (inner_flags == FLAG_END) {
1154 if (inner != "shaded")
1158 eat_whitespace(p, os, parent_context, false);
1160 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1161 outer_type, special, inner);
1163 if (inner_flags == FLAG_ITEM) {
1165 eat_whitespace(p, os, parent_context, false);
1167 parse_box(p, os, flags, inner_flags, outer, parent_context,
1168 outer_type, special, inner);
1173 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1175 parent_context.check_layout(os);
1176 begin_inset(os, "listings\n");
1178 string arg = p.verbatimOption();
1179 os << "lstparams " << '"' << arg << '"' << '\n';
1180 if (arg.find("\\color") != string::npos)
1181 preamble.registerAutomaticallyLoadedPackage("color");
1184 os << "inline true\n";
1186 os << "inline false\n";
1187 os << "status collapsed\n";
1188 Context context(true, parent_context.textclass);
1189 context.layout = &parent_context.textclass.plainLayout();
1192 s = p.plainCommand('!', '!', "lstinline");
1193 context.new_paragraph(os);
1194 context.check_layout(os);
1196 s = p.plainEnvironment("lstlisting");
1197 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1199 os << "\n\\backslash\n";
1200 else if (*it == '\n') {
1201 // avoid adding an empty paragraph at the end
1203 context.new_paragraph(os);
1204 context.check_layout(os);
1209 context.check_end_layout(os);
1214 /// parse an unknown environment
1215 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1216 unsigned flags, bool outer,
1217 Context & parent_context)
1219 if (name == "tabbing")
1220 // We need to remember that we have to handle '\=' specially
1221 flags |= FLAG_TABBING;
1223 // We need to translate font changes and paragraphs inside the
1224 // environment to ERT if we have a non standard font.
1225 // Otherwise things like
1226 // \large\begin{foo}\huge bar\end{foo}
1228 bool const specialfont =
1229 (parent_context.font != parent_context.normalfont);
1230 bool const new_layout_allowed = parent_context.new_layout_allowed;
1232 parent_context.new_layout_allowed = false;
1233 handle_ert(os, "\\begin{" + name + "}", parent_context);
1234 parse_text_snippet(p, os, flags, outer, parent_context);
1235 handle_ert(os, "\\end{" + name + "}", parent_context);
1237 parent_context.new_layout_allowed = new_layout_allowed;
1241 void parse_environment(Parser & p, ostream & os, bool outer,
1242 string & last_env, Context & parent_context)
1244 Layout const * newlayout;
1245 InsetLayout const * newinsetlayout = 0;
1246 string const name = p.getArg('{', '}');
1247 const bool is_starred = suffixIs(name, '*');
1248 string const unstarred_name = rtrim(name, "*");
1249 active_environments.push_back(name);
1251 if (is_math_env(name)) {
1252 parent_context.check_layout(os);
1253 begin_inset(os, "Formula ");
1254 os << "\\begin{" << name << "}";
1255 parse_math(p, os, FLAG_END, MATH_MODE);
1256 os << "\\end{" << name << "}";
1258 if (is_display_math_env(name)) {
1259 // Prevent the conversion of a line break to a space
1260 // (bug 7668). This does not change the output, but
1261 // looks ugly in LyX.
1262 eat_whitespace(p, os, parent_context, false);
1266 else if (is_known(name, preamble.polyglossia_languages)) {
1267 // We must begin a new paragraph if not already done
1268 if (! parent_context.atParagraphStart()) {
1269 parent_context.check_end_layout(os);
1270 parent_context.new_paragraph(os);
1272 // save the language in the context so that it is
1273 // handled by parse_text
1274 parent_context.font.language = preamble.polyglossia2lyx(name);
1275 parse_text(p, os, FLAG_END, outer, parent_context);
1276 // Just in case the environment is empty
1277 parent_context.extra_stuff.erase();
1278 // We must begin a new paragraph to reset the language
1279 parent_context.new_paragraph(os);
1283 else if (unstarred_name == "tabular" || name == "longtable") {
1284 eat_whitespace(p, os, parent_context, false);
1285 string width = "0pt";
1286 if (name == "tabular*") {
1287 width = lyx::translate_len(p.getArg('{', '}'));
1288 eat_whitespace(p, os, parent_context, false);
1290 parent_context.check_layout(os);
1291 begin_inset(os, "Tabular ");
1292 handle_tabular(p, os, name, width, parent_context);
1297 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1298 eat_whitespace(p, os, parent_context, false);
1299 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1300 eat_whitespace(p, os, parent_context, false);
1301 parent_context.check_layout(os);
1302 begin_inset(os, "Float " + unstarred_name + "\n");
1303 // store the float type for subfloats
1304 // subfloats only work with figures and tables
1305 if (unstarred_name == "figure")
1306 float_type = unstarred_name;
1307 else if (unstarred_name == "table")
1308 float_type = unstarred_name;
1312 os << "placement " << opt << '\n';
1313 if (contains(opt, "H"))
1314 preamble.registerAutomaticallyLoadedPackage("float");
1316 Floating const & fl = parent_context.textclass.floats()
1317 .getType(unstarred_name);
1318 if (!fl.floattype().empty() && fl.usesFloatPkg())
1319 preamble.registerAutomaticallyLoadedPackage("float");
1322 os << "wide " << convert<string>(is_starred)
1323 << "\nsideways false"
1324 << "\nstatus open\n\n";
1325 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1327 // We don't need really a new paragraph, but
1328 // we must make sure that the next item gets a \begin_layout.
1329 parent_context.new_paragraph(os);
1331 // the float is parsed thus delete the type
1335 else if (unstarred_name == "sidewaysfigure"
1336 || unstarred_name == "sidewaystable") {
1337 eat_whitespace(p, os, parent_context, false);
1338 parent_context.check_layout(os);
1339 if (unstarred_name == "sidewaysfigure")
1340 begin_inset(os, "Float figure\n");
1342 begin_inset(os, "Float table\n");
1343 os << "wide " << convert<string>(is_starred)
1344 << "\nsideways true"
1345 << "\nstatus open\n\n";
1346 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1348 // We don't need really a new paragraph, but
1349 // we must make sure that the next item gets a \begin_layout.
1350 parent_context.new_paragraph(os);
1352 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1355 else if (name == "wrapfigure" || name == "wraptable") {
1356 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1357 eat_whitespace(p, os, parent_context, false);
1358 parent_context.check_layout(os);
1361 string overhang = "0col%";
1364 lines = p.getArg('[', ']');
1365 string const placement = p.getArg('{', '}');
1367 overhang = p.getArg('[', ']');
1368 string const width = p.getArg('{', '}');
1370 if (name == "wrapfigure")
1371 begin_inset(os, "Wrap figure\n");
1373 begin_inset(os, "Wrap table\n");
1374 os << "lines " << lines
1375 << "\nplacement " << placement
1376 << "\noverhang " << lyx::translate_len(overhang)
1377 << "\nwidth " << lyx::translate_len(width)
1378 << "\nstatus open\n\n";
1379 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1381 // We don't need really a new paragraph, but
1382 // we must make sure that the next item gets a \begin_layout.
1383 parent_context.new_paragraph(os);
1385 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1388 else if (name == "minipage") {
1389 eat_whitespace(p, os, parent_context, false);
1390 // Test whether this is an outer box of a shaded box
1392 // swallow arguments
1393 while (p.hasOpt()) {
1395 p.skip_spaces(true);
1398 p.skip_spaces(true);
1399 Token t = p.get_token();
1400 bool shaded = false;
1401 if (t.asInput() == "\\begin") {
1402 p.skip_spaces(true);
1403 if (p.getArg('{', '}') == "shaded")
1408 parse_outer_box(p, os, FLAG_END, outer,
1409 parent_context, name, "shaded");
1411 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1416 else if (name == "comment") {
1417 eat_whitespace(p, os, parent_context, false);
1418 parent_context.check_layout(os);
1419 begin_inset(os, "Note Comment\n");
1420 os << "status open\n";
1421 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1424 skip_braces(p); // eat {} that might by set by LyX behind comments
1425 preamble.registerAutomaticallyLoadedPackage("verbatim");
1428 else if (name == "verbatim") {
1429 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1430 string const s = p.plainEnvironment("verbatim");
1431 string::const_iterator it2 = s.begin();
1432 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1434 os << "\\backslash ";
1435 else if (*it == '\n') {
1437 // avoid adding an empty paragraph at the end
1438 // FIXME: if there are 2 consecutive spaces at the end ignore it
1439 // because LyX will re-add a \n
1440 // This hack must be removed once bug 8049 is fixed!
1441 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1442 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1446 os << "\n\\end_layout\n\n";
1448 // reset to Standard layout
1449 os << "\n\\begin_layout Standard\n";
1452 else if (name == "CJK") {
1453 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1454 // It is impossible to decide if a CJK environment was in its own paragraph or within
1455 // a line. We therefore always assume a paragraph since the latter is a rare case.
1456 eat_whitespace(p, os, parent_context, false);
1457 parent_context.check_end_layout(os);
1458 // store the encoding to be able to reset it
1459 string const encoding_old = p.getEncoding();
1460 string const encoding = p.getArg('{', '}');
1461 // FIXME: For some reason JIS does not work. Although the text
1462 // in tests/CJK.tex is identical with the SJIS version if you
1463 // convert both snippets using the recode command line utility,
1464 // the resulting .lyx file contains some extra characters if
1465 // you set buggy_encoding to false for JIS.
1466 bool const buggy_encoding = encoding == "JIS";
1467 if (!buggy_encoding)
1468 p.setEncoding(encoding);
1470 // FIXME: This will read garbage, since the data is not encoded in utf8.
1471 p.setEncoding("utf8");
1473 // LyX only supports the same mapping for all CJK
1474 // environments, so we might need to output everything as ERT
1475 string const mapping = trim(p.getArg('{', '}'));
1476 char const * const * const where =
1477 is_known(encoding, supported_CJK_encodings);
1478 if (!buggy_encoding && !preamble.fontCJKSet())
1479 preamble.fontCJK(mapping);
1480 bool knownMapping = mapping == preamble.fontCJK();
1481 if (buggy_encoding || !knownMapping || !where) {
1482 parent_context.check_layout(os);
1483 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1485 // we must parse the content as verbatim because e.g. JIS can contain
1486 // normally invalid characters
1487 // FIXME: This works only for the most simple cases.
1488 // Since TeX control characters are not parsed,
1489 // things like comments are completely wrong.
1490 string const s = p.plainEnvironment("CJK");
1491 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1493 handle_ert(os, "\\", parent_context);
1494 else if (*it == '$')
1495 handle_ert(os, "$", parent_context);
1499 handle_ert(os, "\\end{" + name + "}",
1503 supported_CJK_languages[where - supported_CJK_encodings];
1504 // store the language because we must reset it at the end
1505 string const lang_old = parent_context.font.language;
1506 parent_context.font.language = lang;
1507 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1508 parent_context.font.language = lang_old;
1509 parent_context.new_paragraph(os);
1511 p.setEncoding(encoding_old);
1515 else if (name == "lyxgreyedout") {
1516 eat_whitespace(p, os, parent_context, false);
1517 parent_context.check_layout(os);
1518 begin_inset(os, "Note Greyedout\n");
1519 os << "status open\n";
1520 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1523 if (!preamble.notefontcolor().empty())
1524 preamble.registerAutomaticallyLoadedPackage("color");
1527 else if (name == "framed" || name == "shaded") {
1528 eat_whitespace(p, os, parent_context, false);
1529 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1533 else if (name == "lstlisting") {
1534 eat_whitespace(p, os, parent_context, false);
1535 parse_listings(p, os, parent_context, false);
1539 else if (!parent_context.new_layout_allowed)
1540 parse_unknown_environment(p, name, os, FLAG_END, outer,
1543 // Alignment and spacing settings
1544 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1545 // therefore are totally broken!
1546 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1547 // they are commands not environments. They are furthermore switches that
1548 // can be ended by another switches, but also by commands like \footnote or
1549 // \parbox. So the only safe way is to leave them untouched.
1550 else if (name == "center" || name == "centering" ||
1551 name == "flushleft" || name == "flushright" ||
1552 name == "singlespace" || name == "onehalfspace" ||
1553 name == "doublespace" || name == "spacing") {
1554 eat_whitespace(p, os, parent_context, false);
1555 // We must begin a new paragraph if not already done
1556 if (! parent_context.atParagraphStart()) {
1557 parent_context.check_end_layout(os);
1558 parent_context.new_paragraph(os);
1560 if (name == "flushleft")
1561 parent_context.add_extra_stuff("\\align left\n");
1562 else if (name == "flushright")
1563 parent_context.add_extra_stuff("\\align right\n");
1564 else if (name == "center" || name == "centering")
1565 parent_context.add_extra_stuff("\\align center\n");
1566 else if (name == "singlespace")
1567 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1568 else if (name == "onehalfspace") {
1569 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1570 preamble.registerAutomaticallyLoadedPackage("setspace");
1571 } else if (name == "doublespace") {
1572 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1573 preamble.registerAutomaticallyLoadedPackage("setspace");
1574 } else if (name == "spacing") {
1575 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1576 preamble.registerAutomaticallyLoadedPackage("setspace");
1578 parse_text(p, os, FLAG_END, outer, parent_context);
1579 // Just in case the environment is empty
1580 parent_context.extra_stuff.erase();
1581 // We must begin a new paragraph to reset the alignment
1582 parent_context.new_paragraph(os);
1586 // The single '=' is meant here.
1587 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1588 eat_whitespace(p, os, parent_context, false);
1589 Context context(true, parent_context.textclass, newlayout,
1590 parent_context.layout, parent_context.font);
1591 if (parent_context.deeper_paragraph) {
1592 // We are beginning a nested environment after a
1593 // deeper paragraph inside the outer list environment.
1594 // Therefore we don't need to output a "begin deeper".
1595 context.need_end_deeper = true;
1597 parent_context.check_end_layout(os);
1598 if (last_env == name) {
1599 // we need to output a separator since LyX would export
1600 // the two environments as one otherwise (bug 5716)
1601 docstring const sep = from_ascii("--Separator--");
1602 TeX2LyXDocClass const & textclass(parent_context.textclass);
1603 if (textclass.hasLayout(sep)) {
1604 Context newcontext(parent_context);
1605 newcontext.layout = &(textclass[sep]);
1606 newcontext.check_layout(os);
1607 newcontext.check_end_layout(os);
1609 parent_context.check_layout(os);
1610 begin_inset(os, "Note Note\n");
1611 os << "status closed\n";
1612 Context newcontext(true, textclass,
1613 &(textclass.defaultLayout()));
1614 newcontext.check_layout(os);
1615 newcontext.check_end_layout(os);
1617 parent_context.check_end_layout(os);
1620 switch (context.layout->latextype) {
1621 case LATEX_LIST_ENVIRONMENT:
1622 context.add_par_extra_stuff("\\labelwidthstring "
1623 + p.verbatim_item() + '\n');
1626 case LATEX_BIB_ENVIRONMENT:
1627 p.verbatim_item(); // swallow next arg
1633 context.check_deeper(os);
1634 // handle known optional and required arguments
1635 // FIXME: Since format 446, layouts do not require anymore all optional
1636 // arguments before the required ones. Needs to be implemented!
1637 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1638 // It is impossible to place anything after the environment name,
1639 // but before the first \\item.
1640 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1641 bool need_layout = true;
1643 while (optargs < context.layout->optArgs()) {
1644 eat_whitespace(p, os, context, false);
1645 if (p.next_token().cat() == catEscape ||
1646 p.next_token().character() != '[')
1648 p.get_token(); // eat '['
1650 context.check_layout(os);
1651 need_layout = false;
1653 // FIXME: Just a workaround. InsetArgument::updateBuffer
1654 // will compute a proper ID for all "999" Arguments
1655 // (which is also what lyx2lyx produces).
1656 // However, tex2lyx should be able to output proper IDs
1658 begin_inset(os, "Argument 999\n");
1659 os << "status collapsed\n\n";
1660 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1662 eat_whitespace(p, os, context, false);
1666 while (reqargs < context.layout->requiredArgs()) {
1667 eat_whitespace(p, os, context, false);
1668 if (p.next_token().cat() != catBegin)
1670 p.get_token(); // eat '{'
1672 context.check_layout(os);
1673 need_layout = false;
1675 // FIXME: Just a workaround. InsetArgument::updateBuffer
1676 // will compute a proper ID for all "999" Arguments
1677 // (which is also what lyx2lyx produces).
1678 // However, tex2lyx should be able to output proper IDs
1680 begin_inset(os, "Argument 999\n");
1681 os << "status collapsed\n\n";
1682 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1684 eat_whitespace(p, os, context, false);
1688 parse_text(p, os, FLAG_END, outer, context);
1689 context.check_end_layout(os);
1690 if (parent_context.deeper_paragraph) {
1691 // We must suppress the "end deeper" because we
1692 // suppressed the "begin deeper" above.
1693 context.need_end_deeper = false;
1695 context.check_end_deeper(os);
1696 parent_context.new_paragraph(os);
1698 if (!preamble.titleLayoutFound())
1699 preamble.titleLayoutFound(newlayout->intitle);
1700 set<string> const & req = newlayout->requires();
1701 set<string>::const_iterator it = req.begin();
1702 set<string>::const_iterator en = req.end();
1703 for (; it != en; ++it)
1704 preamble.registerAutomaticallyLoadedPackage(*it);
1707 // The single '=' is meant here.
1708 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1709 eat_whitespace(p, os, parent_context, false);
1710 parent_context.check_layout(os);
1711 begin_inset(os, "Flex ");
1712 os << to_utf8(newinsetlayout->name()) << '\n'
1713 << "status collapsed\n";
1714 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1718 else if (name == "appendix") {
1719 // This is no good latex style, but it works and is used in some documents...
1720 eat_whitespace(p, os, parent_context, false);
1721 parent_context.check_end_layout(os);
1722 Context context(true, parent_context.textclass, parent_context.layout,
1723 parent_context.layout, parent_context.font);
1724 context.check_layout(os);
1725 os << "\\start_of_appendix\n";
1726 parse_text(p, os, FLAG_END, outer, context);
1727 context.check_end_layout(os);
1731 else if (known_environments.find(name) != known_environments.end()) {
1732 vector<ArgumentType> arguments = known_environments[name];
1733 // The last "argument" denotes wether we may translate the
1734 // environment contents to LyX
1735 // The default required if no argument is given makes us
1736 // compatible with the reLyXre environment.
1737 ArgumentType contents = arguments.empty() ?
1740 if (!arguments.empty())
1741 arguments.pop_back();
1742 // See comment in parse_unknown_environment()
1743 bool const specialfont =
1744 (parent_context.font != parent_context.normalfont);
1745 bool const new_layout_allowed =
1746 parent_context.new_layout_allowed;
1748 parent_context.new_layout_allowed = false;
1749 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1750 outer, parent_context);
1751 if (contents == verbatim)
1752 handle_ert(os, p.verbatimEnvironment(name),
1755 parse_text_snippet(p, os, FLAG_END, outer,
1757 handle_ert(os, "\\end{" + name + "}", parent_context);
1759 parent_context.new_layout_allowed = new_layout_allowed;
1763 parse_unknown_environment(p, name, os, FLAG_END, outer,
1767 active_environments.pop_back();
1771 /// parses a comment and outputs it to \p os.
1772 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1774 LASSERT(t.cat() == catComment, return);
1775 if (!t.cs().empty()) {
1776 context.check_layout(os);
1777 handle_comment(os, '%' + t.cs(), context);
1778 if (p.next_token().cat() == catNewline) {
1779 // A newline after a comment line starts a new
1781 if (context.new_layout_allowed) {
1782 if(!context.atParagraphStart())
1783 // Only start a new paragraph if not already
1784 // done (we might get called recursively)
1785 context.new_paragraph(os);
1787 handle_ert(os, "\n", context);
1788 eat_whitespace(p, os, context, true);
1791 // "%\n" combination
1798 * Reads spaces and comments until the first non-space, non-comment token.
1799 * New paragraphs (double newlines or \\par) are handled like simple spaces
1800 * if \p eatParagraph is true.
1801 * Spaces are skipped, but comments are written to \p os.
1803 void eat_whitespace(Parser & p, ostream & os, Context & context,
1807 Token const & t = p.get_token();
1808 if (t.cat() == catComment)
1809 parse_comment(p, os, t, context);
1810 else if ((! eatParagraph && p.isParagraph()) ||
1811 (t.cat() != catSpace && t.cat() != catNewline)) {
1820 * Set a font attribute, parse text and reset the font attribute.
1821 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1822 * \param currentvalue Current value of the attribute. Is set to the new
1823 * value during parsing.
1824 * \param newvalue New value of the attribute
1826 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1827 Context & context, string const & attribute,
1828 string & currentvalue, string const & newvalue)
1830 context.check_layout(os);
1831 string const oldvalue = currentvalue;
1832 currentvalue = newvalue;
1833 os << '\n' << attribute << ' ' << newvalue << "\n";
1834 parse_text_snippet(p, os, flags, outer, context);
1835 context.check_layout(os);
1836 os << '\n' << attribute << ' ' << oldvalue << "\n";
1837 currentvalue = oldvalue;
1841 /// get the arguments of a natbib or jurabib citation command
1842 void get_cite_arguments(Parser & p, bool natbibOrder,
1843 string & before, string & after)
1845 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1847 // text before the citation
1849 // text after the citation
1850 after = p.getFullOpt();
1852 if (!after.empty()) {
1853 before = p.getFullOpt();
1854 if (natbibOrder && !before.empty())
1855 swap(before, after);
1860 /// Convert filenames with TeX macros and/or quotes to something LyX
1862 string const normalize_filename(string const & name)
1867 Token const & t = p.get_token();
1868 if (t.cat() != catEscape)
1870 else if (t.cs() == "lyxdot") {
1871 // This is used by LyX for simple dots in relative
1875 } else if (t.cs() == "space") {
1878 } else if (t.cs() == "string") {
1879 // Convert \string" to " and \string~ to ~
1880 Token const & n = p.next_token();
1881 if (n.asInput() != "\"" && n.asInput() != "~")
1886 // Strip quotes. This is a bit complicated (see latex_path()).
1887 string full = os.str();
1888 if (!full.empty() && full[0] == '"') {
1889 string base = removeExtension(full);
1890 string ext = getExtension(full);
1891 if (!base.empty() && base[base.length()-1] == '"')
1894 return addExtension(trim(base, "\""), ext);
1895 if (full[full.length()-1] == '"')
1898 return trim(full, "\"");
1904 /// Convert \p name from TeX convention (relative to master file) to LyX
1905 /// convention (relative to .lyx file) if it is relative
1906 void fix_child_filename(string & name)
1908 string const absMasterTeX = getMasterFilePath(true);
1909 bool const isabs = FileName::isAbsolute(name);
1910 // convert from "relative to .tex master" to absolute original path
1912 name = makeAbsPath(name, absMasterTeX).absFileName();
1913 bool copyfile = copyFiles();
1914 string const absParentLyX = getParentFilePath(false);
1917 // convert from absolute original path to "relative to master file"
1918 string const rel = to_utf8(makeRelPath(from_utf8(name),
1919 from_utf8(absMasterTeX)));
1920 // re-interpret "relative to .tex file" as "relative to .lyx file"
1921 // (is different if the master .lyx file resides in a
1922 // different path than the master .tex file)
1923 string const absMasterLyX = getMasterFilePath(false);
1924 abs = makeAbsPath(rel, absMasterLyX).absFileName();
1925 // Do not copy if the new path is impossible to create. Example:
1926 // absMasterTeX = "/foo/bar/"
1927 // absMasterLyX = "/bar/"
1928 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
1929 if (contains(name, "/../"))
1936 // convert from absolute original path to
1937 // "relative to .lyx file"
1938 name = to_utf8(makeRelPath(from_utf8(abs),
1939 from_utf8(absParentLyX)));
1943 // convert from absolute original path to "relative to .lyx file"
1944 name = to_utf8(makeRelPath(from_utf8(name),
1945 from_utf8(absParentLyX)));
1950 void copy_file(FileName const & src, string dstname)
1954 string const absParent = getParentFilePath(false);
1956 if (FileName::isAbsolute(dstname))
1957 dst = FileName(dstname);
1959 dst = makeAbsPath(dstname, absParent);
1960 string const absMaster = getMasterFilePath(false);
1961 FileName const srcpath = src.onlyPath();
1962 FileName const dstpath = dst.onlyPath();
1963 if (equivalent(srcpath, dstpath))
1965 if (!dstpath.isDirectory()) {
1966 if (!dstpath.createPath()) {
1967 cerr << "Warning: Could not create directory for file `"
1968 << dst.absFileName() << "´." << endl;
1972 if (dst.isReadableFile()) {
1973 if (overwriteFiles())
1974 cerr << "Warning: Overwriting existing file `"
1975 << dst.absFileName() << "´." << endl;
1977 cerr << "Warning: Not overwriting existing file `"
1978 << dst.absFileName() << "´." << endl;
1982 if (!src.copyTo(dst))
1983 cerr << "Warning: Could not copy file `" << src.absFileName()
1984 << "´ to `" << dst.absFileName() << "´." << endl;
1988 /// Parse a NoWeb Chunk section. The initial "<<" is already parsed.
1989 void parse_noweb(Parser & p, ostream & os, Context & context)
1991 // assemble the rest of the keyword
1995 Token const & t = p.get_token();
1996 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1999 chunk = (p.good() && p.next_token().asInput() == "=");
2001 name += p.get_token().asInput();
2004 name += t.asInput();
2007 if (!chunk || !context.new_layout_allowed ||
2008 !context.textclass.hasLayout(from_ascii("Chunk"))) {
2009 cerr << "Warning: Could not interpret '" << name
2010 << "'. Ignoring it." << endl;
2014 // We use new_paragraph instead of check_end_layout because the stuff
2015 // following the noweb chunk needs to start with a \begin_layout.
2016 // This may create a new paragraph even if there was none in the
2017 // noweb file, but the alternative is an invalid LyX file. Since
2018 // noweb code chunks are implemented with a layout style in LyX they
2019 // always must be in an own paragraph.
2020 context.new_paragraph(os);
2021 Context newcontext(true, context.textclass,
2022 &context.textclass[from_ascii("Chunk")]);
2023 newcontext.check_layout(os);
2026 Token const & t = p.get_token();
2027 // We abuse the parser a bit, because this is no TeX syntax
2029 if (t.cat() == catEscape)
2030 os << subst(t.asInput(), "\\", "\n\\backslash\n");
2033 Context tmp(false, context.textclass,
2034 &context.textclass[from_ascii("Chunk")]);
2035 tmp.need_end_layout = true;
2036 tmp.check_layout(oss);
2037 os << subst(t.asInput(), "\n", oss.str());
2039 // The chunk is ended by an @ at the beginning of a line.
2040 // After the @ the line may contain a comment and/or
2041 // whitespace, but nothing else.
2042 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
2043 (p.next_token().cat() == catSpace ||
2044 p.next_token().cat() == catNewline ||
2045 p.next_token().cat() == catComment)) {
2046 while (p.good() && p.next_token().cat() == catSpace)
2047 os << p.get_token().asInput();
2048 if (p.next_token().cat() == catComment)
2049 // The comment includes a final '\n'
2050 os << p.get_token().asInput();
2052 if (p.next_token().cat() == catNewline)
2059 newcontext.check_end_layout(os);
2063 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2064 bool is_macro(Parser & p)
2066 Token first = p.curr_token();
2067 if (first.cat() != catEscape || !p.good())
2069 if (first.cs() == "def")
2071 if (first.cs() != "global" && first.cs() != "long")
2073 Token second = p.get_token();
2075 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2076 second.cat() == catNewline || second.cat() == catComment)) {
2077 second = p.get_token();
2080 bool secondvalid = second.cat() == catEscape;
2082 bool thirdvalid = false;
2083 if (p.good() && first.cs() == "global" && secondvalid &&
2084 second.cs() == "long") {
2085 third = p.get_token();
2087 while (p.good() && !p.isParagraph() &&
2088 (third.cat() == catSpace ||
2089 third.cat() == catNewline ||
2090 third.cat() == catComment)) {
2091 third = p.get_token();
2094 thirdvalid = third.cat() == catEscape;
2096 for (int i = 0; i < pos; ++i)
2101 return (first.cs() == "global" || first.cs() == "long") &&
2102 second.cs() == "def";
2103 return first.cs() == "global" && second.cs() == "long" &&
2104 third.cs() == "def";
2108 /// Parse a macro definition (assumes that is_macro() returned true)
2109 void parse_macro(Parser & p, ostream & os, Context & context)
2111 context.check_layout(os);
2112 Token first = p.curr_token();
2115 string command = first.asInput();
2116 if (first.cs() != "def") {
2118 eat_whitespace(p, os, context, false);
2119 second = p.curr_token();
2120 command += second.asInput();
2121 if (second.cs() != "def") {
2123 eat_whitespace(p, os, context, false);
2124 third = p.curr_token();
2125 command += third.asInput();
2128 eat_whitespace(p, os, context, false);
2129 string const name = p.get_token().cs();
2130 eat_whitespace(p, os, context, false);
2136 while (p.next_token().cat() != catBegin) {
2137 if (p.next_token().cat() == catParameter) {
2142 // followed by number?
2143 if (p.next_token().cat() == catOther) {
2144 char c = p.getChar();
2146 // number = current arity + 1?
2147 if (c == arity + '0' + 1)
2152 paramtext += p.get_token().cs();
2154 paramtext += p.get_token().cs();
2159 // only output simple (i.e. compatible) macro as FormulaMacros
2160 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2162 context.check_layout(os);
2163 begin_inset(os, "FormulaMacro");
2164 os << "\n\\def" << ert;
2167 handle_ert(os, command + ert, context);
2171 void registerExternalTemplatePackages(string const & name)
2173 external::TemplateManager const & etm = external::TemplateManager::get();
2174 external::Template const * const et = etm.getTemplateByName(name);
2177 external::Template::Formats::const_iterator cit = et->formats.end();
2179 cit = et->formats.find("PDFLaTeX");
2180 if (cit == et->formats.end())
2181 // If the template has not specified a PDFLaTeX output,
2182 // we try the LaTeX format.
2183 cit = et->formats.find("LaTeX");
2184 if (cit == et->formats.end())
2186 vector<string>::const_iterator qit = cit->second.requirements.begin();
2187 vector<string>::const_iterator qend = cit->second.requirements.end();
2188 for (; qit != qend; ++qit)
2189 preamble.registerAutomaticallyLoadedPackage(*qit);
2192 } // anonymous namespace
2195 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2198 Layout const * newlayout = 0;
2199 InsetLayout const * newinsetlayout = 0;
2200 char const * const * where = 0;
2201 // Store the latest bibliographystyle and nocite{*} option
2202 // (needed for bibtex inset)
2204 string bibliographystyle = "default";
2205 bool const use_natbib = isProvided("natbib");
2206 bool const use_jurabib = isProvided("jurabib");
2209 Token const & t = p.get_token();
2211 // it is impossible to determine the correct encoding for non-CJK Japanese.
2212 // Therefore write a note at the beginning of the document
2213 if (is_nonCJKJapanese) {
2214 context.check_layout(os);
2215 begin_inset(os, "Note Note\n");
2216 os << "status open\n\\begin_layout Plain Layout\n"
2217 << "\\series bold\n"
2218 << "Important information:\n"
2219 << "\\end_layout\n\n"
2220 << "\\begin_layout Plain Layout\n"
2221 << "This document is in Japanese (non-CJK).\n"
2222 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2223 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2224 << " encoding in the document settings.\n"
2225 << "\\end_layout\n";
2227 is_nonCJKJapanese = false;
2231 debugToken(cerr, t, flags);
2234 if (flags & FLAG_ITEM) {
2235 if (t.cat() == catSpace)
2238 flags &= ~FLAG_ITEM;
2239 if (t.cat() == catBegin) {
2240 // skip the brace and collect everything to the next matching
2242 flags |= FLAG_BRACE_LAST;
2246 // handle only this single token, leave the loop if done
2247 flags |= FLAG_LEAVE;
2250 if (t.cat() != catEscape && t.character() == ']' &&
2251 (flags & FLAG_BRACK_LAST))
2253 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2256 // If there is anything between \end{env} and \begin{env} we
2257 // don't need to output a separator.
2258 if (t.cat() != catSpace && t.cat() != catNewline &&
2259 t.asInput() != "\\begin")
2265 if (t.cat() == catMath) {
2266 // we are inside some text mode thingy, so opening new math is allowed
2267 context.check_layout(os);
2268 begin_inset(os, "Formula ");
2269 Token const & n = p.get_token();
2270 bool const display(n.cat() == catMath && outer);
2272 // TeX's $$...$$ syntax for displayed math
2274 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2276 p.get_token(); // skip the second '$' token
2278 // simple $...$ stuff
2281 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2286 // Prevent the conversion of a line break to a
2287 // space (bug 7668). This does not change the
2288 // output, but looks ugly in LyX.
2289 eat_whitespace(p, os, context, false);
2293 else if (t.cat() == catSuper || t.cat() == catSub)
2294 cerr << "catcode " << t << " illegal in text mode\n";
2296 // Basic support for english quotes. This should be
2297 // extended to other quotes, but is not so easy (a
2298 // left english quote is the same as a right german
2300 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2301 context.check_layout(os);
2302 begin_inset(os, "Quotes ");
2308 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2309 context.check_layout(os);
2310 begin_inset(os, "Quotes ");
2317 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2318 context.check_layout(os);
2319 begin_inset(os, "Quotes ");
2326 else if (t.asInput() == "<"
2327 && p.next_token().asInput() == "<" && noweb_mode) {
2329 parse_noweb(p, os, context);
2332 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2333 context.check_layout(os);
2334 begin_inset(os, "Quotes ");
2341 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2342 check_space(p, os, context);
2344 else if (t.character() == '[' && noweb_mode &&
2345 p.next_token().character() == '[') {
2346 // These can contain underscores
2348 string const s = p.getFullOpt() + ']';
2349 if (p.next_token().character() == ']')
2352 cerr << "Warning: Inserting missing ']' in '"
2353 << s << "'." << endl;
2354 handle_ert(os, s, context);
2357 else if (t.cat() == catLetter) {
2358 context.check_layout(os);
2359 // Workaround for bug 4752.
2360 // FIXME: This whole code block needs to be removed
2361 // when the bug is fixed and tex2lyx produces
2362 // the updated file format.
2363 // The replacement algorithm in LyX is so stupid that
2364 // it even translates a phrase if it is part of a word.
2365 bool handled = false;
2366 for (int const * l = known_phrase_lengths; *l; ++l) {
2367 string phrase = t.cs();
2368 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2369 phrase += p.get_token().cs();
2370 if (is_known(phrase, known_coded_phrases)) {
2371 handle_ert(os, phrase, context);
2375 for (size_t i = 1; i < phrase.length(); ++i)
2383 else if (t.cat() == catOther ||
2384 t.cat() == catAlign ||
2385 t.cat() == catParameter) {
2386 // This translates "&" to "\\&" which may be wrong...
2387 context.check_layout(os);
2391 else if (p.isParagraph()) {
2392 if (context.new_layout_allowed)
2393 context.new_paragraph(os);
2395 handle_ert(os, "\\par ", context);
2396 eat_whitespace(p, os, context, true);
2399 else if (t.cat() == catActive) {
2400 context.check_layout(os);
2401 if (t.character() == '~') {
2402 if (context.layout->free_spacing)
2405 begin_inset(os, "space ~\n");
2412 else if (t.cat() == catBegin) {
2413 Token const next = p.next_token();
2414 Token const end = p.next_next_token();
2415 if (next.cat() == catEnd) {
2417 Token const prev = p.prev_token();
2419 if (p.next_token().character() == '`' ||
2420 (prev.character() == '-' &&
2421 p.next_token().character() == '-'))
2422 ; // ignore it in {}`` or -{}-
2424 handle_ert(os, "{}", context);
2425 } else if (next.cat() == catEscape &&
2426 is_known(next.cs(), known_quotes) &&
2427 end.cat() == catEnd) {
2428 // Something like {\textquoteright} (e.g.
2429 // from writer2latex). LyX writes
2430 // \textquoteright{}, so we may skip the
2431 // braces here for better readability.
2432 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2435 context.check_layout(os);
2436 // special handling of font attribute changes
2437 Token const prev = p.prev_token();
2438 TeXFont const oldFont = context.font;
2439 if (next.character() == '[' ||
2440 next.character() == ']' ||
2441 next.character() == '*') {
2443 if (p.next_token().cat() == catEnd) {
2448 handle_ert(os, "{", context);
2449 parse_text_snippet(p, os,
2452 handle_ert(os, "}", context);
2454 } else if (! context.new_layout_allowed) {
2455 handle_ert(os, "{", context);
2456 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2458 handle_ert(os, "}", context);
2459 } else if (is_known(next.cs(), known_sizes)) {
2460 // next will change the size, so we must
2462 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2464 if (!context.atParagraphStart())
2466 << context.font.size << "\n";
2467 } else if (is_known(next.cs(), known_font_families)) {
2468 // next will change the font family, so we
2469 // must reset it here
2470 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2472 if (!context.atParagraphStart())
2474 << context.font.family << "\n";
2475 } else if (is_known(next.cs(), known_font_series)) {
2476 // next will change the font series, so we
2477 // must reset it here
2478 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2480 if (!context.atParagraphStart())
2482 << context.font.series << "\n";
2483 } else if (is_known(next.cs(), known_font_shapes)) {
2484 // next will change the font shape, so we
2485 // must reset it here
2486 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2488 if (!context.atParagraphStart())
2490 << context.font.shape << "\n";
2491 } else if (is_known(next.cs(), known_old_font_families) ||
2492 is_known(next.cs(), known_old_font_series) ||
2493 is_known(next.cs(), known_old_font_shapes)) {
2494 // next will change the font family, series
2495 // and shape, so we must reset it here
2496 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2498 if (!context.atParagraphStart())
2500 << context.font.family
2502 << context.font.series
2504 << context.font.shape << "\n";
2506 handle_ert(os, "{", context);
2507 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2509 handle_ert(os, "}", context);
2514 else if (t.cat() == catEnd) {
2515 if (flags & FLAG_BRACE_LAST) {
2518 cerr << "stray '}' in text\n";
2519 handle_ert(os, "}", context);
2522 else if (t.cat() == catComment)
2523 parse_comment(p, os, t, context);
2526 // control sequences
2529 else if (t.cs() == "(") {
2530 context.check_layout(os);
2531 begin_inset(os, "Formula");
2533 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2538 else if (t.cs() == "[") {
2539 context.check_layout(os);
2540 begin_inset(os, "Formula");
2542 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2545 // Prevent the conversion of a line break to a space
2546 // (bug 7668). This does not change the output, but
2547 // looks ugly in LyX.
2548 eat_whitespace(p, os, context, false);
2551 else if (t.cs() == "begin")
2552 parse_environment(p, os, outer, last_env,
2555 else if (t.cs() == "end") {
2556 if (flags & FLAG_END) {
2557 // eat environment name
2558 string const name = p.getArg('{', '}');
2559 if (name != active_environment())
2560 cerr << "\\end{" + name + "} does not match \\begin{"
2561 + active_environment() + "}\n";
2564 p.error("found 'end' unexpectedly");
2567 else if (t.cs() == "item") {
2569 bool const optarg = p.hasOpt();
2571 // FIXME: This swallows comments, but we cannot use
2572 // eat_whitespace() since we must not output
2573 // anything before the item.
2574 p.skip_spaces(true);
2575 s = p.verbatimOption();
2577 p.skip_spaces(false);
2579 context.check_layout(os);
2580 if (context.has_item) {
2581 // An item in an unknown list-like environment
2582 // FIXME: Do this in check_layout()!
2583 context.has_item = false;
2585 handle_ert(os, "\\item", context);
2587 handle_ert(os, "\\item ", context);
2590 if (context.layout->labeltype != LABEL_MANUAL) {
2591 // LyX does not support \item[\mybullet]
2592 // in itemize environments
2594 os << parse_text_snippet(p2,
2595 FLAG_BRACK_LAST, outer, context);
2596 } else if (!s.empty()) {
2597 // LyX adds braces around the argument,
2598 // so we need to remove them here.
2599 if (s.size() > 2 && s[0] == '{' &&
2600 s[s.size()-1] == '}')
2601 s = s.substr(1, s.size()-2);
2602 // If the argument contains a space we
2603 // must put it into ERT: Otherwise LyX
2604 // would misinterpret the space as
2605 // item delimiter (bug 7663)
2606 if (contains(s, ' ')) {
2607 handle_ert(os, s, context);
2610 os << parse_text_snippet(p2,
2614 // The space is needed to separate the
2615 // item from the rest of the sentence.
2617 eat_whitespace(p, os, context, false);
2622 else if (t.cs() == "bibitem") {
2624 context.check_layout(os);
2625 eat_whitespace(p, os, context, false);
2626 string label = convert_command_inset_arg(p.verbatimOption());
2627 string key = convert_command_inset_arg(p.verbatim_item());
2628 if (contains(label, '\\') || contains(key, '\\')) {
2629 // LyX can't handle LaTeX commands in labels or keys
2630 handle_ert(os, t.asInput() + '[' + label +
2631 "]{" + p.verbatim_item() + '}',
2634 begin_command_inset(os, "bibitem", "bibitem");
2635 os << "label \"" << label << "\"\n"
2636 "key \"" << key << "\"\n";
2641 else if (is_macro(p)) {
2642 // catch the case of \def\inputGnumericTable
2644 if (t.cs() == "def") {
2645 Token second = p.next_token();
2646 if (second.cs() == "inputGnumericTable") {
2650 Token third = p.get_token();
2652 if (third.cs() == "input") {
2656 string name = normalize_filename(p.verbatim_item());
2657 string const path = getMasterFilePath(true);
2658 // We want to preserve relative / absolute filenames,
2659 // therefore path is only used for testing
2660 // The file extension is in every case ".tex".
2661 // So we need to remove this extension and check for
2662 // the original one.
2663 name = removeExtension(name);
2664 if (!makeAbsPath(name, path).exists()) {
2665 char const * const Gnumeric_formats[] = {"gnumeric",
2667 string const Gnumeric_name =
2668 find_file(name, path, Gnumeric_formats);
2669 if (!Gnumeric_name.empty())
2670 name = Gnumeric_name;
2672 FileName const absname = makeAbsPath(name, path);
2673 if (absname.exists()) {
2674 fix_child_filename(name);
2675 copy_file(absname, name);
2677 cerr << "Warning: Could not find file '"
2678 << name << "'." << endl;
2679 context.check_layout(os);
2680 begin_inset(os, "External\n\ttemplate ");
2681 os << "GnumericSpreadsheet\n\tfilename "
2684 context.check_layout(os);
2686 // register the packages that are automatically loaded
2687 // by the Gnumeric template
2688 registerExternalTemplatePackages("GnumericSpreadsheet");
2693 parse_macro(p, os, context);
2696 else if (t.cs() == "noindent") {
2698 context.add_par_extra_stuff("\\noindent\n");
2701 else if (t.cs() == "appendix") {
2702 context.add_par_extra_stuff("\\start_of_appendix\n");
2703 // We need to start a new paragraph. Otherwise the
2704 // appendix in 'bla\appendix\chapter{' would start
2706 context.new_paragraph(os);
2707 // We need to make sure that the paragraph is
2708 // generated even if it is empty. Otherwise the
2709 // appendix in '\par\appendix\par\chapter{' would
2711 context.check_layout(os);
2712 // FIXME: This is a hack to prevent paragraph
2713 // deletion if it is empty. Handle this better!
2715 "%dummy comment inserted by tex2lyx to "
2716 "ensure that this paragraph is not empty",
2718 // Both measures above may generate an additional
2719 // empty paragraph, but that does not hurt, because
2720 // whitespace does not matter here.
2721 eat_whitespace(p, os, context, true);
2724 // Must catch empty dates before findLayout is called below
2725 else if (t.cs() == "date") {
2726 eat_whitespace(p, os, context, false);
2728 string const date = p.verbatim_item();
2731 preamble.suppressDate(true);
2734 preamble.suppressDate(false);
2735 if (context.new_layout_allowed &&
2736 (newlayout = findLayout(context.textclass,
2739 output_command_layout(os, p, outer,
2740 context, newlayout);
2741 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2742 if (!preamble.titleLayoutFound())
2743 preamble.titleLayoutFound(newlayout->intitle);
2744 set<string> const & req = newlayout->requires();
2745 set<string>::const_iterator it = req.begin();
2746 set<string>::const_iterator en = req.end();
2747 for (; it != en; ++it)
2748 preamble.registerAutomaticallyLoadedPackage(*it);
2751 "\\date{" + p.verbatim_item() + '}',
2756 // Starred section headings
2757 // Must attempt to parse "Section*" before "Section".
2758 else if ((p.next_token().asInput() == "*") &&
2759 context.new_layout_allowed &&
2760 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2763 output_command_layout(os, p, outer, context, newlayout);
2765 if (!preamble.titleLayoutFound())
2766 preamble.titleLayoutFound(newlayout->intitle);
2767 set<string> const & req = newlayout->requires();
2768 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2769 preamble.registerAutomaticallyLoadedPackage(*it);
2772 // Section headings and the like
2773 else if (context.new_layout_allowed &&
2774 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2776 output_command_layout(os, p, outer, context, newlayout);
2778 if (!preamble.titleLayoutFound())
2779 preamble.titleLayoutFound(newlayout->intitle);
2780 set<string> const & req = newlayout->requires();
2781 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2782 preamble.registerAutomaticallyLoadedPackage(*it);
2785 else if (t.cs() == "caption") {
2787 context.check_layout(os);
2789 begin_inset(os, "Caption Standard\n");
2790 Context newcontext(true, context.textclass, 0, 0, context.font);
2791 newcontext.check_layout(os);
2792 // FIXME InsetArgument is now properly implemented in InsetLayout
2793 // (for captions, but also for others)
2794 if (p.next_token().cat() != catEscape &&
2795 p.next_token().character() == '[') {
2796 p.get_token(); // eat '['
2797 begin_inset(os, "Argument 1\n");
2798 os << "status collapsed\n";
2799 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2801 eat_whitespace(p, os, context, false);
2803 parse_text(p, os, FLAG_ITEM, outer, context);
2804 context.check_end_layout(os);
2805 // We don't need really a new paragraph, but
2806 // we must make sure that the next item gets a \begin_layout.
2807 context.new_paragraph(os);
2810 newcontext.check_end_layout(os);
2813 else if (t.cs() == "subfloat") {
2814 // the syntax is \subfloat[caption]{content}
2815 // if it is a table of figure depends on the surrounding float
2816 bool has_caption = false;
2818 // do nothing if there is no outer float
2819 if (!float_type.empty()) {
2820 context.check_layout(os);
2822 begin_inset(os, "Float " + float_type + "\n");
2824 << "\nsideways false"
2825 << "\nstatus collapsed\n\n";
2828 if (p.next_token().cat() != catEscape &&
2829 p.next_token().character() == '[') {
2830 p.get_token(); // eat '['
2831 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2835 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2836 // the caption comes always as the last
2838 // we must make sure that the caption gets a \begin_layout
2839 os << "\n\\begin_layout Plain Layout";
2841 begin_inset(os, "Caption Standard\n");
2842 Context newcontext(true, context.textclass,
2843 0, 0, context.font);
2844 newcontext.check_layout(os);
2845 os << caption << "\n";
2846 newcontext.check_end_layout(os);
2847 // We don't need really a new paragraph, but
2848 // we must make sure that the next item gets a \begin_layout.
2849 //newcontext.new_paragraph(os);
2853 // We don't need really a new paragraph, but
2854 // we must make sure that the next item gets a \begin_layout.
2856 context.new_paragraph(os);
2859 context.check_end_layout(os);
2860 // close the layout we opened
2862 os << "\n\\end_layout\n";
2864 // if the float type is not supported or there is no surrounding float
2867 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2868 handle_ert(os, t.asInput() + '[' + opt_arg +
2869 "]{" + p.verbatim_item() + '}', context);
2871 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2875 else if (t.cs() == "includegraphics") {
2876 bool const clip = p.next_token().asInput() == "*";
2879 string const arg = p.getArg('[', ']');
2880 map<string, string> opts;
2881 vector<string> keys;
2882 split_map(arg, opts, keys);
2884 opts["clip"] = string();
2885 string name = normalize_filename(p.verbatim_item());
2887 string const path = getMasterFilePath(true);
2888 // We want to preserve relative / absolute filenames,
2889 // therefore path is only used for testing
2890 if (!makeAbsPath(name, path).exists()) {
2891 // The file extension is probably missing.
2892 // Now try to find it out.
2893 string const dvips_name =
2894 find_file(name, path,
2895 known_dvips_graphics_formats);
2896 string const pdftex_name =
2897 find_file(name, path,
2898 known_pdftex_graphics_formats);
2899 if (!dvips_name.empty()) {
2900 if (!pdftex_name.empty()) {
2901 cerr << "This file contains the "
2903 "\"\\includegraphics{"
2905 "However, files\n\""
2906 << dvips_name << "\" and\n\""
2907 << pdftex_name << "\"\n"
2908 "both exist, so I had to make a "
2909 "choice and took the first one.\n"
2910 "Please move the unwanted one "
2911 "someplace else and try again\n"
2912 "if my choice was wrong."
2916 } else if (!pdftex_name.empty()) {
2922 FileName const absname = makeAbsPath(name, path);
2923 if (absname.exists()) {
2924 fix_child_filename(name);
2925 copy_file(absname, name);
2927 cerr << "Warning: Could not find graphics file '"
2928 << name << "'." << endl;
2930 context.check_layout(os);
2931 begin_inset(os, "Graphics ");
2932 os << "\n\tfilename " << name << '\n';
2933 if (opts.find("width") != opts.end())
2935 << translate_len(opts["width"]) << '\n';
2936 if (opts.find("height") != opts.end())
2938 << translate_len(opts["height"]) << '\n';
2939 if (opts.find("scale") != opts.end()) {
2940 istringstream iss(opts["scale"]);
2944 os << "\tscale " << val << '\n';
2946 if (opts.find("angle") != opts.end()) {
2947 os << "\trotateAngle "
2948 << opts["angle"] << '\n';
2949 vector<string>::const_iterator a =
2950 find(keys.begin(), keys.end(), "angle");
2951 vector<string>::const_iterator s =
2952 find(keys.begin(), keys.end(), "width");
2953 if (s == keys.end())
2954 s = find(keys.begin(), keys.end(), "height");
2955 if (s == keys.end())
2956 s = find(keys.begin(), keys.end(), "scale");
2957 if (s != keys.end() && distance(s, a) > 0)
2958 os << "\tscaleBeforeRotation\n";
2960 if (opts.find("origin") != opts.end()) {
2962 string const opt = opts["origin"];
2963 if (opt.find('l') != string::npos) ss << "left";
2964 if (opt.find('r') != string::npos) ss << "right";
2965 if (opt.find('c') != string::npos) ss << "center";
2966 if (opt.find('t') != string::npos) ss << "Top";
2967 if (opt.find('b') != string::npos) ss << "Bottom";
2968 if (opt.find('B') != string::npos) ss << "Baseline";
2969 if (!ss.str().empty())
2970 os << "\trotateOrigin " << ss.str() << '\n';
2972 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2974 if (opts.find("keepaspectratio") != opts.end())
2975 os << "\tkeepAspectRatio\n";
2976 if (opts.find("clip") != opts.end())
2978 if (opts.find("draft") != opts.end())
2980 if (opts.find("bb") != opts.end())
2981 os << "\tBoundingBox "
2982 << opts["bb"] << '\n';
2983 int numberOfbbOptions = 0;
2984 if (opts.find("bbllx") != opts.end())
2985 numberOfbbOptions++;
2986 if (opts.find("bblly") != opts.end())
2987 numberOfbbOptions++;
2988 if (opts.find("bburx") != opts.end())
2989 numberOfbbOptions++;
2990 if (opts.find("bbury") != opts.end())
2991 numberOfbbOptions++;
2992 if (numberOfbbOptions == 4)
2993 os << "\tBoundingBox "
2994 << opts["bbllx"] << " " << opts["bblly"] << " "
2995 << opts["bburx"] << " " << opts["bbury"] << '\n';
2996 else if (numberOfbbOptions > 0)
2997 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2998 numberOfbbOptions = 0;
2999 if (opts.find("natwidth") != opts.end())
3000 numberOfbbOptions++;
3001 if (opts.find("natheight") != opts.end())
3002 numberOfbbOptions++;
3003 if (numberOfbbOptions == 2)
3004 os << "\tBoundingBox 0bp 0bp "
3005 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3006 else if (numberOfbbOptions > 0)
3007 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3008 ostringstream special;
3009 if (opts.find("hiresbb") != opts.end())
3010 special << "hiresbb,";
3011 if (opts.find("trim") != opts.end())
3013 if (opts.find("viewport") != opts.end())
3014 special << "viewport=" << opts["viewport"] << ',';
3015 if (opts.find("totalheight") != opts.end())
3016 special << "totalheight=" << opts["totalheight"] << ',';
3017 if (opts.find("type") != opts.end())
3018 special << "type=" << opts["type"] << ',';
3019 if (opts.find("ext") != opts.end())
3020 special << "ext=" << opts["ext"] << ',';
3021 if (opts.find("read") != opts.end())
3022 special << "read=" << opts["read"] << ',';
3023 if (opts.find("command") != opts.end())
3024 special << "command=" << opts["command"] << ',';
3025 string s_special = special.str();
3026 if (!s_special.empty()) {
3027 // We had special arguments. Remove the trailing ','.
3028 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3030 // TODO: Handle the unknown settings better.
3031 // Warn about invalid options.
3032 // Check whether some option was given twice.
3034 preamble.registerAutomaticallyLoadedPackage("graphicx");
3037 else if (t.cs() == "footnote" ||
3038 (t.cs() == "thanks" && context.layout->intitle)) {
3040 context.check_layout(os);
3041 begin_inset(os, "Foot\n");
3042 os << "status collapsed\n\n";
3043 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3047 else if (t.cs() == "marginpar") {
3049 context.check_layout(os);
3050 begin_inset(os, "Marginal\n");
3051 os << "status collapsed\n\n";
3052 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3056 else if (t.cs() == "lstinline") {
3058 parse_listings(p, os, context, true);
3061 else if (t.cs() == "ensuremath") {
3063 context.check_layout(os);
3064 string const s = p.verbatim_item();
3065 //FIXME: this never triggers in UTF8
3066 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3069 handle_ert(os, "\\ensuremath{" + s + "}",
3073 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3074 if (preamble.titleLayoutFound()) {
3076 skip_spaces_braces(p);
3078 handle_ert(os, t.asInput(), context);
3081 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3082 context.check_layout(os);
3083 begin_command_inset(os, "toc", t.cs());
3085 skip_spaces_braces(p);
3086 if (t.cs() == "lstlistoflistings")
3087 preamble.registerAutomaticallyLoadedPackage("listings");
3090 else if (t.cs() == "listoffigures") {
3091 context.check_layout(os);
3092 begin_inset(os, "FloatList figure\n");
3094 skip_spaces_braces(p);
3097 else if (t.cs() == "listoftables") {
3098 context.check_layout(os);
3099 begin_inset(os, "FloatList table\n");
3101 skip_spaces_braces(p);
3104 else if (t.cs() == "listof") {
3105 p.skip_spaces(true);
3106 string const name = p.get_token().cs();
3107 if (context.textclass.floats().typeExist(name)) {
3108 context.check_layout(os);
3109 begin_inset(os, "FloatList ");
3112 p.get_token(); // swallow second arg
3114 handle_ert(os, "\\listof{" + name + "}", context);
3117 else if ((where = is_known(t.cs(), known_text_font_families)))
3118 parse_text_attributes(p, os, FLAG_ITEM, outer,
3119 context, "\\family", context.font.family,
3120 known_coded_font_families[where - known_text_font_families]);
3122 else if ((where = is_known(t.cs(), known_text_font_series)))
3123 parse_text_attributes(p, os, FLAG_ITEM, outer,
3124 context, "\\series", context.font.series,
3125 known_coded_font_series[where - known_text_font_series]);
3127 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3128 parse_text_attributes(p, os, FLAG_ITEM, outer,
3129 context, "\\shape", context.font.shape,
3130 known_coded_font_shapes[where - known_text_font_shapes]);
3132 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3133 context.check_layout(os);
3134 TeXFont oldFont = context.font;
3135 context.font.init();
3136 context.font.size = oldFont.size;
3137 os << "\n\\family " << context.font.family << "\n";
3138 os << "\n\\series " << context.font.series << "\n";
3139 os << "\n\\shape " << context.font.shape << "\n";
3140 if (t.cs() == "textnormal") {
3141 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3142 output_font_change(os, context.font, oldFont);
3143 context.font = oldFont;
3145 eat_whitespace(p, os, context, false);
3148 else if (t.cs() == "textcolor") {
3149 // scheme is \textcolor{color name}{text}
3150 string const color = p.verbatim_item();
3151 // we only support the predefined colors of the color package
3152 if (color == "black" || color == "blue" || color == "cyan"
3153 || color == "green" || color == "magenta" || color == "red"
3154 || color == "white" || color == "yellow") {
3155 context.check_layout(os);
3156 os << "\n\\color " << color << "\n";
3157 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3158 context.check_layout(os);
3159 os << "\n\\color inherit\n";
3160 preamble.registerAutomaticallyLoadedPackage("color");
3162 // for custom defined colors
3163 handle_ert(os, t.asInput() + "{" + color + "}", context);
3166 else if (t.cs() == "underbar" || t.cs() == "uline") {
3167 // \underbar is not 100% correct (LyX outputs \uline
3168 // of ulem.sty). The difference is that \ulem allows
3169 // line breaks, and \underbar does not.
3170 // Do NOT handle \underline.
3171 // \underbar cuts through y, g, q, p etc.,
3172 // \underline does not.
3173 context.check_layout(os);
3174 os << "\n\\bar under\n";
3175 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3176 context.check_layout(os);
3177 os << "\n\\bar default\n";
3178 preamble.registerAutomaticallyLoadedPackage("ulem");
3181 else if (t.cs() == "sout") {
3182 context.check_layout(os);
3183 os << "\n\\strikeout on\n";
3184 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3185 context.check_layout(os);
3186 os << "\n\\strikeout default\n";
3187 preamble.registerAutomaticallyLoadedPackage("ulem");
3190 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3191 t.cs() == "emph" || t.cs() == "noun") {
3192 context.check_layout(os);
3193 os << "\n\\" << t.cs() << " on\n";
3194 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3195 context.check_layout(os);
3196 os << "\n\\" << t.cs() << " default\n";
3197 if (t.cs() == "uuline" || t.cs() == "uwave")
3198 preamble.registerAutomaticallyLoadedPackage("ulem");
3201 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3202 context.check_layout(os);
3203 string name = p.getArg('{', '}');
3204 string localtime = p.getArg('{', '}');
3205 preamble.registerAuthor(name);
3206 Author const & author = preamble.getAuthor(name);
3207 // from_gmtime() will fail if LyX decides to output the
3208 // time in the text language.
3209 time_t ptime = from_gmtime(localtime);
3210 if (ptime == static_cast<time_t>(-1)) {
3211 cerr << "Warning: Could not parse time `" << localtime
3212 << "´ for change tracking, using current time instead.\n";
3213 ptime = current_time();
3215 if (t.cs() == "lyxadded")
3216 os << "\n\\change_inserted ";
3218 os << "\n\\change_deleted ";
3219 os << author.bufferId() << ' ' << ptime << '\n';
3220 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3221 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3222 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3223 LaTeXPackages::isAvailable("xcolor");
3224 // No need to test for luatex, since luatex comes in
3225 // two flavours (dvi and pdf), like latex, and those
3226 // are detected by pdflatex.
3227 if (pdflatex || xetex) {
3229 preamble.registerAutomaticallyLoadedPackage("ulem");
3230 preamble.registerAutomaticallyLoadedPackage("xcolor");
3231 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3235 preamble.registerAutomaticallyLoadedPackage("dvipost");
3236 } else if (xcolorulem) {
3237 preamble.registerAutomaticallyLoadedPackage("ulem");
3238 preamble.registerAutomaticallyLoadedPackage("xcolor");
3243 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3244 t.cs() == "vphantom") {
3245 context.check_layout(os);
3246 if (t.cs() == "phantom")
3247 begin_inset(os, "Phantom Phantom\n");
3248 if (t.cs() == "hphantom")
3249 begin_inset(os, "Phantom HPhantom\n");
3250 if (t.cs() == "vphantom")
3251 begin_inset(os, "Phantom VPhantom\n");
3252 os << "status open\n";
3253 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3258 else if (t.cs() == "href") {
3259 context.check_layout(os);
3260 string target = convert_command_inset_arg(p.verbatim_item());
3261 string name = convert_command_inset_arg(p.verbatim_item());
3263 size_t i = target.find(':');
3264 if (i != string::npos) {
3265 type = target.substr(0, i + 1);
3266 if (type == "mailto:" || type == "file:")
3267 target = target.substr(i + 1);
3268 // handle the case that name is equal to target, except of "http://"
3269 else if (target.substr(i + 3) == name && type == "http:")
3272 begin_command_inset(os, "href", "href");
3274 os << "name \"" << name << "\"\n";
3275 os << "target \"" << target << "\"\n";
3276 if (type == "mailto:" || type == "file:")
3277 os << "type \"" << type << "\"\n";
3279 skip_spaces_braces(p);
3282 else if (t.cs() == "lyxline") {
3283 // swallow size argument (it is not used anyway)
3285 if (!context.atParagraphStart()) {
3286 // so our line is in the middle of a paragraph
3287 // we need to add a new line, lest this line
3288 // follow the other content on that line and
3289 // run off the side of the page
3290 // FIXME: This may create an empty paragraph,
3291 // but without that it would not be
3292 // possible to set noindent below.
3293 // Fortunately LaTeX does not care
3294 // about the empty paragraph.
3295 context.new_paragraph(os);
3297 if (preamble.indentParagraphs()) {
3298 // we need to unindent, lest the line be too long
3299 context.add_par_extra_stuff("\\noindent\n");
3301 context.check_layout(os);
3302 begin_command_inset(os, "line", "rule");
3303 os << "offset \"0.5ex\"\n"
3304 "width \"100line%\"\n"
3309 else if (t.cs() == "rule") {
3310 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3311 string const width = p.getArg('{', '}');
3312 string const thickness = p.getArg('{', '}');
3313 context.check_layout(os);
3314 begin_command_inset(os, "line", "rule");
3315 if (!offset.empty())
3316 os << "offset \"" << translate_len(offset) << "\"\n";
3317 os << "width \"" << translate_len(width) << "\"\n"
3318 "height \"" << translate_len(thickness) << "\"\n";
3322 else if (is_known(t.cs(), known_phrases) ||
3323 (t.cs() == "protect" &&
3324 p.next_token().cat() == catEscape &&
3325 is_known(p.next_token().cs(), known_phrases))) {
3326 // LyX sometimes puts a \protect in front, so we have to ignore it
3327 // FIXME: This needs to be changed when bug 4752 is fixed.
3329 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3331 context.check_layout(os);
3332 os << known_coded_phrases[where - known_phrases];
3333 skip_spaces_braces(p);
3336 else if ((where = is_known(t.cs(), known_ref_commands))) {
3337 string const opt = p.getOpt();
3339 context.check_layout(os);
3340 begin_command_inset(os, "ref",
3341 known_coded_ref_commands[where - known_ref_commands]);
3342 os << "reference \""
3343 << convert_command_inset_arg(p.verbatim_item())
3346 if (t.cs() == "vref" || t.cs() == "vpageref")
3347 preamble.registerAutomaticallyLoadedPackage("varioref");
3350 // LyX does not support optional arguments of ref commands
3351 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3352 p.verbatim_item() + "}", context);
3356 else if (use_natbib &&
3357 is_known(t.cs(), known_natbib_commands) &&
3358 ((t.cs() != "citefullauthor" &&
3359 t.cs() != "citeyear" &&
3360 t.cs() != "citeyearpar") ||
3361 p.next_token().asInput() != "*")) {
3362 context.check_layout(os);
3363 string command = t.cs();
3364 if (p.next_token().asInput() == "*") {
3368 if (command == "citefullauthor")
3369 // alternative name for "\\citeauthor*"
3370 command = "citeauthor*";
3372 // text before the citation
3374 // text after the citation
3376 get_cite_arguments(p, true, before, after);
3378 if (command == "cite") {
3379 // \cite without optional argument means
3380 // \citet, \cite with at least one optional
3381 // argument means \citep.
3382 if (before.empty() && after.empty())
3387 if (before.empty() && after == "[]")
3388 // avoid \citet[]{a}
3390 else if (before == "[]" && after == "[]") {
3391 // avoid \citet[][]{a}
3395 // remove the brackets around after and before
3396 if (!after.empty()) {
3398 after.erase(after.length() - 1, 1);
3399 after = convert_command_inset_arg(after);
3401 if (!before.empty()) {
3403 before.erase(before.length() - 1, 1);
3404 before = convert_command_inset_arg(before);
3406 begin_command_inset(os, "citation", command);
3407 os << "after " << '"' << after << '"' << "\n";
3408 os << "before " << '"' << before << '"' << "\n";
3410 << convert_command_inset_arg(p.verbatim_item())
3413 // Need to set the cite engine if natbib is loaded by
3414 // the document class directly
3415 if (preamble.citeEngine() == "basic")
3416 preamble.citeEngine("natbib");
3419 else if (use_jurabib &&
3420 is_known(t.cs(), known_jurabib_commands) &&
3421 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3422 context.check_layout(os);
3423 string command = t.cs();
3424 if (p.next_token().asInput() == "*") {
3428 char argumentOrder = '\0';
3429 vector<string> const options =
3430 preamble.getPackageOptions("jurabib");
3431 if (find(options.begin(), options.end(),
3432 "natbiborder") != options.end())
3433 argumentOrder = 'n';
3434 else if (find(options.begin(), options.end(),
3435 "jurabiborder") != options.end())
3436 argumentOrder = 'j';
3438 // text before the citation
3440 // text after the citation
3442 get_cite_arguments(p, argumentOrder != 'j', before, after);
3444 string const citation = p.verbatim_item();
3445 if (!before.empty() && argumentOrder == '\0') {
3446 cerr << "Warning: Assuming argument order "
3447 "of jurabib version 0.6 for\n'"
3448 << command << before << after << '{'
3449 << citation << "}'.\n"
3450 "Add 'jurabiborder' to the jurabib "
3451 "package options if you used an\n"
3452 "earlier jurabib version." << endl;
3454 if (!after.empty()) {
3456 after.erase(after.length() - 1, 1);
3458 if (!before.empty()) {
3460 before.erase(before.length() - 1, 1);
3462 begin_command_inset(os, "citation", command);
3463 os << "after " << '"' << after << '"' << "\n";
3464 os << "before " << '"' << before << '"' << "\n";
3465 os << "key " << '"' << citation << '"' << "\n";
3467 // Need to set the cite engine if jurabib is loaded by
3468 // the document class directly
3469 if (preamble.citeEngine() == "basic")
3470 preamble.citeEngine("jurabib");
3473 else if (t.cs() == "cite"
3474 || t.cs() == "nocite") {
3475 context.check_layout(os);
3476 string after = convert_command_inset_arg(p.getArg('[', ']'));
3477 string key = convert_command_inset_arg(p.verbatim_item());
3478 // store the case that it is "\nocite{*}" to use it later for
3481 begin_command_inset(os, "citation", t.cs());
3482 os << "after " << '"' << after << '"' << "\n";
3483 os << "key " << '"' << key << '"' << "\n";
3485 } else if (t.cs() == "nocite")
3489 else if (t.cs() == "index" ||
3490 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3491 context.check_layout(os);
3492 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3493 p.getArg('[', ']') : "";
3494 string const kind = arg.empty() ? "idx" : arg;
3495 begin_inset(os, "Index ");
3496 os << kind << "\nstatus collapsed\n";
3497 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3500 preamble.registerAutomaticallyLoadedPackage("splitidx");
3503 else if (t.cs() == "nomenclature") {
3504 context.check_layout(os);
3505 begin_command_inset(os, "nomenclature", "nomenclature");
3506 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3507 if (!prefix.empty())
3508 os << "prefix " << '"' << prefix << '"' << "\n";
3509 os << "symbol " << '"'
3510 << convert_command_inset_arg(p.verbatim_item());
3511 os << "\"\ndescription \""
3512 << convert_command_inset_arg(p.verbatim_item())
3515 preamble.registerAutomaticallyLoadedPackage("nomencl");
3518 else if (t.cs() == "label") {
3519 context.check_layout(os);
3520 begin_command_inset(os, "label", "label");
3522 << convert_command_inset_arg(p.verbatim_item())
3527 else if (t.cs() == "printindex") {
3528 context.check_layout(os);
3529 begin_command_inset(os, "index_print", "printindex");
3530 os << "type \"idx\"\n";
3532 skip_spaces_braces(p);
3533 preamble.registerAutomaticallyLoadedPackage("makeidx");
3534 if (preamble.use_indices() == "true")
3535 preamble.registerAutomaticallyLoadedPackage("splitidx");
3538 else if (t.cs() == "printnomenclature") {
3540 string width_type = "";
3541 context.check_layout(os);
3542 begin_command_inset(os, "nomencl_print", "printnomenclature");
3543 // case of a custom width
3545 width = p.getArg('[', ']');
3546 width = translate_len(width);
3547 width_type = "custom";
3549 // case of no custom width
3550 // the case of no custom width but the width set
3551 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3552 // because the user could have set anything, not only the width
3553 // of the longest label (which would be width_type = "auto")
3554 string label = convert_command_inset_arg(p.getArg('{', '}'));
3555 if (label.empty() && width_type.empty())
3556 width_type = "none";
3557 os << "set_width \"" << width_type << "\"\n";
3558 if (width_type == "custom")
3559 os << "width \"" << width << '\"';
3561 skip_spaces_braces(p);
3562 preamble.registerAutomaticallyLoadedPackage("nomencl");
3565 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3566 context.check_layout(os);
3567 begin_inset(os, "script ");
3568 os << t.cs().substr(4) << '\n';
3569 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3571 if (t.cs() == "textsubscript")
3572 preamble.registerAutomaticallyLoadedPackage("subscript");
3575 else if ((where = is_known(t.cs(), known_quotes))) {
3576 context.check_layout(os);
3577 begin_inset(os, "Quotes ");
3578 os << known_coded_quotes[where - known_quotes];
3580 // LyX adds {} after the quote, so we have to eat
3581 // spaces here if there are any before a possible
3583 eat_whitespace(p, os, context, false);
3587 else if ((where = is_known(t.cs(), known_sizes)) &&
3588 context.new_layout_allowed) {
3589 context.check_layout(os);
3590 TeXFont const oldFont = context.font;
3591 context.font.size = known_coded_sizes[where - known_sizes];
3592 output_font_change(os, oldFont, context.font);
3593 eat_whitespace(p, os, context, false);
3596 else if ((where = is_known(t.cs(), known_font_families)) &&
3597 context.new_layout_allowed) {
3598 context.check_layout(os);
3599 TeXFont const oldFont = context.font;
3600 context.font.family =
3601 known_coded_font_families[where - known_font_families];
3602 output_font_change(os, oldFont, context.font);
3603 eat_whitespace(p, os, context, false);
3606 else if ((where = is_known(t.cs(), known_font_series)) &&
3607 context.new_layout_allowed) {
3608 context.check_layout(os);
3609 TeXFont const oldFont = context.font;
3610 context.font.series =
3611 known_coded_font_series[where - known_font_series];
3612 output_font_change(os, oldFont, context.font);
3613 eat_whitespace(p, os, context, false);
3616 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3617 context.new_layout_allowed) {
3618 context.check_layout(os);
3619 TeXFont const oldFont = context.font;
3620 context.font.shape =
3621 known_coded_font_shapes[where - known_font_shapes];
3622 output_font_change(os, oldFont, context.font);
3623 eat_whitespace(p, os, context, false);
3625 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3626 context.new_layout_allowed) {
3627 context.check_layout(os);
3628 TeXFont const oldFont = context.font;
3629 context.font.init();
3630 context.font.size = oldFont.size;
3631 context.font.family =
3632 known_coded_font_families[where - known_old_font_families];
3633 output_font_change(os, oldFont, context.font);
3634 eat_whitespace(p, os, context, false);
3637 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3638 context.new_layout_allowed) {
3639 context.check_layout(os);
3640 TeXFont const oldFont = context.font;
3641 context.font.init();
3642 context.font.size = oldFont.size;
3643 context.font.series =
3644 known_coded_font_series[where - known_old_font_series];
3645 output_font_change(os, oldFont, context.font);
3646 eat_whitespace(p, os, context, false);
3649 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3650 context.new_layout_allowed) {
3651 context.check_layout(os);
3652 TeXFont const oldFont = context.font;
3653 context.font.init();
3654 context.font.size = oldFont.size;
3655 context.font.shape =
3656 known_coded_font_shapes[where - known_old_font_shapes];
3657 output_font_change(os, oldFont, context.font);
3658 eat_whitespace(p, os, context, false);
3661 else if (t.cs() == "selectlanguage") {
3662 context.check_layout(os);
3663 // save the language for the case that a
3664 // \foreignlanguage is used
3665 context.font.language = babel2lyx(p.verbatim_item());
3666 os << "\n\\lang " << context.font.language << "\n";
3669 else if (t.cs() == "foreignlanguage") {
3670 string const lang = babel2lyx(p.verbatim_item());
3671 parse_text_attributes(p, os, FLAG_ITEM, outer,
3673 context.font.language, lang);
3676 else if (prefixIs(t.cs(), "text")
3677 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3678 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3680 // We have to output the whole command if it has an option
3681 // because LyX doesn't support this yet, see bug #8214,
3682 // only if there is a single option specifying a variant, we can handle it.
3684 string langopts = p.getOpt();
3685 // check if the option contains a variant, if yes, extract it
3686 string::size_type pos_var = langopts.find("variant");
3687 string::size_type i = langopts.find(',');
3688 string::size_type k = langopts.find('=', pos_var);
3689 if (pos_var != string::npos && i == string::npos) {
3691 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3692 lang = preamble.polyglossia2lyx(variant);
3693 parse_text_attributes(p, os, FLAG_ITEM, outer,
3695 context.font.language, lang);
3697 handle_ert(os, t.asInput() + langopts, context);
3699 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3700 parse_text_attributes(p, os, FLAG_ITEM, outer,
3702 context.font.language, lang);
3706 else if (t.cs() == "inputencoding") {
3707 // nothing to write here
3708 string const enc = subst(p.verbatim_item(), "\n", " ");
3712 else if ((where = is_known(t.cs(), known_special_chars))) {
3713 context.check_layout(os);
3714 os << "\\SpecialChar \\"
3715 << known_coded_special_chars[where - known_special_chars]
3717 skip_spaces_braces(p);
3720 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3721 context.check_layout(os);
3722 os << "\\SpecialChar \\nobreakdash-\n";
3726 else if (t.cs() == "textquotedbl") {
3727 context.check_layout(os);
3732 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3733 context.check_layout(os);
3734 os << "\\SpecialChar \\@.\n";
3738 else if (t.cs() == "-") {
3739 context.check_layout(os);
3740 os << "\\SpecialChar \\-\n";
3743 else if (t.cs() == "textasciitilde") {
3744 context.check_layout(os);
3746 skip_spaces_braces(p);
3749 else if (t.cs() == "textasciicircum") {
3750 context.check_layout(os);
3752 skip_spaces_braces(p);
3755 else if (t.cs() == "textbackslash") {
3756 context.check_layout(os);
3757 os << "\n\\backslash\n";
3758 skip_spaces_braces(p);
3761 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3762 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3764 context.check_layout(os);
3768 else if (t.cs() == "char") {
3769 context.check_layout(os);
3770 if (p.next_token().character() == '`') {
3772 if (p.next_token().cs() == "\"") {
3777 handle_ert(os, "\\char`", context);
3780 handle_ert(os, "\\char", context);
3784 else if (t.cs() == "verb") {
3785 context.check_layout(os);
3786 char const delimiter = p.next_token().character();
3787 // \verb is special: The usual escaping rules do not
3788 // apply, e.g. "\verb+\+" is valid and denotes a single
3789 // backslash (bug #4468). Therefore we do not allow
3790 // escaping in getArg().
3791 string const arg = p.getArg(delimiter, delimiter, false);
3793 oss << "\\verb" << delimiter << arg << delimiter;
3794 handle_ert(os, oss.str(), context);
3797 // Problem: \= creates a tabstop inside the tabbing environment
3798 // and else an accent. In the latter case we really would want
3799 // \={o} instead of \= o.
3800 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3801 handle_ert(os, t.asInput(), context);
3803 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3804 else if (t.cs().size() == 1
3805 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3806 context.check_layout(os);
3807 // try to see whether the string is in unicodesymbols
3810 string command = t.asInput() + "{"
3811 + trimSpaceAndEol(p.verbatim_item())
3814 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3815 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3816 termination, rem, &req);
3819 cerr << "When parsing " << command
3820 << ", result is " << to_utf8(s)
3821 << "+" << to_utf8(rem) << endl;
3823 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3824 preamble.registerAutomaticallyLoadedPackage(*it);
3826 // we did not find a non-ert version
3827 handle_ert(os, command, context);
3830 else if (t.cs() == "\\") {
3831 context.check_layout(os);
3833 handle_ert(os, "\\\\" + p.getOpt(), context);
3834 else if (p.next_token().asInput() == "*") {
3836 // getOpt() eats the following space if there
3837 // is no optional argument, but that is OK
3838 // here since it has no effect in the output.
3839 handle_ert(os, "\\\\*" + p.getOpt(), context);
3842 begin_inset(os, "Newline newline");
3847 else if (t.cs() == "newline" ||
3848 (t.cs() == "linebreak" && !p.hasOpt())) {
3849 context.check_layout(os);
3850 begin_inset(os, "Newline ");
3853 skip_spaces_braces(p);
3856 else if (t.cs() == "input" || t.cs() == "include"
3857 || t.cs() == "verbatiminput") {
3858 string name = t.cs();
3859 if (t.cs() == "verbatiminput"
3860 && p.next_token().asInput() == "*")
3861 name += p.get_token().asInput();
3862 context.check_layout(os);
3863 string filename(normalize_filename(p.getArg('{', '}')));
3864 string const path = getMasterFilePath(true);
3865 // We want to preserve relative / absolute filenames,
3866 // therefore path is only used for testing
3867 if ((t.cs() == "include" || t.cs() == "input") &&
3868 !makeAbsPath(filename, path).exists()) {
3869 // The file extension is probably missing.
3870 // Now try to find it out.
3871 string const tex_name =
3872 find_file(filename, path,
3873 known_tex_extensions);
3874 if (!tex_name.empty())
3875 filename = tex_name;
3877 bool external = false;
3879 if (makeAbsPath(filename, path).exists()) {
3880 string const abstexname =
3881 makeAbsPath(filename, path).absFileName();
3882 string const absfigname =
3883 changeExtension(abstexname, ".fig");
3884 fix_child_filename(filename);
3885 string const lyxname =
3886 changeExtension(filename, ".lyx");
3887 string const abslyxname = makeAbsPath(
3888 lyxname, getParentFilePath(false)).absFileName();
3890 if (!skipChildren())
3891 external = FileName(absfigname).exists();
3892 if (t.cs() == "input" && !skipChildren()) {
3893 string const ext = getExtension(abstexname);
3895 // Combined PS/LaTeX:
3896 // x.eps, x.pstex_t (old xfig)
3897 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3898 FileName const absepsname(
3899 changeExtension(abstexname, ".eps"));
3900 FileName const abspstexname(
3901 changeExtension(abstexname, ".pstex"));
3902 bool const xfigeps =
3903 (absepsname.exists() ||
3904 abspstexname.exists()) &&
3907 // Combined PDF/LaTeX:
3908 // x.pdf, x.pdftex_t (old xfig)
3909 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3910 FileName const abspdfname(
3911 changeExtension(abstexname, ".pdf"));
3912 bool const xfigpdf =
3913 abspdfname.exists() &&
3914 (ext == "pdftex_t" || ext == "pdf_t");
3918 // Combined PS/PDF/LaTeX:
3919 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3920 string const absbase2(
3921 removeExtension(abstexname) + "_pspdftex");
3922 FileName const abseps2name(
3923 addExtension(absbase2, ".eps"));
3924 FileName const abspdf2name(
3925 addExtension(absbase2, ".pdf"));
3926 bool const xfigboth =
3927 abspdf2name.exists() &&
3928 abseps2name.exists() && ext == "pspdftex";
3930 xfig = xfigpdf || xfigeps || xfigboth;
3931 external = external && xfig;
3934 outname = changeExtension(filename, ".fig");
3935 FileName abssrc(changeExtension(abstexname, ".fig"));
3936 copy_file(abssrc, outname);
3938 // Don't try to convert, the result
3939 // would be full of ERT.
3941 FileName abssrc(abstexname);
3942 copy_file(abssrc, outname);
3943 } else if (t.cs() != "verbatiminput" &&
3945 tex2lyx(abstexname, FileName(abslyxname),
3948 // no need to call copy_file
3949 // tex2lyx creates the file
3952 FileName abssrc(abstexname);
3953 copy_file(abssrc, outname);
3956 cerr << "Warning: Could not find included file '"
3957 << filename << "'." << endl;
3961 begin_inset(os, "External\n");
3962 os << "\ttemplate XFig\n"
3963 << "\tfilename " << outname << '\n';
3964 registerExternalTemplatePackages("XFig");
3966 begin_command_inset(os, "include", name);
3967 outname = subst(outname, "\"", "\\\"");
3968 os << "preview false\n"
3969 "filename \"" << outname << "\"\n";
3970 if (t.cs() == "verbatiminput")
3971 preamble.registerAutomaticallyLoadedPackage("verbatim");
3976 else if (t.cs() == "bibliographystyle") {
3977 // store new bibliographystyle
3978 bibliographystyle = p.verbatim_item();
3979 // If any other command than \bibliography and
3980 // \nocite{*} follows, we need to output the style
3981 // (because it might be used by that command).
3982 // Otherwise, it will automatically be output by LyX.
3985 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3986 if (t2.cat() == catBegin)
3988 if (t2.cat() != catEscape)
3990 if (t2.cs() == "nocite") {
3991 if (p.getArg('{', '}') == "*")
3993 } else if (t2.cs() == "bibliography")
4000 "\\bibliographystyle{" + bibliographystyle + '}',
4005 else if (t.cs() == "bibliography") {
4006 context.check_layout(os);
4007 begin_command_inset(os, "bibtex", "bibtex");
4008 if (!btprint.empty()) {
4009 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4010 // clear the string because the next BibTeX inset can be without the
4011 // \nocite{*} option
4014 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4015 // Do we have a bibliographystyle set?
4016 if (!bibliographystyle.empty())
4017 os << "options " << '"' << bibliographystyle << '"' << "\n";
4021 else if (t.cs() == "parbox") {
4022 // Test whether this is an outer box of a shaded box
4024 // swallow arguments
4025 while (p.hasOpt()) {
4027 p.skip_spaces(true);
4030 p.skip_spaces(true);
4032 if (p.next_token().cat() == catBegin)
4034 p.skip_spaces(true);
4035 Token to = p.get_token();
4036 bool shaded = false;
4037 if (to.asInput() == "\\begin") {
4038 p.skip_spaces(true);
4039 if (p.getArg('{', '}') == "shaded")
4044 parse_outer_box(p, os, FLAG_ITEM, outer,
4045 context, "parbox", "shaded");
4047 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4051 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4052 t.cs() == "shadowbox" || t.cs() == "doublebox")
4053 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4055 else if (t.cs() == "framebox") {
4056 if (p.next_token().character() == '(') {
4057 //the syntax is: \framebox(x,y)[position]{content}
4058 string arg = t.asInput();
4059 arg += p.getFullParentheseArg();
4060 arg += p.getFullOpt();
4061 eat_whitespace(p, os, context, false);
4062 handle_ert(os, arg + '{', context);
4063 parse_text(p, os, FLAG_ITEM, outer, context);
4064 handle_ert(os, "}", context);
4066 string special = p.getFullOpt();
4067 special += p.getOpt();
4068 // LyX does not yet support \framebox without any option
4069 if (!special.empty())
4070 parse_outer_box(p, os, FLAG_ITEM, outer,
4071 context, t.cs(), special);
4073 eat_whitespace(p, os, context, false);
4074 handle_ert(os, "\\framebox{", context);
4075 parse_text(p, os, FLAG_ITEM, outer, context);
4076 handle_ert(os, "}", context);
4081 //\makebox() is part of the picture environment and different from \makebox{}
4082 //\makebox{} will be parsed by parse_box
4083 else if (t.cs() == "makebox") {
4084 if (p.next_token().character() == '(') {
4085 //the syntax is: \makebox(x,y)[position]{content}
4086 string arg = t.asInput();
4087 arg += p.getFullParentheseArg();
4088 arg += p.getFullOpt();
4089 eat_whitespace(p, os, context, false);
4090 handle_ert(os, arg + '{', context);
4091 parse_text(p, os, FLAG_ITEM, outer, context);
4092 handle_ert(os, "}", context);
4094 //the syntax is: \makebox[width][position]{content}
4095 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4099 else if (t.cs() == "smallskip" ||
4100 t.cs() == "medskip" ||
4101 t.cs() == "bigskip" ||
4102 t.cs() == "vfill") {
4103 context.check_layout(os);
4104 begin_inset(os, "VSpace ");
4107 skip_spaces_braces(p);
4110 else if ((where = is_known(t.cs(), known_spaces))) {
4111 context.check_layout(os);
4112 begin_inset(os, "space ");
4113 os << '\\' << known_coded_spaces[where - known_spaces]
4116 // LaTeX swallows whitespace after all spaces except
4117 // "\\,". We have to do that here, too, because LyX
4118 // adds "{}" which would make the spaces significant.
4120 eat_whitespace(p, os, context, false);
4121 // LyX adds "{}" after all spaces except "\\ " and
4122 // "\\,", so we have to remove "{}".
4123 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4124 // remove the braces after "\\,", too.
4129 else if (t.cs() == "newpage" ||
4130 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4131 t.cs() == "clearpage" ||
4132 t.cs() == "cleardoublepage") {
4133 context.check_layout(os);
4134 begin_inset(os, "Newpage ");
4137 skip_spaces_braces(p);
4140 else if (t.cs() == "DeclareRobustCommand" ||
4141 t.cs() == "DeclareRobustCommandx" ||
4142 t.cs() == "newcommand" ||
4143 t.cs() == "newcommandx" ||
4144 t.cs() == "providecommand" ||
4145 t.cs() == "providecommandx" ||
4146 t.cs() == "renewcommand" ||
4147 t.cs() == "renewcommandx") {
4148 // DeclareRobustCommand, DeclareRobustCommandx,
4149 // providecommand and providecommandx could be handled
4150 // by parse_command(), but we need to call
4151 // add_known_command() here.
4152 string name = t.asInput();
4153 if (p.next_token().asInput() == "*") {
4154 // Starred form. Eat '*'
4158 string const command = p.verbatim_item();
4159 string const opt1 = p.getFullOpt();
4160 string const opt2 = p.getFullOpt();
4161 add_known_command(command, opt1, !opt2.empty());
4162 string const ert = name + '{' + command + '}' +
4164 '{' + p.verbatim_item() + '}';
4166 if (t.cs() == "DeclareRobustCommand" ||
4167 t.cs() == "DeclareRobustCommandx" ||
4168 t.cs() == "providecommand" ||
4169 t.cs() == "providecommandx" ||
4170 name[name.length()-1] == '*')
4171 handle_ert(os, ert, context);
4173 context.check_layout(os);
4174 begin_inset(os, "FormulaMacro");
4180 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4181 // let could be handled by parse_command(),
4182 // but we need to call add_known_command() here.
4183 string ert = t.asInput();
4186 if (p.next_token().cat() == catBegin) {
4187 name = p.verbatim_item();
4188 ert += '{' + name + '}';
4190 name = p.verbatim_item();
4195 if (p.next_token().cat() == catBegin) {
4196 command = p.verbatim_item();
4197 ert += '{' + command + '}';
4199 command = p.verbatim_item();
4202 // If command is known, make name known too, to parse
4203 // its arguments correctly. For this reason we also
4204 // have commands in syntax.default that are hardcoded.
4205 CommandMap::iterator it = known_commands.find(command);
4206 if (it != known_commands.end())
4207 known_commands[t.asInput()] = it->second;
4208 handle_ert(os, ert, context);
4211 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4212 bool starred = false;
4213 if (p.next_token().asInput() == "*") {
4217 string name = t.asInput();
4218 string const length = p.verbatim_item();
4221 bool valid = splitLatexLength(length, valstring, unit);
4222 bool known_hspace = false;
4223 bool known_vspace = false;
4224 bool known_unit = false;
4227 istringstream iss(valstring);
4230 if (t.cs()[0] == 'h') {
4231 if (unit == "\\fill") {
4236 known_hspace = true;
4239 if (unit == "\\smallskipamount") {
4241 known_vspace = true;
4242 } else if (unit == "\\medskipamount") {
4244 known_vspace = true;
4245 } else if (unit == "\\bigskipamount") {
4247 known_vspace = true;
4248 } else if (unit == "\\fill") {
4250 known_vspace = true;
4254 if (!known_hspace && !known_vspace) {
4255 switch (unitFromString(unit)) {
4276 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4277 // Literal horizontal length or known variable
4278 context.check_layout(os);
4279 begin_inset(os, "space ");
4287 if (known_unit && !known_hspace)
4289 << translate_len(length);
4291 } else if (known_unit || known_vspace) {
4292 // Literal vertical length or known variable
4293 context.check_layout(os);
4294 begin_inset(os, "VSpace ");
4302 // LyX can't handle other length variables in Inset VSpace/space
4307 handle_ert(os, name + '{' + unit + '}', context);
4308 else if (value == -1.0)
4309 handle_ert(os, name + "{-" + unit + '}', context);
4311 handle_ert(os, name + '{' + valstring + unit + '}', context);
4313 handle_ert(os, name + '{' + length + '}', context);
4317 // The single '=' is meant here.
4318 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4320 context.check_layout(os);
4321 begin_inset(os, "Flex ");
4322 os << to_utf8(newinsetlayout->name()) << '\n'
4323 << "status collapsed\n";
4324 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4328 else if (t.cs() == "includepdf") {
4330 string const arg = p.getArg('[', ']');
4331 map<string, string> opts;
4332 vector<string> keys;
4333 split_map(arg, opts, keys);
4334 string name = normalize_filename(p.verbatim_item());
4335 string const path = getMasterFilePath(true);
4336 // We want to preserve relative / absolute filenames,
4337 // therefore path is only used for testing
4338 if (!makeAbsPath(name, path).exists()) {
4339 // The file extension is probably missing.
4340 // Now try to find it out.
4341 char const * const pdfpages_format[] = {"pdf", 0};
4342 string const pdftex_name =
4343 find_file(name, path, pdfpages_format);
4344 if (!pdftex_name.empty()) {
4349 FileName const absname = makeAbsPath(name, path);
4350 if (absname.exists())
4352 fix_child_filename(name);
4353 copy_file(absname, name);
4355 cerr << "Warning: Could not find file '"
4356 << name << "'." << endl;
4358 context.check_layout(os);
4359 begin_inset(os, "External\n\ttemplate ");
4360 os << "PDFPages\n\tfilename "
4362 // parse the options
4363 if (opts.find("pages") != opts.end())
4364 os << "\textra LaTeX \"pages="
4365 << opts["pages"] << "\"\n";
4366 if (opts.find("angle") != opts.end())
4367 os << "\trotateAngle "
4368 << opts["angle"] << '\n';
4369 if (opts.find("origin") != opts.end()) {
4371 string const opt = opts["origin"];
4372 if (opt == "tl") ss << "topleft";
4373 if (opt == "bl") ss << "bottomleft";
4374 if (opt == "Bl") ss << "baselineleft";
4375 if (opt == "c") ss << "center";
4376 if (opt == "tc") ss << "topcenter";
4377 if (opt == "bc") ss << "bottomcenter";
4378 if (opt == "Bc") ss << "baselinecenter";
4379 if (opt == "tr") ss << "topright";
4380 if (opt == "br") ss << "bottomright";
4381 if (opt == "Br") ss << "baselineright";
4382 if (!ss.str().empty())
4383 os << "\trotateOrigin " << ss.str() << '\n';
4385 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4387 if (opts.find("width") != opts.end())
4389 << translate_len(opts["width"]) << '\n';
4390 if (opts.find("height") != opts.end())
4392 << translate_len(opts["height"]) << '\n';
4393 if (opts.find("keepaspectratio") != opts.end())
4394 os << "\tkeepAspectRatio\n";
4396 context.check_layout(os);
4397 registerExternalTemplatePackages("PDFPages");
4400 else if (t.cs() == "loadgame") {
4402 string name = normalize_filename(p.verbatim_item());
4403 string const path = getMasterFilePath(true);
4404 // We want to preserve relative / absolute filenames,
4405 // therefore path is only used for testing
4406 if (!makeAbsPath(name, path).exists()) {
4407 // The file extension is probably missing.
4408 // Now try to find it out.
4409 char const * const lyxskak_format[] = {"fen", 0};
4410 string const lyxskak_name =
4411 find_file(name, path, lyxskak_format);
4412 if (!lyxskak_name.empty())
4413 name = lyxskak_name;
4415 FileName const absname = makeAbsPath(name, path);
4416 if (absname.exists())
4418 fix_child_filename(name);
4419 copy_file(absname, name);
4421 cerr << "Warning: Could not find file '"
4422 << name << "'." << endl;
4423 context.check_layout(os);
4424 begin_inset(os, "External\n\ttemplate ");
4425 os << "ChessDiagram\n\tfilename "
4428 context.check_layout(os);
4429 // after a \loadgame follows a \showboard
4430 if (p.get_token().asInput() == "showboard")
4432 registerExternalTemplatePackages("ChessDiagram");
4436 // try to see whether the string is in unicodesymbols
4437 // Only use text mode commands, since we are in text mode here,
4438 // and math commands may be invalid (bug 6797)
4442 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4443 Encodings::TEXT_CMD, termination, rem, &req);
4446 cerr << "When parsing " << t.cs()
4447 << ", result is " << to_utf8(s)
4448 << "+" << to_utf8(rem) << endl;
4449 context.check_layout(os);
4452 skip_spaces_braces(p);
4453 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4454 preamble.registerAutomaticallyLoadedPackage(*it);
4456 //cerr << "#: " << t << " mode: " << mode << endl;
4457 // heuristic: read up to next non-nested space
4459 string s = t.asInput();
4460 string z = p.verbatim_item();
4461 while (p.good() && z != " " && !z.empty()) {
4462 //cerr << "read: " << z << endl;
4464 z = p.verbatim_item();
4466 cerr << "found ERT: " << s << endl;
4467 handle_ert(os, s + ' ', context);
4470 string name = t.asInput();
4471 if (p.next_token().asInput() == "*") {
4472 // Starred commands like \vspace*{}
4473 p.get_token(); // Eat '*'
4476 if (!parse_command(name, p, os, outer, context))
4477 handle_ert(os, name, context);
4481 if (flags & FLAG_LEAVE) {
4482 flags &= ~FLAG_LEAVE;
4489 string guessLanguage(Parser & p, string const & lang)
4491 typedef std::map<std::string, size_t> LangMap;
4492 // map from language names to number of characters
4495 for (char const * const * i = supported_CJK_languages; *i; i++)
4496 used[string(*i)] = 0;
4499 Token const t = p.get_token();
4500 // comments are not counted for any language
4501 if (t.cat() == catComment)
4503 // commands are not counted as well, but we need to detect
4504 // \begin{CJK} and switch encoding if needed
4505 if (t.cat() == catEscape) {
4506 if (t.cs() == "inputencoding") {
4507 string const enc = subst(p.verbatim_item(), "\n", " ");
4511 if (t.cs() != "begin")
4514 // Non-CJK content is counted for lang.
4515 // We do not care about the real language here:
4516 // If we have more non-CJK contents than CJK contents,
4517 // we simply use the language that was specified as
4518 // babel main language.
4519 used[lang] += t.asInput().length();
4522 // Now we are starting an environment
4524 string const name = p.getArg('{', '}');
4525 if (name != "CJK") {
4529 // It is a CJK environment
4531 /* name = */ p.getArg('{', '}');
4532 string const encoding = p.getArg('{', '}');
4533 /* mapping = */ p.getArg('{', '}');
4534 string const encoding_old = p.getEncoding();
4535 char const * const * const where =
4536 is_known(encoding, supported_CJK_encodings);
4538 p.setEncoding(encoding);
4540 p.setEncoding("utf8");
4541 string const text = p.verbatimEnvironment("CJK");
4542 p.setEncoding(encoding_old);
4545 // ignore contents in unknown CJK encoding
4548 // the language of the text
4550 supported_CJK_languages[where - supported_CJK_encodings];
4551 used[cjk] += text.length();
4553 LangMap::const_iterator use = used.begin();
4554 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4555 if (it->second > use->second)