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"
34 using namespace lyx::support;
39 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
40 Context const & context)
42 Context newcontext(true, context.textclass);
43 newcontext.font = context.font;
44 parse_text(p, os, flags, outer, newcontext);
45 newcontext.check_end_layout(os);
51 /// parses a paragraph snippet, useful for example for \\emph{...}
52 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
55 Context newcontext(context);
56 // Don't inherit the extra stuff
57 newcontext.extra_stuff.clear();
58 parse_text(p, os, flags, outer, newcontext);
59 // Make sure that we don't create invalid .lyx files
60 context.need_layout = newcontext.need_layout;
61 context.need_end_layout = newcontext.need_end_layout;
66 * Thin wrapper around parse_text_snippet() using a string.
68 * We completely ignore \c context.need_layout and \c context.need_end_layout,
69 * because our return value is not used directly (otherwise the stream version
70 * of parse_text_snippet() could be used). That means that the caller needs
71 * to do layout management manually.
72 * This is intended to parse text that does not create any layout changes.
74 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
77 Context newcontext(context);
78 newcontext.need_layout = false;
79 newcontext.need_end_layout = false;
80 newcontext.new_layout_allowed = false;
81 // Avoid warning by Context::~Context()
82 newcontext.extra_stuff.clear();
84 parse_text_snippet(p, os, flags, outer, newcontext);
89 char const * const known_latex_commands[] = { "ref", "cite", "label",
90 "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
95 * We can't put these into known_latex_commands because the argument order
96 * is reversed in lyx if there are 2 arguments.
97 * The starred forms are also known.
99 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
100 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
101 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
105 * We can't put these into known_latex_commands because the argument order
106 * is reversed in lyx if there are 2 arguments.
107 * No starred form other than "cite*" known.
109 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
110 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
111 // jurabib commands not (yet) supported by LyX:
113 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
114 // "footciteauthor", "footciteyear", "footciteyearpar",
115 "citefield", "citetitle", "cite*", 0 };
117 /// LaTeX names for quotes
118 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
119 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
120 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
121 "guilsinglleft", "frq", "guilsinglright", 0};
123 /// the same as known_quotes with .lyx names
124 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
125 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
126 "gld", "grd", "gls", "ers", "fls",
127 "fls", "frs", "frs", 0};
129 /// LaTeX names for font sizes
130 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
131 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
133 /// the same as known_sizes with .lyx names
134 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
135 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
137 /// LaTeX 2.09 names for font families
138 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
140 /// LaTeX names for font families
141 char const * const known_font_families[] = { "rmfamily", "sffamily",
144 /// the same as known_old_font_families and known_font_families with .lyx names
145 char const * const known_coded_font_families[] = { "roman", "sans",
148 /// LaTeX 2.09 names for font series
149 char const * const known_old_font_series[] = { "bf", 0};
151 /// LaTeX names for font series
152 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
154 /// the same as known_old_font_series and known_font_series with .lyx names
155 char const * const known_coded_font_series[] = { "bold", "medium", 0};
157 /// LaTeX 2.09 names for font shapes
158 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
160 /// LaTeX names for font shapes
161 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
164 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
165 char const * const known_coded_font_shapes[] = { "italic", "slanted",
166 "smallcaps", "up", 0};
169 * Graphics file extensions known by the dvips driver of the graphics package.
170 * These extensions are used to complete the filename of an included
171 * graphics file if it does not contain an extension.
172 * The order must be the same that latex uses to find a file, because we
173 * will use the first extension that matches.
174 * This is only an approximation for the common cases. If we would want to
175 * do it right in all cases, we would need to know which graphics driver is
176 * used and know the extensions of every driver of the graphics package.
178 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
179 "ps.gz", "eps.Z", "ps.Z", 0};
182 * Graphics file extensions known by the pdftex driver of the graphics package.
183 * \sa known_dvips_graphics_formats
185 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
189 * Known file extensions for TeX files as used by \\include.
191 char const * const known_tex_extensions[] = {"tex", 0};
193 /// spaces known by InsetSpace
194 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
195 "qquad", "enspace", "enskip", "negthinspace", 0};
197 /// the same as known_spaces with .lyx names
198 char const * const known_coded_spaces[] = { "space{}", "space{}",
199 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
200 "negthinspace{}", 0};
203 /// splits "x=z, y=b" into a map
204 map<string, string> split_map(string const & s)
206 map<string, string> res;
209 for (size_t i = 0; i < v.size(); ++i) {
210 size_t const pos = v[i].find('=');
211 string const index = v[i].substr(0, pos);
212 string const value = v[i].substr(pos + 1, string::npos);
213 res[trim(index)] = trim(value);
220 * Split a LaTeX length into value and unit.
221 * The latter can be a real unit like "pt", or a latex length variable
222 * like "\textwidth". The unit may contain additional stuff like glue
223 * lengths, but we don't care, because such lengths are ERT anyway.
224 * \returns true if \p value and \p unit are valid.
226 bool splitLatexLength(string const & len, string & value, string & unit)
230 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
231 //'4,5' is a valid LaTeX length number. Change it to '4.5'
232 string const length = subst(len, ',', '.');
233 if (i == string::npos)
236 if (len[0] == '\\') {
237 // We had something like \textwidth without a factor
243 value = trim(string(length, 0, i));
247 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
248 if (contains(len, '\\'))
249 unit = trim(string(len, i));
251 unit = ascii_lowercase(trim(string(len, i)));
256 /// A simple function to translate a latex length to something lyx can
257 /// understand. Not perfect, but rather best-effort.
258 bool translate_len(string const & length, string & valstring, string & unit)
260 if (!splitLatexLength(length, valstring, unit))
262 // LyX uses percent values
264 istringstream iss(valstring);
269 string const percentval = oss.str();
271 if (unit.empty() || unit[0] != '\\')
273 string::size_type const i = unit.find(' ');
274 string const endlen = (i == string::npos) ? string() : string(unit, i);
275 if (unit == "\\textwidth") {
276 valstring = percentval;
277 unit = "text%" + endlen;
278 } else if (unit == "\\columnwidth") {
279 valstring = percentval;
280 unit = "col%" + endlen;
281 } else if (unit == "\\paperwidth") {
282 valstring = percentval;
283 unit = "page%" + endlen;
284 } else if (unit == "\\linewidth") {
285 valstring = percentval;
286 unit = "line%" + endlen;
287 } else if (unit == "\\paperheight") {
288 valstring = percentval;
289 unit = "pheight%" + endlen;
290 } else if (unit == "\\textheight") {
291 valstring = percentval;
292 unit = "theight%" + endlen;
300 string translate_len(string const & length)
304 if (translate_len(length, value, unit))
306 // If the input is invalid, return what we have.
314 * Translates a LaTeX length into \p value, \p unit and
315 * \p special parts suitable for a box inset.
316 * The difference from translate_len() is that a box inset knows about
317 * some special "units" that are stored in \p special.
319 void translate_box_len(string const & length, string & value, string & unit, string & special)
321 if (translate_len(length, value, unit)) {
322 if (unit == "\\height" || unit == "\\depth" ||
323 unit == "\\totalheight" || unit == "\\width") {
324 special = unit.substr(1);
325 // The unit is not used, but LyX requires a dummy setting
338 * Find a file with basename \p name in path \p path and an extension
341 string find_file(string const & name, string const & path,
342 char const * const * extensions)
344 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
346 for (char const * const * what = extensions; *what; ++what) {
347 string const trial = addExtension(name, *what);
348 if (makeAbsPath(trial, path).exists())
355 void begin_inset(ostream & os, string const & name)
357 os << "\n\\begin_inset " << name;
361 void end_inset(ostream & os)
363 os << "\n\\end_inset\n\n";
367 void skip_braces(Parser & p)
369 if (p.next_token().cat() != catBegin)
372 if (p.next_token().cat() == catEnd) {
380 void handle_ert(ostream & os, string const & s, Context & context)
382 // We must have a valid layout before outputting the ERT inset.
383 context.check_layout(os);
384 Context newcontext(true, context.textclass);
385 begin_inset(os, "ERT");
386 os << "\nstatus collapsed\n";
387 newcontext.check_layout(os);
388 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
390 os << "\n\\backslash\n";
391 else if (*it == '\n') {
392 newcontext.new_paragraph(os);
393 newcontext.check_layout(os);
397 newcontext.check_end_layout(os);
402 void handle_comment(ostream & os, string const & s, Context & context)
404 // TODO: Handle this better
405 Context newcontext(true, context.textclass);
406 begin_inset(os, "ERT");
407 os << "\nstatus collapsed\n";
408 newcontext.check_layout(os);
409 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
411 os << "\n\\backslash\n";
415 // make sure that our comment is the last thing on the line
416 newcontext.new_paragraph(os);
417 newcontext.check_layout(os);
418 newcontext.check_end_layout(os);
423 class isLayout : public unary_function<LayoutPtr, bool> {
425 isLayout(string const name) : name_(name) {}
426 bool operator()(LayoutPtr const & ptr) const {
427 return ptr->latexname() == name_;
434 LayoutPtr findLayout(TextClass const & textclass,
437 TextClass::const_iterator beg = textclass.begin();
438 TextClass::const_iterator end = textclass.end();
440 TextClass::const_iterator
441 it = find_if(beg, end, isLayout(name));
443 return (it == end) ? LayoutPtr() : *it;
447 void eat_whitespace(Parser &, ostream &, Context &, bool);
450 void output_command_layout(ostream & os, Parser & p, bool outer,
451 Context & parent_context,
454 parent_context.check_end_layout(os);
455 Context context(true, parent_context.textclass, newlayout,
456 parent_context.layout, parent_context.font);
457 if (parent_context.deeper_paragraph) {
458 // We are beginning a nested environment after a
459 // deeper paragraph inside the outer list environment.
460 // Therefore we don't need to output a "begin deeper".
461 context.need_end_deeper = true;
463 context.check_deeper(os);
464 context.check_layout(os);
465 if (context.layout->optionalargs > 0) {
466 eat_whitespace(p, os, context, false);
467 if (p.next_token().character() == '[') {
468 p.get_token(); // eat '['
469 begin_inset(os, "OptArg\n");
470 os << "status collapsed\n\n";
471 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
473 eat_whitespace(p, os, context, false);
476 parse_text(p, os, FLAG_ITEM, outer, context);
477 context.check_end_layout(os);
478 if (parent_context.deeper_paragraph) {
479 // We must suppress the "end deeper" because we
480 // suppressed the "begin deeper" above.
481 context.need_end_deeper = false;
483 context.check_end_deeper(os);
484 // We don't need really a new paragraph, but
485 // we must make sure that the next item gets a \begin_layout.
486 parent_context.new_paragraph(os);
491 * Output a space if necessary.
492 * This function gets called for every whitespace token.
494 * We have three cases here:
495 * 1. A space must be suppressed. Example: The lyxcode case below
496 * 2. A space may be suppressed. Example: Spaces before "\par"
497 * 3. A space must not be suppressed. Example: A space between two words
499 * We currently handle only 1. and 3 and from 2. only the case of
500 * spaces before newlines as a side effect.
502 * 2. could be used to suppress as many spaces as possible. This has two effects:
503 * - Reimporting LyX generated LaTeX files changes almost no whitespace
504 * - Superflous whitespace from non LyX generated LaTeX files is removed.
505 * The drawback is that the logic inside the function becomes
506 * complicated, and that is the reason why it is not implemented.
508 void check_space(Parser const & p, ostream & os, Context & context)
510 Token const next = p.next_token();
511 Token const curr = p.curr_token();
512 // A space before a single newline and vice versa must be ignored
513 // LyX emits a newline before \end{lyxcode}.
514 // This newline must be ignored,
515 // otherwise LyX will add an additional protected space.
516 if (next.cat() == catSpace ||
517 next.cat() == catNewline ||
518 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
521 context.check_layout(os);
527 * Parse all arguments of \p command
529 void parse_arguments(string const & command,
530 vector<ArgumentType> const & template_arguments,
531 Parser & p, ostream & os, bool outer, Context & context)
533 string ert = command;
534 size_t no_arguments = template_arguments.size();
535 for (size_t i = 0; i < no_arguments; ++i) {
536 switch (template_arguments[i]) {
538 // This argument contains regular LaTeX
539 handle_ert(os, ert + '{', context);
540 eat_whitespace(p, os, context, false);
541 parse_text(p, os, FLAG_ITEM, outer, context);
545 // This argument may contain special characters
546 ert += '{' + p.verbatim_item() + '}';
553 handle_ert(os, ert, context);
558 * Check whether \p command is a known command. If yes,
559 * handle the command with all arguments.
560 * \return true if the command was parsed, false otherwise.
562 bool parse_command(string const & command, Parser & p, ostream & os,
563 bool outer, Context & context)
565 if (known_commands.find(command) != known_commands.end()) {
566 parse_arguments(command, known_commands[command], p, os,
574 /// Parses a minipage or parbox
575 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
576 Context & parent_context, bool use_parbox)
580 // We need to set the height to the LaTeX default of 1\\totalheight
581 // for the case when no height argument is given
582 string height_value = "1";
583 string height_unit = "in";
584 string height_special = "totalheight";
586 if (p.next_token().asInput() == "[") {
587 position = p.getArg('[', ']');
588 if (position != "t" && position != "c" && position != "b") {
590 cerr << "invalid position for minipage/parbox" << endl;
592 if (p.next_token().asInput() == "[") {
593 latex_height = p.getArg('[', ']');
594 translate_box_len(latex_height, height_value, height_unit, height_special);
596 if (p.next_token().asInput() == "[") {
597 inner_pos = p.getArg('[', ']');
598 if (inner_pos != "c" && inner_pos != "t" &&
599 inner_pos != "b" && inner_pos != "s") {
600 inner_pos = position;
601 cerr << "invalid inner_pos for minipage/parbox"
609 string const latex_width = p.verbatim_item();
610 translate_len(latex_width, width_value, width_unit);
611 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
612 // LyX can't handle length variables
617 ss << "\\begin{minipage}";
618 if (!position.empty())
619 ss << '[' << position << ']';
620 if (!latex_height.empty())
621 ss << '[' << latex_height << ']';
622 if (!inner_pos.empty())
623 ss << '[' << inner_pos << ']';
624 ss << "{" << latex_width << "}";
627 handle_ert(os, ss.str(), parent_context);
628 parent_context.new_paragraph(os);
629 parse_text_in_inset(p, os, flags, outer, parent_context);
631 handle_ert(os, "}", parent_context);
633 handle_ert(os, "\\end{minipage}", parent_context);
635 // LyX does not like empty positions, so we have
636 // to set them to the LaTeX default values here.
637 if (position.empty())
639 if (inner_pos.empty())
640 inner_pos = position;
641 parent_context.check_layout(os);
642 begin_inset(os, "Box Frameless\n");
643 os << "position \"" << position << "\"\n";
644 os << "hor_pos \"c\"\n";
645 os << "has_inner_box 1\n";
646 os << "inner_pos \"" << inner_pos << "\"\n";
647 os << "use_parbox " << use_parbox << "\n";
648 os << "width \"" << width_value << width_unit << "\"\n";
649 os << "special \"none\"\n";
650 os << "height \"" << height_value << height_unit << "\"\n";
651 os << "height_special \"" << height_special << "\"\n";
652 os << "status open\n\n";
653 parse_text_in_inset(p, os, flags, outer, parent_context);
655 #ifdef PRESERVE_LAYOUT
656 // lyx puts a % after the end of the minipage
657 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
659 //handle_comment(os, "%dummy", parent_context);
662 parent_context.new_paragraph(os);
664 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
665 //handle_comment(os, "%dummy", parent_context);
668 // We add a protected space if something real follows
669 if (p.good() && p.next_token().cat() != catComment) {
670 os << "\\InsetSpace ~\n";
678 /// parse an unknown environment
679 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
680 unsigned flags, bool outer,
681 Context & parent_context)
683 if (name == "tabbing")
684 // We need to remember that we have to handle '\=' specially
685 flags |= FLAG_TABBING;
687 // We need to translate font changes and paragraphs inside the
688 // environment to ERT if we have a non standard font.
689 // Otherwise things like
690 // \large\begin{foo}\huge bar\end{foo}
692 bool const specialfont =
693 (parent_context.font != parent_context.normalfont);
694 bool const new_layout_allowed = parent_context.new_layout_allowed;
696 parent_context.new_layout_allowed = false;
697 handle_ert(os, "\\begin{" + name + "}", parent_context);
698 parse_text_snippet(p, os, flags, outer, parent_context);
699 handle_ert(os, "\\end{" + name + "}", parent_context);
701 parent_context.new_layout_allowed = new_layout_allowed;
705 void parse_environment(Parser & p, ostream & os, bool outer,
706 Context & parent_context)
709 string const name = p.getArg('{', '}');
710 const bool is_starred = suffixIs(name, '*');
711 string const unstarred_name = rtrim(name, "*");
712 active_environments.push_back(name);
714 if (is_math_env(name)) {
715 parent_context.check_layout(os);
716 begin_inset(os, "Formula ");
717 os << "\\begin{" << name << "}";
718 parse_math(p, os, FLAG_END, MATH_MODE);
719 os << "\\end{" << name << "}";
723 else if (name == "tabular" || name == "longtable") {
724 eat_whitespace(p, os, parent_context, false);
725 parent_context.check_layout(os);
726 begin_inset(os, "Tabular ");
727 handle_tabular(p, os, name == "longtable", parent_context);
732 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
733 eat_whitespace(p, os, parent_context, false);
734 parent_context.check_layout(os);
735 begin_inset(os, "Float " + unstarred_name + "\n");
736 if (p.next_token().asInput() == "[") {
737 os << "placement " << p.getArg('[', ']') << '\n';
739 os << "wide " << convert<string>(is_starred)
740 << "\nsideways false"
741 << "\nstatus open\n\n";
742 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
744 // We don't need really a new paragraph, but
745 // we must make sure that the next item gets a \begin_layout.
746 parent_context.new_paragraph(os);
750 else if (name == "minipage") {
751 eat_whitespace(p, os, parent_context, false);
752 parse_box(p, os, FLAG_END, outer, parent_context, false);
756 else if (name == "comment") {
757 eat_whitespace(p, os, parent_context, false);
758 parent_context.check_layout(os);
759 begin_inset(os, "Note Comment\n");
760 os << "status open\n";
761 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
766 else if (name == "lyxgreyedout") {
767 eat_whitespace(p, os, parent_context, false);
768 parent_context.check_layout(os);
769 begin_inset(os, "Note Greyedout\n");
770 os << "status open\n";
771 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
776 else if (name == "framed") {
777 eat_whitespace(p, os, parent_context, false);
778 parent_context.check_layout(os);
779 begin_inset(os, "Note Framed\n");
780 os << "status open\n";
781 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
786 else if (name == "shaded") {
787 eat_whitespace(p, os, parent_context, false);
788 parent_context.check_layout(os);
789 begin_inset(os, "Note Shaded\n");
790 os << "status open\n";
791 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
796 else if (!parent_context.new_layout_allowed)
797 parse_unknown_environment(p, name, os, FLAG_END, outer,
800 // Alignment settings
801 else if (name == "center" || name == "flushleft" || name == "flushright" ||
802 name == "centering" || name == "raggedright" || name == "raggedleft") {
803 eat_whitespace(p, os, parent_context, false);
804 // We must begin a new paragraph if not already done
805 if (! parent_context.atParagraphStart()) {
806 parent_context.check_end_layout(os);
807 parent_context.new_paragraph(os);
809 if (name == "flushleft" || name == "raggedright")
810 parent_context.add_extra_stuff("\\align left\n");
811 else if (name == "flushright" || name == "raggedleft")
812 parent_context.add_extra_stuff("\\align right\n");
814 parent_context.add_extra_stuff("\\align center\n");
815 parse_text(p, os, FLAG_END, outer, parent_context);
816 // Just in case the environment is empty ..
817 parent_context.extra_stuff.erase();
818 // We must begin a new paragraph to reset the alignment
819 parent_context.new_paragraph(os);
823 // The single '=' is meant here.
824 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
825 newlayout->isEnvironment()) {
826 eat_whitespace(p, os, parent_context, false);
827 Context context(true, parent_context.textclass, newlayout,
828 parent_context.layout, parent_context.font);
829 if (parent_context.deeper_paragraph) {
830 // We are beginning a nested environment after a
831 // deeper paragraph inside the outer list environment.
832 // Therefore we don't need to output a "begin deeper".
833 context.need_end_deeper = true;
835 parent_context.check_end_layout(os);
836 switch (context.layout->latextype) {
837 case LATEX_LIST_ENVIRONMENT:
838 context.extra_stuff = "\\labelwidthstring "
839 + p.verbatim_item() + '\n';
842 case LATEX_BIB_ENVIRONMENT:
843 p.verbatim_item(); // swallow next arg
849 context.check_deeper(os);
850 parse_text(p, os, FLAG_END, outer, context);
851 context.check_end_layout(os);
852 if (parent_context.deeper_paragraph) {
853 // We must suppress the "end deeper" because we
854 // suppressed the "begin deeper" above.
855 context.need_end_deeper = false;
857 context.check_end_deeper(os);
858 parent_context.new_paragraph(os);
862 else if (name == "appendix") {
863 // This is no good latex style, but it works and is used in some documents...
864 eat_whitespace(p, os, parent_context, false);
865 parent_context.check_end_layout(os);
866 Context context(true, parent_context.textclass, parent_context.layout,
867 parent_context.layout, parent_context.font);
868 context.check_layout(os);
869 os << "\\start_of_appendix\n";
870 parse_text(p, os, FLAG_END, outer, context);
871 context.check_end_layout(os);
875 else if (known_environments.find(name) != known_environments.end()) {
876 vector<ArgumentType> arguments = known_environments[name];
877 // The last "argument" denotes wether we may translate the
878 // environment contents to LyX
879 // The default required if no argument is given makes us
880 // compatible with the reLyXre environment.
881 ArgumentType contents = arguments.empty() ?
884 if (!arguments.empty())
885 arguments.pop_back();
886 // See comment in parse_unknown_environment()
887 bool const specialfont =
888 (parent_context.font != parent_context.normalfont);
889 bool const new_layout_allowed =
890 parent_context.new_layout_allowed;
892 parent_context.new_layout_allowed = false;
893 parse_arguments("\\begin{" + name + "}", arguments, p, os,
894 outer, parent_context);
895 if (contents == verbatim)
896 handle_ert(os, p.verbatimEnvironment(name),
899 parse_text_snippet(p, os, FLAG_END, outer,
901 handle_ert(os, "\\end{" + name + "}", parent_context);
903 parent_context.new_layout_allowed = new_layout_allowed;
907 parse_unknown_environment(p, name, os, FLAG_END, outer,
910 active_environments.pop_back();
914 /// parses a comment and outputs it to \p os.
915 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
917 BOOST_ASSERT(t.cat() == catComment);
918 if (!t.cs().empty()) {
919 context.check_layout(os);
920 handle_comment(os, '%' + t.cs(), context);
921 if (p.next_token().cat() == catNewline) {
922 // A newline after a comment line starts a new
924 if (context.new_layout_allowed) {
925 if(!context.atParagraphStart())
926 // Only start a new paragraph if not already
927 // done (we might get called recursively)
928 context.new_paragraph(os);
930 handle_ert(os, "\n", context);
931 eat_whitespace(p, os, context, true);
941 * Reads spaces and comments until the first non-space, non-comment token.
942 * New paragraphs (double newlines or \\par) are handled like simple spaces
943 * if \p eatParagraph is true.
944 * Spaces are skipped, but comments are written to \p os.
946 void eat_whitespace(Parser & p, ostream & os, Context & context,
950 Token const & t = p.get_token();
951 if (t.cat() == catComment)
952 parse_comment(p, os, t, context);
953 else if ((! eatParagraph && p.isParagraph()) ||
954 (t.cat() != catSpace && t.cat() != catNewline)) {
963 * Set a font attribute, parse text and reset the font attribute.
964 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
965 * \param currentvalue Current value of the attribute. Is set to the new
966 * value during parsing.
967 * \param newvalue New value of the attribute
969 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
970 Context & context, string const & attribute,
971 string & currentvalue, string const & newvalue)
973 context.check_layout(os);
974 string const oldvalue = currentvalue;
975 currentvalue = newvalue;
976 os << '\n' << attribute << ' ' << newvalue << "\n";
977 parse_text_snippet(p, os, flags, outer, context);
978 context.check_layout(os);
979 os << '\n' << attribute << ' ' << oldvalue << "\n";
980 currentvalue = oldvalue;
984 /// get the arguments of a natbib or jurabib citation command
985 void get_cite_arguments(Parser & p, bool natbibOrder,
986 string & before, string & after)
988 // We need to distinguish "" and "[]", so we can't use p.getOpt().
990 // text before the citation
992 // text after the citation
993 after = p.getFullOpt();
995 if (!after.empty()) {
996 before = p.getFullOpt();
997 if (natbibOrder && !before.empty())
1003 /// Convert filenames with TeX macros and/or quotes to something LyX
1005 string const normalize_filename(string const & name)
1007 Parser p(trim(name, "\""));
1010 Token const & t = p.get_token();
1011 if (t.cat() != catEscape)
1013 else if (t.cs() == "lyxdot") {
1014 // This is used by LyX for simple dots in relative
1018 } else if (t.cs() == "space") {
1028 /// Convert \p name from TeX convention (relative to master file) to LyX
1029 /// convention (relative to .lyx file) if it is relative
1030 void fix_relative_filename(string & name)
1032 if (absolutePath(name))
1034 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1036 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1037 from_utf8(getParentFilePath())));
1041 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1042 void parse_noweb(Parser & p, ostream & os, Context & context)
1044 // assemble the rest of the keyword
1048 Token const & t = p.get_token();
1049 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1052 scrap = (p.good() && p.next_token().asInput() == "=");
1054 name += p.get_token().asInput();
1057 name += t.asInput();
1060 if (!scrap || !context.new_layout_allowed ||
1061 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1062 cerr << "Warning: Could not interpret '" << name
1063 << "'. Ignoring it." << endl;
1067 // We use new_paragraph instead of check_end_layout because the stuff
1068 // following the noweb chunk needs to start with a \begin_layout.
1069 // This may create a new paragraph even if there was none in the
1070 // noweb file, but the alternative is an invalid LyX file. Since
1071 // noweb code chunks are implemented with a layout style in LyX they
1072 // always must be in an own paragraph.
1073 context.new_paragraph(os);
1074 Context newcontext(true, context.textclass,
1075 context.textclass[from_ascii("Scrap")]);
1076 newcontext.check_layout(os);
1079 Token const & t = p.get_token();
1080 // We abuse the parser a bit, because this is no TeX syntax
1082 if (t.cat() == catEscape)
1083 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1085 os << subst(t.asInput(), "\n", "\n\\newline\n");
1086 // The scrap chunk is ended by an @ at the beginning of a line.
1087 // After the @ the line may contain a comment and/or
1088 // whitespace, but nothing else.
1089 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1090 (p.next_token().cat() == catSpace ||
1091 p.next_token().cat() == catNewline ||
1092 p.next_token().cat() == catComment)) {
1093 while (p.good() && p.next_token().cat() == catSpace)
1094 os << p.get_token().asInput();
1095 if (p.next_token().cat() == catComment)
1096 // The comment includes a final '\n'
1097 os << p.get_token().asInput();
1099 if (p.next_token().cat() == catNewline)
1106 newcontext.check_end_layout(os);
1109 } // anonymous namespace
1112 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1115 LayoutPtr newlayout;
1116 // store the current selectlanguage to be used after \foreignlanguage
1118 // Store the latest bibliographystyle (needed for bibtex inset)
1119 string bibliographystyle;
1120 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1121 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1123 Token const & t = p.get_token();
1126 cerr << "t: " << t << " flags: " << flags << "\n";
1129 if (flags & FLAG_ITEM) {
1130 if (t.cat() == catSpace)
1133 flags &= ~FLAG_ITEM;
1134 if (t.cat() == catBegin) {
1135 // skip the brace and collect everything to the next matching
1137 flags |= FLAG_BRACE_LAST;
1141 // handle only this single token, leave the loop if done
1142 flags |= FLAG_LEAVE;
1145 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1151 if (t.cat() == catMath) {
1152 // we are inside some text mode thingy, so opening new math is allowed
1153 context.check_layout(os);
1154 begin_inset(os, "Formula ");
1155 Token const & n = p.get_token();
1156 if (n.cat() == catMath && outer) {
1157 // TeX's $$...$$ syntax for displayed math
1159 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1161 p.get_token(); // skip the second '$' token
1163 // simple $...$ stuff
1166 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1172 else if (t.cat() == catSuper || t.cat() == catSub)
1173 cerr << "catcode " << t << " illegal in text mode\n";
1175 // Basic support for english quotes. This should be
1176 // extended to other quotes, but is not so easy (a
1177 // left english quote is the same as a right german
1179 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1180 context.check_layout(os);
1181 begin_inset(os, "Quotes ");
1187 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1188 context.check_layout(os);
1189 begin_inset(os, "Quotes ");
1196 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1197 context.check_layout(os);
1198 begin_inset(os, "Quotes ");
1205 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1206 context.check_layout(os);
1207 begin_inset(os, "Quotes ");
1214 else if (t.asInput() == "<"
1215 && p.next_token().asInput() == "<" && noweb_mode) {
1217 parse_noweb(p, os, context);
1220 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1221 check_space(p, os, context);
1223 else if (t.character() == '[' && noweb_mode &&
1224 p.next_token().character() == '[') {
1225 // These can contain underscores
1227 string const s = p.getFullOpt() + ']';
1228 if (p.next_token().character() == ']')
1231 cerr << "Warning: Inserting missing ']' in '"
1232 << s << "'." << endl;
1233 handle_ert(os, s, context);
1236 else if (t.cat() == catLetter ||
1237 t.cat() == catOther ||
1238 t.cat() == catAlign ||
1239 t.cat() == catParameter) {
1240 // This translates "&" to "\\&" which may be wrong...
1241 context.check_layout(os);
1242 os << t.character();
1245 else if (p.isParagraph()) {
1246 if (context.new_layout_allowed)
1247 context.new_paragraph(os);
1249 handle_ert(os, "\\par ", context);
1250 eat_whitespace(p, os, context, true);
1253 else if (t.cat() == catActive) {
1254 context.check_layout(os);
1255 if (t.character() == '~') {
1256 if (context.layout->free_spacing)
1259 os << "\\InsetSpace ~\n";
1261 os << t.character();
1264 else if (t.cat() == catBegin &&
1265 p.next_token().cat() == catEnd) {
1267 Token const prev = p.prev_token();
1269 if (p.next_token().character() == '`' ||
1270 (prev.character() == '-' &&
1271 p.next_token().character() == '-'))
1272 ; // ignore it in {}`` or -{}-
1274 handle_ert(os, "{}", context);
1278 else if (t.cat() == catBegin) {
1279 context.check_layout(os);
1280 // special handling of font attribute changes
1281 Token const prev = p.prev_token();
1282 Token const next = p.next_token();
1283 TeXFont const oldFont = context.font;
1284 if (next.character() == '[' ||
1285 next.character() == ']' ||
1286 next.character() == '*') {
1288 if (p.next_token().cat() == catEnd) {
1289 os << next.character();
1293 handle_ert(os, "{", context);
1294 parse_text_snippet(p, os,
1297 handle_ert(os, "}", context);
1299 } else if (! context.new_layout_allowed) {
1300 handle_ert(os, "{", context);
1301 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1303 handle_ert(os, "}", context);
1304 } else if (is_known(next.cs(), known_sizes)) {
1305 // next will change the size, so we must
1307 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1309 if (!context.atParagraphStart())
1311 << context.font.size << "\n";
1312 } else if (is_known(next.cs(), known_font_families)) {
1313 // next will change the font family, so we
1314 // must reset it here
1315 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1317 if (!context.atParagraphStart())
1319 << context.font.family << "\n";
1320 } else if (is_known(next.cs(), known_font_series)) {
1321 // next will change the font series, so we
1322 // must reset it here
1323 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1325 if (!context.atParagraphStart())
1327 << context.font.series << "\n";
1328 } else if (is_known(next.cs(), known_font_shapes)) {
1329 // next will change the font shape, so we
1330 // must reset it here
1331 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1333 if (!context.atParagraphStart())
1335 << context.font.shape << "\n";
1336 } else if (is_known(next.cs(), known_old_font_families) ||
1337 is_known(next.cs(), known_old_font_series) ||
1338 is_known(next.cs(), known_old_font_shapes)) {
1339 // next will change the font family, series
1340 // and shape, so we must reset it here
1341 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1343 if (!context.atParagraphStart())
1345 << context.font.family
1347 << context.font.series
1349 << context.font.shape << "\n";
1351 handle_ert(os, "{", context);
1352 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1354 handle_ert(os, "}", context);
1358 else if (t.cat() == catEnd) {
1359 if (flags & FLAG_BRACE_LAST) {
1362 cerr << "stray '}' in text\n";
1363 handle_ert(os, "}", context);
1366 else if (t.cat() == catComment)
1367 parse_comment(p, os, t, context);
1370 // control sequences
1373 else if (t.cs() == "(") {
1374 context.check_layout(os);
1375 begin_inset(os, "Formula");
1377 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1382 else if (t.cs() == "[") {
1383 context.check_layout(os);
1384 begin_inset(os, "Formula");
1386 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1391 else if (t.cs() == "begin")
1392 parse_environment(p, os, outer, context);
1394 else if (t.cs() == "end") {
1395 if (flags & FLAG_END) {
1396 // eat environment name
1397 string const name = p.getArg('{', '}');
1398 if (name != active_environment())
1399 cerr << "\\end{" + name + "} does not match \\begin{"
1400 + active_environment() + "}\n";
1403 p.error("found 'end' unexpectedly");
1406 else if (t.cs() == "item") {
1409 bool optarg = false;
1410 if (p.next_token().character() == '[') {
1411 p.get_token(); // eat '['
1412 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1417 context.check_layout(os);
1418 if (context.has_item) {
1419 // An item in an unknown list-like environment
1420 // FIXME: Do this in check_layout()!
1421 context.has_item = false;
1423 handle_ert(os, "\\item", context);
1425 handle_ert(os, "\\item ", context);
1428 if (context.layout->labeltype != LABEL_MANUAL) {
1429 // lyx does not support \item[\mybullet]
1430 // in itemize environments
1431 handle_ert(os, "[", context);
1433 handle_ert(os, "]", context);
1434 } else if (!s.empty()) {
1435 // The space is needed to separate the
1436 // item from the rest of the sentence.
1438 eat_whitespace(p, os, context, false);
1443 else if (t.cs() == "bibitem") {
1445 context.check_layout(os);
1448 os << '{' << p.verbatim_item() << '}' << "\n";
1451 else if (t.cs() == "def") {
1452 context.check_layout(os);
1453 eat_whitespace(p, os, context, false);
1454 string name = p.get_token().cs();
1455 eat_whitespace(p, os, context, false);
1461 while (p.next_token().cat() != catBegin) {
1462 if (p.next_token().cat() == catParameter) {
1467 // followed by number?
1468 if (p.next_token().cat() == catOther) {
1469 char c = p.getChar();
1471 // number = current arity + 1?
1472 if (c == arity + '0' + 1)
1477 paramtext += p.get_token().asString();
1479 paramtext += p.get_token().asString();
1484 // only output simple (i.e. compatible) macro as FormulaMacros
1485 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1487 context.check_layout(os);
1488 begin_inset(os, "FormulaMacro");
1492 handle_ert(os, ert, context);
1495 else if (t.cs() == "noindent") {
1497 context.add_extra_stuff("\\noindent\n");
1500 else if (t.cs() == "appendix") {
1501 context.add_extra_stuff("\\start_of_appendix\n");
1502 // We need to start a new paragraph. Otherwise the
1503 // appendix in 'bla\appendix\chapter{' would start
1505 context.new_paragraph(os);
1506 // We need to make sure that the paragraph is
1507 // generated even if it is empty. Otherwise the
1508 // appendix in '\par\appendix\par\chapter{' would
1510 context.check_layout(os);
1511 // FIXME: This is a hack to prevent paragraph
1512 // deletion if it is empty. Handle this better!
1514 "%dummy comment inserted by tex2lyx to "
1515 "ensure that this paragraph is not empty",
1517 // Both measures above may generate an additional
1518 // empty paragraph, but that does not hurt, because
1519 // whitespace does not matter here.
1520 eat_whitespace(p, os, context, true);
1523 // Must attempt to parse "Section*" before "Section".
1524 else if ((p.next_token().asInput() == "*") &&
1525 context.new_layout_allowed &&
1526 // The single '=' is meant here.
1527 (newlayout = findLayout(context.textclass,
1528 t.cs() + '*')).get() &&
1529 newlayout->isCommand()) {
1531 output_command_layout(os, p, outer, context, newlayout);
1535 // The single '=' is meant here.
1536 else if (context.new_layout_allowed &&
1537 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1538 newlayout->isCommand()) {
1539 output_command_layout(os, p, outer, context, newlayout);
1543 // Special handling for \caption
1544 // FIXME: remove this when InsetCaption is supported.
1545 else if (context.new_layout_allowed &&
1546 t.cs() == captionlayout->latexname()) {
1547 output_command_layout(os, p, outer, context,
1552 else if (t.cs() == "includegraphics") {
1553 bool const clip = p.next_token().asInput() == "*";
1556 map<string, string> opts = split_map(p.getArg('[', ']'));
1558 opts["clip"] = string();
1559 string name = normalize_filename(p.verbatim_item());
1561 string const path = getMasterFilePath();
1562 // We want to preserve relative / absolute filenames,
1563 // therefore path is only used for testing
1564 // FIXME UNICODE encoding of name and path may be
1565 // wrong (makeAbsPath expects utf8)
1566 if (!makeAbsPath(name, path).exists()) {
1567 // The file extension is probably missing.
1568 // Now try to find it out.
1569 string const dvips_name =
1570 find_file(name, path,
1571 known_dvips_graphics_formats);
1572 string const pdftex_name =
1573 find_file(name, path,
1574 known_pdftex_graphics_formats);
1575 if (!dvips_name.empty()) {
1576 if (!pdftex_name.empty()) {
1577 cerr << "This file contains the "
1579 "\"\\includegraphics{"
1581 "However, files\n\""
1582 << dvips_name << "\" and\n\""
1583 << pdftex_name << "\"\n"
1584 "both exist, so I had to make a "
1585 "choice and took the first one.\n"
1586 "Please move the unwanted one "
1587 "someplace else and try again\n"
1588 "if my choice was wrong."
1592 } else if (!pdftex_name.empty())
1596 // FIXME UNICODE encoding of name and path may be
1597 // wrong (makeAbsPath expects utf8)
1598 if (makeAbsPath(name, path).exists())
1599 fix_relative_filename(name);
1601 cerr << "Warning: Could not find graphics file '"
1602 << name << "'." << endl;
1604 context.check_layout(os);
1605 begin_inset(os, "Graphics ");
1606 os << "\n\tfilename " << name << '\n';
1607 if (opts.find("width") != opts.end())
1609 << translate_len(opts["width"]) << '\n';
1610 if (opts.find("height") != opts.end())
1612 << translate_len(opts["height"]) << '\n';
1613 if (opts.find("scale") != opts.end()) {
1614 istringstream iss(opts["scale"]);
1618 os << "\tscale " << val << '\n';
1620 if (opts.find("angle") != opts.end())
1621 os << "\trotateAngle "
1622 << opts["angle"] << '\n';
1623 if (opts.find("origin") != opts.end()) {
1625 string const opt = opts["origin"];
1626 if (opt.find('l') != string::npos) ss << "left";
1627 if (opt.find('r') != string::npos) ss << "right";
1628 if (opt.find('c') != string::npos) ss << "center";
1629 if (opt.find('t') != string::npos) ss << "Top";
1630 if (opt.find('b') != string::npos) ss << "Bottom";
1631 if (opt.find('B') != string::npos) ss << "Baseline";
1632 if (!ss.str().empty())
1633 os << "\trotateOrigin " << ss.str() << '\n';
1635 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1637 if (opts.find("keepaspectratio") != opts.end())
1638 os << "\tkeepAspectRatio\n";
1639 if (opts.find("clip") != opts.end())
1641 if (opts.find("draft") != opts.end())
1643 if (opts.find("bb") != opts.end())
1644 os << "\tBoundingBox "
1645 << opts["bb"] << '\n';
1646 int numberOfbbOptions = 0;
1647 if (opts.find("bbllx") != opts.end())
1648 numberOfbbOptions++;
1649 if (opts.find("bblly") != opts.end())
1650 numberOfbbOptions++;
1651 if (opts.find("bburx") != opts.end())
1652 numberOfbbOptions++;
1653 if (opts.find("bbury") != opts.end())
1654 numberOfbbOptions++;
1655 if (numberOfbbOptions == 4)
1656 os << "\tBoundingBox "
1657 << opts["bbllx"] << " " << opts["bblly"] << " "
1658 << opts["bburx"] << " " << opts["bbury"] << '\n';
1659 else if (numberOfbbOptions > 0)
1660 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1661 numberOfbbOptions = 0;
1662 if (opts.find("natwidth") != opts.end())
1663 numberOfbbOptions++;
1664 if (opts.find("natheight") != opts.end())
1665 numberOfbbOptions++;
1666 if (numberOfbbOptions == 2)
1667 os << "\tBoundingBox 0bp 0bp "
1668 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1669 else if (numberOfbbOptions > 0)
1670 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1671 ostringstream special;
1672 if (opts.find("hiresbb") != opts.end())
1673 special << "hiresbb,";
1674 if (opts.find("trim") != opts.end())
1676 if (opts.find("viewport") != opts.end())
1677 special << "viewport=" << opts["viewport"] << ',';
1678 if (opts.find("totalheight") != opts.end())
1679 special << "totalheight=" << opts["totalheight"] << ',';
1680 if (opts.find("type") != opts.end())
1681 special << "type=" << opts["type"] << ',';
1682 if (opts.find("ext") != opts.end())
1683 special << "ext=" << opts["ext"] << ',';
1684 if (opts.find("read") != opts.end())
1685 special << "read=" << opts["read"] << ',';
1686 if (opts.find("command") != opts.end())
1687 special << "command=" << opts["command"] << ',';
1688 string s_special = special.str();
1689 if (!s_special.empty()) {
1690 // We had special arguments. Remove the trailing ','.
1691 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1693 // TODO: Handle the unknown settings better.
1694 // Warn about invalid options.
1695 // Check whether some option was given twice.
1699 else if (t.cs() == "footnote" ||
1700 (t.cs() == "thanks" && context.layout->intitle)) {
1702 context.check_layout(os);
1703 begin_inset(os, "Foot\n");
1704 os << "status collapsed\n\n";
1705 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1709 else if (t.cs() == "marginpar") {
1711 context.check_layout(os);
1712 begin_inset(os, "Marginal\n");
1713 os << "status collapsed\n\n";
1714 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1718 else if (t.cs() == "ensuremath") {
1720 context.check_layout(os);
1721 string const s = p.verbatim_item();
1722 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1725 handle_ert(os, "\\ensuremath{" + s + "}",
1729 else if (t.cs() == "hfill") {
1730 context.check_layout(os);
1731 os << "\n\\hfill\n";
1736 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1737 // FIXME: Somehow prevent title layouts if
1738 // "maketitle" was not found
1740 skip_braces(p); // swallow this
1743 else if (t.cs() == "tableofcontents") {
1745 context.check_layout(os);
1746 begin_inset(os, "LatexCommand \\tableofcontents\n");
1748 skip_braces(p); // swallow this
1751 else if (t.cs() == "listoffigures") {
1753 context.check_layout(os);
1754 begin_inset(os, "FloatList figure\n");
1756 skip_braces(p); // swallow this
1759 else if (t.cs() == "listoftables") {
1761 context.check_layout(os);
1762 begin_inset(os, "FloatList table\n");
1764 skip_braces(p); // swallow this
1767 else if (t.cs() == "listof") {
1768 p.skip_spaces(true);
1769 string const name = p.get_token().asString();
1770 if (context.textclass.floats().typeExist(name)) {
1771 context.check_layout(os);
1772 begin_inset(os, "FloatList ");
1775 p.get_token(); // swallow second arg
1777 handle_ert(os, "\\listof{" + name + "}", context);
1780 else if (t.cs() == "textrm")
1781 parse_text_attributes(p, os, FLAG_ITEM, outer,
1782 context, "\\family",
1783 context.font.family, "roman");
1785 else if (t.cs() == "textsf")
1786 parse_text_attributes(p, os, FLAG_ITEM, outer,
1787 context, "\\family",
1788 context.font.family, "sans");
1790 else if (t.cs() == "texttt")
1791 parse_text_attributes(p, os, FLAG_ITEM, outer,
1792 context, "\\family",
1793 context.font.family, "typewriter");
1795 else if (t.cs() == "textmd")
1796 parse_text_attributes(p, os, FLAG_ITEM, outer,
1797 context, "\\series",
1798 context.font.series, "medium");
1800 else if (t.cs() == "textbf")
1801 parse_text_attributes(p, os, FLAG_ITEM, outer,
1802 context, "\\series",
1803 context.font.series, "bold");
1805 else if (t.cs() == "textup")
1806 parse_text_attributes(p, os, FLAG_ITEM, outer,
1808 context.font.shape, "up");
1810 else if (t.cs() == "textit")
1811 parse_text_attributes(p, os, FLAG_ITEM, outer,
1813 context.font.shape, "italic");
1815 else if (t.cs() == "textsl")
1816 parse_text_attributes(p, os, FLAG_ITEM, outer,
1818 context.font.shape, "slanted");
1820 else if (t.cs() == "textsc")
1821 parse_text_attributes(p, os, FLAG_ITEM, outer,
1823 context.font.shape, "smallcaps");
1825 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1826 context.check_layout(os);
1827 TeXFont oldFont = context.font;
1828 context.font.init();
1829 context.font.size = oldFont.size;
1830 os << "\n\\family " << context.font.family << "\n";
1831 os << "\n\\series " << context.font.series << "\n";
1832 os << "\n\\shape " << context.font.shape << "\n";
1833 if (t.cs() == "textnormal") {
1834 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1835 output_font_change(os, context.font, oldFont);
1836 context.font = oldFont;
1838 eat_whitespace(p, os, context, false);
1841 else if (t.cs() == "underbar") {
1842 // Do NOT handle \underline.
1843 // \underbar cuts through y, g, q, p etc.,
1844 // \underline does not.
1845 context.check_layout(os);
1846 os << "\n\\bar under\n";
1847 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1848 context.check_layout(os);
1849 os << "\n\\bar default\n";
1852 else if (t.cs() == "emph" || t.cs() == "noun") {
1853 context.check_layout(os);
1854 os << "\n\\" << t.cs() << " on\n";
1855 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1856 context.check_layout(os);
1857 os << "\n\\" << t.cs() << " default\n";
1860 else if (use_natbib &&
1861 is_known(t.cs(), known_natbib_commands) &&
1862 ((t.cs() != "citefullauthor" &&
1863 t.cs() != "citeyear" &&
1864 t.cs() != "citeyearpar") ||
1865 p.next_token().asInput() != "*")) {
1866 context.check_layout(os);
1868 // \citet[before][after]{a} \citet[after][before]{a}
1869 // \citet[before][]{a} \citet[][before]{a}
1870 // \citet[after]{a} \citet[after]{a}
1871 // \citet{a} \citet{a}
1872 string command = '\\' + t.cs();
1873 if (p.next_token().asInput() == "*") {
1877 if (command == "\\citefullauthor")
1878 // alternative name for "\\citeauthor*"
1879 command = "\\citeauthor*";
1881 // text before the citation
1883 // text after the citation
1885 get_cite_arguments(p, true, before, after);
1887 if (command == "\\cite") {
1888 // \cite without optional argument means
1889 // \citet, \cite with at least one optional
1890 // argument means \citep.
1891 if (before.empty() && after.empty())
1892 command = "\\citet";
1894 command = "\\citep";
1896 if (before.empty() && after == "[]")
1897 // avoid \citet[]{a}
1899 else if (before == "[]" && after == "[]") {
1900 // avoid \citet[][]{a}
1904 begin_inset(os, "LatexCommand ");
1905 os << command << after << before
1906 << '{' << p.verbatim_item() << "}\n";
1910 else if (use_jurabib &&
1911 is_known(t.cs(), known_jurabib_commands)) {
1912 context.check_layout(os);
1913 string const command = '\\' + t.cs();
1914 char argumentOrder = '\0';
1915 vector<string> const & options = used_packages["jurabib"];
1916 if (find(options.begin(), options.end(),
1917 "natbiborder") != options.end())
1918 argumentOrder = 'n';
1919 else if (find(options.begin(), options.end(),
1920 "jurabiborder") != options.end())
1921 argumentOrder = 'j';
1923 // text before the citation
1925 // text after the citation
1927 get_cite_arguments(p, argumentOrder != 'j', before, after);
1929 string const citation = p.verbatim_item();
1930 if (!before.empty() && argumentOrder == '\0') {
1931 cerr << "Warning: Assuming argument order "
1932 "of jurabib version 0.6 for\n'"
1933 << command << before << after << '{'
1934 << citation << "}'.\n"
1935 "Add 'jurabiborder' to the jurabib "
1936 "package options if you used an\n"
1937 "earlier jurabib version." << endl;
1939 begin_inset(os, "LatexCommand ");
1940 os << command << after << before
1941 << '{' << citation << "}\n";
1945 else if (is_known(t.cs(), known_latex_commands)) {
1946 // This needs to be after the check for natbib and
1947 // jurabib commands, because "cite" has different
1948 // arguments with natbib and jurabib.
1949 context.check_layout(os);
1950 begin_inset(os, "LatexCommand ");
1951 os << '\\' << t.cs();
1952 // lyx cannot handle newlines in a latex command
1953 // FIXME: Move the substitution into parser::getOpt()?
1954 os << subst(p.getOpt(), "\n", " ");
1955 os << subst(p.getOpt(), "\n", " ");
1956 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1960 else if (is_known(t.cs(), known_quotes)) {
1961 char const * const * where = is_known(t.cs(), known_quotes);
1962 context.check_layout(os);
1963 begin_inset(os, "Quotes ");
1964 os << known_coded_quotes[where - known_quotes];
1966 // LyX adds {} after the quote, so we have to eat
1967 // spaces here if there are any before a possible
1969 eat_whitespace(p, os, context, false);
1973 else if (is_known(t.cs(), known_sizes) &&
1974 context.new_layout_allowed) {
1975 char const * const * where = is_known(t.cs(), known_sizes);
1976 context.check_layout(os);
1977 TeXFont const oldFont = context.font;
1978 context.font.size = known_coded_sizes[where - known_sizes];
1979 output_font_change(os, oldFont, context.font);
1980 eat_whitespace(p, os, context, false);
1983 else if (is_known(t.cs(), known_font_families) &&
1984 context.new_layout_allowed) {
1985 char const * const * where =
1986 is_known(t.cs(), known_font_families);
1987 context.check_layout(os);
1988 TeXFont const oldFont = context.font;
1989 context.font.family =
1990 known_coded_font_families[where - known_font_families];
1991 output_font_change(os, oldFont, context.font);
1992 eat_whitespace(p, os, context, false);
1995 else if (is_known(t.cs(), known_font_series) &&
1996 context.new_layout_allowed) {
1997 char const * const * where =
1998 is_known(t.cs(), known_font_series);
1999 context.check_layout(os);
2000 TeXFont const oldFont = context.font;
2001 context.font.series =
2002 known_coded_font_series[where - known_font_series];
2003 output_font_change(os, oldFont, context.font);
2004 eat_whitespace(p, os, context, false);
2007 else if (is_known(t.cs(), known_font_shapes) &&
2008 context.new_layout_allowed) {
2009 char const * const * where =
2010 is_known(t.cs(), known_font_shapes);
2011 context.check_layout(os);
2012 TeXFont const oldFont = context.font;
2013 context.font.shape =
2014 known_coded_font_shapes[where - known_font_shapes];
2015 output_font_change(os, oldFont, context.font);
2016 eat_whitespace(p, os, context, false);
2018 else if (is_known(t.cs(), known_old_font_families) &&
2019 context.new_layout_allowed) {
2020 char const * const * where =
2021 is_known(t.cs(), known_old_font_families);
2022 context.check_layout(os);
2023 TeXFont const oldFont = context.font;
2024 context.font.init();
2025 context.font.size = oldFont.size;
2026 context.font.family =
2027 known_coded_font_families[where - known_old_font_families];
2028 output_font_change(os, oldFont, context.font);
2029 eat_whitespace(p, os, context, false);
2032 else if (is_known(t.cs(), known_old_font_series) &&
2033 context.new_layout_allowed) {
2034 char const * const * where =
2035 is_known(t.cs(), known_old_font_series);
2036 context.check_layout(os);
2037 TeXFont const oldFont = context.font;
2038 context.font.init();
2039 context.font.size = oldFont.size;
2040 context.font.series =
2041 known_coded_font_series[where - known_old_font_series];
2042 output_font_change(os, oldFont, context.font);
2043 eat_whitespace(p, os, context, false);
2046 else if (is_known(t.cs(), known_old_font_shapes) &&
2047 context.new_layout_allowed) {
2048 char const * const * where =
2049 is_known(t.cs(), known_old_font_shapes);
2050 context.check_layout(os);
2051 TeXFont const oldFont = context.font;
2052 context.font.init();
2053 context.font.size = oldFont.size;
2054 context.font.shape =
2055 known_coded_font_shapes[where - known_old_font_shapes];
2056 output_font_change(os, oldFont, context.font);
2057 eat_whitespace(p, os, context, false);
2060 else if (t.cs() == "selectlanguage") {
2061 context.check_layout(os);
2062 // save the language for the case that a \foreignlanguage is used
2063 selectlang = subst(p.verbatim_item(), "\n", " ");
2064 os << "\\lang " << selectlang << "\n";
2068 else if (t.cs() == "foreignlanguage") {
2069 context.check_layout(os);
2070 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2071 os << subst(p.verbatim_item(), "\n", " ");
2072 // set back to last selectlanguage
2073 os << "\n\\lang " << selectlang << "\n";
2076 else if (t.cs() == "inputencoding")
2077 // write nothing because this is done by LyX using the "\lang"
2078 // information given by selectlanguage and foreignlanguage
2079 subst(p.verbatim_item(), "\n", " ");
2081 else if (t.cs() == "LyX" || t.cs() == "TeX"
2082 || t.cs() == "LaTeX") {
2083 context.check_layout(os);
2085 skip_braces(p); // eat {}
2088 else if (t.cs() == "LaTeXe") {
2089 context.check_layout(os);
2091 skip_braces(p); // eat {}
2094 else if (t.cs() == "ldots") {
2095 context.check_layout(os);
2097 os << "\\SpecialChar \\ldots{}\n";
2100 else if (t.cs() == "lyxarrow") {
2101 context.check_layout(os);
2102 os << "\\SpecialChar \\menuseparator\n";
2106 else if (t.cs() == "textcompwordmark") {
2107 context.check_layout(os);
2108 os << "\\SpecialChar \\textcompwordmark{}\n";
2112 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2113 context.check_layout(os);
2114 os << "\\SpecialChar \\@.\n";
2118 else if (t.cs() == "-") {
2119 context.check_layout(os);
2120 os << "\\SpecialChar \\-\n";
2123 else if (t.cs() == "textasciitilde") {
2124 context.check_layout(os);
2129 else if (t.cs() == "textasciicircum") {
2130 context.check_layout(os);
2135 else if (t.cs() == "textbackslash") {
2136 context.check_layout(os);
2137 os << "\n\\backslash\n";
2141 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2142 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2144 context.check_layout(os);
2148 else if (t.cs() == "char") {
2149 context.check_layout(os);
2150 if (p.next_token().character() == '`') {
2152 if (p.next_token().cs() == "\"") {
2157 handle_ert(os, "\\char`", context);
2160 handle_ert(os, "\\char", context);
2164 else if (t.cs() == "verb") {
2165 context.check_layout(os);
2166 char const delimiter = p.next_token().character();
2167 string const arg = p.getArg(delimiter, delimiter);
2169 oss << "\\verb" << delimiter << arg << delimiter;
2170 handle_ert(os, oss.str(), context);
2173 else if (t.cs() == "\"") {
2174 context.check_layout(os);
2175 string const name = p.verbatim_item();
2176 if (name == "a") os << '\xe4';
2177 else if (name == "o") os << '\xf6';
2178 else if (name == "u") os << '\xfc';
2179 else if (name == "A") os << '\xc4';
2180 else if (name == "O") os << '\xd6';
2181 else if (name == "U") os << '\xdc';
2182 else handle_ert(os, "\"{" + name + "}", context);
2185 // Problem: \= creates a tabstop inside the tabbing environment
2186 // and else an accent. In the latter case we really would want
2187 // \={o} instead of \= o.
2188 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2189 handle_ert(os, t.asInput(), context);
2191 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2192 || t.cs() == "'" || t.cs() == "`"
2193 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2194 // we need the trim as the LyX parser chokes on such spaces
2195 // The argument of InsetLatexAccent is parsed as a
2196 // subset of LaTeX, so don't parse anything here,
2197 // but use the raw argument.
2198 // Otherwise we would convert \~{\i} wrongly.
2199 // This will of course not translate \~{\ss} to \~{ß},
2200 // but that does at least compile and does only look
2201 // strange on screen.
2202 context.check_layout(os);
2203 os << "\\i \\" << t.cs() << "{"
2204 << trim(p.verbatim_item(), " ")
2208 else if (t.cs() == "ss") {
2209 context.check_layout(os);
2211 skip_braces(p); // eat {}
2214 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2216 context.check_layout(os);
2217 os << "\\i \\" << t.cs() << "{}\n";
2218 skip_braces(p); // eat {}
2221 else if (t.cs() == "\\") {
2222 context.check_layout(os);
2223 string const next = p.next_token().asInput();
2225 handle_ert(os, "\\\\" + p.getOpt(), context);
2226 else if (next == "*") {
2228 handle_ert(os, "\\\\*" + p.getOpt(), context);
2231 os << "\n\\newline\n";
2235 else if (t.cs() == "newline" ||
2236 t.cs() == "linebreak") {
2237 context.check_layout(os);
2238 os << "\n\\" << t.cs() << "\n";
2239 skip_braces(p); // eat {}
2242 else if (t.cs() == "href") {
2243 context.check_layout(os);
2244 begin_inset(os, "CommandInset ");
2245 os << t.cs() << "\n";
2246 os << "LatexCommand " << t.cs() << "\n";
2249 // the first argument is "type:target", "type:" is optional
2250 // the second argument the name
2251 string href_target = subst(p.verbatim_item(), "\n", " ");
2252 string href_name = subst(p.verbatim_item(), "\n", " ");
2254 // serach for the ":" to divide type from target
2255 if ((pos = href_target.find(":", 0)) != string::npos){
2256 href_type = href_target;
2257 href_type.erase(pos + 1, href_type.length());
2258 href_target.erase(0, pos + 1);
2261 os << "name " << '"' << href_name << '"' << "\n";
2262 os << "target " << '"' << href_target << '"' << "\n";
2264 os << "type " << '"' << href_type << '"' << "\n";
2268 else if (t.cs() == "input" || t.cs() == "include"
2269 || t.cs() == "verbatiminput") {
2270 string name = '\\' + t.cs();
2271 if (t.cs() == "verbatiminput"
2272 && p.next_token().asInput() == "*")
2273 name += p.get_token().asInput();
2274 context.check_layout(os);
2275 begin_inset(os, "Include ");
2276 string filename(normalize_filename(p.getArg('{', '}')));
2277 string const path = getMasterFilePath();
2278 // We want to preserve relative / absolute filenames,
2279 // therefore path is only used for testing
2280 // FIXME UNICODE encoding of filename and path may be
2281 // wrong (makeAbsPath expects utf8)
2282 if ((t.cs() == "include" || t.cs() == "input") &&
2283 !makeAbsPath(filename, path).exists()) {
2284 // The file extension is probably missing.
2285 // Now try to find it out.
2286 string const tex_name =
2287 find_file(filename, path,
2288 known_tex_extensions);
2289 if (!tex_name.empty())
2290 filename = tex_name;
2292 // FIXME UNICODE encoding of filename and path may be
2293 // wrong (makeAbsPath expects utf8)
2294 if (makeAbsPath(filename, path).exists()) {
2295 string const abstexname =
2296 makeAbsPath(filename, path).absFilename();
2297 string const abslyxname =
2298 changeExtension(abstexname, ".lyx");
2299 fix_relative_filename(filename);
2300 string const lyxname =
2301 changeExtension(filename, ".lyx");
2302 if (t.cs() != "verbatiminput" &&
2303 tex2lyx(abstexname, FileName(abslyxname))) {
2304 os << name << '{' << lyxname << "}\n";
2306 os << name << '{' << filename << "}\n";
2309 cerr << "Warning: Could not find included file '"
2310 << filename << "'." << endl;
2311 os << name << '{' << filename << "}\n";
2313 os << "preview false\n";
2317 else if (t.cs() == "bibliographystyle") {
2318 // store new bibliographystyle
2319 bibliographystyle = p.verbatim_item();
2320 // output new bibliographystyle.
2321 // This is only necessary if used in some other macro than \bibliography.
2322 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2325 else if (t.cs() == "bibliography") {
2326 context.check_layout(os);
2327 begin_inset(os, "LatexCommand ");
2329 // Do we have a bibliographystyle set?
2330 if (!bibliographystyle.empty()) {
2331 os << '[' << bibliographystyle << ']';
2333 os << '{' << p.verbatim_item() << "}\n";
2337 else if (t.cs() == "parbox")
2338 parse_box(p, os, FLAG_ITEM, outer, context, true);
2340 else if (t.cs() == "smallskip" ||
2341 t.cs() == "medskip" ||
2342 t.cs() == "bigskip" ||
2343 t.cs() == "vfill") {
2344 context.check_layout(os);
2345 begin_inset(os, "VSpace ");
2351 else if (is_known(t.cs(), known_spaces)) {
2352 char const * const * where = is_known(t.cs(), known_spaces);
2353 context.check_layout(os);
2354 begin_inset(os, "InsetSpace ");
2355 os << '\\' << known_coded_spaces[where - known_spaces]
2357 // LaTeX swallows whitespace after all spaces except
2358 // "\\,". We have to do that here, too, because LyX
2359 // adds "{}" which would make the spaces significant.
2361 eat_whitespace(p, os, context, false);
2362 // LyX adds "{}" after all spaces except "\\ " and
2363 // "\\,", so we have to remove "{}".
2364 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2365 // remove the braces after "\\,", too.
2370 else if (t.cs() == "newpage" ||
2371 t.cs() == "pagebreak" ||
2372 t.cs() == "clearpage" ||
2373 t.cs() == "cleardoublepage") {
2374 context.check_layout(os);
2375 os << "\n\\" << t.cs() << "\n";
2376 skip_braces(p); // eat {}
2379 else if (t.cs() == "newcommand" ||
2380 t.cs() == "providecommand" ||
2381 t.cs() == "renewcommand") {
2382 // these could be handled by parse_command(), but
2383 // we need to call add_known_command() here.
2384 string name = t.asInput();
2385 if (p.next_token().asInput() == "*") {
2386 // Starred form. Eat '*'
2390 string const command = p.verbatim_item();
2391 string const opt1 = p.getOpt();
2392 string const opt2 = p.getFullOpt();
2393 add_known_command(command, opt1, !opt2.empty());
2394 string const ert = name + '{' + command + '}' +
2396 '{' + p.verbatim_item() + '}';
2398 context.check_layout(os);
2399 begin_inset(os, "FormulaMacro");
2404 else if (t.cs() == "vspace") {
2405 bool starred = false;
2406 if (p.next_token().asInput() == "*") {
2410 string const length = p.verbatim_item();
2413 bool valid = splitLatexLength(length, valstring, unit);
2414 bool known_vspace = false;
2415 bool known_unit = false;
2418 istringstream iss(valstring);
2421 if (unit == "\\smallskipamount") {
2423 known_vspace = true;
2424 } else if (unit == "\\medskipamount") {
2426 known_vspace = true;
2427 } else if (unit == "\\bigskipamount") {
2429 known_vspace = true;
2430 } else if (unit == "\\fill") {
2432 known_vspace = true;
2435 if (!known_vspace) {
2436 switch (unitFromString(unit)) {
2457 if (known_unit || known_vspace) {
2458 // Literal length or known variable
2459 context.check_layout(os);
2460 begin_inset(os, "VSpace ");
2468 // LyX can't handle other length variables in Inset VSpace
2469 string name = t.asInput();
2474 handle_ert(os, name + '{' + unit + '}', context);
2475 else if (value == -1.0)
2476 handle_ert(os, name + "{-" + unit + '}', context);
2478 handle_ert(os, name + '{' + valstring + unit + '}', context);
2480 handle_ert(os, name + '{' + length + '}', context);
2485 //cerr << "#: " << t << " mode: " << mode << endl;
2486 // heuristic: read up to next non-nested space
2488 string s = t.asInput();
2489 string z = p.verbatim_item();
2490 while (p.good() && z != " " && z.size()) {
2491 //cerr << "read: " << z << endl;
2493 z = p.verbatim_item();
2495 cerr << "found ERT: " << s << endl;
2496 handle_ert(os, s + ' ', context);
2498 string name = t.asInput();
2499 if (p.next_token().asInput() == "*") {
2500 // Starred commands like \vspace*{}
2501 p.get_token(); // Eat '*'
2504 if (! parse_command(name, p, os, outer, context))
2505 handle_ert(os, name, context);
2508 if (flags & FLAG_LEAVE) {
2509 flags &= ~FLAG_LEAVE;