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
9 * Full author contact details are available in file CREDITS.
19 #include "FloatList.h"
23 #include "support/lstrings.h"
24 #include "support/convert.h"
25 #include "support/filetools.h"
37 using std::ostringstream;
38 using std::istringstream;
44 using support::addExtension;
45 using support::changeExtension;
46 using support::FileName;
47 using support::makeAbsPath;
48 using support::makeRelPath;
50 using support::suffixIs;
51 using support::contains;
55 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
56 Context const & context)
58 Context newcontext(true, context.textclass);
59 newcontext.font = context.font;
60 parse_text(p, os, flags, outer, newcontext);
61 newcontext.check_end_layout(os);
67 /// parses a paragraph snippet, useful for example for \\emph{...}
68 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
71 Context newcontext(context);
72 // Don't inherit the extra stuff
73 newcontext.extra_stuff.clear();
74 parse_text(p, os, flags, outer, newcontext);
75 // Make sure that we don't create invalid .lyx files
76 context.need_layout = newcontext.need_layout;
77 context.need_end_layout = newcontext.need_end_layout;
82 * Thin wrapper around parse_text_snippet() using a string.
84 * We completely ignore \c context.need_layout and \c context.need_end_layout,
85 * because our return value is not used directly (otherwise the stream version
86 * of parse_text_snippet() could be used). That means that the caller needs
87 * to do layout management manually.
88 * This is intended to parse text that does not create any layout changes.
90 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
93 Context newcontext(context);
94 newcontext.need_layout = false;
95 newcontext.need_end_layout = false;
96 newcontext.new_layout_allowed = false;
97 // Avoid warning by Context::~Context()
98 newcontext.extra_stuff.clear();
100 parse_text_snippet(p, os, flags, outer, newcontext);
105 char const * const known_latex_commands[] = { "ref", "cite", "label",
106 "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
111 * We can't put these into known_latex_commands because the argument order
112 * is reversed in lyx if there are 2 arguments.
113 * The starred forms are also known.
115 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
116 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
117 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
121 * We can't put these into known_latex_commands because the argument order
122 * is reversed in lyx if there are 2 arguments.
123 * No starred form other than "cite*" known.
125 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
126 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
127 // jurabib commands not (yet) supported by LyX:
129 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
130 // "footciteauthor", "footciteyear", "footciteyearpar",
131 "citefield", "citetitle", "cite*", 0 };
133 /// LaTeX names for quotes
134 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
135 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
137 /// the same as known_quotes with .lyx names
138 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
139 "grd", "gls", "fls", "frs", 0};
141 /// LaTeX names for font sizes
142 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
143 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
145 /// the same as known_sizes with .lyx names
146 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
147 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
149 /// LaTeX 2.09 names for font families
150 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
152 /// LaTeX names for font families
153 char const * const known_font_families[] = { "rmfamily", "sffamily",
156 /// the same as known_old_font_families and known_font_families with .lyx names
157 char const * const known_coded_font_families[] = { "roman", "sans",
160 /// LaTeX 2.09 names for font series
161 char const * const known_old_font_series[] = { "bf", 0};
163 /// LaTeX names for font series
164 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
166 /// the same as known_old_font_series and known_font_series with .lyx names
167 char const * const known_coded_font_series[] = { "bold", "medium", 0};
169 /// LaTeX 2.09 names for font shapes
170 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
172 /// LaTeX names for font shapes
173 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
176 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
177 char const * const known_coded_font_shapes[] = { "italic", "slanted",
178 "smallcaps", "up", 0};
181 * Graphics file extensions known by the dvips driver of the graphics package.
182 * These extensions are used to complete the filename of an included
183 * graphics file if it does not contain an extension.
184 * The order must be the same that latex uses to find a file, because we
185 * will use the first extension that matches.
186 * This is only an approximation for the common cases. If we would want to
187 * do it right in all cases, we would need to know which graphics driver is
188 * used and know the extensions of every driver of the graphics package.
190 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
191 "ps.gz", "eps.Z", "ps.Z", 0};
194 * Graphics file extensions known by the pdftex driver of the graphics package.
195 * \sa known_dvips_graphics_formats
197 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
201 * Known file extensions for TeX files as used by \\include.
203 char const * const known_tex_extensions[] = {"tex", 0};
205 /// spaces known by InsetSpace
206 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
207 "qquad", "enspace", "enskip", "negthinspace", 0};
209 /// the same as known_spaces with .lyx names
210 char const * const known_coded_spaces[] = { "space{}", "space{}",
211 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
212 "negthinspace{}", 0};
215 /// splits "x=z, y=b" into a map
216 map<string, string> split_map(string const & s)
218 map<string, string> res;
221 for (size_t i = 0; i < v.size(); ++i) {
222 size_t const pos = v[i].find('=');
223 string const index = v[i].substr(0, pos);
224 string const value = v[i].substr(pos + 1, string::npos);
225 res[trim(index)] = trim(value);
232 * Split a LaTeX length into value and unit.
233 * The latter can be a real unit like "pt", or a latex length variable
234 * like "\textwidth". The unit may contain additional stuff like glue
235 * lengths, but we don't care, because such lengths are ERT anyway.
236 * \returns true if \p value and \p unit are valid.
238 bool splitLatexLength(string const & len, string & value, string & unit)
242 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
243 //'4,5' is a valid LaTeX length number. Change it to '4.5'
244 string const length = subst(len, ',', '.');
245 if (i == string::npos)
248 if (len[0] == '\\') {
249 // We had something like \textwidth without a factor
255 value = trim(string(length, 0, i));
259 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
260 if (contains(len, '\\'))
261 unit = trim(string(len, i));
263 unit = support::ascii_lowercase(trim(string(len, i)));
268 /// A simple function to translate a latex length to something lyx can
269 /// understand. Not perfect, but rather best-effort.
270 bool translate_len(string const & length, string & valstring, string & unit)
272 if (!splitLatexLength(length, valstring, unit))
274 // LyX uses percent values
276 istringstream iss(valstring);
281 string const percentval = oss.str();
283 if (unit.empty() || unit[0] != '\\')
285 string::size_type const i = unit.find(' ');
286 string const endlen = (i == string::npos) ? string() : string(unit, i);
287 if (unit == "\\textwidth") {
288 valstring = percentval;
289 unit = "text%" + endlen;
290 } else if (unit == "\\columnwidth") {
291 valstring = percentval;
292 unit = "col%" + endlen;
293 } else if (unit == "\\paperwidth") {
294 valstring = percentval;
295 unit = "page%" + endlen;
296 } else if (unit == "\\linewidth") {
297 valstring = percentval;
298 unit = "line%" + endlen;
299 } else if (unit == "\\paperheight") {
300 valstring = percentval;
301 unit = "pheight%" + endlen;
302 } else if (unit == "\\textheight") {
303 valstring = percentval;
304 unit = "theight%" + endlen;
312 string translate_len(string const & length)
316 if (translate_len(length, value, unit))
318 // If the input is invalid, return what we have.
326 * Translates a LaTeX length into \p value, \p unit and
327 * \p special parts suitable for a box inset.
328 * The difference from translate_len() is that a box inset knows about
329 * some special "units" that are stored in \p special.
331 void translate_box_len(string const & length, string & value, string & unit, string & special)
333 if (translate_len(length, value, unit)) {
334 if (unit == "\\height" || unit == "\\depth" ||
335 unit == "\\totalheight" || unit == "\\width") {
336 special = unit.substr(1);
337 // The unit is not used, but LyX requires a dummy setting
350 * Find a file with basename \p name in path \p path and an extension
353 string find_file(string const & name, string const & path,
354 char const * const * extensions)
356 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
358 for (char const * const * what = extensions; *what; ++what) {
359 string const trial = addExtension(name, *what);
360 if (makeAbsPath(trial, path).exists())
367 void begin_inset(ostream & os, string const & name)
369 os << "\n\\begin_inset " << name;
373 void end_inset(ostream & os)
375 os << "\n\\end_inset\n\n";
379 void skip_braces(Parser & p)
381 if (p.next_token().cat() != catBegin)
384 if (p.next_token().cat() == catEnd) {
392 void handle_ert(ostream & os, string const & s, Context & context)
394 // We must have a valid layout before outputting the ERT inset.
395 context.check_layout(os);
396 Context newcontext(true, context.textclass);
397 begin_inset(os, "ERT");
398 os << "\nstatus collapsed\n";
399 newcontext.check_layout(os);
400 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
402 os << "\n\\backslash\n";
403 else if (*it == '\n') {
404 newcontext.new_paragraph(os);
405 newcontext.check_layout(os);
409 newcontext.check_end_layout(os);
414 void handle_comment(ostream & os, string const & s, Context & context)
416 // TODO: Handle this better
417 Context newcontext(true, context.textclass);
418 begin_inset(os, "ERT");
419 os << "\nstatus collapsed\n";
420 newcontext.check_layout(os);
421 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
423 os << "\n\\backslash\n";
427 // make sure that our comment is the last thing on the line
428 newcontext.new_paragraph(os);
429 newcontext.check_layout(os);
430 newcontext.check_end_layout(os);
435 class isLayout : public std::unary_function<LayoutPtr, bool> {
437 isLayout(string const name) : name_(name) {}
438 bool operator()(LayoutPtr const & ptr) const {
439 return ptr->latexname() == name_;
446 LayoutPtr findLayout(TextClass const & textclass,
449 TextClass::const_iterator beg = textclass.begin();
450 TextClass::const_iterator end = textclass.end();
452 TextClass::const_iterator
453 it = std::find_if(beg, end, isLayout(name));
455 return (it == end) ? LayoutPtr() : *it;
459 void eat_whitespace(Parser &, ostream &, Context &, bool);
462 void output_command_layout(ostream & os, Parser & p, bool outer,
463 Context & parent_context,
466 parent_context.check_end_layout(os);
467 Context context(true, parent_context.textclass, newlayout,
468 parent_context.layout, parent_context.font);
469 if (parent_context.deeper_paragraph) {
470 // We are beginning a nested environment after a
471 // deeper paragraph inside the outer list environment.
472 // Therefore we don't need to output a "begin deeper".
473 context.need_end_deeper = true;
475 context.check_deeper(os);
476 context.check_layout(os);
477 if (context.layout->optionalargs > 0) {
478 eat_whitespace(p, os, context, false);
479 if (p.next_token().character() == '[') {
480 p.get_token(); // eat '['
481 begin_inset(os, "OptArg\n");
482 os << "status collapsed\n\n";
483 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
485 eat_whitespace(p, os, context, false);
488 parse_text(p, os, FLAG_ITEM, outer, context);
489 context.check_end_layout(os);
490 if (parent_context.deeper_paragraph) {
491 // We must suppress the "end deeper" because we
492 // suppressed the "begin deeper" above.
493 context.need_end_deeper = false;
495 context.check_end_deeper(os);
496 // We don't need really a new paragraph, but
497 // we must make sure that the next item gets a \begin_layout.
498 parent_context.new_paragraph(os);
503 * Output a space if necessary.
504 * This function gets called for every whitespace token.
506 * We have three cases here:
507 * 1. A space must be suppressed. Example: The lyxcode case below
508 * 2. A space may be suppressed. Example: Spaces before "\par"
509 * 3. A space must not be suppressed. Example: A space between two words
511 * We currently handle only 1. and 3 and from 2. only the case of
512 * spaces before newlines as a side effect.
514 * 2. could be used to suppress as many spaces as possible. This has two effects:
515 * - Reimporting LyX generated LaTeX files changes almost no whitespace
516 * - Superflous whitespace from non LyX generated LaTeX files is removed.
517 * The drawback is that the logic inside the function becomes
518 * complicated, and that is the reason why it is not implemented.
520 void check_space(Parser const & p, ostream & os, Context & context)
522 Token const next = p.next_token();
523 Token const curr = p.curr_token();
524 // A space before a single newline and vice versa must be ignored
525 // LyX emits a newline before \end{lyxcode}.
526 // This newline must be ignored,
527 // otherwise LyX will add an additional protected space.
528 if (next.cat() == catSpace ||
529 next.cat() == catNewline ||
530 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
533 context.check_layout(os);
539 * Parse all arguments of \p command
541 void parse_arguments(string const & command,
542 vector<ArgumentType> const & template_arguments,
543 Parser & p, ostream & os, bool outer, Context & context)
545 string ert = command;
546 size_t no_arguments = template_arguments.size();
547 for (size_t i = 0; i < no_arguments; ++i) {
548 switch (template_arguments[i]) {
550 // This argument contains regular LaTeX
551 handle_ert(os, ert + '{', context);
552 eat_whitespace(p, os, context, false);
553 parse_text(p, os, FLAG_ITEM, outer, context);
557 // This argument may contain special characters
558 ert += '{' + p.verbatim_item() + '}';
565 handle_ert(os, ert, context);
570 * Check whether \p command is a known command. If yes,
571 * handle the command with all arguments.
572 * \return true if the command was parsed, false otherwise.
574 bool parse_command(string const & command, Parser & p, ostream & os,
575 bool outer, Context & context)
577 if (known_commands.find(command) != known_commands.end()) {
578 parse_arguments(command, known_commands[command], p, os,
586 /// Parses a minipage or parbox
587 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
588 Context & parent_context, bool use_parbox)
592 // We need to set the height to the LaTeX default of 1\\totalheight
593 // for the case when no height argument is given
594 string height_value = "1";
595 string height_unit = "in";
596 string height_special = "totalheight";
598 if (p.next_token().asInput() == "[") {
599 position = p.getArg('[', ']');
600 if (position != "t" && position != "c" && position != "b") {
602 cerr << "invalid position for minipage/parbox" << endl;
604 if (p.next_token().asInput() == "[") {
605 latex_height = p.getArg('[', ']');
606 translate_box_len(latex_height, height_value, height_unit, height_special);
608 if (p.next_token().asInput() == "[") {
609 inner_pos = p.getArg('[', ']');
610 if (inner_pos != "c" && inner_pos != "t" &&
611 inner_pos != "b" && inner_pos != "s") {
612 inner_pos = position;
613 cerr << "invalid inner_pos for minipage/parbox"
621 string const latex_width = p.verbatim_item();
622 translate_len(latex_width, width_value, width_unit);
623 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
624 // LyX can't handle length variables
629 ss << "\\begin{minipage}";
630 if (!position.empty())
631 ss << '[' << position << ']';
632 if (!latex_height.empty())
633 ss << '[' << latex_height << ']';
634 if (!inner_pos.empty())
635 ss << '[' << inner_pos << ']';
636 ss << "{" << latex_width << "}";
639 handle_ert(os, ss.str(), parent_context);
640 parent_context.new_paragraph(os);
641 parse_text_in_inset(p, os, flags, outer, parent_context);
643 handle_ert(os, "}", parent_context);
645 handle_ert(os, "\\end{minipage}", parent_context);
647 // LyX does not like empty positions, so we have
648 // to set them to the LaTeX default values here.
649 if (position.empty())
651 if (inner_pos.empty())
652 inner_pos = position;
653 parent_context.check_layout(os);
654 begin_inset(os, "Box Frameless\n");
655 os << "position \"" << position << "\"\n";
656 os << "hor_pos \"c\"\n";
657 os << "has_inner_box 1\n";
658 os << "inner_pos \"" << inner_pos << "\"\n";
659 os << "use_parbox " << use_parbox << "\n";
660 os << "width \"" << width_value << width_unit << "\"\n";
661 os << "special \"none\"\n";
662 os << "height \"" << height_value << height_unit << "\"\n";
663 os << "height_special \"" << height_special << "\"\n";
664 os << "status open\n\n";
665 parse_text_in_inset(p, os, flags, outer, parent_context);
667 #ifdef PRESERVE_LAYOUT
668 // lyx puts a % after the end of the minipage
669 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
671 //handle_comment(os, "%dummy", parent_context);
674 parent_context.new_paragraph(os);
676 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
677 //handle_comment(os, "%dummy", parent_context);
680 // We add a protected space if something real follows
681 if (p.good() && p.next_token().cat() != catComment) {
682 os << "\\InsetSpace ~\n";
690 /// parse an unknown environment
691 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
692 unsigned flags, bool outer,
693 Context & parent_context)
695 if (name == "tabbing")
696 // We need to remember that we have to handle '\=' specially
697 flags |= FLAG_TABBING;
699 // We need to translate font changes and paragraphs inside the
700 // environment to ERT if we have a non standard font.
701 // Otherwise things like
702 // \large\begin{foo}\huge bar\end{foo}
704 bool const specialfont =
705 (parent_context.font != parent_context.normalfont);
706 bool const new_layout_allowed = parent_context.new_layout_allowed;
708 parent_context.new_layout_allowed = false;
709 handle_ert(os, "\\begin{" + name + "}", parent_context);
710 parse_text_snippet(p, os, flags, outer, parent_context);
711 handle_ert(os, "\\end{" + name + "}", parent_context);
713 parent_context.new_layout_allowed = new_layout_allowed;
717 void parse_environment(Parser & p, ostream & os, bool outer,
718 Context & parent_context)
721 string const name = p.getArg('{', '}');
722 const bool is_starred = suffixIs(name, '*');
723 string const unstarred_name = rtrim(name, "*");
724 active_environments.push_back(name);
726 if (is_math_env(name)) {
727 parent_context.check_layout(os);
728 begin_inset(os, "Formula ");
729 os << "\\begin{" << name << "}";
730 parse_math(p, os, FLAG_END, MATH_MODE);
731 os << "\\end{" << name << "}";
735 else if (name == "tabular" || name == "longtable") {
736 eat_whitespace(p, os, parent_context, false);
737 parent_context.check_layout(os);
738 begin_inset(os, "Tabular ");
739 handle_tabular(p, os, name == "longtable", parent_context);
744 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
745 eat_whitespace(p, os, parent_context, false);
746 parent_context.check_layout(os);
747 begin_inset(os, "Float " + unstarred_name + "\n");
748 if (p.next_token().asInput() == "[") {
749 os << "placement " << p.getArg('[', ']') << '\n';
751 os << "wide " << convert<string>(is_starred)
752 << "\nsideways false"
753 << "\nstatus open\n\n";
754 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
756 // We don't need really a new paragraph, but
757 // we must make sure that the next item gets a \begin_layout.
758 parent_context.new_paragraph(os);
762 else if (name == "minipage") {
763 eat_whitespace(p, os, parent_context, false);
764 parse_box(p, os, FLAG_END, outer, parent_context, false);
768 else if (name == "comment") {
769 eat_whitespace(p, os, parent_context, false);
770 parent_context.check_layout(os);
771 begin_inset(os, "Note Comment\n");
772 os << "status open\n";
773 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
778 else if (name == "lyxgreyedout") {
779 eat_whitespace(p, os, parent_context, false);
780 parent_context.check_layout(os);
781 begin_inset(os, "Note Greyedout\n");
782 os << "status open\n";
783 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
788 else if (name == "framed") {
789 eat_whitespace(p, os, parent_context, false);
790 parent_context.check_layout(os);
791 begin_inset(os, "Note Framed\n");
792 os << "status open\n";
793 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
798 else if (name == "shaded") {
799 eat_whitespace(p, os, parent_context, false);
800 parent_context.check_layout(os);
801 begin_inset(os, "Note Shaded\n");
802 os << "status open\n";
803 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
808 else if (!parent_context.new_layout_allowed)
809 parse_unknown_environment(p, name, os, FLAG_END, outer,
812 // Alignment settings
813 else if (name == "center" || name == "flushleft" || name == "flushright" ||
814 name == "centering" || name == "raggedright" || name == "raggedleft") {
815 eat_whitespace(p, os, parent_context, false);
816 // We must begin a new paragraph if not already done
817 if (! parent_context.atParagraphStart()) {
818 parent_context.check_end_layout(os);
819 parent_context.new_paragraph(os);
821 if (name == "flushleft" || name == "raggedright")
822 parent_context.add_extra_stuff("\\align left\n");
823 else if (name == "flushright" || name == "raggedleft")
824 parent_context.add_extra_stuff("\\align right\n");
826 parent_context.add_extra_stuff("\\align center\n");
827 parse_text(p, os, FLAG_END, outer, parent_context);
828 // Just in case the environment is empty ..
829 parent_context.extra_stuff.erase();
830 // We must begin a new paragraph to reset the alignment
831 parent_context.new_paragraph(os);
835 // The single '=' is meant here.
836 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
837 newlayout->isEnvironment()) {
838 eat_whitespace(p, os, parent_context, false);
839 Context context(true, parent_context.textclass, newlayout,
840 parent_context.layout, parent_context.font);
841 if (parent_context.deeper_paragraph) {
842 // We are beginning a nested environment after a
843 // deeper paragraph inside the outer list environment.
844 // Therefore we don't need to output a "begin deeper".
845 context.need_end_deeper = true;
847 parent_context.check_end_layout(os);
848 switch (context.layout->latextype) {
849 case LATEX_LIST_ENVIRONMENT:
850 context.extra_stuff = "\\labelwidthstring "
851 + p.verbatim_item() + '\n';
854 case LATEX_BIB_ENVIRONMENT:
855 p.verbatim_item(); // swallow next arg
861 context.check_deeper(os);
862 parse_text(p, os, FLAG_END, outer, context);
863 context.check_end_layout(os);
864 if (parent_context.deeper_paragraph) {
865 // We must suppress the "end deeper" because we
866 // suppressed the "begin deeper" above.
867 context.need_end_deeper = false;
869 context.check_end_deeper(os);
870 parent_context.new_paragraph(os);
874 else if (name == "appendix") {
875 // This is no good latex style, but it works and is used in some documents...
876 eat_whitespace(p, os, parent_context, false);
877 parent_context.check_end_layout(os);
878 Context context(true, parent_context.textclass, parent_context.layout,
879 parent_context.layout, parent_context.font);
880 context.check_layout(os);
881 os << "\\start_of_appendix\n";
882 parse_text(p, os, FLAG_END, outer, context);
883 context.check_end_layout(os);
887 else if (known_environments.find(name) != known_environments.end()) {
888 vector<ArgumentType> arguments = known_environments[name];
889 // The last "argument" denotes wether we may translate the
890 // environment contents to LyX
891 // The default required if no argument is given makes us
892 // compatible with the reLyXre environment.
893 ArgumentType contents = arguments.empty() ?
896 if (!arguments.empty())
897 arguments.pop_back();
898 // See comment in parse_unknown_environment()
899 bool const specialfont =
900 (parent_context.font != parent_context.normalfont);
901 bool const new_layout_allowed =
902 parent_context.new_layout_allowed;
904 parent_context.new_layout_allowed = false;
905 parse_arguments("\\begin{" + name + "}", arguments, p, os,
906 outer, parent_context);
907 if (contents == verbatim)
908 handle_ert(os, p.verbatimEnvironment(name),
911 parse_text_snippet(p, os, FLAG_END, outer,
913 handle_ert(os, "\\end{" + name + "}", parent_context);
915 parent_context.new_layout_allowed = new_layout_allowed;
919 parse_unknown_environment(p, name, os, FLAG_END, outer,
922 active_environments.pop_back();
926 /// parses a comment and outputs it to \p os.
927 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
929 BOOST_ASSERT(t.cat() == catComment);
930 if (!t.cs().empty()) {
931 context.check_layout(os);
932 handle_comment(os, '%' + t.cs(), context);
933 if (p.next_token().cat() == catNewline) {
934 // A newline after a comment line starts a new
936 if (context.new_layout_allowed) {
937 if(!context.atParagraphStart())
938 // Only start a new paragraph if not already
939 // done (we might get called recursively)
940 context.new_paragraph(os);
942 handle_ert(os, "\n", context);
943 eat_whitespace(p, os, context, true);
953 * Reads spaces and comments until the first non-space, non-comment token.
954 * New paragraphs (double newlines or \\par) are handled like simple spaces
955 * if \p eatParagraph is true.
956 * Spaces are skipped, but comments are written to \p os.
958 void eat_whitespace(Parser & p, ostream & os, Context & context,
962 Token const & t = p.get_token();
963 if (t.cat() == catComment)
964 parse_comment(p, os, t, context);
965 else if ((! eatParagraph && p.isParagraph()) ||
966 (t.cat() != catSpace && t.cat() != catNewline)) {
975 * Set a font attribute, parse text and reset the font attribute.
976 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
977 * \param currentvalue Current value of the attribute. Is set to the new
978 * value during parsing.
979 * \param newvalue New value of the attribute
981 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
982 Context & context, string const & attribute,
983 string & currentvalue, string const & newvalue)
985 context.check_layout(os);
986 string const oldvalue = currentvalue;
987 currentvalue = newvalue;
988 os << '\n' << attribute << ' ' << newvalue << "\n";
989 parse_text_snippet(p, os, flags, outer, context);
990 context.check_layout(os);
991 os << '\n' << attribute << ' ' << oldvalue << "\n";
992 currentvalue = oldvalue;
996 /// get the arguments of a natbib or jurabib citation command
997 void get_cite_arguments(Parser & p, bool natbibOrder,
998 string & before, string & after)
1000 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1002 // text before the citation
1004 // text after the citation
1005 after = p.getFullOpt();
1007 if (!after.empty()) {
1008 before = p.getFullOpt();
1009 if (natbibOrder && !before.empty())
1010 std::swap(before, after);
1015 /// Convert filenames with TeX macros and/or quotes to something LyX
1017 string const normalize_filename(string const & name)
1019 Parser p(trim(name, "\""));
1022 Token const & t = p.get_token();
1023 if (t.cat() != catEscape)
1025 else if (t.cs() == "lyxdot") {
1026 // This is used by LyX for simple dots in relative
1030 } else if (t.cs() == "space") {
1040 /// Convert \p name from TeX convention (relative to master file) to LyX
1041 /// convention (relative to .lyx file) if it is relative
1042 void fix_relative_filename(string & name)
1044 if (lyx::support::absolutePath(name))
1046 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1048 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1049 from_utf8(getParentFilePath())));
1053 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1054 void parse_noweb(Parser & p, ostream & os, Context & context)
1056 // assemble the rest of the keyword
1060 Token const & t = p.get_token();
1061 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1064 scrap = (p.good() && p.next_token().asInput() == "=");
1066 name += p.get_token().asInput();
1069 name += t.asInput();
1072 if (!scrap || !context.new_layout_allowed ||
1073 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1074 cerr << "Warning: Could not interpret '" << name
1075 << "'. Ignoring it." << endl;
1079 // We use new_paragraph instead of check_end_layout because the stuff
1080 // following the noweb chunk needs to start with a \begin_layout.
1081 // This may create a new paragraph even if there was none in the
1082 // noweb file, but the alternative is an invalid LyX file. Since
1083 // noweb code chunks are implemented with a layout style in LyX they
1084 // always must be in an own paragraph.
1085 context.new_paragraph(os);
1086 Context newcontext(true, context.textclass,
1087 context.textclass[from_ascii("Scrap")]);
1088 newcontext.check_layout(os);
1091 Token const & t = p.get_token();
1092 // We abuse the parser a bit, because this is no TeX syntax
1094 if (t.cat() == catEscape)
1095 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1097 os << subst(t.asInput(), "\n", "\n\\newline\n");
1098 // The scrap chunk is ended by an @ at the beginning of a line.
1099 // After the @ the line may contain a comment and/or
1100 // whitespace, but nothing else.
1101 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1102 (p.next_token().cat() == catSpace ||
1103 p.next_token().cat() == catNewline ||
1104 p.next_token().cat() == catComment)) {
1105 while (p.good() && p.next_token().cat() == catSpace)
1106 os << p.get_token().asInput();
1107 if (p.next_token().cat() == catComment)
1108 // The comment includes a final '\n'
1109 os << p.get_token().asInput();
1111 if (p.next_token().cat() == catNewline)
1118 newcontext.check_end_layout(os);
1121 } // anonymous namespace
1124 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1127 LayoutPtr newlayout;
1128 // Store the latest bibliographystyle (needed for bibtex inset)
1129 string bibliographystyle;
1130 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1131 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1133 Token const & t = p.get_token();
1136 cerr << "t: " << t << " flags: " << flags << "\n";
1139 if (flags & FLAG_ITEM) {
1140 if (t.cat() == catSpace)
1143 flags &= ~FLAG_ITEM;
1144 if (t.cat() == catBegin) {
1145 // skip the brace and collect everything to the next matching
1147 flags |= FLAG_BRACE_LAST;
1151 // handle only this single token, leave the loop if done
1152 flags |= FLAG_LEAVE;
1155 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1161 if (t.cat() == catMath) {
1162 // we are inside some text mode thingy, so opening new math is allowed
1163 context.check_layout(os);
1164 begin_inset(os, "Formula ");
1165 Token const & n = p.get_token();
1166 if (n.cat() == catMath && outer) {
1167 // TeX's $$...$$ syntax for displayed math
1169 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1171 p.get_token(); // skip the second '$' token
1173 // simple $...$ stuff
1176 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1182 else if (t.cat() == catSuper || t.cat() == catSub)
1183 cerr << "catcode " << t << " illegal in text mode\n";
1185 // Basic support for english quotes. This should be
1186 // extended to other quotes, but is not so easy (a
1187 // left english quote is the same as a right german
1189 else if (t.asInput() == "`"
1190 && p.next_token().asInput() == "`") {
1191 context.check_layout(os);
1192 begin_inset(os, "Quotes ");
1198 else if (t.asInput() == "'"
1199 && p.next_token().asInput() == "'") {
1200 context.check_layout(os);
1201 begin_inset(os, "Quotes ");
1208 else if (t.asInput() == "<"
1209 && p.next_token().asInput() == "<" && noweb_mode) {
1211 parse_noweb(p, os, context);
1214 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1215 check_space(p, os, context);
1217 else if (t.character() == '[' && noweb_mode &&
1218 p.next_token().character() == '[') {
1219 // These can contain underscores
1221 string const s = p.getFullOpt() + ']';
1222 if (p.next_token().character() == ']')
1225 cerr << "Warning: Inserting missing ']' in '"
1226 << s << "'." << endl;
1227 handle_ert(os, s, context);
1230 else if (t.cat() == catLetter ||
1231 t.cat() == catOther ||
1232 t.cat() == catAlign ||
1233 t.cat() == catParameter) {
1234 // This translates "&" to "\\&" which may be wrong...
1235 context.check_layout(os);
1236 os << t.character();
1239 else if (p.isParagraph()) {
1240 if (context.new_layout_allowed)
1241 context.new_paragraph(os);
1243 handle_ert(os, "\\par ", context);
1244 eat_whitespace(p, os, context, true);
1247 else if (t.cat() == catActive) {
1248 context.check_layout(os);
1249 if (t.character() == '~') {
1250 if (context.layout->free_spacing)
1253 os << "\\InsetSpace ~\n";
1255 os << t.character();
1258 else if (t.cat() == catBegin &&
1259 p.next_token().cat() == catEnd) {
1261 Token const prev = p.prev_token();
1263 if (p.next_token().character() == '`' ||
1264 (prev.character() == '-' &&
1265 p.next_token().character() == '-'))
1266 ; // ignore it in {}`` or -{}-
1268 handle_ert(os, "{}", context);
1272 else if (t.cat() == catBegin) {
1273 context.check_layout(os);
1274 // special handling of font attribute changes
1275 Token const prev = p.prev_token();
1276 Token const next = p.next_token();
1277 TeXFont const oldFont = context.font;
1278 if (next.character() == '[' ||
1279 next.character() == ']' ||
1280 next.character() == '*') {
1282 if (p.next_token().cat() == catEnd) {
1283 os << next.character();
1287 handle_ert(os, "{", context);
1288 parse_text_snippet(p, os,
1291 handle_ert(os, "}", context);
1293 } else if (! context.new_layout_allowed) {
1294 handle_ert(os, "{", context);
1295 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1297 handle_ert(os, "}", context);
1298 } else if (is_known(next.cs(), known_sizes)) {
1299 // next will change the size, so we must
1301 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1303 if (!context.atParagraphStart())
1305 << context.font.size << "\n";
1306 } else if (is_known(next.cs(), known_font_families)) {
1307 // next will change the font family, so we
1308 // must reset it here
1309 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1311 if (!context.atParagraphStart())
1313 << context.font.family << "\n";
1314 } else if (is_known(next.cs(), known_font_series)) {
1315 // next will change the font series, so we
1316 // must reset it here
1317 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1319 if (!context.atParagraphStart())
1321 << context.font.series << "\n";
1322 } else if (is_known(next.cs(), known_font_shapes)) {
1323 // next will change the font shape, so we
1324 // must reset it here
1325 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1327 if (!context.atParagraphStart())
1329 << context.font.shape << "\n";
1330 } else if (is_known(next.cs(), known_old_font_families) ||
1331 is_known(next.cs(), known_old_font_series) ||
1332 is_known(next.cs(), known_old_font_shapes)) {
1333 // next will change the font family, series
1334 // and shape, so we must reset it here
1335 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1337 if (!context.atParagraphStart())
1339 << context.font.family
1341 << context.font.series
1343 << context.font.shape << "\n";
1345 handle_ert(os, "{", context);
1346 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1348 handle_ert(os, "}", context);
1352 else if (t.cat() == catEnd) {
1353 if (flags & FLAG_BRACE_LAST) {
1356 cerr << "stray '}' in text\n";
1357 handle_ert(os, "}", context);
1360 else if (t.cat() == catComment)
1361 parse_comment(p, os, t, context);
1364 // control sequences
1367 else if (t.cs() == "(") {
1368 context.check_layout(os);
1369 begin_inset(os, "Formula");
1371 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1376 else if (t.cs() == "[") {
1377 context.check_layout(os);
1378 begin_inset(os, "Formula");
1380 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1385 else if (t.cs() == "begin")
1386 parse_environment(p, os, outer, context);
1388 else if (t.cs() == "end") {
1389 if (flags & FLAG_END) {
1390 // eat environment name
1391 string const name = p.getArg('{', '}');
1392 if (name != active_environment())
1393 cerr << "\\end{" + name + "} does not match \\begin{"
1394 + active_environment() + "}\n";
1397 p.error("found 'end' unexpectedly");
1400 else if (t.cs() == "item") {
1403 bool optarg = false;
1404 if (p.next_token().character() == '[') {
1405 p.get_token(); // eat '['
1406 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1411 context.check_layout(os);
1412 if (context.has_item) {
1413 // An item in an unknown list-like environment
1414 // FIXME: Do this in check_layout()!
1415 context.has_item = false;
1417 handle_ert(os, "\\item", context);
1419 handle_ert(os, "\\item ", context);
1422 if (context.layout->labeltype != LABEL_MANUAL) {
1423 // lyx does not support \item[\mybullet]
1424 // in itemize environments
1425 handle_ert(os, "[", context);
1427 handle_ert(os, "]", context);
1428 } else if (!s.empty()) {
1429 // The space is needed to separate the
1430 // item from the rest of the sentence.
1432 eat_whitespace(p, os, context, false);
1437 else if (t.cs() == "bibitem") {
1439 context.check_layout(os);
1442 os << '{' << p.verbatim_item() << '}' << "\n";
1445 else if (t.cs() == "def") {
1446 context.check_layout(os);
1447 eat_whitespace(p, os, context, false);
1448 string name = p.get_token().cs();
1449 eat_whitespace(p, os, context, false);
1455 while (p.next_token().cat() != catBegin) {
1456 if (p.next_token().cat() == catParameter) {
1461 // followed by number?
1462 if (p.next_token().cat() == catOther) {
1463 char c = p.getChar();
1465 // number = current arity + 1?
1466 if (c == arity + '0' + 1)
1471 paramtext += p.get_token().asString();
1473 paramtext += p.get_token().asString();
1478 // only output simple (i.e. compatible) macro as FormulaMacros
1479 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1481 context.check_layout(os);
1482 begin_inset(os, "FormulaMacro");
1486 handle_ert(os, ert, context);
1489 else if (t.cs() == "noindent") {
1491 context.add_extra_stuff("\\noindent\n");
1494 else if (t.cs() == "appendix") {
1495 context.add_extra_stuff("\\start_of_appendix\n");
1496 // We need to start a new paragraph. Otherwise the
1497 // appendix in 'bla\appendix\chapter{' would start
1499 context.new_paragraph(os);
1500 // We need to make sure that the paragraph is
1501 // generated even if it is empty. Otherwise the
1502 // appendix in '\par\appendix\par\chapter{' would
1504 context.check_layout(os);
1505 // FIXME: This is a hack to prevent paragraph
1506 // deletion if it is empty. Handle this better!
1508 "%dummy comment inserted by tex2lyx to "
1509 "ensure that this paragraph is not empty",
1511 // Both measures above may generate an additional
1512 // empty paragraph, but that does not hurt, because
1513 // whitespace does not matter here.
1514 eat_whitespace(p, os, context, true);
1517 // Must attempt to parse "Section*" before "Section".
1518 else if ((p.next_token().asInput() == "*") &&
1519 context.new_layout_allowed &&
1520 // The single '=' is meant here.
1521 (newlayout = findLayout(context.textclass,
1522 t.cs() + '*')).get() &&
1523 newlayout->isCommand()) {
1525 output_command_layout(os, p, outer, context, newlayout);
1529 // The single '=' is meant here.
1530 else if (context.new_layout_allowed &&
1531 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1532 newlayout->isCommand()) {
1533 output_command_layout(os, p, outer, context, newlayout);
1537 // Special handling for \caption
1538 // FIXME: remove this when InsetCaption is supported.
1539 else if (context.new_layout_allowed &&
1540 t.cs() == captionlayout->latexname()) {
1541 output_command_layout(os, p, outer, context,
1546 else if (t.cs() == "includegraphics") {
1547 bool const clip = p.next_token().asInput() == "*";
1550 map<string, string> opts = split_map(p.getArg('[', ']'));
1552 opts["clip"] = string();
1553 string name = normalize_filename(p.verbatim_item());
1555 string const path = getMasterFilePath();
1556 // We want to preserve relative / absolute filenames,
1557 // therefore path is only used for testing
1558 // FIXME UNICODE encoding of name and path may be
1559 // wrong (makeAbsPath expects utf8)
1560 if (!makeAbsPath(name, path).exists()) {
1561 // The file extension is probably missing.
1562 // Now try to find it out.
1563 string const dvips_name =
1564 find_file(name, path,
1565 known_dvips_graphics_formats);
1566 string const pdftex_name =
1567 find_file(name, path,
1568 known_pdftex_graphics_formats);
1569 if (!dvips_name.empty()) {
1570 if (!pdftex_name.empty()) {
1571 cerr << "This file contains the "
1573 "\"\\includegraphics{"
1575 "However, files\n\""
1576 << dvips_name << "\" and\n\""
1577 << pdftex_name << "\"\n"
1578 "both exist, so I had to make a "
1579 "choice and took the first one.\n"
1580 "Please move the unwanted one "
1581 "someplace else and try again\n"
1582 "if my choice was wrong."
1586 } else if (!pdftex_name.empty())
1590 // FIXME UNICODE encoding of name and path may be
1591 // wrong (makeAbsPath expects utf8)
1592 if (makeAbsPath(name, path).exists())
1593 fix_relative_filename(name);
1595 cerr << "Warning: Could not find graphics file '"
1596 << name << "'." << endl;
1598 context.check_layout(os);
1599 begin_inset(os, "Graphics ");
1600 os << "\n\tfilename " << name << '\n';
1601 if (opts.find("width") != opts.end())
1603 << translate_len(opts["width"]) << '\n';
1604 if (opts.find("height") != opts.end())
1606 << translate_len(opts["height"]) << '\n';
1607 if (opts.find("scale") != opts.end()) {
1608 istringstream iss(opts["scale"]);
1612 os << "\tscale " << val << '\n';
1614 if (opts.find("angle") != opts.end())
1615 os << "\trotateAngle "
1616 << opts["angle"] << '\n';
1617 if (opts.find("origin") != opts.end()) {
1619 string const opt = opts["origin"];
1620 if (opt.find('l') != string::npos) ss << "left";
1621 if (opt.find('r') != string::npos) ss << "right";
1622 if (opt.find('c') != string::npos) ss << "center";
1623 if (opt.find('t') != string::npos) ss << "Top";
1624 if (opt.find('b') != string::npos) ss << "Bottom";
1625 if (opt.find('B') != string::npos) ss << "Baseline";
1626 if (!ss.str().empty())
1627 os << "\trotateOrigin " << ss.str() << '\n';
1629 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1631 if (opts.find("keepaspectratio") != opts.end())
1632 os << "\tkeepAspectRatio\n";
1633 if (opts.find("clip") != opts.end())
1635 if (opts.find("draft") != opts.end())
1637 if (opts.find("bb") != opts.end())
1638 os << "\tBoundingBox "
1639 << opts["bb"] << '\n';
1640 int numberOfbbOptions = 0;
1641 if (opts.find("bbllx") != opts.end())
1642 numberOfbbOptions++;
1643 if (opts.find("bblly") != opts.end())
1644 numberOfbbOptions++;
1645 if (opts.find("bburx") != opts.end())
1646 numberOfbbOptions++;
1647 if (opts.find("bbury") != opts.end())
1648 numberOfbbOptions++;
1649 if (numberOfbbOptions == 4)
1650 os << "\tBoundingBox "
1651 << opts["bbllx"] << opts["bblly"]
1652 << opts["bburx"] << opts["bbury"] << '\n';
1653 else if (numberOfbbOptions > 0)
1654 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1655 numberOfbbOptions = 0;
1656 if (opts.find("natwidth") != opts.end())
1657 numberOfbbOptions++;
1658 if (opts.find("natheight") != opts.end())
1659 numberOfbbOptions++;
1660 if (numberOfbbOptions == 2)
1661 os << "\tBoundingBox 0bp 0bp "
1662 << opts["natwidth"] << opts["natheight"] << '\n';
1663 else if (numberOfbbOptions > 0)
1664 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1665 ostringstream special;
1666 if (opts.find("hiresbb") != opts.end())
1667 special << "hiresbb,";
1668 if (opts.find("trim") != opts.end())
1670 if (opts.find("viewport") != opts.end())
1671 special << "viewport=" << opts["viewport"] << ',';
1672 if (opts.find("totalheight") != opts.end())
1673 special << "totalheight=" << opts["totalheight"] << ',';
1674 if (opts.find("type") != opts.end())
1675 special << "type=" << opts["type"] << ',';
1676 if (opts.find("ext") != opts.end())
1677 special << "ext=" << opts["ext"] << ',';
1678 if (opts.find("read") != opts.end())
1679 special << "read=" << opts["read"] << ',';
1680 if (opts.find("command") != opts.end())
1681 special << "command=" << opts["command"] << ',';
1682 string s_special = special.str();
1683 if (!s_special.empty()) {
1684 // We had special arguments. Remove the trailing ','.
1685 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1687 // TODO: Handle the unknown settings better.
1688 // Warn about invalid options.
1689 // Check whether some option was given twice.
1693 else if (t.cs() == "footnote" ||
1694 (t.cs() == "thanks" && context.layout->intitle)) {
1696 context.check_layout(os);
1697 begin_inset(os, "Foot\n");
1698 os << "status collapsed\n\n";
1699 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1703 else if (t.cs() == "marginpar") {
1705 context.check_layout(os);
1706 begin_inset(os, "Marginal\n");
1707 os << "status collapsed\n\n";
1708 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1712 else if (t.cs() == "ensuremath") {
1714 context.check_layout(os);
1715 string const s = p.verbatim_item();
1716 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1719 handle_ert(os, "\\ensuremath{" + s + "}",
1723 else if (t.cs() == "hfill") {
1724 context.check_layout(os);
1725 os << "\n\\hfill\n";
1730 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1731 // FIXME: Somehow prevent title layouts if
1732 // "maketitle" was not found
1734 skip_braces(p); // swallow this
1737 else if (t.cs() == "tableofcontents") {
1739 context.check_layout(os);
1740 begin_inset(os, "LatexCommand \\tableofcontents\n");
1742 skip_braces(p); // swallow this
1745 else if (t.cs() == "listoffigures") {
1747 context.check_layout(os);
1748 begin_inset(os, "FloatList figure\n");
1750 skip_braces(p); // swallow this
1753 else if (t.cs() == "listoftables") {
1755 context.check_layout(os);
1756 begin_inset(os, "FloatList table\n");
1758 skip_braces(p); // swallow this
1761 else if (t.cs() == "listof") {
1762 p.skip_spaces(true);
1763 string const name = p.get_token().asString();
1764 if (context.textclass.floats().typeExist(name)) {
1765 context.check_layout(os);
1766 begin_inset(os, "FloatList ");
1769 p.get_token(); // swallow second arg
1771 handle_ert(os, "\\listof{" + name + "}", context);
1774 else if (t.cs() == "textrm")
1775 parse_text_attributes(p, os, FLAG_ITEM, outer,
1776 context, "\\family",
1777 context.font.family, "roman");
1779 else if (t.cs() == "textsf")
1780 parse_text_attributes(p, os, FLAG_ITEM, outer,
1781 context, "\\family",
1782 context.font.family, "sans");
1784 else if (t.cs() == "texttt")
1785 parse_text_attributes(p, os, FLAG_ITEM, outer,
1786 context, "\\family",
1787 context.font.family, "typewriter");
1789 else if (t.cs() == "textmd")
1790 parse_text_attributes(p, os, FLAG_ITEM, outer,
1791 context, "\\series",
1792 context.font.series, "medium");
1794 else if (t.cs() == "textbf")
1795 parse_text_attributes(p, os, FLAG_ITEM, outer,
1796 context, "\\series",
1797 context.font.series, "bold");
1799 else if (t.cs() == "textup")
1800 parse_text_attributes(p, os, FLAG_ITEM, outer,
1802 context.font.shape, "up");
1804 else if (t.cs() == "textit")
1805 parse_text_attributes(p, os, FLAG_ITEM, outer,
1807 context.font.shape, "italic");
1809 else if (t.cs() == "textsl")
1810 parse_text_attributes(p, os, FLAG_ITEM, outer,
1812 context.font.shape, "slanted");
1814 else if (t.cs() == "textsc")
1815 parse_text_attributes(p, os, FLAG_ITEM, outer,
1817 context.font.shape, "smallcaps");
1819 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1820 context.check_layout(os);
1821 TeXFont oldFont = context.font;
1822 context.font.init();
1823 context.font.size = oldFont.size;
1824 os << "\n\\family " << context.font.family << "\n";
1825 os << "\n\\series " << context.font.series << "\n";
1826 os << "\n\\shape " << context.font.shape << "\n";
1827 if (t.cs() == "textnormal") {
1828 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1829 output_font_change(os, context.font, oldFont);
1830 context.font = oldFont;
1832 eat_whitespace(p, os, context, false);
1835 else if (t.cs() == "underbar") {
1836 // Do NOT handle \underline.
1837 // \underbar cuts through y, g, q, p etc.,
1838 // \underline does not.
1839 context.check_layout(os);
1840 os << "\n\\bar under\n";
1841 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1842 context.check_layout(os);
1843 os << "\n\\bar default\n";
1846 else if (t.cs() == "emph" || t.cs() == "noun") {
1847 context.check_layout(os);
1848 os << "\n\\" << t.cs() << " on\n";
1849 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1850 context.check_layout(os);
1851 os << "\n\\" << t.cs() << " default\n";
1854 else if (use_natbib &&
1855 is_known(t.cs(), known_natbib_commands) &&
1856 ((t.cs() != "citefullauthor" &&
1857 t.cs() != "citeyear" &&
1858 t.cs() != "citeyearpar") ||
1859 p.next_token().asInput() != "*")) {
1860 context.check_layout(os);
1862 // \citet[before][after]{a} \citet[after][before]{a}
1863 // \citet[before][]{a} \citet[][before]{a}
1864 // \citet[after]{a} \citet[after]{a}
1865 // \citet{a} \citet{a}
1866 string command = '\\' + t.cs();
1867 if (p.next_token().asInput() == "*") {
1871 if (command == "\\citefullauthor")
1872 // alternative name for "\\citeauthor*"
1873 command = "\\citeauthor*";
1875 // text before the citation
1877 // text after the citation
1879 get_cite_arguments(p, true, before, after);
1881 if (command == "\\cite") {
1882 // \cite without optional argument means
1883 // \citet, \cite with at least one optional
1884 // argument means \citep.
1885 if (before.empty() && after.empty())
1886 command = "\\citet";
1888 command = "\\citep";
1890 if (before.empty() && after == "[]")
1891 // avoid \citet[]{a}
1893 else if (before == "[]" && after == "[]") {
1894 // avoid \citet[][]{a}
1898 begin_inset(os, "LatexCommand ");
1899 os << command << after << before
1900 << '{' << p.verbatim_item() << "}\n";
1904 else if (use_jurabib &&
1905 is_known(t.cs(), known_jurabib_commands)) {
1906 context.check_layout(os);
1907 string const command = '\\' + t.cs();
1908 char argumentOrder = '\0';
1909 vector<string> const & options = used_packages["jurabib"];
1910 if (std::find(options.begin(), options.end(),
1911 "natbiborder") != options.end())
1912 argumentOrder = 'n';
1913 else if (std::find(options.begin(), options.end(),
1914 "jurabiborder") != options.end())
1915 argumentOrder = 'j';
1917 // text before the citation
1919 // text after the citation
1921 get_cite_arguments(p, argumentOrder != 'j', before, after);
1923 string const citation = p.verbatim_item();
1924 if (!before.empty() && argumentOrder == '\0') {
1925 cerr << "Warning: Assuming argument order "
1926 "of jurabib version 0.6 for\n'"
1927 << command << before << after << '{'
1928 << citation << "}'.\n"
1929 "Add 'jurabiborder' to the jurabib "
1930 "package options if you used an\n"
1931 "earlier jurabib version." << endl;
1933 begin_inset(os, "LatexCommand ");
1934 os << command << after << before
1935 << '{' << citation << "}\n";
1939 else if (is_known(t.cs(), known_latex_commands)) {
1940 // This needs to be after the check for natbib and
1941 // jurabib commands, because "cite" has different
1942 // arguments with natbib and jurabib.
1943 context.check_layout(os);
1944 begin_inset(os, "LatexCommand ");
1945 os << '\\' << t.cs();
1946 // lyx cannot handle newlines in a latex command
1947 // FIXME: Move the substitution into parser::getOpt()?
1948 os << subst(p.getOpt(), "\n", " ");
1949 os << subst(p.getOpt(), "\n", " ");
1950 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1954 else if (is_known(t.cs(), known_quotes)) {
1955 char const * const * where = is_known(t.cs(), known_quotes);
1956 context.check_layout(os);
1957 begin_inset(os, "Quotes ");
1958 os << known_coded_quotes[where - known_quotes];
1960 // LyX adds {} after the quote, so we have to eat
1961 // spaces here if there are any before a possible
1963 eat_whitespace(p, os, context, false);
1967 else if (is_known(t.cs(), known_sizes) &&
1968 context.new_layout_allowed) {
1969 char const * const * where = is_known(t.cs(), known_sizes);
1970 context.check_layout(os);
1971 TeXFont const oldFont = context.font;
1972 context.font.size = known_coded_sizes[where - known_sizes];
1973 output_font_change(os, oldFont, context.font);
1974 eat_whitespace(p, os, context, false);
1977 else if (is_known(t.cs(), known_font_families) &&
1978 context.new_layout_allowed) {
1979 char const * const * where =
1980 is_known(t.cs(), known_font_families);
1981 context.check_layout(os);
1982 TeXFont const oldFont = context.font;
1983 context.font.family =
1984 known_coded_font_families[where - known_font_families];
1985 output_font_change(os, oldFont, context.font);
1986 eat_whitespace(p, os, context, false);
1989 else if (is_known(t.cs(), known_font_series) &&
1990 context.new_layout_allowed) {
1991 char const * const * where =
1992 is_known(t.cs(), known_font_series);
1993 context.check_layout(os);
1994 TeXFont const oldFont = context.font;
1995 context.font.series =
1996 known_coded_font_series[where - known_font_series];
1997 output_font_change(os, oldFont, context.font);
1998 eat_whitespace(p, os, context, false);
2001 else if (is_known(t.cs(), known_font_shapes) &&
2002 context.new_layout_allowed) {
2003 char const * const * where =
2004 is_known(t.cs(), known_font_shapes);
2005 context.check_layout(os);
2006 TeXFont const oldFont = context.font;
2007 context.font.shape =
2008 known_coded_font_shapes[where - known_font_shapes];
2009 output_font_change(os, oldFont, context.font);
2010 eat_whitespace(p, os, context, false);
2012 else if (is_known(t.cs(), known_old_font_families) &&
2013 context.new_layout_allowed) {
2014 char const * const * where =
2015 is_known(t.cs(), known_old_font_families);
2016 context.check_layout(os);
2017 TeXFont const oldFont = context.font;
2018 context.font.init();
2019 context.font.size = oldFont.size;
2020 context.font.family =
2021 known_coded_font_families[where - known_old_font_families];
2022 output_font_change(os, oldFont, context.font);
2023 eat_whitespace(p, os, context, false);
2026 else if (is_known(t.cs(), known_old_font_series) &&
2027 context.new_layout_allowed) {
2028 char const * const * where =
2029 is_known(t.cs(), known_old_font_series);
2030 context.check_layout(os);
2031 TeXFont const oldFont = context.font;
2032 context.font.init();
2033 context.font.size = oldFont.size;
2034 context.font.series =
2035 known_coded_font_series[where - known_old_font_series];
2036 output_font_change(os, oldFont, context.font);
2037 eat_whitespace(p, os, context, false);
2040 else if (is_known(t.cs(), known_old_font_shapes) &&
2041 context.new_layout_allowed) {
2042 char const * const * where =
2043 is_known(t.cs(), known_old_font_shapes);
2044 context.check_layout(os);
2045 TeXFont const oldFont = context.font;
2046 context.font.init();
2047 context.font.size = oldFont.size;
2048 context.font.shape =
2049 known_coded_font_shapes[where - known_old_font_shapes];
2050 output_font_change(os, oldFont, context.font);
2051 eat_whitespace(p, os, context, false);
2054 else if (t.cs() == "LyX" || t.cs() == "TeX"
2055 || t.cs() == "LaTeX") {
2056 context.check_layout(os);
2058 skip_braces(p); // eat {}
2061 else if (t.cs() == "LaTeXe") {
2062 context.check_layout(os);
2064 skip_braces(p); // eat {}
2067 else if (t.cs() == "ldots") {
2068 context.check_layout(os);
2070 os << "\\SpecialChar \\ldots{}\n";
2073 else if (t.cs() == "lyxarrow") {
2074 context.check_layout(os);
2075 os << "\\SpecialChar \\menuseparator\n";
2079 else if (t.cs() == "textcompwordmark") {
2080 context.check_layout(os);
2081 os << "\\SpecialChar \\textcompwordmark{}\n";
2085 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2086 context.check_layout(os);
2087 os << "\\SpecialChar \\@.\n";
2091 else if (t.cs() == "-") {
2092 context.check_layout(os);
2093 os << "\\SpecialChar \\-\n";
2096 else if (t.cs() == "textasciitilde") {
2097 context.check_layout(os);
2102 else if (t.cs() == "textasciicircum") {
2103 context.check_layout(os);
2108 else if (t.cs() == "textbackslash") {
2109 context.check_layout(os);
2110 os << "\n\\backslash\n";
2114 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2115 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2117 context.check_layout(os);
2121 else if (t.cs() == "char") {
2122 context.check_layout(os);
2123 if (p.next_token().character() == '`') {
2125 if (p.next_token().cs() == "\"") {
2130 handle_ert(os, "\\char`", context);
2133 handle_ert(os, "\\char", context);
2137 else if (t.cs() == "verb") {
2138 context.check_layout(os);
2139 char const delimiter = p.next_token().character();
2140 string const arg = p.getArg(delimiter, delimiter);
2142 oss << "\\verb" << delimiter << arg << delimiter;
2143 handle_ert(os, oss.str(), context);
2146 else if (t.cs() == "\"") {
2147 context.check_layout(os);
2148 string const name = p.verbatim_item();
2149 if (name == "a") os << '\xe4';
2150 else if (name == "o") os << '\xf6';
2151 else if (name == "u") os << '\xfc';
2152 else if (name == "A") os << '\xc4';
2153 else if (name == "O") os << '\xd6';
2154 else if (name == "U") os << '\xdc';
2155 else handle_ert(os, "\"{" + name + "}", context);
2158 // Problem: \= creates a tabstop inside the tabbing environment
2159 // and else an accent. In the latter case we really would want
2160 // \={o} instead of \= o.
2161 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2162 handle_ert(os, t.asInput(), context);
2164 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2165 || t.cs() == "'" || t.cs() == "`"
2166 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2167 // we need the trim as the LyX parser chokes on such spaces
2168 // The argument of InsetLatexAccent is parsed as a
2169 // subset of LaTeX, so don't parse anything here,
2170 // but use the raw argument.
2171 // Otherwise we would convert \~{\i} wrongly.
2172 // This will of course not translate \~{\ss} to \~{ß},
2173 // but that does at least compile and does only look
2174 // strange on screen.
2175 context.check_layout(os);
2176 os << "\\i \\" << t.cs() << "{"
2177 << trim(p.verbatim_item(), " ")
2181 else if (t.cs() == "ss") {
2182 context.check_layout(os);
2184 skip_braces(p); // eat {}
2187 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2189 context.check_layout(os);
2190 os << "\\i \\" << t.cs() << "{}\n";
2191 skip_braces(p); // eat {}
2194 else if (t.cs() == "\\") {
2195 context.check_layout(os);
2196 string const next = p.next_token().asInput();
2198 handle_ert(os, "\\\\" + p.getOpt(), context);
2199 else if (next == "*") {
2201 handle_ert(os, "\\\\*" + p.getOpt(), context);
2204 os << "\n\\newline\n";
2208 else if (t.cs() == "newline" ||
2209 t.cs() == "linebreak") {
2210 context.check_layout(os);
2211 os << "\n\\" << t.cs() << "\n";
2212 skip_braces(p); // eat {}
2215 else if (t.cs() == "href") {
2216 context.check_layout(os);
2217 begin_inset(os, "CommandInset ");
2218 os << t.cs() << "\n";
2219 os << "LatexCommand " << t.cs() << "\n";
2222 // the first argument is "type:target", "type:" is optional
2223 // the second argument the name
2224 string href_target = subst(p.verbatim_item(), "\n", " ");
2225 string href_name = subst(p.verbatim_item(), "\n", " ");
2227 // serach for the ":" to divide type from target
2228 if ((pos = href_target.find(":", 0)) != string::npos){
2229 href_type = href_target;
2230 href_type.erase(pos + 1, href_type.length());
2231 href_target.erase(0, pos + 1);
2234 os << "name " << '"' << href_name << '"' << "\n";
2235 os << "target " << '"' << href_target << '"' << "\n";
2237 os << "type " << '"' << href_type << '"' << "\n";
2241 else if (t.cs() == "input" || t.cs() == "include"
2242 || t.cs() == "verbatiminput") {
2243 string name = '\\' + t.cs();
2244 if (t.cs() == "verbatiminput"
2245 && p.next_token().asInput() == "*")
2246 name += p.get_token().asInput();
2247 context.check_layout(os);
2248 begin_inset(os, "Include ");
2249 string filename(normalize_filename(p.getArg('{', '}')));
2250 string const path = getMasterFilePath();
2251 // We want to preserve relative / absolute filenames,
2252 // therefore path is only used for testing
2253 // FIXME UNICODE encoding of filename and path may be
2254 // wrong (makeAbsPath expects utf8)
2255 if ((t.cs() == "include" || t.cs() == "input") &&
2256 !makeAbsPath(filename, path).exists()) {
2257 // The file extension is probably missing.
2258 // Now try to find it out.
2259 string const tex_name =
2260 find_file(filename, path,
2261 known_tex_extensions);
2262 if (!tex_name.empty())
2263 filename = tex_name;
2265 // FIXME UNICODE encoding of filename and path may be
2266 // wrong (makeAbsPath expects utf8)
2267 if (makeAbsPath(filename, path).exists()) {
2268 string const abstexname =
2269 makeAbsPath(filename, path).absFilename();
2270 string const abslyxname =
2271 changeExtension(abstexname, ".lyx");
2272 fix_relative_filename(filename);
2273 string const lyxname =
2274 changeExtension(filename, ".lyx");
2275 if (t.cs() != "verbatiminput" &&
2276 tex2lyx(abstexname, FileName(abslyxname))) {
2277 os << name << '{' << lyxname << "}\n";
2279 os << name << '{' << filename << "}\n";
2282 cerr << "Warning: Could not find included file '"
2283 << filename << "'." << endl;
2284 os << name << '{' << filename << "}\n";
2286 os << "preview false\n";
2290 else if (t.cs() == "bibliographystyle") {
2291 // store new bibliographystyle
2292 bibliographystyle = p.verbatim_item();
2293 // output new bibliographystyle.
2294 // This is only necessary if used in some other macro than \bibliography.
2295 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2298 else if (t.cs() == "bibliography") {
2299 context.check_layout(os);
2300 begin_inset(os, "LatexCommand ");
2302 // Do we have a bibliographystyle set?
2303 if (!bibliographystyle.empty()) {
2304 os << '[' << bibliographystyle << ']';
2306 os << '{' << p.verbatim_item() << "}\n";
2310 else if (t.cs() == "parbox")
2311 parse_box(p, os, FLAG_ITEM, outer, context, true);
2313 else if (t.cs() == "smallskip" ||
2314 t.cs() == "medskip" ||
2315 t.cs() == "bigskip" ||
2316 t.cs() == "vfill") {
2317 context.check_layout(os);
2318 begin_inset(os, "VSpace ");
2324 else if (is_known(t.cs(), known_spaces)) {
2325 char const * const * where = is_known(t.cs(), known_spaces);
2326 context.check_layout(os);
2327 begin_inset(os, "InsetSpace ");
2328 os << '\\' << known_coded_spaces[where - known_spaces]
2330 // LaTeX swallows whitespace after all spaces except
2331 // "\\,". We have to do that here, too, because LyX
2332 // adds "{}" which would make the spaces significant.
2334 eat_whitespace(p, os, context, false);
2335 // LyX adds "{}" after all spaces except "\\ " and
2336 // "\\,", so we have to remove "{}".
2337 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2338 // remove the braces after "\\,", too.
2343 else if (t.cs() == "newpage" ||
2344 t.cs() == "pagebreak" ||
2345 t.cs() == "clearpage" ||
2346 t.cs() == "cleardoublepage") {
2347 context.check_layout(os);
2348 os << "\n\\" << t.cs() << "\n";
2349 skip_braces(p); // eat {}
2352 else if (t.cs() == "newcommand" ||
2353 t.cs() == "providecommand" ||
2354 t.cs() == "renewcommand") {
2355 // these could be handled by parse_command(), but
2356 // we need to call add_known_command() here.
2357 string name = t.asInput();
2358 if (p.next_token().asInput() == "*") {
2359 // Starred form. Eat '*'
2363 string const command = p.verbatim_item();
2364 string const opt1 = p.getOpt();
2365 string const opt2 = p.getFullOpt();
2366 add_known_command(command, opt1, !opt2.empty());
2367 string const ert = name + '{' + command + '}' +
2369 '{' + p.verbatim_item() + '}';
2371 context.check_layout(os);
2372 begin_inset(os, "FormulaMacro");
2377 else if (t.cs() == "vspace") {
2378 bool starred = false;
2379 if (p.next_token().asInput() == "*") {
2383 string const length = p.verbatim_item();
2386 bool valid = splitLatexLength(length, valstring, unit);
2387 bool known_vspace = false;
2388 bool known_unit = false;
2391 istringstream iss(valstring);
2394 if (unit == "\\smallskipamount") {
2396 known_vspace = true;
2397 } else if (unit == "\\medskipamount") {
2399 known_vspace = true;
2400 } else if (unit == "\\bigskipamount") {
2402 known_vspace = true;
2403 } else if (unit == "\\fill") {
2405 known_vspace = true;
2408 if (!known_vspace) {
2409 switch (unitFromString(unit)) {
2430 if (known_unit || known_vspace) {
2431 // Literal length or known variable
2432 context.check_layout(os);
2433 begin_inset(os, "VSpace ");
2441 // LyX can't handle other length variables in Inset VSpace
2442 string name = t.asInput();
2447 handle_ert(os, name + '{' + unit + '}', context);
2448 else if (value == -1.0)
2449 handle_ert(os, name + "{-" + unit + '}', context);
2451 handle_ert(os, name + '{' + valstring + unit + '}', context);
2453 handle_ert(os, name + '{' + length + '}', context);
2458 //cerr << "#: " << t << " mode: " << mode << endl;
2459 // heuristic: read up to next non-nested space
2461 string s = t.asInput();
2462 string z = p.verbatim_item();
2463 while (p.good() && z != " " && z.size()) {
2464 //cerr << "read: " << z << endl;
2466 z = p.verbatim_item();
2468 cerr << "found ERT: " << s << endl;
2469 handle_ert(os, s + ' ', context);
2471 string name = t.asInput();
2472 if (p.next_token().asInput() == "*") {
2473 // Starred commands like \vspace*{}
2474 p.get_token(); // Eat '*'
2477 if (! parse_command(name, p, os, outer, context))
2478 handle_ert(os, name, context);
2481 if (flags & FLAG_LEAVE) {
2482 flags &= ~FLAG_LEAVE;