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.
20 #include "FloatList.h"
24 #include "support/lstrings.h"
25 #include "support/convert.h"
26 #include "support/filetools.h"
38 using std::ostringstream;
39 using std::istringstream;
45 using support::addExtension;
46 using support::changeExtension;
47 using support::FileName;
48 using support::makeAbsPath;
49 using support::makeRelPath;
51 using support::suffixIs;
52 using support::contains;
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context)
59 Context newcontext(true, context.textclass);
60 newcontext.font = context.font;
61 parse_text(p, os, flags, outer, newcontext);
62 newcontext.check_end_layout(os);
68 /// parses a paragraph snippet, useful for example for \\emph{...}
69 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
72 Context newcontext(context);
73 // Don't inherit the extra stuff
74 newcontext.extra_stuff.clear();
75 parse_text(p, os, flags, outer, newcontext);
76 // Make sure that we don't create invalid .lyx files
77 context.need_layout = newcontext.need_layout;
78 context.need_end_layout = newcontext.need_end_layout;
83 * Thin wrapper around parse_text_snippet() using a string.
85 * We completely ignore \c context.need_layout and \c context.need_end_layout,
86 * because our return value is not used directly (otherwise the stream version
87 * of parse_text_snippet() could be used). That means that the caller needs
88 * to do layout management manually.
89 * This is intended to parse text that does not create any layout changes.
91 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
94 Context newcontext(context);
95 newcontext.need_layout = false;
96 newcontext.need_end_layout = false;
97 newcontext.new_layout_allowed = false;
98 // Avoid warning by Context::~Context()
99 newcontext.extra_stuff.clear();
101 parse_text_snippet(p, os, flags, outer, newcontext);
106 char const * const known_latex_commands[] = { "ref", "cite", "label",
107 "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
112 * We can't put these into known_latex_commands because the argument order
113 * is reversed in lyx if there are 2 arguments.
114 * The starred forms are also known.
116 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
117 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
118 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
122 * We can't put these into known_latex_commands because the argument order
123 * is reversed in lyx if there are 2 arguments.
124 * No starred form other than "cite*" known.
126 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
127 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
128 // jurabib commands not (yet) supported by LyX:
130 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
131 // "footciteauthor", "footciteyear", "footciteyearpar",
132 "citefield", "citetitle", "cite*", 0 };
134 /// LaTeX names for quotes
135 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
136 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
137 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
138 "guilsinglleft", "frq", "guilsinglright", 0};
140 /// the same as known_quotes with .lyx names
141 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
142 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
143 "gld", "grd", "gls", "ers", "fls",
144 "fls", "frs", "frs", 0};
146 /// LaTeX names for font sizes
147 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
148 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
150 /// the same as known_sizes with .lyx names
151 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
152 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
154 /// LaTeX 2.09 names for font families
155 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
157 /// LaTeX names for font families
158 char const * const known_font_families[] = { "rmfamily", "sffamily",
161 /// the same as known_old_font_families and known_font_families with .lyx names
162 char const * const known_coded_font_families[] = { "roman", "sans",
165 /// LaTeX 2.09 names for font series
166 char const * const known_old_font_series[] = { "bf", 0};
168 /// LaTeX names for font series
169 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
171 /// the same as known_old_font_series and known_font_series with .lyx names
172 char const * const known_coded_font_series[] = { "bold", "medium", 0};
174 /// LaTeX 2.09 names for font shapes
175 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
177 /// LaTeX names for font shapes
178 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
181 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
182 char const * const known_coded_font_shapes[] = { "italic", "slanted",
183 "smallcaps", "up", 0};
186 * Graphics file extensions known by the dvips driver of the graphics package.
187 * These extensions are used to complete the filename of an included
188 * graphics file if it does not contain an extension.
189 * The order must be the same that latex uses to find a file, because we
190 * will use the first extension that matches.
191 * This is only an approximation for the common cases. If we would want to
192 * do it right in all cases, we would need to know which graphics driver is
193 * used and know the extensions of every driver of the graphics package.
195 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
196 "ps.gz", "eps.Z", "ps.Z", 0};
199 * Graphics file extensions known by the pdftex driver of the graphics package.
200 * \sa known_dvips_graphics_formats
202 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
206 * Known file extensions for TeX files as used by \\include.
208 char const * const known_tex_extensions[] = {"tex", 0};
210 /// spaces known by InsetSpace
211 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
212 "qquad", "enspace", "enskip", "negthinspace", 0};
214 /// the same as known_spaces with .lyx names
215 char const * const known_coded_spaces[] = { "space{}", "space{}",
216 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
217 "negthinspace{}", 0};
220 /// splits "x=z, y=b" into a map
221 map<string, string> split_map(string const & s)
223 map<string, string> res;
226 for (size_t i = 0; i < v.size(); ++i) {
227 size_t const pos = v[i].find('=');
228 string const index = v[i].substr(0, pos);
229 string const value = v[i].substr(pos + 1, string::npos);
230 res[trim(index)] = trim(value);
237 * Split a LaTeX length into value and unit.
238 * The latter can be a real unit like "pt", or a latex length variable
239 * like "\textwidth". The unit may contain additional stuff like glue
240 * lengths, but we don't care, because such lengths are ERT anyway.
241 * \returns true if \p value and \p unit are valid.
243 bool splitLatexLength(string const & len, string & value, string & unit)
247 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
248 //'4,5' is a valid LaTeX length number. Change it to '4.5'
249 string const length = subst(len, ',', '.');
250 if (i == string::npos)
253 if (len[0] == '\\') {
254 // We had something like \textwidth without a factor
260 value = trim(string(length, 0, i));
264 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
265 if (contains(len, '\\'))
266 unit = trim(string(len, i));
268 unit = support::ascii_lowercase(trim(string(len, i)));
273 /// A simple function to translate a latex length to something lyx can
274 /// understand. Not perfect, but rather best-effort.
275 bool translate_len(string const & length, string & valstring, string & unit)
277 if (!splitLatexLength(length, valstring, unit))
279 // LyX uses percent values
281 istringstream iss(valstring);
286 string const percentval = oss.str();
288 if (unit.empty() || unit[0] != '\\')
290 string::size_type const i = unit.find(' ');
291 string const endlen = (i == string::npos) ? string() : string(unit, i);
292 if (unit == "\\textwidth") {
293 valstring = percentval;
294 unit = "text%" + endlen;
295 } else if (unit == "\\columnwidth") {
296 valstring = percentval;
297 unit = "col%" + endlen;
298 } else if (unit == "\\paperwidth") {
299 valstring = percentval;
300 unit = "page%" + endlen;
301 } else if (unit == "\\linewidth") {
302 valstring = percentval;
303 unit = "line%" + endlen;
304 } else if (unit == "\\paperheight") {
305 valstring = percentval;
306 unit = "pheight%" + endlen;
307 } else if (unit == "\\textheight") {
308 valstring = percentval;
309 unit = "theight%" + endlen;
317 string translate_len(string const & length)
321 if (translate_len(length, value, unit))
323 // If the input is invalid, return what we have.
331 * Translates a LaTeX length into \p value, \p unit and
332 * \p special parts suitable for a box inset.
333 * The difference from translate_len() is that a box inset knows about
334 * some special "units" that are stored in \p special.
336 void translate_box_len(string const & length, string & value, string & unit, string & special)
338 if (translate_len(length, value, unit)) {
339 if (unit == "\\height" || unit == "\\depth" ||
340 unit == "\\totalheight" || unit == "\\width") {
341 special = unit.substr(1);
342 // The unit is not used, but LyX requires a dummy setting
355 * Find a file with basename \p name in path \p path and an extension
358 string find_file(string const & name, string const & path,
359 char const * const * extensions)
361 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
363 for (char const * const * what = extensions; *what; ++what) {
364 string const trial = addExtension(name, *what);
365 if (makeAbsPath(trial, path).exists())
372 void begin_inset(ostream & os, string const & name)
374 os << "\n\\begin_inset " << name;
378 void end_inset(ostream & os)
380 os << "\n\\end_inset\n\n";
384 void skip_braces(Parser & p)
386 if (p.next_token().cat() != catBegin)
389 if (p.next_token().cat() == catEnd) {
397 void handle_ert(ostream & os, string const & s, Context & context)
399 // We must have a valid layout before outputting the ERT inset.
400 context.check_layout(os);
401 Context newcontext(true, context.textclass);
402 begin_inset(os, "ERT");
403 os << "\nstatus collapsed\n";
404 newcontext.check_layout(os);
405 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
407 os << "\n\\backslash\n";
408 else if (*it == '\n') {
409 newcontext.new_paragraph(os);
410 newcontext.check_layout(os);
414 newcontext.check_end_layout(os);
419 void handle_comment(ostream & os, string const & s, Context & context)
421 // TODO: Handle this better
422 Context newcontext(true, context.textclass);
423 begin_inset(os, "ERT");
424 os << "\nstatus collapsed\n";
425 newcontext.check_layout(os);
426 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
428 os << "\n\\backslash\n";
432 // make sure that our comment is the last thing on the line
433 newcontext.new_paragraph(os);
434 newcontext.check_layout(os);
435 newcontext.check_end_layout(os);
440 class isLayout : public std::unary_function<LayoutPtr, bool> {
442 isLayout(string const name) : name_(name) {}
443 bool operator()(LayoutPtr const & ptr) const {
444 return ptr->latexname() == name_;
451 LayoutPtr findLayout(TextClass const & textclass,
454 TextClass::const_iterator beg = textclass.begin();
455 TextClass::const_iterator end = textclass.end();
457 TextClass::const_iterator
458 it = std::find_if(beg, end, isLayout(name));
460 return (it == end) ? LayoutPtr() : *it;
464 void eat_whitespace(Parser &, ostream &, Context &, bool);
467 void output_command_layout(ostream & os, Parser & p, bool outer,
468 Context & parent_context,
471 parent_context.check_end_layout(os);
472 Context context(true, parent_context.textclass, newlayout,
473 parent_context.layout, parent_context.font);
474 if (parent_context.deeper_paragraph) {
475 // We are beginning a nested environment after a
476 // deeper paragraph inside the outer list environment.
477 // Therefore we don't need to output a "begin deeper".
478 context.need_end_deeper = true;
480 context.check_deeper(os);
481 context.check_layout(os);
482 if (context.layout->optionalargs > 0) {
483 eat_whitespace(p, os, context, false);
484 if (p.next_token().character() == '[') {
485 p.get_token(); // eat '['
486 begin_inset(os, "OptArg\n");
487 os << "status collapsed\n\n";
488 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
490 eat_whitespace(p, os, context, false);
493 parse_text(p, os, FLAG_ITEM, outer, context);
494 context.check_end_layout(os);
495 if (parent_context.deeper_paragraph) {
496 // We must suppress the "end deeper" because we
497 // suppressed the "begin deeper" above.
498 context.need_end_deeper = false;
500 context.check_end_deeper(os);
501 // We don't need really a new paragraph, but
502 // we must make sure that the next item gets a \begin_layout.
503 parent_context.new_paragraph(os);
508 * Output a space if necessary.
509 * This function gets called for every whitespace token.
511 * We have three cases here:
512 * 1. A space must be suppressed. Example: The lyxcode case below
513 * 2. A space may be suppressed. Example: Spaces before "\par"
514 * 3. A space must not be suppressed. Example: A space between two words
516 * We currently handle only 1. and 3 and from 2. only the case of
517 * spaces before newlines as a side effect.
519 * 2. could be used to suppress as many spaces as possible. This has two effects:
520 * - Reimporting LyX generated LaTeX files changes almost no whitespace
521 * - Superflous whitespace from non LyX generated LaTeX files is removed.
522 * The drawback is that the logic inside the function becomes
523 * complicated, and that is the reason why it is not implemented.
525 void check_space(Parser const & p, ostream & os, Context & context)
527 Token const next = p.next_token();
528 Token const curr = p.curr_token();
529 // A space before a single newline and vice versa must be ignored
530 // LyX emits a newline before \end{lyxcode}.
531 // This newline must be ignored,
532 // otherwise LyX will add an additional protected space.
533 if (next.cat() == catSpace ||
534 next.cat() == catNewline ||
535 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
538 context.check_layout(os);
544 * Parse all arguments of \p command
546 void parse_arguments(string const & command,
547 vector<ArgumentType> const & template_arguments,
548 Parser & p, ostream & os, bool outer, Context & context)
550 string ert = command;
551 size_t no_arguments = template_arguments.size();
552 for (size_t i = 0; i < no_arguments; ++i) {
553 switch (template_arguments[i]) {
555 // This argument contains regular LaTeX
556 handle_ert(os, ert + '{', context);
557 eat_whitespace(p, os, context, false);
558 parse_text(p, os, FLAG_ITEM, outer, context);
562 // This argument may contain special characters
563 ert += '{' + p.verbatim_item() + '}';
570 handle_ert(os, ert, context);
575 * Check whether \p command is a known command. If yes,
576 * handle the command with all arguments.
577 * \return true if the command was parsed, false otherwise.
579 bool parse_command(string const & command, Parser & p, ostream & os,
580 bool outer, Context & context)
582 if (known_commands.find(command) != known_commands.end()) {
583 parse_arguments(command, known_commands[command], p, os,
591 /// Parses a minipage or parbox
592 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
593 Context & parent_context, bool use_parbox)
597 // We need to set the height to the LaTeX default of 1\\totalheight
598 // for the case when no height argument is given
599 string height_value = "1";
600 string height_unit = "in";
601 string height_special = "totalheight";
603 if (p.next_token().asInput() == "[") {
604 position = p.getArg('[', ']');
605 if (position != "t" && position != "c" && position != "b") {
607 cerr << "invalid position for minipage/parbox" << endl;
609 if (p.next_token().asInput() == "[") {
610 latex_height = p.getArg('[', ']');
611 translate_box_len(latex_height, height_value, height_unit, height_special);
613 if (p.next_token().asInput() == "[") {
614 inner_pos = p.getArg('[', ']');
615 if (inner_pos != "c" && inner_pos != "t" &&
616 inner_pos != "b" && inner_pos != "s") {
617 inner_pos = position;
618 cerr << "invalid inner_pos for minipage/parbox"
626 string const latex_width = p.verbatim_item();
627 translate_len(latex_width, width_value, width_unit);
628 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
629 // LyX can't handle length variables
634 ss << "\\begin{minipage}";
635 if (!position.empty())
636 ss << '[' << position << ']';
637 if (!latex_height.empty())
638 ss << '[' << latex_height << ']';
639 if (!inner_pos.empty())
640 ss << '[' << inner_pos << ']';
641 ss << "{" << latex_width << "}";
644 handle_ert(os, ss.str(), parent_context);
645 parent_context.new_paragraph(os);
646 parse_text_in_inset(p, os, flags, outer, parent_context);
648 handle_ert(os, "}", parent_context);
650 handle_ert(os, "\\end{minipage}", parent_context);
652 // LyX does not like empty positions, so we have
653 // to set them to the LaTeX default values here.
654 if (position.empty())
656 if (inner_pos.empty())
657 inner_pos = position;
658 parent_context.check_layout(os);
659 begin_inset(os, "Box Frameless\n");
660 os << "position \"" << position << "\"\n";
661 os << "hor_pos \"c\"\n";
662 os << "has_inner_box 1\n";
663 os << "inner_pos \"" << inner_pos << "\"\n";
664 os << "use_parbox " << use_parbox << "\n";
665 os << "width \"" << width_value << width_unit << "\"\n";
666 os << "special \"none\"\n";
667 os << "height \"" << height_value << height_unit << "\"\n";
668 os << "height_special \"" << height_special << "\"\n";
669 os << "status open\n\n";
670 parse_text_in_inset(p, os, flags, outer, parent_context);
672 #ifdef PRESERVE_LAYOUT
673 // lyx puts a % after the end of the minipage
674 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
676 //handle_comment(os, "%dummy", parent_context);
679 parent_context.new_paragraph(os);
681 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
682 //handle_comment(os, "%dummy", parent_context);
685 // We add a protected space if something real follows
686 if (p.good() && p.next_token().cat() != catComment) {
687 os << "\\InsetSpace ~\n";
695 /// parse an unknown environment
696 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
697 unsigned flags, bool outer,
698 Context & parent_context)
700 if (name == "tabbing")
701 // We need to remember that we have to handle '\=' specially
702 flags |= FLAG_TABBING;
704 // We need to translate font changes and paragraphs inside the
705 // environment to ERT if we have a non standard font.
706 // Otherwise things like
707 // \large\begin{foo}\huge bar\end{foo}
709 bool const specialfont =
710 (parent_context.font != parent_context.normalfont);
711 bool const new_layout_allowed = parent_context.new_layout_allowed;
713 parent_context.new_layout_allowed = false;
714 handle_ert(os, "\\begin{" + name + "}", parent_context);
715 parse_text_snippet(p, os, flags, outer, parent_context);
716 handle_ert(os, "\\end{" + name + "}", parent_context);
718 parent_context.new_layout_allowed = new_layout_allowed;
722 void parse_environment(Parser & p, ostream & os, bool outer,
723 Context & parent_context)
726 string const name = p.getArg('{', '}');
727 const bool is_starred = suffixIs(name, '*');
728 string const unstarred_name = rtrim(name, "*");
729 active_environments.push_back(name);
731 if (is_math_env(name)) {
732 parent_context.check_layout(os);
733 begin_inset(os, "Formula ");
734 os << "\\begin{" << name << "}";
735 parse_math(p, os, FLAG_END, MATH_MODE);
736 os << "\\end{" << name << "}";
740 else if (name == "tabular" || name == "longtable") {
741 eat_whitespace(p, os, parent_context, false);
742 parent_context.check_layout(os);
743 begin_inset(os, "Tabular ");
744 handle_tabular(p, os, name == "longtable", parent_context);
749 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
750 eat_whitespace(p, os, parent_context, false);
751 parent_context.check_layout(os);
752 begin_inset(os, "Float " + unstarred_name + "\n");
753 if (p.next_token().asInput() == "[") {
754 os << "placement " << p.getArg('[', ']') << '\n';
756 os << "wide " << convert<string>(is_starred)
757 << "\nsideways false"
758 << "\nstatus open\n\n";
759 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
761 // We don't need really a new paragraph, but
762 // we must make sure that the next item gets a \begin_layout.
763 parent_context.new_paragraph(os);
767 else if (name == "minipage") {
768 eat_whitespace(p, os, parent_context, false);
769 parse_box(p, os, FLAG_END, outer, parent_context, false);
773 else if (name == "comment") {
774 eat_whitespace(p, os, parent_context, false);
775 parent_context.check_layout(os);
776 begin_inset(os, "Note Comment\n");
777 os << "status open\n";
778 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
783 else if (name == "lyxgreyedout") {
784 eat_whitespace(p, os, parent_context, false);
785 parent_context.check_layout(os);
786 begin_inset(os, "Note Greyedout\n");
787 os << "status open\n";
788 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
793 else if (name == "framed") {
794 eat_whitespace(p, os, parent_context, false);
795 parent_context.check_layout(os);
796 begin_inset(os, "Note Framed\n");
797 os << "status open\n";
798 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
803 else if (name == "shaded") {
804 eat_whitespace(p, os, parent_context, false);
805 parent_context.check_layout(os);
806 begin_inset(os, "Note Shaded\n");
807 os << "status open\n";
808 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
813 else if (!parent_context.new_layout_allowed)
814 parse_unknown_environment(p, name, os, FLAG_END, outer,
817 // Alignment settings
818 else if (name == "center" || name == "flushleft" || name == "flushright" ||
819 name == "centering" || name == "raggedright" || name == "raggedleft") {
820 eat_whitespace(p, os, parent_context, false);
821 // We must begin a new paragraph if not already done
822 if (! parent_context.atParagraphStart()) {
823 parent_context.check_end_layout(os);
824 parent_context.new_paragraph(os);
826 if (name == "flushleft" || name == "raggedright")
827 parent_context.add_extra_stuff("\\align left\n");
828 else if (name == "flushright" || name == "raggedleft")
829 parent_context.add_extra_stuff("\\align right\n");
831 parent_context.add_extra_stuff("\\align center\n");
832 parse_text(p, os, FLAG_END, outer, parent_context);
833 // Just in case the environment is empty ..
834 parent_context.extra_stuff.erase();
835 // We must begin a new paragraph to reset the alignment
836 parent_context.new_paragraph(os);
840 // The single '=' is meant here.
841 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
842 newlayout->isEnvironment()) {
843 eat_whitespace(p, os, parent_context, false);
844 Context context(true, parent_context.textclass, newlayout,
845 parent_context.layout, parent_context.font);
846 if (parent_context.deeper_paragraph) {
847 // We are beginning a nested environment after a
848 // deeper paragraph inside the outer list environment.
849 // Therefore we don't need to output a "begin deeper".
850 context.need_end_deeper = true;
852 parent_context.check_end_layout(os);
853 switch (context.layout->latextype) {
854 case LATEX_LIST_ENVIRONMENT:
855 context.extra_stuff = "\\labelwidthstring "
856 + p.verbatim_item() + '\n';
859 case LATEX_BIB_ENVIRONMENT:
860 p.verbatim_item(); // swallow next arg
866 context.check_deeper(os);
867 parse_text(p, os, FLAG_END, outer, context);
868 context.check_end_layout(os);
869 if (parent_context.deeper_paragraph) {
870 // We must suppress the "end deeper" because we
871 // suppressed the "begin deeper" above.
872 context.need_end_deeper = false;
874 context.check_end_deeper(os);
875 parent_context.new_paragraph(os);
879 else if (name == "appendix") {
880 // This is no good latex style, but it works and is used in some documents...
881 eat_whitespace(p, os, parent_context, false);
882 parent_context.check_end_layout(os);
883 Context context(true, parent_context.textclass, parent_context.layout,
884 parent_context.layout, parent_context.font);
885 context.check_layout(os);
886 os << "\\start_of_appendix\n";
887 parse_text(p, os, FLAG_END, outer, context);
888 context.check_end_layout(os);
892 else if (known_environments.find(name) != known_environments.end()) {
893 vector<ArgumentType> arguments = known_environments[name];
894 // The last "argument" denotes wether we may translate the
895 // environment contents to LyX
896 // The default required if no argument is given makes us
897 // compatible with the reLyXre environment.
898 ArgumentType contents = arguments.empty() ?
901 if (!arguments.empty())
902 arguments.pop_back();
903 // See comment in parse_unknown_environment()
904 bool const specialfont =
905 (parent_context.font != parent_context.normalfont);
906 bool const new_layout_allowed =
907 parent_context.new_layout_allowed;
909 parent_context.new_layout_allowed = false;
910 parse_arguments("\\begin{" + name + "}", arguments, p, os,
911 outer, parent_context);
912 if (contents == verbatim)
913 handle_ert(os, p.verbatimEnvironment(name),
916 parse_text_snippet(p, os, FLAG_END, outer,
918 handle_ert(os, "\\end{" + name + "}", parent_context);
920 parent_context.new_layout_allowed = new_layout_allowed;
924 parse_unknown_environment(p, name, os, FLAG_END, outer,
927 active_environments.pop_back();
931 /// parses a comment and outputs it to \p os.
932 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
934 BOOST_ASSERT(t.cat() == catComment);
935 if (!t.cs().empty()) {
936 context.check_layout(os);
937 handle_comment(os, '%' + t.cs(), context);
938 if (p.next_token().cat() == catNewline) {
939 // A newline after a comment line starts a new
941 if (context.new_layout_allowed) {
942 if(!context.atParagraphStart())
943 // Only start a new paragraph if not already
944 // done (we might get called recursively)
945 context.new_paragraph(os);
947 handle_ert(os, "\n", context);
948 eat_whitespace(p, os, context, true);
958 * Reads spaces and comments until the first non-space, non-comment token.
959 * New paragraphs (double newlines or \\par) are handled like simple spaces
960 * if \p eatParagraph is true.
961 * Spaces are skipped, but comments are written to \p os.
963 void eat_whitespace(Parser & p, ostream & os, Context & context,
967 Token const & t = p.get_token();
968 if (t.cat() == catComment)
969 parse_comment(p, os, t, context);
970 else if ((! eatParagraph && p.isParagraph()) ||
971 (t.cat() != catSpace && t.cat() != catNewline)) {
980 * Set a font attribute, parse text and reset the font attribute.
981 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
982 * \param currentvalue Current value of the attribute. Is set to the new
983 * value during parsing.
984 * \param newvalue New value of the attribute
986 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
987 Context & context, string const & attribute,
988 string & currentvalue, string const & newvalue)
990 context.check_layout(os);
991 string const oldvalue = currentvalue;
992 currentvalue = newvalue;
993 os << '\n' << attribute << ' ' << newvalue << "\n";
994 parse_text_snippet(p, os, flags, outer, context);
995 context.check_layout(os);
996 os << '\n' << attribute << ' ' << oldvalue << "\n";
997 currentvalue = oldvalue;
1001 /// get the arguments of a natbib or jurabib citation command
1002 void get_cite_arguments(Parser & p, bool natbibOrder,
1003 string & before, string & after)
1005 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1007 // text before the citation
1009 // text after the citation
1010 after = p.getFullOpt();
1012 if (!after.empty()) {
1013 before = p.getFullOpt();
1014 if (natbibOrder && !before.empty())
1015 std::swap(before, after);
1020 /// Convert filenames with TeX macros and/or quotes to something LyX
1022 string const normalize_filename(string const & name)
1024 Parser p(trim(name, "\""));
1027 Token const & t = p.get_token();
1028 if (t.cat() != catEscape)
1030 else if (t.cs() == "lyxdot") {
1031 // This is used by LyX for simple dots in relative
1035 } else if (t.cs() == "space") {
1045 /// Convert \p name from TeX convention (relative to master file) to LyX
1046 /// convention (relative to .lyx file) if it is relative
1047 void fix_relative_filename(string & name)
1049 if (lyx::support::absolutePath(name))
1051 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1053 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1054 from_utf8(getParentFilePath())));
1058 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1059 void parse_noweb(Parser & p, ostream & os, Context & context)
1061 // assemble the rest of the keyword
1065 Token const & t = p.get_token();
1066 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1069 scrap = (p.good() && p.next_token().asInput() == "=");
1071 name += p.get_token().asInput();
1074 name += t.asInput();
1077 if (!scrap || !context.new_layout_allowed ||
1078 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1079 cerr << "Warning: Could not interpret '" << name
1080 << "'. Ignoring it." << endl;
1084 // We use new_paragraph instead of check_end_layout because the stuff
1085 // following the noweb chunk needs to start with a \begin_layout.
1086 // This may create a new paragraph even if there was none in the
1087 // noweb file, but the alternative is an invalid LyX file. Since
1088 // noweb code chunks are implemented with a layout style in LyX they
1089 // always must be in an own paragraph.
1090 context.new_paragraph(os);
1091 Context newcontext(true, context.textclass,
1092 context.textclass[from_ascii("Scrap")]);
1093 newcontext.check_layout(os);
1096 Token const & t = p.get_token();
1097 // We abuse the parser a bit, because this is no TeX syntax
1099 if (t.cat() == catEscape)
1100 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1102 os << subst(t.asInput(), "\n", "\n\\newline\n");
1103 // The scrap chunk is ended by an @ at the beginning of a line.
1104 // After the @ the line may contain a comment and/or
1105 // whitespace, but nothing else.
1106 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1107 (p.next_token().cat() == catSpace ||
1108 p.next_token().cat() == catNewline ||
1109 p.next_token().cat() == catComment)) {
1110 while (p.good() && p.next_token().cat() == catSpace)
1111 os << p.get_token().asInput();
1112 if (p.next_token().cat() == catComment)
1113 // The comment includes a final '\n'
1114 os << p.get_token().asInput();
1116 if (p.next_token().cat() == catNewline)
1123 newcontext.check_end_layout(os);
1126 } // anonymous namespace
1129 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1132 LayoutPtr newlayout;
1133 // store the current selectlanguage to be used after \foreignlanguage
1135 // Store the latest bibliographystyle (needed for bibtex inset)
1136 string bibliographystyle;
1137 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1138 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1140 Token const & t = p.get_token();
1143 cerr << "t: " << t << " flags: " << flags << "\n";
1146 if (flags & FLAG_ITEM) {
1147 if (t.cat() == catSpace)
1150 flags &= ~FLAG_ITEM;
1151 if (t.cat() == catBegin) {
1152 // skip the brace and collect everything to the next matching
1154 flags |= FLAG_BRACE_LAST;
1158 // handle only this single token, leave the loop if done
1159 flags |= FLAG_LEAVE;
1162 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1168 if (t.cat() == catMath) {
1169 // we are inside some text mode thingy, so opening new math is allowed
1170 context.check_layout(os);
1171 begin_inset(os, "Formula ");
1172 Token const & n = p.get_token();
1173 if (n.cat() == catMath && outer) {
1174 // TeX's $$...$$ syntax for displayed math
1176 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1178 p.get_token(); // skip the second '$' token
1180 // simple $...$ stuff
1183 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1189 else if (t.cat() == catSuper || t.cat() == catSub)
1190 cerr << "catcode " << t << " illegal in text mode\n";
1192 // Basic support for english quotes. This should be
1193 // extended to other quotes, but is not so easy (a
1194 // left english quote is the same as a right german
1196 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1197 context.check_layout(os);
1198 begin_inset(os, "Quotes ");
1204 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1205 context.check_layout(os);
1206 begin_inset(os, "Quotes ");
1213 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1214 context.check_layout(os);
1215 begin_inset(os, "Quotes ");
1222 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1223 context.check_layout(os);
1224 begin_inset(os, "Quotes ");
1231 else if (t.asInput() == "<"
1232 && p.next_token().asInput() == "<" && noweb_mode) {
1234 parse_noweb(p, os, context);
1237 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1238 check_space(p, os, context);
1240 else if (t.character() == '[' && noweb_mode &&
1241 p.next_token().character() == '[') {
1242 // These can contain underscores
1244 string const s = p.getFullOpt() + ']';
1245 if (p.next_token().character() == ']')
1248 cerr << "Warning: Inserting missing ']' in '"
1249 << s << "'." << endl;
1250 handle_ert(os, s, context);
1253 else if (t.cat() == catLetter ||
1254 t.cat() == catOther ||
1255 t.cat() == catAlign ||
1256 t.cat() == catParameter) {
1257 // This translates "&" to "\\&" which may be wrong...
1258 context.check_layout(os);
1259 os << t.character();
1262 else if (p.isParagraph()) {
1263 if (context.new_layout_allowed)
1264 context.new_paragraph(os);
1266 handle_ert(os, "\\par ", context);
1267 eat_whitespace(p, os, context, true);
1270 else if (t.cat() == catActive) {
1271 context.check_layout(os);
1272 if (t.character() == '~') {
1273 if (context.layout->free_spacing)
1276 os << "\\InsetSpace ~\n";
1278 os << t.character();
1281 else if (t.cat() == catBegin &&
1282 p.next_token().cat() == catEnd) {
1284 Token const prev = p.prev_token();
1286 if (p.next_token().character() == '`' ||
1287 (prev.character() == '-' &&
1288 p.next_token().character() == '-'))
1289 ; // ignore it in {}`` or -{}-
1291 handle_ert(os, "{}", context);
1295 else if (t.cat() == catBegin) {
1296 context.check_layout(os);
1297 // special handling of font attribute changes
1298 Token const prev = p.prev_token();
1299 Token const next = p.next_token();
1300 TeXFont const oldFont = context.font;
1301 if (next.character() == '[' ||
1302 next.character() == ']' ||
1303 next.character() == '*') {
1305 if (p.next_token().cat() == catEnd) {
1306 os << next.character();
1310 handle_ert(os, "{", context);
1311 parse_text_snippet(p, os,
1314 handle_ert(os, "}", context);
1316 } else if (! context.new_layout_allowed) {
1317 handle_ert(os, "{", context);
1318 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1320 handle_ert(os, "}", context);
1321 } else if (is_known(next.cs(), known_sizes)) {
1322 // next will change the size, so we must
1324 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1326 if (!context.atParagraphStart())
1328 << context.font.size << "\n";
1329 } else if (is_known(next.cs(), known_font_families)) {
1330 // next will change the font family, so we
1331 // must reset it here
1332 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1334 if (!context.atParagraphStart())
1336 << context.font.family << "\n";
1337 } else if (is_known(next.cs(), known_font_series)) {
1338 // next will change the font series, so we
1339 // must reset it here
1340 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1342 if (!context.atParagraphStart())
1344 << context.font.series << "\n";
1345 } else if (is_known(next.cs(), known_font_shapes)) {
1346 // next will change the font shape, so we
1347 // must reset it here
1348 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1350 if (!context.atParagraphStart())
1352 << context.font.shape << "\n";
1353 } else if (is_known(next.cs(), known_old_font_families) ||
1354 is_known(next.cs(), known_old_font_series) ||
1355 is_known(next.cs(), known_old_font_shapes)) {
1356 // next will change the font family, series
1357 // and shape, so we must reset it here
1358 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1360 if (!context.atParagraphStart())
1362 << context.font.family
1364 << context.font.series
1366 << context.font.shape << "\n";
1368 handle_ert(os, "{", context);
1369 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1371 handle_ert(os, "}", context);
1375 else if (t.cat() == catEnd) {
1376 if (flags & FLAG_BRACE_LAST) {
1379 cerr << "stray '}' in text\n";
1380 handle_ert(os, "}", context);
1383 else if (t.cat() == catComment)
1384 parse_comment(p, os, t, context);
1387 // control sequences
1390 else if (t.cs() == "(") {
1391 context.check_layout(os);
1392 begin_inset(os, "Formula");
1394 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1399 else if (t.cs() == "[") {
1400 context.check_layout(os);
1401 begin_inset(os, "Formula");
1403 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1408 else if (t.cs() == "begin")
1409 parse_environment(p, os, outer, context);
1411 else if (t.cs() == "end") {
1412 if (flags & FLAG_END) {
1413 // eat environment name
1414 string const name = p.getArg('{', '}');
1415 if (name != active_environment())
1416 cerr << "\\end{" + name + "} does not match \\begin{"
1417 + active_environment() + "}\n";
1420 p.error("found 'end' unexpectedly");
1423 else if (t.cs() == "item") {
1426 bool optarg = false;
1427 if (p.next_token().character() == '[') {
1428 p.get_token(); // eat '['
1429 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1434 context.check_layout(os);
1435 if (context.has_item) {
1436 // An item in an unknown list-like environment
1437 // FIXME: Do this in check_layout()!
1438 context.has_item = false;
1440 handle_ert(os, "\\item", context);
1442 handle_ert(os, "\\item ", context);
1445 if (context.layout->labeltype != LABEL_MANUAL) {
1446 // lyx does not support \item[\mybullet]
1447 // in itemize environments
1448 handle_ert(os, "[", context);
1450 handle_ert(os, "]", context);
1451 } else if (!s.empty()) {
1452 // The space is needed to separate the
1453 // item from the rest of the sentence.
1455 eat_whitespace(p, os, context, false);
1460 else if (t.cs() == "bibitem") {
1462 context.check_layout(os);
1465 os << '{' << p.verbatim_item() << '}' << "\n";
1468 else if (t.cs() == "def") {
1469 context.check_layout(os);
1470 eat_whitespace(p, os, context, false);
1471 string name = p.get_token().cs();
1472 eat_whitespace(p, os, context, false);
1478 while (p.next_token().cat() != catBegin) {
1479 if (p.next_token().cat() == catParameter) {
1484 // followed by number?
1485 if (p.next_token().cat() == catOther) {
1486 char c = p.getChar();
1488 // number = current arity + 1?
1489 if (c == arity + '0' + 1)
1494 paramtext += p.get_token().asString();
1496 paramtext += p.get_token().asString();
1501 // only output simple (i.e. compatible) macro as FormulaMacros
1502 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1504 context.check_layout(os);
1505 begin_inset(os, "FormulaMacro");
1509 handle_ert(os, ert, context);
1512 else if (t.cs() == "noindent") {
1514 context.add_extra_stuff("\\noindent\n");
1517 else if (t.cs() == "appendix") {
1518 context.add_extra_stuff("\\start_of_appendix\n");
1519 // We need to start a new paragraph. Otherwise the
1520 // appendix in 'bla\appendix\chapter{' would start
1522 context.new_paragraph(os);
1523 // We need to make sure that the paragraph is
1524 // generated even if it is empty. Otherwise the
1525 // appendix in '\par\appendix\par\chapter{' would
1527 context.check_layout(os);
1528 // FIXME: This is a hack to prevent paragraph
1529 // deletion if it is empty. Handle this better!
1531 "%dummy comment inserted by tex2lyx to "
1532 "ensure that this paragraph is not empty",
1534 // Both measures above may generate an additional
1535 // empty paragraph, but that does not hurt, because
1536 // whitespace does not matter here.
1537 eat_whitespace(p, os, context, true);
1540 // Must attempt to parse "Section*" before "Section".
1541 else if ((p.next_token().asInput() == "*") &&
1542 context.new_layout_allowed &&
1543 // The single '=' is meant here.
1544 (newlayout = findLayout(context.textclass,
1545 t.cs() + '*')).get() &&
1546 newlayout->isCommand()) {
1548 output_command_layout(os, p, outer, context, newlayout);
1552 // The single '=' is meant here.
1553 else if (context.new_layout_allowed &&
1554 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1555 newlayout->isCommand()) {
1556 output_command_layout(os, p, outer, context, newlayout);
1560 // Special handling for \caption
1561 // FIXME: remove this when InsetCaption is supported.
1562 else if (context.new_layout_allowed &&
1563 t.cs() == captionlayout->latexname()) {
1564 output_command_layout(os, p, outer, context,
1569 else if (t.cs() == "includegraphics") {
1570 bool const clip = p.next_token().asInput() == "*";
1573 map<string, string> opts = split_map(p.getArg('[', ']'));
1575 opts["clip"] = string();
1576 string name = normalize_filename(p.verbatim_item());
1578 string const path = getMasterFilePath();
1579 // We want to preserve relative / absolute filenames,
1580 // therefore path is only used for testing
1581 // FIXME UNICODE encoding of name and path may be
1582 // wrong (makeAbsPath expects utf8)
1583 if (!makeAbsPath(name, path).exists()) {
1584 // The file extension is probably missing.
1585 // Now try to find it out.
1586 string const dvips_name =
1587 find_file(name, path,
1588 known_dvips_graphics_formats);
1589 string const pdftex_name =
1590 find_file(name, path,
1591 known_pdftex_graphics_formats);
1592 if (!dvips_name.empty()) {
1593 if (!pdftex_name.empty()) {
1594 cerr << "This file contains the "
1596 "\"\\includegraphics{"
1598 "However, files\n\""
1599 << dvips_name << "\" and\n\""
1600 << pdftex_name << "\"\n"
1601 "both exist, so I had to make a "
1602 "choice and took the first one.\n"
1603 "Please move the unwanted one "
1604 "someplace else and try again\n"
1605 "if my choice was wrong."
1609 } else if (!pdftex_name.empty())
1613 // FIXME UNICODE encoding of name and path may be
1614 // wrong (makeAbsPath expects utf8)
1615 if (makeAbsPath(name, path).exists())
1616 fix_relative_filename(name);
1618 cerr << "Warning: Could not find graphics file '"
1619 << name << "'." << endl;
1621 context.check_layout(os);
1622 begin_inset(os, "Graphics ");
1623 os << "\n\tfilename " << name << '\n';
1624 if (opts.find("width") != opts.end())
1626 << translate_len(opts["width"]) << '\n';
1627 if (opts.find("height") != opts.end())
1629 << translate_len(opts["height"]) << '\n';
1630 if (opts.find("scale") != opts.end()) {
1631 istringstream iss(opts["scale"]);
1635 os << "\tscale " << val << '\n';
1637 if (opts.find("angle") != opts.end())
1638 os << "\trotateAngle "
1639 << opts["angle"] << '\n';
1640 if (opts.find("origin") != opts.end()) {
1642 string const opt = opts["origin"];
1643 if (opt.find('l') != string::npos) ss << "left";
1644 if (opt.find('r') != string::npos) ss << "right";
1645 if (opt.find('c') != string::npos) ss << "center";
1646 if (opt.find('t') != string::npos) ss << "Top";
1647 if (opt.find('b') != string::npos) ss << "Bottom";
1648 if (opt.find('B') != string::npos) ss << "Baseline";
1649 if (!ss.str().empty())
1650 os << "\trotateOrigin " << ss.str() << '\n';
1652 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1654 if (opts.find("keepaspectratio") != opts.end())
1655 os << "\tkeepAspectRatio\n";
1656 if (opts.find("clip") != opts.end())
1658 if (opts.find("draft") != opts.end())
1660 if (opts.find("bb") != opts.end())
1661 os << "\tBoundingBox "
1662 << opts["bb"] << '\n';
1663 int numberOfbbOptions = 0;
1664 if (opts.find("bbllx") != opts.end())
1665 numberOfbbOptions++;
1666 if (opts.find("bblly") != opts.end())
1667 numberOfbbOptions++;
1668 if (opts.find("bburx") != opts.end())
1669 numberOfbbOptions++;
1670 if (opts.find("bbury") != opts.end())
1671 numberOfbbOptions++;
1672 if (numberOfbbOptions == 4)
1673 os << "\tBoundingBox "
1674 << opts["bbllx"] << " " << opts["bblly"] << " "
1675 << opts["bburx"] << " " << opts["bbury"] << '\n';
1676 else if (numberOfbbOptions > 0)
1677 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1678 numberOfbbOptions = 0;
1679 if (opts.find("natwidth") != opts.end())
1680 numberOfbbOptions++;
1681 if (opts.find("natheight") != opts.end())
1682 numberOfbbOptions++;
1683 if (numberOfbbOptions == 2)
1684 os << "\tBoundingBox 0bp 0bp "
1685 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1686 else if (numberOfbbOptions > 0)
1687 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1688 ostringstream special;
1689 if (opts.find("hiresbb") != opts.end())
1690 special << "hiresbb,";
1691 if (opts.find("trim") != opts.end())
1693 if (opts.find("viewport") != opts.end())
1694 special << "viewport=" << opts["viewport"] << ',';
1695 if (opts.find("totalheight") != opts.end())
1696 special << "totalheight=" << opts["totalheight"] << ',';
1697 if (opts.find("type") != opts.end())
1698 special << "type=" << opts["type"] << ',';
1699 if (opts.find("ext") != opts.end())
1700 special << "ext=" << opts["ext"] << ',';
1701 if (opts.find("read") != opts.end())
1702 special << "read=" << opts["read"] << ',';
1703 if (opts.find("command") != opts.end())
1704 special << "command=" << opts["command"] << ',';
1705 string s_special = special.str();
1706 if (!s_special.empty()) {
1707 // We had special arguments. Remove the trailing ','.
1708 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1710 // TODO: Handle the unknown settings better.
1711 // Warn about invalid options.
1712 // Check whether some option was given twice.
1716 else if (t.cs() == "footnote" ||
1717 (t.cs() == "thanks" && context.layout->intitle)) {
1719 context.check_layout(os);
1720 begin_inset(os, "Foot\n");
1721 os << "status collapsed\n\n";
1722 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1726 else if (t.cs() == "marginpar") {
1728 context.check_layout(os);
1729 begin_inset(os, "Marginal\n");
1730 os << "status collapsed\n\n";
1731 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1735 else if (t.cs() == "ensuremath") {
1737 context.check_layout(os);
1738 string const s = p.verbatim_item();
1739 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1742 handle_ert(os, "\\ensuremath{" + s + "}",
1746 else if (t.cs() == "hfill") {
1747 context.check_layout(os);
1748 os << "\n\\hfill\n";
1753 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1754 // FIXME: Somehow prevent title layouts if
1755 // "maketitle" was not found
1757 skip_braces(p); // swallow this
1760 else if (t.cs() == "tableofcontents") {
1762 context.check_layout(os);
1763 begin_inset(os, "LatexCommand \\tableofcontents\n");
1765 skip_braces(p); // swallow this
1768 else if (t.cs() == "listoffigures") {
1770 context.check_layout(os);
1771 begin_inset(os, "FloatList figure\n");
1773 skip_braces(p); // swallow this
1776 else if (t.cs() == "listoftables") {
1778 context.check_layout(os);
1779 begin_inset(os, "FloatList table\n");
1781 skip_braces(p); // swallow this
1784 else if (t.cs() == "listof") {
1785 p.skip_spaces(true);
1786 string const name = p.get_token().asString();
1787 if (context.textclass.floats().typeExist(name)) {
1788 context.check_layout(os);
1789 begin_inset(os, "FloatList ");
1792 p.get_token(); // swallow second arg
1794 handle_ert(os, "\\listof{" + name + "}", context);
1797 else if (t.cs() == "textrm")
1798 parse_text_attributes(p, os, FLAG_ITEM, outer,
1799 context, "\\family",
1800 context.font.family, "roman");
1802 else if (t.cs() == "textsf")
1803 parse_text_attributes(p, os, FLAG_ITEM, outer,
1804 context, "\\family",
1805 context.font.family, "sans");
1807 else if (t.cs() == "texttt")
1808 parse_text_attributes(p, os, FLAG_ITEM, outer,
1809 context, "\\family",
1810 context.font.family, "typewriter");
1812 else if (t.cs() == "textmd")
1813 parse_text_attributes(p, os, FLAG_ITEM, outer,
1814 context, "\\series",
1815 context.font.series, "medium");
1817 else if (t.cs() == "textbf")
1818 parse_text_attributes(p, os, FLAG_ITEM, outer,
1819 context, "\\series",
1820 context.font.series, "bold");
1822 else if (t.cs() == "textup")
1823 parse_text_attributes(p, os, FLAG_ITEM, outer,
1825 context.font.shape, "up");
1827 else if (t.cs() == "textit")
1828 parse_text_attributes(p, os, FLAG_ITEM, outer,
1830 context.font.shape, "italic");
1832 else if (t.cs() == "textsl")
1833 parse_text_attributes(p, os, FLAG_ITEM, outer,
1835 context.font.shape, "slanted");
1837 else if (t.cs() == "textsc")
1838 parse_text_attributes(p, os, FLAG_ITEM, outer,
1840 context.font.shape, "smallcaps");
1842 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1843 context.check_layout(os);
1844 TeXFont oldFont = context.font;
1845 context.font.init();
1846 context.font.size = oldFont.size;
1847 os << "\n\\family " << context.font.family << "\n";
1848 os << "\n\\series " << context.font.series << "\n";
1849 os << "\n\\shape " << context.font.shape << "\n";
1850 if (t.cs() == "textnormal") {
1851 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1852 output_font_change(os, context.font, oldFont);
1853 context.font = oldFont;
1855 eat_whitespace(p, os, context, false);
1858 else if (t.cs() == "underbar") {
1859 // Do NOT handle \underline.
1860 // \underbar cuts through y, g, q, p etc.,
1861 // \underline does not.
1862 context.check_layout(os);
1863 os << "\n\\bar under\n";
1864 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1865 context.check_layout(os);
1866 os << "\n\\bar default\n";
1869 else if (t.cs() == "emph" || t.cs() == "noun") {
1870 context.check_layout(os);
1871 os << "\n\\" << t.cs() << " on\n";
1872 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1873 context.check_layout(os);
1874 os << "\n\\" << t.cs() << " default\n";
1877 else if (use_natbib &&
1878 is_known(t.cs(), known_natbib_commands) &&
1879 ((t.cs() != "citefullauthor" &&
1880 t.cs() != "citeyear" &&
1881 t.cs() != "citeyearpar") ||
1882 p.next_token().asInput() != "*")) {
1883 context.check_layout(os);
1885 // \citet[before][after]{a} \citet[after][before]{a}
1886 // \citet[before][]{a} \citet[][before]{a}
1887 // \citet[after]{a} \citet[after]{a}
1888 // \citet{a} \citet{a}
1889 string command = '\\' + t.cs();
1890 if (p.next_token().asInput() == "*") {
1894 if (command == "\\citefullauthor")
1895 // alternative name for "\\citeauthor*"
1896 command = "\\citeauthor*";
1898 // text before the citation
1900 // text after the citation
1902 get_cite_arguments(p, true, before, after);
1904 if (command == "\\cite") {
1905 // \cite without optional argument means
1906 // \citet, \cite with at least one optional
1907 // argument means \citep.
1908 if (before.empty() && after.empty())
1909 command = "\\citet";
1911 command = "\\citep";
1913 if (before.empty() && after == "[]")
1914 // avoid \citet[]{a}
1916 else if (before == "[]" && after == "[]") {
1917 // avoid \citet[][]{a}
1921 begin_inset(os, "LatexCommand ");
1922 os << command << after << before
1923 << '{' << p.verbatim_item() << "}\n";
1927 else if (use_jurabib &&
1928 is_known(t.cs(), known_jurabib_commands)) {
1929 context.check_layout(os);
1930 string const command = '\\' + t.cs();
1931 char argumentOrder = '\0';
1932 vector<string> const & options = used_packages["jurabib"];
1933 if (std::find(options.begin(), options.end(),
1934 "natbiborder") != options.end())
1935 argumentOrder = 'n';
1936 else if (std::find(options.begin(), options.end(),
1937 "jurabiborder") != options.end())
1938 argumentOrder = 'j';
1940 // text before the citation
1942 // text after the citation
1944 get_cite_arguments(p, argumentOrder != 'j', before, after);
1946 string const citation = p.verbatim_item();
1947 if (!before.empty() && argumentOrder == '\0') {
1948 cerr << "Warning: Assuming argument order "
1949 "of jurabib version 0.6 for\n'"
1950 << command << before << after << '{'
1951 << citation << "}'.\n"
1952 "Add 'jurabiborder' to the jurabib "
1953 "package options if you used an\n"
1954 "earlier jurabib version." << endl;
1956 begin_inset(os, "LatexCommand ");
1957 os << command << after << before
1958 << '{' << citation << "}\n";
1962 else if (is_known(t.cs(), known_latex_commands)) {
1963 // This needs to be after the check for natbib and
1964 // jurabib commands, because "cite" has different
1965 // arguments with natbib and jurabib.
1966 context.check_layout(os);
1967 begin_inset(os, "LatexCommand ");
1968 os << '\\' << t.cs();
1969 // lyx cannot handle newlines in a latex command
1970 // FIXME: Move the substitution into parser::getOpt()?
1971 os << subst(p.getOpt(), "\n", " ");
1972 os << subst(p.getOpt(), "\n", " ");
1973 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1977 else if (is_known(t.cs(), known_quotes)) {
1978 char const * const * where = is_known(t.cs(), known_quotes);
1979 context.check_layout(os);
1980 begin_inset(os, "Quotes ");
1981 os << known_coded_quotes[where - known_quotes];
1983 // LyX adds {} after the quote, so we have to eat
1984 // spaces here if there are any before a possible
1986 eat_whitespace(p, os, context, false);
1990 else if (is_known(t.cs(), known_sizes) &&
1991 context.new_layout_allowed) {
1992 char const * const * where = is_known(t.cs(), known_sizes);
1993 context.check_layout(os);
1994 TeXFont const oldFont = context.font;
1995 context.font.size = known_coded_sizes[where - known_sizes];
1996 output_font_change(os, oldFont, context.font);
1997 eat_whitespace(p, os, context, false);
2000 else if (is_known(t.cs(), known_font_families) &&
2001 context.new_layout_allowed) {
2002 char const * const * where =
2003 is_known(t.cs(), known_font_families);
2004 context.check_layout(os);
2005 TeXFont const oldFont = context.font;
2006 context.font.family =
2007 known_coded_font_families[where - known_font_families];
2008 output_font_change(os, oldFont, context.font);
2009 eat_whitespace(p, os, context, false);
2012 else if (is_known(t.cs(), known_font_series) &&
2013 context.new_layout_allowed) {
2014 char const * const * where =
2015 is_known(t.cs(), known_font_series);
2016 context.check_layout(os);
2017 TeXFont const oldFont = context.font;
2018 context.font.series =
2019 known_coded_font_series[where - known_font_series];
2020 output_font_change(os, oldFont, context.font);
2021 eat_whitespace(p, os, context, false);
2024 else if (is_known(t.cs(), known_font_shapes) &&
2025 context.new_layout_allowed) {
2026 char const * const * where =
2027 is_known(t.cs(), known_font_shapes);
2028 context.check_layout(os);
2029 TeXFont const oldFont = context.font;
2030 context.font.shape =
2031 known_coded_font_shapes[where - known_font_shapes];
2032 output_font_change(os, oldFont, context.font);
2033 eat_whitespace(p, os, context, false);
2035 else if (is_known(t.cs(), known_old_font_families) &&
2036 context.new_layout_allowed) {
2037 char const * const * where =
2038 is_known(t.cs(), known_old_font_families);
2039 context.check_layout(os);
2040 TeXFont const oldFont = context.font;
2041 context.font.init();
2042 context.font.size = oldFont.size;
2043 context.font.family =
2044 known_coded_font_families[where - known_old_font_families];
2045 output_font_change(os, oldFont, context.font);
2046 eat_whitespace(p, os, context, false);
2049 else if (is_known(t.cs(), known_old_font_series) &&
2050 context.new_layout_allowed) {
2051 char const * const * where =
2052 is_known(t.cs(), known_old_font_series);
2053 context.check_layout(os);
2054 TeXFont const oldFont = context.font;
2055 context.font.init();
2056 context.font.size = oldFont.size;
2057 context.font.series =
2058 known_coded_font_series[where - known_old_font_series];
2059 output_font_change(os, oldFont, context.font);
2060 eat_whitespace(p, os, context, false);
2063 else if (is_known(t.cs(), known_old_font_shapes) &&
2064 context.new_layout_allowed) {
2065 char const * const * where =
2066 is_known(t.cs(), known_old_font_shapes);
2067 context.check_layout(os);
2068 TeXFont const oldFont = context.font;
2069 context.font.init();
2070 context.font.size = oldFont.size;
2071 context.font.shape =
2072 known_coded_font_shapes[where - known_old_font_shapes];
2073 output_font_change(os, oldFont, context.font);
2074 eat_whitespace(p, os, context, false);
2077 else if (t.cs() == "selectlanguage") {
2078 context.check_layout(os);
2079 // save the language for the case that a \foreignlanguage is used
2080 selectlang = subst(p.verbatim_item(), "\n", " ");
2081 os << "\\lang " << selectlang << "\n";
2085 else if (t.cs() == "foreignlanguage") {
2086 context.check_layout(os);
2087 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2088 os << subst(p.verbatim_item(), "\n", " ");
2089 // set back to last selectlanguage
2090 os << "\n\\lang " << selectlang << "\n";
2093 else if (t.cs() == "inputencoding")
2094 // write nothing because this is done by LyX using the "\lang"
2095 // information given by selectlanguage and foreignlanguage
2096 subst(p.verbatim_item(), "\n", " ");
2098 else if (t.cs() == "LyX" || t.cs() == "TeX"
2099 || t.cs() == "LaTeX") {
2100 context.check_layout(os);
2102 skip_braces(p); // eat {}
2105 else if (t.cs() == "LaTeXe") {
2106 context.check_layout(os);
2108 skip_braces(p); // eat {}
2111 else if (t.cs() == "ldots") {
2112 context.check_layout(os);
2114 os << "\\SpecialChar \\ldots{}\n";
2117 else if (t.cs() == "lyxarrow") {
2118 context.check_layout(os);
2119 os << "\\SpecialChar \\menuseparator\n";
2123 else if (t.cs() == "textcompwordmark") {
2124 context.check_layout(os);
2125 os << "\\SpecialChar \\textcompwordmark{}\n";
2129 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2130 context.check_layout(os);
2131 os << "\\SpecialChar \\@.\n";
2135 else if (t.cs() == "-") {
2136 context.check_layout(os);
2137 os << "\\SpecialChar \\-\n";
2140 else if (t.cs() == "textasciitilde") {
2141 context.check_layout(os);
2146 else if (t.cs() == "textasciicircum") {
2147 context.check_layout(os);
2152 else if (t.cs() == "textbackslash") {
2153 context.check_layout(os);
2154 os << "\n\\backslash\n";
2158 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2159 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2161 context.check_layout(os);
2165 else if (t.cs() == "char") {
2166 context.check_layout(os);
2167 if (p.next_token().character() == '`') {
2169 if (p.next_token().cs() == "\"") {
2174 handle_ert(os, "\\char`", context);
2177 handle_ert(os, "\\char", context);
2181 else if (t.cs() == "verb") {
2182 context.check_layout(os);
2183 char const delimiter = p.next_token().character();
2184 string const arg = p.getArg(delimiter, delimiter);
2186 oss << "\\verb" << delimiter << arg << delimiter;
2187 handle_ert(os, oss.str(), context);
2190 else if (t.cs() == "\"") {
2191 context.check_layout(os);
2192 string const name = p.verbatim_item();
2193 if (name == "a") os << '\xe4';
2194 else if (name == "o") os << '\xf6';
2195 else if (name == "u") os << '\xfc';
2196 else if (name == "A") os << '\xc4';
2197 else if (name == "O") os << '\xd6';
2198 else if (name == "U") os << '\xdc';
2199 else handle_ert(os, "\"{" + name + "}", context);
2202 // Problem: \= creates a tabstop inside the tabbing environment
2203 // and else an accent. In the latter case we really would want
2204 // \={o} instead of \= o.
2205 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2206 handle_ert(os, t.asInput(), context);
2208 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2209 || t.cs() == "'" || t.cs() == "`"
2210 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2211 // we need the trim as the LyX parser chokes on such spaces
2212 // The argument of InsetLatexAccent is parsed as a
2213 // subset of LaTeX, so don't parse anything here,
2214 // but use the raw argument.
2215 // Otherwise we would convert \~{\i} wrongly.
2216 // This will of course not translate \~{\ss} to \~{ß},
2217 // but that does at least compile and does only look
2218 // strange on screen.
2219 context.check_layout(os);
2220 os << "\\i \\" << t.cs() << "{"
2221 << trim(p.verbatim_item(), " ")
2225 else if (t.cs() == "ss") {
2226 context.check_layout(os);
2228 skip_braces(p); // eat {}
2231 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2233 context.check_layout(os);
2234 os << "\\i \\" << t.cs() << "{}\n";
2235 skip_braces(p); // eat {}
2238 else if (t.cs() == "\\") {
2239 context.check_layout(os);
2240 string const next = p.next_token().asInput();
2242 handle_ert(os, "\\\\" + p.getOpt(), context);
2243 else if (next == "*") {
2245 handle_ert(os, "\\\\*" + p.getOpt(), context);
2248 os << "\n\\newline\n";
2252 else if (t.cs() == "newline" ||
2253 t.cs() == "linebreak") {
2254 context.check_layout(os);
2255 os << "\n\\" << t.cs() << "\n";
2256 skip_braces(p); // eat {}
2259 else if (t.cs() == "href") {
2260 context.check_layout(os);
2261 begin_inset(os, "CommandInset ");
2262 os << t.cs() << "\n";
2263 os << "LatexCommand " << t.cs() << "\n";
2266 // the first argument is "type:target", "type:" is optional
2267 // the second argument the name
2268 string href_target = subst(p.verbatim_item(), "\n", " ");
2269 string href_name = subst(p.verbatim_item(), "\n", " ");
2271 // serach for the ":" to divide type from target
2272 if ((pos = href_target.find(":", 0)) != string::npos){
2273 href_type = href_target;
2274 href_type.erase(pos + 1, href_type.length());
2275 href_target.erase(0, pos + 1);
2278 os << "name " << '"' << href_name << '"' << "\n";
2279 os << "target " << '"' << href_target << '"' << "\n";
2281 os << "type " << '"' << href_type << '"' << "\n";
2285 else if (t.cs() == "input" || t.cs() == "include"
2286 || t.cs() == "verbatiminput") {
2287 string name = '\\' + t.cs();
2288 if (t.cs() == "verbatiminput"
2289 && p.next_token().asInput() == "*")
2290 name += p.get_token().asInput();
2291 context.check_layout(os);
2292 begin_inset(os, "Include ");
2293 string filename(normalize_filename(p.getArg('{', '}')));
2294 string const path = getMasterFilePath();
2295 // We want to preserve relative / absolute filenames,
2296 // therefore path is only used for testing
2297 // FIXME UNICODE encoding of filename and path may be
2298 // wrong (makeAbsPath expects utf8)
2299 if ((t.cs() == "include" || t.cs() == "input") &&
2300 !makeAbsPath(filename, path).exists()) {
2301 // The file extension is probably missing.
2302 // Now try to find it out.
2303 string const tex_name =
2304 find_file(filename, path,
2305 known_tex_extensions);
2306 if (!tex_name.empty())
2307 filename = tex_name;
2309 // FIXME UNICODE encoding of filename and path may be
2310 // wrong (makeAbsPath expects utf8)
2311 if (makeAbsPath(filename, path).exists()) {
2312 string const abstexname =
2313 makeAbsPath(filename, path).absFilename();
2314 string const abslyxname =
2315 changeExtension(abstexname, ".lyx");
2316 fix_relative_filename(filename);
2317 string const lyxname =
2318 changeExtension(filename, ".lyx");
2319 if (t.cs() != "verbatiminput" &&
2320 tex2lyx(abstexname, FileName(abslyxname))) {
2321 os << name << '{' << lyxname << "}\n";
2323 os << name << '{' << filename << "}\n";
2326 cerr << "Warning: Could not find included file '"
2327 << filename << "'." << endl;
2328 os << name << '{' << filename << "}\n";
2330 os << "preview false\n";
2334 else if (t.cs() == "bibliographystyle") {
2335 // store new bibliographystyle
2336 bibliographystyle = p.verbatim_item();
2337 // output new bibliographystyle.
2338 // This is only necessary if used in some other macro than \bibliography.
2339 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2342 else if (t.cs() == "bibliography") {
2343 context.check_layout(os);
2344 begin_inset(os, "LatexCommand ");
2346 // Do we have a bibliographystyle set?
2347 if (!bibliographystyle.empty()) {
2348 os << '[' << bibliographystyle << ']';
2350 os << '{' << p.verbatim_item() << "}\n";
2354 else if (t.cs() == "parbox")
2355 parse_box(p, os, FLAG_ITEM, outer, context, true);
2357 else if (t.cs() == "smallskip" ||
2358 t.cs() == "medskip" ||
2359 t.cs() == "bigskip" ||
2360 t.cs() == "vfill") {
2361 context.check_layout(os);
2362 begin_inset(os, "VSpace ");
2368 else if (is_known(t.cs(), known_spaces)) {
2369 char const * const * where = is_known(t.cs(), known_spaces);
2370 context.check_layout(os);
2371 begin_inset(os, "InsetSpace ");
2372 os << '\\' << known_coded_spaces[where - known_spaces]
2374 // LaTeX swallows whitespace after all spaces except
2375 // "\\,". We have to do that here, too, because LyX
2376 // adds "{}" which would make the spaces significant.
2378 eat_whitespace(p, os, context, false);
2379 // LyX adds "{}" after all spaces except "\\ " and
2380 // "\\,", so we have to remove "{}".
2381 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2382 // remove the braces after "\\,", too.
2387 else if (t.cs() == "newpage" ||
2388 t.cs() == "pagebreak" ||
2389 t.cs() == "clearpage" ||
2390 t.cs() == "cleardoublepage") {
2391 context.check_layout(os);
2392 os << "\n\\" << t.cs() << "\n";
2393 skip_braces(p); // eat {}
2396 else if (t.cs() == "newcommand" ||
2397 t.cs() == "providecommand" ||
2398 t.cs() == "renewcommand") {
2399 // these could be handled by parse_command(), but
2400 // we need to call add_known_command() here.
2401 string name = t.asInput();
2402 if (p.next_token().asInput() == "*") {
2403 // Starred form. Eat '*'
2407 string const command = p.verbatim_item();
2408 string const opt1 = p.getOpt();
2409 string const opt2 = p.getFullOpt();
2410 add_known_command(command, opt1, !opt2.empty());
2411 string const ert = name + '{' + command + '}' +
2413 '{' + p.verbatim_item() + '}';
2415 context.check_layout(os);
2416 begin_inset(os, "FormulaMacro");
2421 else if (t.cs() == "vspace") {
2422 bool starred = false;
2423 if (p.next_token().asInput() == "*") {
2427 string const length = p.verbatim_item();
2430 bool valid = splitLatexLength(length, valstring, unit);
2431 bool known_vspace = false;
2432 bool known_unit = false;
2435 istringstream iss(valstring);
2438 if (unit == "\\smallskipamount") {
2440 known_vspace = true;
2441 } else if (unit == "\\medskipamount") {
2443 known_vspace = true;
2444 } else if (unit == "\\bigskipamount") {
2446 known_vspace = true;
2447 } else if (unit == "\\fill") {
2449 known_vspace = true;
2452 if (!known_vspace) {
2453 switch (unitFromString(unit)) {
2474 if (known_unit || known_vspace) {
2475 // Literal length or known variable
2476 context.check_layout(os);
2477 begin_inset(os, "VSpace ");
2485 // LyX can't handle other length variables in Inset VSpace
2486 string name = t.asInput();
2491 handle_ert(os, name + '{' + unit + '}', context);
2492 else if (value == -1.0)
2493 handle_ert(os, name + "{-" + unit + '}', context);
2495 handle_ert(os, name + '{' + valstring + unit + '}', context);
2497 handle_ert(os, name + '{' + length + '}', context);
2502 //cerr << "#: " << t << " mode: " << mode << endl;
2503 // heuristic: read up to next non-nested space
2505 string s = t.asInput();
2506 string z = p.verbatim_item();
2507 while (p.good() && z != " " && z.size()) {
2508 //cerr << "read: " << z << endl;
2510 z = p.verbatim_item();
2512 cerr << "found ERT: " << s << endl;
2513 handle_ert(os, s + ' ', context);
2515 string name = t.asInput();
2516 if (p.next_token().asInput() == "*") {
2517 // Starred commands like \vspace*{}
2518 p.get_token(); // Eat '*'
2521 if (! parse_command(name, p, os, outer, context))
2522 handle_ert(os, name, context);
2525 if (flags & FLAG_LEAVE) {
2526 flags &= ~FLAG_LEAVE;