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/convert.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/lstrings.h"
35 using namespace lyx::support;
40 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
41 Context const & context)
43 Context newcontext(true, context.textclass);
44 newcontext.font = context.font;
45 parse_text(p, os, flags, outer, newcontext);
46 newcontext.check_end_layout(os);
52 /// parses a paragraph snippet, useful for example for \\emph{...}
53 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
56 Context newcontext(context);
57 // Don't inherit the extra stuff
58 newcontext.extra_stuff.clear();
59 parse_text(p, os, flags, outer, newcontext);
60 // Make sure that we don't create invalid .lyx files
61 context.need_layout = newcontext.need_layout;
62 context.need_end_layout = newcontext.need_end_layout;
67 * Thin wrapper around parse_text_snippet() using a string.
69 * We completely ignore \c context.need_layout and \c context.need_end_layout,
70 * because our return value is not used directly (otherwise the stream version
71 * of parse_text_snippet() could be used). That means that the caller needs
72 * to do layout management manually.
73 * This is intended to parse text that does not create any layout changes.
75 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
78 Context newcontext(context);
79 newcontext.need_layout = false;
80 newcontext.need_end_layout = false;
81 newcontext.new_layout_allowed = false;
82 // Avoid warning by Context::~Context()
83 newcontext.extra_stuff.clear();
85 parse_text_snippet(p, os, flags, outer, newcontext);
90 char const * const known_latex_commands[] = { "ref", "cite", "nocite", "label",
91 "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
96 * We can't put these into known_latex_commands because the argument order
97 * is reversed in lyx if there are 2 arguments.
98 * The starred forms are also known.
100 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
101 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
102 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
106 * We can't put these into known_latex_commands because the argument order
107 * is reversed in lyx if there are 2 arguments.
108 * No starred form other than "cite*" known.
110 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
111 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
112 // jurabib commands not (yet) supported by LyX:
114 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
115 // "footciteauthor", "footciteyear", "footciteyearpar",
116 "citefield", "citetitle", "cite*", 0 };
118 /// LaTeX names for quotes
119 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
120 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
121 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
122 "guilsinglleft", "frq", "guilsinglright", 0};
124 /// the same as known_quotes with .lyx names
125 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
126 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
127 "gld", "grd", "gls", "ers", "fls",
128 "fls", "frs", "frs", 0};
130 /// LaTeX names for font sizes
131 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
132 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
134 /// the same as known_sizes with .lyx names
135 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
136 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
138 /// LaTeX 2.09 names for font families
139 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
141 /// LaTeX names for font families
142 char const * const known_font_families[] = { "rmfamily", "sffamily",
145 /// the same as known_old_font_families and known_font_families with .lyx names
146 char const * const known_coded_font_families[] = { "roman", "sans",
149 /// LaTeX 2.09 names for font series
150 char const * const known_old_font_series[] = { "bf", 0};
152 /// LaTeX names for font series
153 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
155 /// the same as known_old_font_series and known_font_series with .lyx names
156 char const * const known_coded_font_series[] = { "bold", "medium", 0};
158 /// LaTeX 2.09 names for font shapes
159 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
161 /// LaTeX names for font shapes
162 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
165 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
166 char const * const known_coded_font_shapes[] = { "italic", "slanted",
167 "smallcaps", "up", 0};
170 * Graphics file extensions known by the dvips driver of the graphics package.
171 * These extensions are used to complete the filename of an included
172 * graphics file if it does not contain an extension.
173 * The order must be the same that latex uses to find a file, because we
174 * will use the first extension that matches.
175 * This is only an approximation for the common cases. If we would want to
176 * do it right in all cases, we would need to know which graphics driver is
177 * used and know the extensions of every driver of the graphics package.
179 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
180 "ps.gz", "eps.Z", "ps.Z", 0};
183 * Graphics file extensions known by the pdftex driver of the graphics package.
184 * \sa known_dvips_graphics_formats
186 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
190 * Known file extensions for TeX files as used by \\include.
192 char const * const known_tex_extensions[] = {"tex", 0};
194 /// spaces known by InsetSpace
195 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
196 "qquad", "enspace", "enskip", "negthinspace", 0};
198 /// the same as known_spaces with .lyx names
199 char const * const known_coded_spaces[] = { "space{}", "space{}",
200 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
201 "negthinspace{}", 0};
204 /// splits "x=z, y=b" into a map
205 map<string, string> split_map(string const & s)
207 map<string, string> res;
210 for (size_t i = 0; i < v.size(); ++i) {
211 size_t const pos = v[i].find('=');
212 string const index = v[i].substr(0, pos);
213 string const value = v[i].substr(pos + 1, string::npos);
214 res[trim(index)] = trim(value);
221 * Split a LaTeX length into value and unit.
222 * The latter can be a real unit like "pt", or a latex length variable
223 * like "\textwidth". The unit may contain additional stuff like glue
224 * lengths, but we don't care, because such lengths are ERT anyway.
225 * \returns true if \p value and \p unit are valid.
227 bool splitLatexLength(string const & len, string & value, string & unit)
231 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
232 //'4,5' is a valid LaTeX length number. Change it to '4.5'
233 string const length = subst(len, ',', '.');
234 if (i == string::npos)
237 if (len[0] == '\\') {
238 // We had something like \textwidth without a factor
244 value = trim(string(length, 0, i));
248 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
249 if (contains(len, '\\'))
250 unit = trim(string(len, i));
252 unit = ascii_lowercase(trim(string(len, i)));
257 /// A simple function to translate a latex length to something lyx can
258 /// understand. Not perfect, but rather best-effort.
259 bool translate_len(string const & length, string & valstring, string & unit)
261 if (!splitLatexLength(length, valstring, unit))
263 // LyX uses percent values
265 istringstream iss(valstring);
270 string const percentval = oss.str();
272 if (unit.empty() || unit[0] != '\\')
274 string::size_type const i = unit.find(' ');
275 string const endlen = (i == string::npos) ? string() : string(unit, i);
276 if (unit == "\\textwidth") {
277 valstring = percentval;
278 unit = "text%" + endlen;
279 } else if (unit == "\\columnwidth") {
280 valstring = percentval;
281 unit = "col%" + endlen;
282 } else if (unit == "\\paperwidth") {
283 valstring = percentval;
284 unit = "page%" + endlen;
285 } else if (unit == "\\linewidth") {
286 valstring = percentval;
287 unit = "line%" + endlen;
288 } else if (unit == "\\paperheight") {
289 valstring = percentval;
290 unit = "pheight%" + endlen;
291 } else if (unit == "\\textheight") {
292 valstring = percentval;
293 unit = "theight%" + endlen;
301 string translate_len(string const & length)
305 if (translate_len(length, value, unit))
307 // If the input is invalid, return what we have.
315 * Translates a LaTeX length into \p value, \p unit and
316 * \p special parts suitable for a box inset.
317 * The difference from translate_len() is that a box inset knows about
318 * some special "units" that are stored in \p special.
320 void translate_box_len(string const & length, string & value, string & unit, string & special)
322 if (translate_len(length, value, unit)) {
323 if (unit == "\\height" || unit == "\\depth" ||
324 unit == "\\totalheight" || unit == "\\width") {
325 special = unit.substr(1);
326 // The unit is not used, but LyX requires a dummy setting
339 * Find a file with basename \p name in path \p path and an extension
342 string find_file(string const & name, string const & path,
343 char const * const * extensions)
345 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
347 for (char const * const * what = extensions; *what; ++what) {
348 string const trial = addExtension(name, *what);
349 if (makeAbsPath(trial, path).exists())
356 void begin_inset(ostream & os, string const & name)
358 os << "\n\\begin_inset " << name;
362 void end_inset(ostream & os)
364 os << "\n\\end_inset\n\n";
368 void skip_braces(Parser & p)
370 if (p.next_token().cat() != catBegin)
373 if (p.next_token().cat() == catEnd) {
381 void handle_ert(ostream & os, string const & s, Context & context)
383 // We must have a valid layout before outputting the ERT inset.
384 context.check_layout(os);
385 Context newcontext(true, context.textclass);
386 begin_inset(os, "ERT");
387 os << "\nstatus collapsed\n";
388 newcontext.check_layout(os);
389 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
391 os << "\n\\backslash\n";
392 else if (*it == '\n') {
393 newcontext.new_paragraph(os);
394 newcontext.check_layout(os);
398 newcontext.check_end_layout(os);
403 void handle_comment(ostream & os, string const & s, Context & context)
405 // TODO: Handle this better
406 Context newcontext(true, context.textclass);
407 begin_inset(os, "ERT");
408 os << "\nstatus collapsed\n";
409 newcontext.check_layout(os);
410 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
412 os << "\n\\backslash\n";
416 // make sure that our comment is the last thing on the line
417 newcontext.new_paragraph(os);
418 newcontext.check_layout(os);
419 newcontext.check_end_layout(os);
424 LayoutPtr findLayout(TextClass const & textclass, string const & name)
426 DocumentClass::const_iterator lit = textclass.begin();
427 DocumentClass::const_iterator len = textclass.end();
428 for (; lit != len; ++lit)
429 if (lit->latexname() == name)
435 void eat_whitespace(Parser &, ostream &, Context &, bool);
438 void output_command_layout(ostream & os, Parser & p, bool outer,
439 Context & parent_context,
442 parent_context.check_end_layout(os);
443 Context context(true, parent_context.textclass, newlayout,
444 parent_context.layout, parent_context.font);
445 if (parent_context.deeper_paragraph) {
446 // We are beginning a nested environment after a
447 // deeper paragraph inside the outer list environment.
448 // Therefore we don't need to output a "begin deeper".
449 context.need_end_deeper = true;
451 context.check_deeper(os);
452 context.check_layout(os);
453 if (context.layout->optionalargs > 0) {
454 eat_whitespace(p, os, context, false);
455 if (p.next_token().character() == '[') {
456 p.get_token(); // eat '['
457 begin_inset(os, "OptArg\n");
458 os << "status collapsed\n\n";
459 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
461 eat_whitespace(p, os, context, false);
464 parse_text(p, os, FLAG_ITEM, outer, context);
465 context.check_end_layout(os);
466 if (parent_context.deeper_paragraph) {
467 // We must suppress the "end deeper" because we
468 // suppressed the "begin deeper" above.
469 context.need_end_deeper = false;
471 context.check_end_deeper(os);
472 // We don't need really a new paragraph, but
473 // we must make sure that the next item gets a \begin_layout.
474 parent_context.new_paragraph(os);
479 * Output a space if necessary.
480 * This function gets called for every whitespace token.
482 * We have three cases here:
483 * 1. A space must be suppressed. Example: The lyxcode case below
484 * 2. A space may be suppressed. Example: Spaces before "\par"
485 * 3. A space must not be suppressed. Example: A space between two words
487 * We currently handle only 1. and 3 and from 2. only the case of
488 * spaces before newlines as a side effect.
490 * 2. could be used to suppress as many spaces as possible. This has two effects:
491 * - Reimporting LyX generated LaTeX files changes almost no whitespace
492 * - Superflous whitespace from non LyX generated LaTeX files is removed.
493 * The drawback is that the logic inside the function becomes
494 * complicated, and that is the reason why it is not implemented.
496 void check_space(Parser const & p, ostream & os, Context & context)
498 Token const next = p.next_token();
499 Token const curr = p.curr_token();
500 // A space before a single newline and vice versa must be ignored
501 // LyX emits a newline before \end{lyxcode}.
502 // This newline must be ignored,
503 // otherwise LyX will add an additional protected space.
504 if (next.cat() == catSpace ||
505 next.cat() == catNewline ||
506 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
509 context.check_layout(os);
515 * Parse all arguments of \p command
517 void parse_arguments(string const & command,
518 vector<ArgumentType> const & template_arguments,
519 Parser & p, ostream & os, bool outer, Context & context)
521 string ert = command;
522 size_t no_arguments = template_arguments.size();
523 for (size_t i = 0; i < no_arguments; ++i) {
524 switch (template_arguments[i]) {
526 // This argument contains regular LaTeX
527 handle_ert(os, ert + '{', context);
528 eat_whitespace(p, os, context, false);
529 parse_text(p, os, FLAG_ITEM, outer, context);
533 // This argument may contain special characters
534 ert += '{' + p.verbatim_item() + '}';
541 handle_ert(os, ert, context);
546 * Check whether \p command is a known command. If yes,
547 * handle the command with all arguments.
548 * \return true if the command was parsed, false otherwise.
550 bool parse_command(string const & command, Parser & p, ostream & os,
551 bool outer, Context & context)
553 if (known_commands.find(command) != known_commands.end()) {
554 parse_arguments(command, known_commands[command], p, os,
562 /// Parses a minipage or parbox
563 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
564 Context & parent_context, bool use_parbox)
568 // We need to set the height to the LaTeX default of 1\\totalheight
569 // for the case when no height argument is given
570 string height_value = "1";
571 string height_unit = "in";
572 string height_special = "totalheight";
574 if (p.next_token().asInput() == "[") {
575 position = p.getArg('[', ']');
576 if (position != "t" && position != "c" && position != "b") {
578 cerr << "invalid position for minipage/parbox" << endl;
580 if (p.next_token().asInput() == "[") {
581 latex_height = p.getArg('[', ']');
582 translate_box_len(latex_height, height_value, height_unit, height_special);
584 if (p.next_token().asInput() == "[") {
585 inner_pos = p.getArg('[', ']');
586 if (inner_pos != "c" && inner_pos != "t" &&
587 inner_pos != "b" && inner_pos != "s") {
588 inner_pos = position;
589 cerr << "invalid inner_pos for minipage/parbox"
597 string const latex_width = p.verbatim_item();
598 translate_len(latex_width, width_value, width_unit);
599 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
600 // LyX can't handle length variables
605 ss << "\\begin{minipage}";
606 if (!position.empty())
607 ss << '[' << position << ']';
608 if (!latex_height.empty())
609 ss << '[' << latex_height << ']';
610 if (!inner_pos.empty())
611 ss << '[' << inner_pos << ']';
612 ss << "{" << latex_width << "}";
615 handle_ert(os, ss.str(), parent_context);
616 parent_context.new_paragraph(os);
617 parse_text_in_inset(p, os, flags, outer, parent_context);
619 handle_ert(os, "}", parent_context);
621 handle_ert(os, "\\end{minipage}", parent_context);
623 // LyX does not like empty positions, so we have
624 // to set them to the LaTeX default values here.
625 if (position.empty())
627 if (inner_pos.empty())
628 inner_pos = position;
629 parent_context.check_layout(os);
630 begin_inset(os, "Box Frameless\n");
631 os << "position \"" << position << "\"\n";
632 os << "hor_pos \"c\"\n";
633 os << "has_inner_box 1\n";
634 os << "inner_pos \"" << inner_pos << "\"\n";
635 os << "use_parbox " << use_parbox << "\n";
636 os << "width \"" << width_value << width_unit << "\"\n";
637 os << "special \"none\"\n";
638 os << "height \"" << height_value << height_unit << "\"\n";
639 os << "height_special \"" << height_special << "\"\n";
640 os << "status open\n\n";
641 parse_text_in_inset(p, os, flags, outer, parent_context);
643 #ifdef PRESERVE_LAYOUT
644 // lyx puts a % after the end of the minipage
645 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
647 //handle_comment(os, "%dummy", parent_context);
650 parent_context.new_paragraph(os);
652 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
653 //handle_comment(os, "%dummy", parent_context);
656 // We add a protected space if something real follows
657 if (p.good() && p.next_token().cat() != catComment) {
658 os << "\\InsetSpace ~\n";
666 /// parse an unknown environment
667 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
668 unsigned flags, bool outer,
669 Context & parent_context)
671 if (name == "tabbing")
672 // We need to remember that we have to handle '\=' specially
673 flags |= FLAG_TABBING;
675 // We need to translate font changes and paragraphs inside the
676 // environment to ERT if we have a non standard font.
677 // Otherwise things like
678 // \large\begin{foo}\huge bar\end{foo}
680 bool const specialfont =
681 (parent_context.font != parent_context.normalfont);
682 bool const new_layout_allowed = parent_context.new_layout_allowed;
684 parent_context.new_layout_allowed = false;
685 handle_ert(os, "\\begin{" + name + "}", parent_context);
686 parse_text_snippet(p, os, flags, outer, parent_context);
687 handle_ert(os, "\\end{" + name + "}", parent_context);
689 parent_context.new_layout_allowed = new_layout_allowed;
693 void parse_environment(Parser & p, ostream & os, bool outer,
694 Context & parent_context)
697 string const name = p.getArg('{', '}');
698 const bool is_starred = suffixIs(name, '*');
699 string const unstarred_name = rtrim(name, "*");
700 active_environments.push_back(name);
702 if (is_math_env(name)) {
703 parent_context.check_layout(os);
704 begin_inset(os, "Formula ");
705 os << "\\begin{" << name << "}";
706 parse_math(p, os, FLAG_END, MATH_MODE);
707 os << "\\end{" << name << "}";
711 else if (name == "tabular" || name == "longtable") {
712 eat_whitespace(p, os, parent_context, false);
713 parent_context.check_layout(os);
714 begin_inset(os, "Tabular ");
715 handle_tabular(p, os, name == "longtable", parent_context);
720 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
721 eat_whitespace(p, os, parent_context, false);
722 parent_context.check_layout(os);
723 begin_inset(os, "Float " + unstarred_name + "\n");
724 if (p.next_token().asInput() == "[") {
725 os << "placement " << p.getArg('[', ']') << '\n';
727 os << "wide " << convert<string>(is_starred)
728 << "\nsideways false"
729 << "\nstatus open\n\n";
730 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
732 // We don't need really a new paragraph, but
733 // we must make sure that the next item gets a \begin_layout.
734 parent_context.new_paragraph(os);
738 else if (name == "minipage") {
739 eat_whitespace(p, os, parent_context, false);
740 parse_box(p, os, FLAG_END, outer, parent_context, false);
744 else if (name == "comment") {
745 eat_whitespace(p, os, parent_context, false);
746 parent_context.check_layout(os);
747 begin_inset(os, "Note Comment\n");
748 os << "status open\n";
749 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
754 else if (name == "lyxgreyedout") {
755 eat_whitespace(p, os, parent_context, false);
756 parent_context.check_layout(os);
757 begin_inset(os, "Note Greyedout\n");
758 os << "status open\n";
759 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
764 else if (name == "framed") {
765 eat_whitespace(p, os, parent_context, false);
766 parent_context.check_layout(os);
767 begin_inset(os, "Note Framed\n");
768 os << "status open\n";
769 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
774 else if (name == "shaded") {
775 eat_whitespace(p, os, parent_context, false);
776 parent_context.check_layout(os);
777 begin_inset(os, "Note Shaded\n");
778 os << "status open\n";
779 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
784 else if (!parent_context.new_layout_allowed)
785 parse_unknown_environment(p, name, os, FLAG_END, outer,
788 // Alignment settings
789 else if (name == "center" || name == "flushleft" || name == "flushright" ||
790 name == "centering" || name == "raggedright" || name == "raggedleft") {
791 eat_whitespace(p, os, parent_context, false);
792 // We must begin a new paragraph if not already done
793 if (! parent_context.atParagraphStart()) {
794 parent_context.check_end_layout(os);
795 parent_context.new_paragraph(os);
797 if (name == "flushleft" || name == "raggedright")
798 parent_context.add_extra_stuff("\\align left\n");
799 else if (name == "flushright" || name == "raggedleft")
800 parent_context.add_extra_stuff("\\align right\n");
802 parent_context.add_extra_stuff("\\align center\n");
803 parse_text(p, os, FLAG_END, outer, parent_context);
804 // Just in case the environment is empty ..
805 parent_context.extra_stuff.erase();
806 // We must begin a new paragraph to reset the alignment
807 parent_context.new_paragraph(os);
811 // The single '=' is meant here.
812 else if ((newlayout = findLayout(parent_context.textclass, name)) &&
813 newlayout->isEnvironment()) {
814 eat_whitespace(p, os, parent_context, false);
815 Context context(true, parent_context.textclass, newlayout,
816 parent_context.layout, parent_context.font);
817 if (parent_context.deeper_paragraph) {
818 // We are beginning a nested environment after a
819 // deeper paragraph inside the outer list environment.
820 // Therefore we don't need to output a "begin deeper".
821 context.need_end_deeper = true;
823 parent_context.check_end_layout(os);
824 switch (context.layout->latextype) {
825 case LATEX_LIST_ENVIRONMENT:
826 context.extra_stuff = "\\labelwidthstring "
827 + p.verbatim_item() + '\n';
830 case LATEX_BIB_ENVIRONMENT:
831 p.verbatim_item(); // swallow next arg
837 context.check_deeper(os);
838 parse_text(p, os, FLAG_END, outer, context);
839 context.check_end_layout(os);
840 if (parent_context.deeper_paragraph) {
841 // We must suppress the "end deeper" because we
842 // suppressed the "begin deeper" above.
843 context.need_end_deeper = false;
845 context.check_end_deeper(os);
846 parent_context.new_paragraph(os);
850 else if (name == "appendix") {
851 // This is no good latex style, but it works and is used in some documents...
852 eat_whitespace(p, os, parent_context, false);
853 parent_context.check_end_layout(os);
854 Context context(true, parent_context.textclass, parent_context.layout,
855 parent_context.layout, parent_context.font);
856 context.check_layout(os);
857 os << "\\start_of_appendix\n";
858 parse_text(p, os, FLAG_END, outer, context);
859 context.check_end_layout(os);
863 else if (known_environments.find(name) != known_environments.end()) {
864 vector<ArgumentType> arguments = known_environments[name];
865 // The last "argument" denotes wether we may translate the
866 // environment contents to LyX
867 // The default required if no argument is given makes us
868 // compatible with the reLyXre environment.
869 ArgumentType contents = arguments.empty() ?
872 if (!arguments.empty())
873 arguments.pop_back();
874 // See comment in parse_unknown_environment()
875 bool const specialfont =
876 (parent_context.font != parent_context.normalfont);
877 bool const new_layout_allowed =
878 parent_context.new_layout_allowed;
880 parent_context.new_layout_allowed = false;
881 parse_arguments("\\begin{" + name + "}", arguments, p, os,
882 outer, parent_context);
883 if (contents == verbatim)
884 handle_ert(os, p.verbatimEnvironment(name),
887 parse_text_snippet(p, os, FLAG_END, outer,
889 handle_ert(os, "\\end{" + name + "}", parent_context);
891 parent_context.new_layout_allowed = new_layout_allowed;
895 parse_unknown_environment(p, name, os, FLAG_END, outer,
898 active_environments.pop_back();
902 /// parses a comment and outputs it to \p os.
903 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
905 BOOST_ASSERT(t.cat() == catComment);
906 if (!t.cs().empty()) {
907 context.check_layout(os);
908 handle_comment(os, '%' + t.cs(), context);
909 if (p.next_token().cat() == catNewline) {
910 // A newline after a comment line starts a new
912 if (context.new_layout_allowed) {
913 if(!context.atParagraphStart())
914 // Only start a new paragraph if not already
915 // done (we might get called recursively)
916 context.new_paragraph(os);
918 handle_ert(os, "\n", context);
919 eat_whitespace(p, os, context, true);
929 * Reads spaces and comments until the first non-space, non-comment token.
930 * New paragraphs (double newlines or \\par) are handled like simple spaces
931 * if \p eatParagraph is true.
932 * Spaces are skipped, but comments are written to \p os.
934 void eat_whitespace(Parser & p, ostream & os, Context & context,
938 Token const & t = p.get_token();
939 if (t.cat() == catComment)
940 parse_comment(p, os, t, context);
941 else if ((! eatParagraph && p.isParagraph()) ||
942 (t.cat() != catSpace && t.cat() != catNewline)) {
951 * Set a font attribute, parse text and reset the font attribute.
952 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
953 * \param currentvalue Current value of the attribute. Is set to the new
954 * value during parsing.
955 * \param newvalue New value of the attribute
957 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
958 Context & context, string const & attribute,
959 string & currentvalue, string const & newvalue)
961 context.check_layout(os);
962 string const oldvalue = currentvalue;
963 currentvalue = newvalue;
964 os << '\n' << attribute << ' ' << newvalue << "\n";
965 parse_text_snippet(p, os, flags, outer, context);
966 context.check_layout(os);
967 os << '\n' << attribute << ' ' << oldvalue << "\n";
968 currentvalue = oldvalue;
972 /// get the arguments of a natbib or jurabib citation command
973 void get_cite_arguments(Parser & p, bool natbibOrder,
974 string & before, string & after)
976 // We need to distinguish "" and "[]", so we can't use p.getOpt().
978 // text before the citation
980 // text after the citation
981 after = p.getFullOpt();
983 if (!after.empty()) {
984 before = p.getFullOpt();
985 if (natbibOrder && !before.empty())
991 /// Convert filenames with TeX macros and/or quotes to something LyX
993 string const normalize_filename(string const & name)
995 Parser p(trim(name, "\""));
998 Token const & t = p.get_token();
999 if (t.cat() != catEscape)
1001 else if (t.cs() == "lyxdot") {
1002 // This is used by LyX for simple dots in relative
1006 } else if (t.cs() == "space") {
1016 /// Convert \p name from TeX convention (relative to master file) to LyX
1017 /// convention (relative to .lyx file) if it is relative
1018 void fix_relative_filename(string & name)
1020 FileName fname(name);
1021 if (fname.isAbsolute())
1024 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1026 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1027 from_utf8(getParentFilePath())));
1031 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1032 void parse_noweb(Parser & p, ostream & os, Context & context)
1034 // assemble the rest of the keyword
1038 Token const & t = p.get_token();
1039 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1042 scrap = (p.good() && p.next_token().asInput() == "=");
1044 name += p.get_token().asInput();
1047 name += t.asInput();
1050 if (!scrap || !context.new_layout_allowed ||
1051 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1052 cerr << "Warning: Could not interpret '" << name
1053 << "'. Ignoring it." << endl;
1057 // We use new_paragraph instead of check_end_layout because the stuff
1058 // following the noweb chunk needs to start with a \begin_layout.
1059 // This may create a new paragraph even if there was none in the
1060 // noweb file, but the alternative is an invalid LyX file. Since
1061 // noweb code chunks are implemented with a layout style in LyX they
1062 // always must be in an own paragraph.
1063 context.new_paragraph(os);
1064 Context newcontext(true, context.textclass,
1065 &context.textclass[from_ascii("Scrap")]);
1066 newcontext.check_layout(os);
1069 Token const & t = p.get_token();
1070 // We abuse the parser a bit, because this is no TeX syntax
1072 if (t.cat() == catEscape)
1073 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1075 os << subst(t.asInput(), "\n", "\n\\newline\n");
1076 // The scrap chunk is ended by an @ at the beginning of a line.
1077 // After the @ the line may contain a comment and/or
1078 // whitespace, but nothing else.
1079 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1080 (p.next_token().cat() == catSpace ||
1081 p.next_token().cat() == catNewline ||
1082 p.next_token().cat() == catComment)) {
1083 while (p.good() && p.next_token().cat() == catSpace)
1084 os << p.get_token().asInput();
1085 if (p.next_token().cat() == catComment)
1086 // The comment includes a final '\n'
1087 os << p.get_token().asInput();
1089 if (p.next_token().cat() == catNewline)
1096 newcontext.check_end_layout(os);
1099 } // anonymous namespace
1102 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1105 LayoutPtr newlayout;
1106 // store the current selectlanguage to be used after \foreignlanguage
1108 // Store the latest bibliographystyle (needed for bibtex inset)
1109 string bibliographystyle;
1110 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1111 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1113 Token const & t = p.get_token();
1116 cerr << "t: " << t << " flags: " << flags << "\n";
1119 if (flags & FLAG_ITEM) {
1120 if (t.cat() == catSpace)
1123 flags &= ~FLAG_ITEM;
1124 if (t.cat() == catBegin) {
1125 // skip the brace and collect everything to the next matching
1127 flags |= FLAG_BRACE_LAST;
1131 // handle only this single token, leave the loop if done
1132 flags |= FLAG_LEAVE;
1135 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1141 if (t.cat() == catMath) {
1142 // we are inside some text mode thingy, so opening new math is allowed
1143 context.check_layout(os);
1144 begin_inset(os, "Formula ");
1145 Token const & n = p.get_token();
1146 if (n.cat() == catMath && outer) {
1147 // TeX's $$...$$ syntax for displayed math
1149 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1151 p.get_token(); // skip the second '$' token
1153 // simple $...$ stuff
1156 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1162 else if (t.cat() == catSuper || t.cat() == catSub)
1163 cerr << "catcode " << t << " illegal in text mode\n";
1165 // Basic support for english quotes. This should be
1166 // extended to other quotes, but is not so easy (a
1167 // left english quote is the same as a right german
1169 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1170 context.check_layout(os);
1171 begin_inset(os, "Quotes ");
1177 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1178 context.check_layout(os);
1179 begin_inset(os, "Quotes ");
1186 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1187 context.check_layout(os);
1188 begin_inset(os, "Quotes ");
1195 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1196 context.check_layout(os);
1197 begin_inset(os, "Quotes ");
1204 else if (t.asInput() == "<"
1205 && p.next_token().asInput() == "<" && noweb_mode) {
1207 parse_noweb(p, os, context);
1210 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1211 check_space(p, os, context);
1213 else if (t.character() == '[' && noweb_mode &&
1214 p.next_token().character() == '[') {
1215 // These can contain underscores
1217 string const s = p.getFullOpt() + ']';
1218 if (p.next_token().character() == ']')
1221 cerr << "Warning: Inserting missing ']' in '"
1222 << s << "'." << endl;
1223 handle_ert(os, s, context);
1226 else if (t.cat() == catLetter ||
1227 t.cat() == catOther ||
1228 t.cat() == catAlign ||
1229 t.cat() == catParameter) {
1230 // This translates "&" to "\\&" which may be wrong...
1231 context.check_layout(os);
1232 os << t.character();
1235 else if (p.isParagraph()) {
1236 if (context.new_layout_allowed)
1237 context.new_paragraph(os);
1239 handle_ert(os, "\\par ", context);
1240 eat_whitespace(p, os, context, true);
1243 else if (t.cat() == catActive) {
1244 context.check_layout(os);
1245 if (t.character() == '~') {
1246 if (context.layout->free_spacing)
1249 os << "\\InsetSpace ~\n";
1251 os << t.character();
1254 else if (t.cat() == catBegin &&
1255 p.next_token().cat() == catEnd) {
1257 Token const prev = p.prev_token();
1259 if (p.next_token().character() == '`' ||
1260 (prev.character() == '-' &&
1261 p.next_token().character() == '-'))
1262 ; // ignore it in {}`` or -{}-
1264 handle_ert(os, "{}", context);
1268 else if (t.cat() == catBegin) {
1269 context.check_layout(os);
1270 // special handling of font attribute changes
1271 Token const prev = p.prev_token();
1272 Token const next = p.next_token();
1273 TeXFont const oldFont = context.font;
1274 if (next.character() == '[' ||
1275 next.character() == ']' ||
1276 next.character() == '*') {
1278 if (p.next_token().cat() == catEnd) {
1279 os << next.character();
1283 handle_ert(os, "{", context);
1284 parse_text_snippet(p, os,
1287 handle_ert(os, "}", context);
1289 } else if (! context.new_layout_allowed) {
1290 handle_ert(os, "{", context);
1291 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1293 handle_ert(os, "}", context);
1294 } else if (is_known(next.cs(), known_sizes)) {
1295 // next will change the size, so we must
1297 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1299 if (!context.atParagraphStart())
1301 << context.font.size << "\n";
1302 } else if (is_known(next.cs(), known_font_families)) {
1303 // next will change the font family, so we
1304 // must reset it here
1305 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1307 if (!context.atParagraphStart())
1309 << context.font.family << "\n";
1310 } else if (is_known(next.cs(), known_font_series)) {
1311 // next will change the font series, so we
1312 // must reset it here
1313 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1315 if (!context.atParagraphStart())
1317 << context.font.series << "\n";
1318 } else if (is_known(next.cs(), known_font_shapes)) {
1319 // next will change the font shape, so we
1320 // must reset it here
1321 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1323 if (!context.atParagraphStart())
1325 << context.font.shape << "\n";
1326 } else if (is_known(next.cs(), known_old_font_families) ||
1327 is_known(next.cs(), known_old_font_series) ||
1328 is_known(next.cs(), known_old_font_shapes)) {
1329 // next will change the font family, series
1330 // and shape, so we must reset it here
1331 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1333 if (!context.atParagraphStart())
1335 << context.font.family
1337 << context.font.series
1339 << context.font.shape << "\n";
1341 handle_ert(os, "{", context);
1342 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1344 handle_ert(os, "}", context);
1348 else if (t.cat() == catEnd) {
1349 if (flags & FLAG_BRACE_LAST) {
1352 cerr << "stray '}' in text\n";
1353 handle_ert(os, "}", context);
1356 else if (t.cat() == catComment)
1357 parse_comment(p, os, t, context);
1360 // control sequences
1363 else if (t.cs() == "(") {
1364 context.check_layout(os);
1365 begin_inset(os, "Formula");
1367 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1372 else if (t.cs() == "[") {
1373 context.check_layout(os);
1374 begin_inset(os, "Formula");
1376 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1381 else if (t.cs() == "begin")
1382 parse_environment(p, os, outer, context);
1384 else if (t.cs() == "end") {
1385 if (flags & FLAG_END) {
1386 // eat environment name
1387 string const name = p.getArg('{', '}');
1388 if (name != active_environment())
1389 cerr << "\\end{" + name + "} does not match \\begin{"
1390 + active_environment() + "}\n";
1393 p.error("found 'end' unexpectedly");
1396 else if (t.cs() == "item") {
1399 bool optarg = false;
1400 if (p.next_token().character() == '[') {
1401 p.get_token(); // eat '['
1402 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1407 context.check_layout(os);
1408 if (context.has_item) {
1409 // An item in an unknown list-like environment
1410 // FIXME: Do this in check_layout()!
1411 context.has_item = false;
1413 handle_ert(os, "\\item", context);
1415 handle_ert(os, "\\item ", context);
1418 if (context.layout->labeltype != LABEL_MANUAL) {
1419 // lyx does not support \item[\mybullet]
1420 // in itemize environments
1421 handle_ert(os, "[", context);
1423 handle_ert(os, "]", context);
1424 } else if (!s.empty()) {
1425 // The space is needed to separate the
1426 // item from the rest of the sentence.
1428 eat_whitespace(p, os, context, false);
1433 else if (t.cs() == "bibitem") {
1435 context.check_layout(os);
1438 os << '{' << p.verbatim_item() << '}' << "\n";
1441 else if (t.cs() == "def") {
1442 context.check_layout(os);
1443 eat_whitespace(p, os, context, false);
1444 string name = p.get_token().cs();
1445 eat_whitespace(p, os, context, false);
1451 while (p.next_token().cat() != catBegin) {
1452 if (p.next_token().cat() == catParameter) {
1457 // followed by number?
1458 if (p.next_token().cat() == catOther) {
1459 char c = p.getChar();
1461 // number = current arity + 1?
1462 if (c == arity + '0' + 1)
1467 paramtext += p.get_token().asString();
1469 paramtext += p.get_token().asString();
1474 // only output simple (i.e. compatible) macro as FormulaMacros
1475 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1477 context.check_layout(os);
1478 begin_inset(os, "FormulaMacro");
1482 handle_ert(os, ert, context);
1485 else if (t.cs() == "noindent") {
1487 context.add_extra_stuff("\\noindent\n");
1490 else if (t.cs() == "appendix") {
1491 context.add_extra_stuff("\\start_of_appendix\n");
1492 // We need to start a new paragraph. Otherwise the
1493 // appendix in 'bla\appendix\chapter{' would start
1495 context.new_paragraph(os);
1496 // We need to make sure that the paragraph is
1497 // generated even if it is empty. Otherwise the
1498 // appendix in '\par\appendix\par\chapter{' would
1500 context.check_layout(os);
1501 // FIXME: This is a hack to prevent paragraph
1502 // deletion if it is empty. Handle this better!
1504 "%dummy comment inserted by tex2lyx to "
1505 "ensure that this paragraph is not empty",
1507 // Both measures above may generate an additional
1508 // empty paragraph, but that does not hurt, because
1509 // whitespace does not matter here.
1510 eat_whitespace(p, os, context, true);
1513 // Must attempt to parse "Section*" before "Section".
1514 else if ((p.next_token().asInput() == "*") &&
1515 context.new_layout_allowed &&
1516 // The single '=' is meant here.
1517 (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1518 newlayout->isCommand()) {
1520 output_command_layout(os, p, outer, context, newlayout);
1524 // The single '=' is meant here.
1525 else if (context.new_layout_allowed &&
1526 (newlayout = findLayout(context.textclass, t.cs())) &&
1527 newlayout->isCommand()) {
1528 output_command_layout(os, p, outer, context, newlayout);
1532 // Special handling for \caption
1533 // FIXME: remove this when InsetCaption is supported.
1534 else if (context.new_layout_allowed &&
1535 t.cs() == captionlayout->latexname()) {
1536 output_command_layout(os, p, outer, context,
1541 else if (t.cs() == "includegraphics") {
1542 bool const clip = p.next_token().asInput() == "*";
1545 map<string, string> opts = split_map(p.getArg('[', ']'));
1547 opts["clip"] = string();
1548 string name = normalize_filename(p.verbatim_item());
1550 string const path = getMasterFilePath();
1551 // We want to preserve relative / absolute filenames,
1552 // therefore path is only used for testing
1553 // FIXME UNICODE encoding of name and path may be
1554 // wrong (makeAbsPath expects utf8)
1555 if (!makeAbsPath(name, path).exists()) {
1556 // The file extension is probably missing.
1557 // Now try to find it out.
1558 string const dvips_name =
1559 find_file(name, path,
1560 known_dvips_graphics_formats);
1561 string const pdftex_name =
1562 find_file(name, path,
1563 known_pdftex_graphics_formats);
1564 if (!dvips_name.empty()) {
1565 if (!pdftex_name.empty()) {
1566 cerr << "This file contains the "
1568 "\"\\includegraphics{"
1570 "However, files\n\""
1571 << dvips_name << "\" and\n\""
1572 << pdftex_name << "\"\n"
1573 "both exist, so I had to make a "
1574 "choice and took the first one.\n"
1575 "Please move the unwanted one "
1576 "someplace else and try again\n"
1577 "if my choice was wrong."
1581 } else if (!pdftex_name.empty())
1585 // FIXME UNICODE encoding of name and path may be
1586 // wrong (makeAbsPath expects utf8)
1587 if (makeAbsPath(name, path).exists())
1588 fix_relative_filename(name);
1590 cerr << "Warning: Could not find graphics file '"
1591 << name << "'." << endl;
1593 context.check_layout(os);
1594 begin_inset(os, "Graphics ");
1595 os << "\n\tfilename " << name << '\n';
1596 if (opts.find("width") != opts.end())
1598 << translate_len(opts["width"]) << '\n';
1599 if (opts.find("height") != opts.end())
1601 << translate_len(opts["height"]) << '\n';
1602 if (opts.find("scale") != opts.end()) {
1603 istringstream iss(opts["scale"]);
1607 os << "\tscale " << val << '\n';
1609 if (opts.find("angle") != opts.end())
1610 os << "\trotateAngle "
1611 << opts["angle"] << '\n';
1612 if (opts.find("origin") != opts.end()) {
1614 string const opt = opts["origin"];
1615 if (opt.find('l') != string::npos) ss << "left";
1616 if (opt.find('r') != string::npos) ss << "right";
1617 if (opt.find('c') != string::npos) ss << "center";
1618 if (opt.find('t') != string::npos) ss << "Top";
1619 if (opt.find('b') != string::npos) ss << "Bottom";
1620 if (opt.find('B') != string::npos) ss << "Baseline";
1621 if (!ss.str().empty())
1622 os << "\trotateOrigin " << ss.str() << '\n';
1624 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1626 if (opts.find("keepaspectratio") != opts.end())
1627 os << "\tkeepAspectRatio\n";
1628 if (opts.find("clip") != opts.end())
1630 if (opts.find("draft") != opts.end())
1632 if (opts.find("bb") != opts.end())
1633 os << "\tBoundingBox "
1634 << opts["bb"] << '\n';
1635 int numberOfbbOptions = 0;
1636 if (opts.find("bbllx") != opts.end())
1637 numberOfbbOptions++;
1638 if (opts.find("bblly") != opts.end())
1639 numberOfbbOptions++;
1640 if (opts.find("bburx") != opts.end())
1641 numberOfbbOptions++;
1642 if (opts.find("bbury") != opts.end())
1643 numberOfbbOptions++;
1644 if (numberOfbbOptions == 4)
1645 os << "\tBoundingBox "
1646 << opts["bbllx"] << " " << opts["bblly"] << " "
1647 << opts["bburx"] << " " << opts["bbury"] << '\n';
1648 else if (numberOfbbOptions > 0)
1649 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1650 numberOfbbOptions = 0;
1651 if (opts.find("natwidth") != opts.end())
1652 numberOfbbOptions++;
1653 if (opts.find("natheight") != opts.end())
1654 numberOfbbOptions++;
1655 if (numberOfbbOptions == 2)
1656 os << "\tBoundingBox 0bp 0bp "
1657 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1658 else if (numberOfbbOptions > 0)
1659 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1660 ostringstream special;
1661 if (opts.find("hiresbb") != opts.end())
1662 special << "hiresbb,";
1663 if (opts.find("trim") != opts.end())
1665 if (opts.find("viewport") != opts.end())
1666 special << "viewport=" << opts["viewport"] << ',';
1667 if (opts.find("totalheight") != opts.end())
1668 special << "totalheight=" << opts["totalheight"] << ',';
1669 if (opts.find("type") != opts.end())
1670 special << "type=" << opts["type"] << ',';
1671 if (opts.find("ext") != opts.end())
1672 special << "ext=" << opts["ext"] << ',';
1673 if (opts.find("read") != opts.end())
1674 special << "read=" << opts["read"] << ',';
1675 if (opts.find("command") != opts.end())
1676 special << "command=" << opts["command"] << ',';
1677 string s_special = special.str();
1678 if (!s_special.empty()) {
1679 // We had special arguments. Remove the trailing ','.
1680 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1682 // TODO: Handle the unknown settings better.
1683 // Warn about invalid options.
1684 // Check whether some option was given twice.
1688 else if (t.cs() == "footnote" ||
1689 (t.cs() == "thanks" && context.layout->intitle)) {
1691 context.check_layout(os);
1692 begin_inset(os, "Foot\n");
1693 os << "status collapsed\n\n";
1694 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1698 else if (t.cs() == "marginpar") {
1700 context.check_layout(os);
1701 begin_inset(os, "Marginal\n");
1702 os << "status collapsed\n\n";
1703 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1707 else if (t.cs() == "ensuremath") {
1709 context.check_layout(os);
1710 string const s = p.verbatim_item();
1711 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1714 handle_ert(os, "\\ensuremath{" + s + "}",
1718 else if (t.cs() == "hfill") {
1719 context.check_layout(os);
1720 os << "\n\\hfill\n";
1725 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1726 // FIXME: Somehow prevent title layouts if
1727 // "maketitle" was not found
1729 skip_braces(p); // swallow this
1732 else if (t.cs() == "tableofcontents") {
1734 context.check_layout(os);
1735 begin_inset(os, "LatexCommand \\tableofcontents\n");
1737 skip_braces(p); // swallow this
1740 else if (t.cs() == "listoffigures") {
1742 context.check_layout(os);
1743 begin_inset(os, "FloatList figure\n");
1745 skip_braces(p); // swallow this
1748 else if (t.cs() == "listoftables") {
1750 context.check_layout(os);
1751 begin_inset(os, "FloatList table\n");
1753 skip_braces(p); // swallow this
1756 else if (t.cs() == "listof") {
1757 p.skip_spaces(true);
1758 string const name = p.get_token().asString();
1759 if (context.textclass.floats().typeExist(name)) {
1760 context.check_layout(os);
1761 begin_inset(os, "FloatList ");
1764 p.get_token(); // swallow second arg
1766 handle_ert(os, "\\listof{" + name + "}", context);
1769 else if (t.cs() == "textrm")
1770 parse_text_attributes(p, os, FLAG_ITEM, outer,
1771 context, "\\family",
1772 context.font.family, "roman");
1774 else if (t.cs() == "textsf")
1775 parse_text_attributes(p, os, FLAG_ITEM, outer,
1776 context, "\\family",
1777 context.font.family, "sans");
1779 else if (t.cs() == "texttt")
1780 parse_text_attributes(p, os, FLAG_ITEM, outer,
1781 context, "\\family",
1782 context.font.family, "typewriter");
1784 else if (t.cs() == "textmd")
1785 parse_text_attributes(p, os, FLAG_ITEM, outer,
1786 context, "\\series",
1787 context.font.series, "medium");
1789 else if (t.cs() == "textbf")
1790 parse_text_attributes(p, os, FLAG_ITEM, outer,
1791 context, "\\series",
1792 context.font.series, "bold");
1794 else if (t.cs() == "textup")
1795 parse_text_attributes(p, os, FLAG_ITEM, outer,
1797 context.font.shape, "up");
1799 else if (t.cs() == "textit")
1800 parse_text_attributes(p, os, FLAG_ITEM, outer,
1802 context.font.shape, "italic");
1804 else if (t.cs() == "textsl")
1805 parse_text_attributes(p, os, FLAG_ITEM, outer,
1807 context.font.shape, "slanted");
1809 else if (t.cs() == "textsc")
1810 parse_text_attributes(p, os, FLAG_ITEM, outer,
1812 context.font.shape, "smallcaps");
1814 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1815 context.check_layout(os);
1816 TeXFont oldFont = context.font;
1817 context.font.init();
1818 context.font.size = oldFont.size;
1819 os << "\n\\family " << context.font.family << "\n";
1820 os << "\n\\series " << context.font.series << "\n";
1821 os << "\n\\shape " << context.font.shape << "\n";
1822 if (t.cs() == "textnormal") {
1823 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1824 output_font_change(os, context.font, oldFont);
1825 context.font = oldFont;
1827 eat_whitespace(p, os, context, false);
1830 else if (t.cs() == "underbar") {
1831 // Do NOT handle \underline.
1832 // \underbar cuts through y, g, q, p etc.,
1833 // \underline does not.
1834 context.check_layout(os);
1835 os << "\n\\bar under\n";
1836 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1837 context.check_layout(os);
1838 os << "\n\\bar default\n";
1841 else if (t.cs() == "emph" || t.cs() == "noun") {
1842 context.check_layout(os);
1843 os << "\n\\" << t.cs() << " on\n";
1844 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1845 context.check_layout(os);
1846 os << "\n\\" << t.cs() << " default\n";
1849 else if (use_natbib &&
1850 is_known(t.cs(), known_natbib_commands) &&
1851 ((t.cs() != "citefullauthor" &&
1852 t.cs() != "citeyear" &&
1853 t.cs() != "citeyearpar") ||
1854 p.next_token().asInput() != "*")) {
1855 context.check_layout(os);
1857 // \citet[before][after]{a} \citet[after][before]{a}
1858 // \citet[before][]{a} \citet[][before]{a}
1859 // \citet[after]{a} \citet[after]{a}
1860 // \citet{a} \citet{a}
1861 string command = '\\' + t.cs();
1862 if (p.next_token().asInput() == "*") {
1866 if (command == "\\citefullauthor")
1867 // alternative name for "\\citeauthor*"
1868 command = "\\citeauthor*";
1870 // text before the citation
1872 // text after the citation
1874 get_cite_arguments(p, true, before, after);
1876 if (command == "\\cite") {
1877 // \cite without optional argument means
1878 // \citet, \cite with at least one optional
1879 // argument means \citep.
1880 if (before.empty() && after.empty())
1881 command = "\\citet";
1883 command = "\\citep";
1885 if (before.empty() && after == "[]")
1886 // avoid \citet[]{a}
1888 else if (before == "[]" && after == "[]") {
1889 // avoid \citet[][]{a}
1893 begin_inset(os, "LatexCommand ");
1894 os << command << after << before
1895 << '{' << p.verbatim_item() << "}\n";
1899 else if (use_jurabib &&
1900 is_known(t.cs(), known_jurabib_commands)) {
1901 context.check_layout(os);
1902 string const command = '\\' + t.cs();
1903 char argumentOrder = '\0';
1904 vector<string> const & options = used_packages["jurabib"];
1905 if (find(options.begin(), options.end(),
1906 "natbiborder") != options.end())
1907 argumentOrder = 'n';
1908 else if (find(options.begin(), options.end(),
1909 "jurabiborder") != options.end())
1910 argumentOrder = 'j';
1912 // text before the citation
1914 // text after the citation
1916 get_cite_arguments(p, argumentOrder != 'j', before, after);
1918 string const citation = p.verbatim_item();
1919 if (!before.empty() && argumentOrder == '\0') {
1920 cerr << "Warning: Assuming argument order "
1921 "of jurabib version 0.6 for\n'"
1922 << command << before << after << '{'
1923 << citation << "}'.\n"
1924 "Add 'jurabiborder' to the jurabib "
1925 "package options if you used an\n"
1926 "earlier jurabib version." << endl;
1928 begin_inset(os, "LatexCommand ");
1929 os << command << after << before
1930 << '{' << citation << "}\n";
1934 else if (is_known(t.cs(), known_latex_commands)) {
1935 // This needs to be after the check for natbib and
1936 // jurabib commands, because "cite" has different
1937 // arguments with natbib and jurabib.
1938 context.check_layout(os);
1939 begin_inset(os, "LatexCommand ");
1940 os << '\\' << t.cs();
1941 // lyx cannot handle newlines in a latex command
1942 // FIXME: Move the substitution into parser::getOpt()?
1943 os << subst(p.getOpt(), "\n", " ");
1944 os << subst(p.getOpt(), "\n", " ");
1945 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1949 else if (is_known(t.cs(), known_quotes)) {
1950 char const * const * where = is_known(t.cs(), known_quotes);
1951 context.check_layout(os);
1952 begin_inset(os, "Quotes ");
1953 os << known_coded_quotes[where - known_quotes];
1955 // LyX adds {} after the quote, so we have to eat
1956 // spaces here if there are any before a possible
1958 eat_whitespace(p, os, context, false);
1962 else if (is_known(t.cs(), known_sizes) &&
1963 context.new_layout_allowed) {
1964 char const * const * where = is_known(t.cs(), known_sizes);
1965 context.check_layout(os);
1966 TeXFont const oldFont = context.font;
1967 context.font.size = known_coded_sizes[where - known_sizes];
1968 output_font_change(os, oldFont, context.font);
1969 eat_whitespace(p, os, context, false);
1972 else if (is_known(t.cs(), known_font_families) &&
1973 context.new_layout_allowed) {
1974 char const * const * where =
1975 is_known(t.cs(), known_font_families);
1976 context.check_layout(os);
1977 TeXFont const oldFont = context.font;
1978 context.font.family =
1979 known_coded_font_families[where - known_font_families];
1980 output_font_change(os, oldFont, context.font);
1981 eat_whitespace(p, os, context, false);
1984 else if (is_known(t.cs(), known_font_series) &&
1985 context.new_layout_allowed) {
1986 char const * const * where =
1987 is_known(t.cs(), known_font_series);
1988 context.check_layout(os);
1989 TeXFont const oldFont = context.font;
1990 context.font.series =
1991 known_coded_font_series[where - known_font_series];
1992 output_font_change(os, oldFont, context.font);
1993 eat_whitespace(p, os, context, false);
1996 else if (is_known(t.cs(), known_font_shapes) &&
1997 context.new_layout_allowed) {
1998 char const * const * where =
1999 is_known(t.cs(), known_font_shapes);
2000 context.check_layout(os);
2001 TeXFont const oldFont = context.font;
2002 context.font.shape =
2003 known_coded_font_shapes[where - known_font_shapes];
2004 output_font_change(os, oldFont, context.font);
2005 eat_whitespace(p, os, context, false);
2007 else if (is_known(t.cs(), known_old_font_families) &&
2008 context.new_layout_allowed) {
2009 char const * const * where =
2010 is_known(t.cs(), known_old_font_families);
2011 context.check_layout(os);
2012 TeXFont const oldFont = context.font;
2013 context.font.init();
2014 context.font.size = oldFont.size;
2015 context.font.family =
2016 known_coded_font_families[where - known_old_font_families];
2017 output_font_change(os, oldFont, context.font);
2018 eat_whitespace(p, os, context, false);
2021 else if (is_known(t.cs(), known_old_font_series) &&
2022 context.new_layout_allowed) {
2023 char const * const * where =
2024 is_known(t.cs(), known_old_font_series);
2025 context.check_layout(os);
2026 TeXFont const oldFont = context.font;
2027 context.font.init();
2028 context.font.size = oldFont.size;
2029 context.font.series =
2030 known_coded_font_series[where - known_old_font_series];
2031 output_font_change(os, oldFont, context.font);
2032 eat_whitespace(p, os, context, false);
2035 else if (is_known(t.cs(), known_old_font_shapes) &&
2036 context.new_layout_allowed) {
2037 char const * const * where =
2038 is_known(t.cs(), known_old_font_shapes);
2039 context.check_layout(os);
2040 TeXFont const oldFont = context.font;
2041 context.font.init();
2042 context.font.size = oldFont.size;
2043 context.font.shape =
2044 known_coded_font_shapes[where - known_old_font_shapes];
2045 output_font_change(os, oldFont, context.font);
2046 eat_whitespace(p, os, context, false);
2049 else if (t.cs() == "selectlanguage") {
2050 context.check_layout(os);
2051 // save the language for the case that a \foreignlanguage is used
2052 selectlang = subst(p.verbatim_item(), "\n", " ");
2053 os << "\\lang " << selectlang << "\n";
2057 else if (t.cs() == "foreignlanguage") {
2058 context.check_layout(os);
2059 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2060 os << subst(p.verbatim_item(), "\n", " ");
2061 // set back to last selectlanguage
2062 os << "\n\\lang " << selectlang << "\n";
2065 else if (t.cs() == "inputencoding")
2066 // write nothing because this is done by LyX using the "\lang"
2067 // information given by selectlanguage and foreignlanguage
2068 subst(p.verbatim_item(), "\n", " ");
2070 else if (t.cs() == "LyX" || t.cs() == "TeX"
2071 || t.cs() == "LaTeX") {
2072 context.check_layout(os);
2074 skip_braces(p); // eat {}
2077 else if (t.cs() == "LaTeXe") {
2078 context.check_layout(os);
2080 skip_braces(p); // eat {}
2083 else if (t.cs() == "ldots") {
2084 context.check_layout(os);
2086 os << "\\SpecialChar \\ldots{}\n";
2089 else if (t.cs() == "lyxarrow") {
2090 context.check_layout(os);
2091 os << "\\SpecialChar \\menuseparator\n";
2095 else if (t.cs() == "textcompwordmark") {
2096 context.check_layout(os);
2097 os << "\\SpecialChar \\textcompwordmark{}\n";
2101 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2102 context.check_layout(os);
2103 os << "\\SpecialChar \\@.\n";
2107 else if (t.cs() == "-") {
2108 context.check_layout(os);
2109 os << "\\SpecialChar \\-\n";
2112 else if (t.cs() == "textasciitilde") {
2113 context.check_layout(os);
2118 else if (t.cs() == "textasciicircum") {
2119 context.check_layout(os);
2124 else if (t.cs() == "textbackslash") {
2125 context.check_layout(os);
2126 os << "\n\\backslash\n";
2130 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2131 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2133 context.check_layout(os);
2137 else if (t.cs() == "char") {
2138 context.check_layout(os);
2139 if (p.next_token().character() == '`') {
2141 if (p.next_token().cs() == "\"") {
2146 handle_ert(os, "\\char`", context);
2149 handle_ert(os, "\\char", context);
2153 else if (t.cs() == "verb") {
2154 context.check_layout(os);
2155 char const delimiter = p.next_token().character();
2156 string const arg = p.getArg(delimiter, delimiter);
2158 oss << "\\verb" << delimiter << arg << delimiter;
2159 handle_ert(os, oss.str(), context);
2162 else if (t.cs() == "\"") {
2163 context.check_layout(os);
2164 string const name = p.verbatim_item();
2165 if (name == "a") os << '\xe4';
2166 else if (name == "o") os << '\xf6';
2167 else if (name == "u") os << '\xfc';
2168 else if (name == "A") os << '\xc4';
2169 else if (name == "O") os << '\xd6';
2170 else if (name == "U") os << '\xdc';
2171 else handle_ert(os, "\"{" + name + "}", context);
2174 // Problem: \= creates a tabstop inside the tabbing environment
2175 // and else an accent. In the latter case we really would want
2176 // \={o} instead of \= o.
2177 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2178 handle_ert(os, t.asInput(), context);
2180 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2181 || t.cs() == "'" || t.cs() == "`"
2182 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2183 // we need the trim as the LyX parser chokes on such spaces
2184 // The argument of InsetLatexAccent is parsed as a
2185 // subset of LaTeX, so don't parse anything here,
2186 // but use the raw argument.
2187 // Otherwise we would convert \~{\i} wrongly.
2188 // This will of course not translate \~{\ss} to \~{ß},
2189 // but that does at least compile and does only look
2190 // strange on screen.
2191 context.check_layout(os);
2192 os << "\\i \\" << t.cs() << "{"
2193 << trim(p.verbatim_item(), " ")
2197 else if (t.cs() == "ss") {
2198 context.check_layout(os);
2200 skip_braces(p); // eat {}
2203 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2205 context.check_layout(os);
2206 os << "\\i \\" << t.cs() << "{}\n";
2207 skip_braces(p); // eat {}
2210 else if (t.cs() == "\\") {
2211 context.check_layout(os);
2212 string const next = p.next_token().asInput();
2214 handle_ert(os, "\\\\" + p.getOpt(), context);
2215 else if (next == "*") {
2217 handle_ert(os, "\\\\*" + p.getOpt(), context);
2220 os << "\n\\newline\n";
2224 else if (t.cs() == "newline" ||
2225 t.cs() == "linebreak") {
2226 context.check_layout(os);
2227 os << "\n\\" << t.cs() << "\n";
2228 skip_braces(p); // eat {}
2231 else if (t.cs() == "href") {
2232 context.check_layout(os);
2233 begin_inset(os, "CommandInset ");
2234 os << t.cs() << "\n";
2235 os << "LatexCommand " << t.cs() << "\n";
2238 // the first argument is "type:target", "type:" is optional
2239 // the second argument the name
2240 string href_target = subst(p.verbatim_item(), "\n", " ");
2241 string href_name = subst(p.verbatim_item(), "\n", " ");
2243 // serach for the ":" to divide type from target
2244 if ((pos = href_target.find(":", 0)) != string::npos){
2245 href_type = href_target;
2246 href_type.erase(pos + 1, href_type.length());
2247 href_target.erase(0, pos + 1);
2250 os << "name " << '"' << href_name << '"' << "\n";
2251 os << "target " << '"' << href_target << '"' << "\n";
2253 os << "type " << '"' << href_type << '"' << "\n";
2257 else if (t.cs() == "input" || t.cs() == "include"
2258 || t.cs() == "verbatiminput") {
2259 string name = '\\' + t.cs();
2260 if (t.cs() == "verbatiminput"
2261 && p.next_token().asInput() == "*")
2262 name += p.get_token().asInput();
2263 context.check_layout(os);
2264 begin_inset(os, "Include ");
2265 string filename(normalize_filename(p.getArg('{', '}')));
2266 string const path = getMasterFilePath();
2267 // We want to preserve relative / absolute filenames,
2268 // therefore path is only used for testing
2269 // FIXME UNICODE encoding of filename and path may be
2270 // wrong (makeAbsPath expects utf8)
2271 if ((t.cs() == "include" || t.cs() == "input") &&
2272 !makeAbsPath(filename, path).exists()) {
2273 // The file extension is probably missing.
2274 // Now try to find it out.
2275 string const tex_name =
2276 find_file(filename, path,
2277 known_tex_extensions);
2278 if (!tex_name.empty())
2279 filename = tex_name;
2281 // FIXME UNICODE encoding of filename and path may be
2282 // wrong (makeAbsPath expects utf8)
2283 if (makeAbsPath(filename, path).exists()) {
2284 string const abstexname =
2285 makeAbsPath(filename, path).absFilename();
2286 string const abslyxname =
2287 changeExtension(abstexname, ".lyx");
2288 fix_relative_filename(filename);
2289 string const lyxname =
2290 changeExtension(filename, ".lyx");
2291 if (t.cs() != "verbatiminput" &&
2292 tex2lyx(abstexname, FileName(abslyxname))) {
2293 os << name << '{' << lyxname << "}\n";
2295 os << name << '{' << filename << "}\n";
2298 cerr << "Warning: Could not find included file '"
2299 << filename << "'." << endl;
2300 os << name << '{' << filename << "}\n";
2302 os << "preview false\n";
2306 else if (t.cs() == "bibliographystyle") {
2307 // store new bibliographystyle
2308 bibliographystyle = p.verbatim_item();
2309 // output new bibliographystyle.
2310 // This is only necessary if used in some other macro than \bibliography.
2311 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2314 else if (t.cs() == "bibliography") {
2315 context.check_layout(os);
2316 begin_inset(os, "LatexCommand ");
2318 // Do we have a bibliographystyle set?
2319 if (!bibliographystyle.empty()) {
2320 os << '[' << bibliographystyle << ']';
2322 os << '{' << p.verbatim_item() << "}\n";
2326 else if (t.cs() == "parbox")
2327 parse_box(p, os, FLAG_ITEM, outer, context, true);
2329 else if (t.cs() == "smallskip" ||
2330 t.cs() == "medskip" ||
2331 t.cs() == "bigskip" ||
2332 t.cs() == "vfill") {
2333 context.check_layout(os);
2334 begin_inset(os, "VSpace ");
2340 else if (is_known(t.cs(), known_spaces)) {
2341 char const * const * where = is_known(t.cs(), known_spaces);
2342 context.check_layout(os);
2343 begin_inset(os, "InsetSpace ");
2344 os << '\\' << known_coded_spaces[where - known_spaces]
2346 // LaTeX swallows whitespace after all spaces except
2347 // "\\,". We have to do that here, too, because LyX
2348 // adds "{}" which would make the spaces significant.
2350 eat_whitespace(p, os, context, false);
2351 // LyX adds "{}" after all spaces except "\\ " and
2352 // "\\,", so we have to remove "{}".
2353 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2354 // remove the braces after "\\,", too.
2359 else if (t.cs() == "newpage" ||
2360 t.cs() == "pagebreak" ||
2361 t.cs() == "clearpage" ||
2362 t.cs() == "cleardoublepage") {
2363 context.check_layout(os);
2364 os << "\n\\" << t.cs() << "\n";
2365 skip_braces(p); // eat {}
2368 else if (t.cs() == "newcommand" ||
2369 t.cs() == "providecommand" ||
2370 t.cs() == "renewcommand" ||
2371 t.cs() == "newlyxcommand") {
2372 // these could be handled by parse_command(), but
2373 // we need to call add_known_command() here.
2374 string name = t.asInput();
2375 if (p.next_token().asInput() == "*") {
2376 // Starred form. Eat '*'
2380 string const command = p.verbatim_item();
2381 string const opt1 = p.getOpt();
2383 unsigned optionalsNum = 0;
2385 string const opt = p.getFullOpt();
2391 add_known_command(command, opt1, optionalsNum);
2392 string const ert = name + '{' + command + '}' + opt1
2393 + optionals + '{' + p.verbatim_item() + '}';
2395 context.check_layout(os);
2396 begin_inset(os, "FormulaMacro");
2401 else if (t.cs() == "vspace") {
2402 bool starred = false;
2403 if (p.next_token().asInput() == "*") {
2407 string const length = p.verbatim_item();
2410 bool valid = splitLatexLength(length, valstring, unit);
2411 bool known_vspace = false;
2412 bool known_unit = false;
2415 istringstream iss(valstring);
2418 if (unit == "\\smallskipamount") {
2420 known_vspace = true;
2421 } else if (unit == "\\medskipamount") {
2423 known_vspace = true;
2424 } else if (unit == "\\bigskipamount") {
2426 known_vspace = true;
2427 } else if (unit == "\\fill") {
2429 known_vspace = true;
2432 if (!known_vspace) {
2433 switch (unitFromString(unit)) {
2454 if (known_unit || known_vspace) {
2455 // Literal length or known variable
2456 context.check_layout(os);
2457 begin_inset(os, "VSpace ");
2465 // LyX can't handle other length variables in Inset VSpace
2466 string name = t.asInput();
2471 handle_ert(os, name + '{' + unit + '}', context);
2472 else if (value == -1.0)
2473 handle_ert(os, name + "{-" + unit + '}', context);
2475 handle_ert(os, name + '{' + valstring + unit + '}', context);
2477 handle_ert(os, name + '{' + length + '}', context);
2482 //cerr << "#: " << t << " mode: " << mode << endl;
2483 // heuristic: read up to next non-nested space
2485 string s = t.asInput();
2486 string z = p.verbatim_item();
2487 while (p.good() && z != " " && z.size()) {
2488 //cerr << "read: " << z << endl;
2490 z = p.verbatim_item();
2492 cerr << "found ERT: " << s << endl;
2493 handle_ert(os, s + ' ', context);
2495 string name = t.asInput();
2496 if (p.next_token().asInput() == "*") {
2497 // Starred commands like \vspace*{}
2498 p.get_token(); // Eat '*'
2501 if (! parse_command(name, p, os, outer, context))
2502 handle_ert(os, name, context);
2505 if (flags & FLAG_LEAVE) {
2506 flags &= ~FLAG_LEAVE;