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 for (size_t i = 0; i != textclass.layoutCount(); ++i)
427 if (textclass.layout(i)->latexname() == name)
428 return textclass.layout(i);
433 void eat_whitespace(Parser &, ostream &, Context &, bool);
436 void output_command_layout(ostream & os, Parser & p, bool outer,
437 Context & parent_context,
440 parent_context.check_end_layout(os);
441 Context context(true, parent_context.textclass, newlayout,
442 parent_context.layout, parent_context.font);
443 if (parent_context.deeper_paragraph) {
444 // We are beginning a nested environment after a
445 // deeper paragraph inside the outer list environment.
446 // Therefore we don't need to output a "begin deeper".
447 context.need_end_deeper = true;
449 context.check_deeper(os);
450 context.check_layout(os);
451 if (context.layout->optionalargs > 0) {
452 eat_whitespace(p, os, context, false);
453 if (p.next_token().character() == '[') {
454 p.get_token(); // eat '['
455 begin_inset(os, "OptArg\n");
456 os << "status collapsed\n\n";
457 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
459 eat_whitespace(p, os, context, false);
462 parse_text(p, os, FLAG_ITEM, outer, context);
463 context.check_end_layout(os);
464 if (parent_context.deeper_paragraph) {
465 // We must suppress the "end deeper" because we
466 // suppressed the "begin deeper" above.
467 context.need_end_deeper = false;
469 context.check_end_deeper(os);
470 // We don't need really a new paragraph, but
471 // we must make sure that the next item gets a \begin_layout.
472 parent_context.new_paragraph(os);
477 * Output a space if necessary.
478 * This function gets called for every whitespace token.
480 * We have three cases here:
481 * 1. A space must be suppressed. Example: The lyxcode case below
482 * 2. A space may be suppressed. Example: Spaces before "\par"
483 * 3. A space must not be suppressed. Example: A space between two words
485 * We currently handle only 1. and 3 and from 2. only the case of
486 * spaces before newlines as a side effect.
488 * 2. could be used to suppress as many spaces as possible. This has two effects:
489 * - Reimporting LyX generated LaTeX files changes almost no whitespace
490 * - Superflous whitespace from non LyX generated LaTeX files is removed.
491 * The drawback is that the logic inside the function becomes
492 * complicated, and that is the reason why it is not implemented.
494 void check_space(Parser const & p, ostream & os, Context & context)
496 Token const next = p.next_token();
497 Token const curr = p.curr_token();
498 // A space before a single newline and vice versa must be ignored
499 // LyX emits a newline before \end{lyxcode}.
500 // This newline must be ignored,
501 // otherwise LyX will add an additional protected space.
502 if (next.cat() == catSpace ||
503 next.cat() == catNewline ||
504 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
507 context.check_layout(os);
513 * Parse all arguments of \p command
515 void parse_arguments(string const & command,
516 vector<ArgumentType> const & template_arguments,
517 Parser & p, ostream & os, bool outer, Context & context)
519 string ert = command;
520 size_t no_arguments = template_arguments.size();
521 for (size_t i = 0; i < no_arguments; ++i) {
522 switch (template_arguments[i]) {
524 // This argument contains regular LaTeX
525 handle_ert(os, ert + '{', context);
526 eat_whitespace(p, os, context, false);
527 parse_text(p, os, FLAG_ITEM, outer, context);
531 // This argument may contain special characters
532 ert += '{' + p.verbatim_item() + '}';
539 handle_ert(os, ert, context);
544 * Check whether \p command is a known command. If yes,
545 * handle the command with all arguments.
546 * \return true if the command was parsed, false otherwise.
548 bool parse_command(string const & command, Parser & p, ostream & os,
549 bool outer, Context & context)
551 if (known_commands.find(command) != known_commands.end()) {
552 parse_arguments(command, known_commands[command], p, os,
560 /// Parses a minipage or parbox
561 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
562 Context & parent_context, bool use_parbox)
566 // We need to set the height to the LaTeX default of 1\\totalheight
567 // for the case when no height argument is given
568 string height_value = "1";
569 string height_unit = "in";
570 string height_special = "totalheight";
572 if (p.next_token().asInput() == "[") {
573 position = p.getArg('[', ']');
574 if (position != "t" && position != "c" && position != "b") {
576 cerr << "invalid position for minipage/parbox" << endl;
578 if (p.next_token().asInput() == "[") {
579 latex_height = p.getArg('[', ']');
580 translate_box_len(latex_height, height_value, height_unit, height_special);
582 if (p.next_token().asInput() == "[") {
583 inner_pos = p.getArg('[', ']');
584 if (inner_pos != "c" && inner_pos != "t" &&
585 inner_pos != "b" && inner_pos != "s") {
586 inner_pos = position;
587 cerr << "invalid inner_pos for minipage/parbox"
595 string const latex_width = p.verbatim_item();
596 translate_len(latex_width, width_value, width_unit);
597 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
598 // LyX can't handle length variables
603 ss << "\\begin{minipage}";
604 if (!position.empty())
605 ss << '[' << position << ']';
606 if (!latex_height.empty())
607 ss << '[' << latex_height << ']';
608 if (!inner_pos.empty())
609 ss << '[' << inner_pos << ']';
610 ss << "{" << latex_width << "}";
613 handle_ert(os, ss.str(), parent_context);
614 parent_context.new_paragraph(os);
615 parse_text_in_inset(p, os, flags, outer, parent_context);
617 handle_ert(os, "}", parent_context);
619 handle_ert(os, "\\end{minipage}", parent_context);
621 // LyX does not like empty positions, so we have
622 // to set them to the LaTeX default values here.
623 if (position.empty())
625 if (inner_pos.empty())
626 inner_pos = position;
627 parent_context.check_layout(os);
628 begin_inset(os, "Box Frameless\n");
629 os << "position \"" << position << "\"\n";
630 os << "hor_pos \"c\"\n";
631 os << "has_inner_box 1\n";
632 os << "inner_pos \"" << inner_pos << "\"\n";
633 os << "use_parbox " << use_parbox << "\n";
634 os << "width \"" << width_value << width_unit << "\"\n";
635 os << "special \"none\"\n";
636 os << "height \"" << height_value << height_unit << "\"\n";
637 os << "height_special \"" << height_special << "\"\n";
638 os << "status open\n\n";
639 parse_text_in_inset(p, os, flags, outer, parent_context);
641 #ifdef PRESERVE_LAYOUT
642 // lyx puts a % after the end of the minipage
643 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
645 //handle_comment(os, "%dummy", parent_context);
648 parent_context.new_paragraph(os);
650 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
651 //handle_comment(os, "%dummy", parent_context);
654 // We add a protected space if something real follows
655 if (p.good() && p.next_token().cat() != catComment) {
656 os << "\\InsetSpace ~\n";
664 /// parse an unknown environment
665 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
666 unsigned flags, bool outer,
667 Context & parent_context)
669 if (name == "tabbing")
670 // We need to remember that we have to handle '\=' specially
671 flags |= FLAG_TABBING;
673 // We need to translate font changes and paragraphs inside the
674 // environment to ERT if we have a non standard font.
675 // Otherwise things like
676 // \large\begin{foo}\huge bar\end{foo}
678 bool const specialfont =
679 (parent_context.font != parent_context.normalfont);
680 bool const new_layout_allowed = parent_context.new_layout_allowed;
682 parent_context.new_layout_allowed = false;
683 handle_ert(os, "\\begin{" + name + "}", parent_context);
684 parse_text_snippet(p, os, flags, outer, parent_context);
685 handle_ert(os, "\\end{" + name + "}", parent_context);
687 parent_context.new_layout_allowed = new_layout_allowed;
691 void parse_environment(Parser & p, ostream & os, bool outer,
692 Context & parent_context)
695 string const name = p.getArg('{', '}');
696 const bool is_starred = suffixIs(name, '*');
697 string const unstarred_name = rtrim(name, "*");
698 active_environments.push_back(name);
700 if (is_math_env(name)) {
701 parent_context.check_layout(os);
702 begin_inset(os, "Formula ");
703 os << "\\begin{" << name << "}";
704 parse_math(p, os, FLAG_END, MATH_MODE);
705 os << "\\end{" << name << "}";
709 else if (name == "tabular" || name == "longtable") {
710 eat_whitespace(p, os, parent_context, false);
711 parent_context.check_layout(os);
712 begin_inset(os, "Tabular ");
713 handle_tabular(p, os, name == "longtable", parent_context);
718 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
719 eat_whitespace(p, os, parent_context, false);
720 parent_context.check_layout(os);
721 begin_inset(os, "Float " + unstarred_name + "\n");
722 if (p.next_token().asInput() == "[") {
723 os << "placement " << p.getArg('[', ']') << '\n';
725 os << "wide " << convert<string>(is_starred)
726 << "\nsideways false"
727 << "\nstatus open\n\n";
728 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
730 // We don't need really a new paragraph, but
731 // we must make sure that the next item gets a \begin_layout.
732 parent_context.new_paragraph(os);
736 else if (name == "minipage") {
737 eat_whitespace(p, os, parent_context, false);
738 parse_box(p, os, FLAG_END, outer, parent_context, false);
742 else if (name == "comment") {
743 eat_whitespace(p, os, parent_context, false);
744 parent_context.check_layout(os);
745 begin_inset(os, "Note Comment\n");
746 os << "status open\n";
747 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
752 else if (name == "lyxgreyedout") {
753 eat_whitespace(p, os, parent_context, false);
754 parent_context.check_layout(os);
755 begin_inset(os, "Note Greyedout\n");
756 os << "status open\n";
757 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
762 else if (name == "framed") {
763 eat_whitespace(p, os, parent_context, false);
764 parent_context.check_layout(os);
765 begin_inset(os, "Note Framed\n");
766 os << "status open\n";
767 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
772 else if (name == "shaded") {
773 eat_whitespace(p, os, parent_context, false);
774 parent_context.check_layout(os);
775 begin_inset(os, "Note Shaded\n");
776 os << "status open\n";
777 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
782 else if (!parent_context.new_layout_allowed)
783 parse_unknown_environment(p, name, os, FLAG_END, outer,
786 // Alignment settings
787 else if (name == "center" || name == "flushleft" || name == "flushright" ||
788 name == "centering" || name == "raggedright" || name == "raggedleft") {
789 eat_whitespace(p, os, parent_context, false);
790 // We must begin a new paragraph if not already done
791 if (! parent_context.atParagraphStart()) {
792 parent_context.check_end_layout(os);
793 parent_context.new_paragraph(os);
795 if (name == "flushleft" || name == "raggedright")
796 parent_context.add_extra_stuff("\\align left\n");
797 else if (name == "flushright" || name == "raggedleft")
798 parent_context.add_extra_stuff("\\align right\n");
800 parent_context.add_extra_stuff("\\align center\n");
801 parse_text(p, os, FLAG_END, outer, parent_context);
802 // Just in case the environment is empty ..
803 parent_context.extra_stuff.erase();
804 // We must begin a new paragraph to reset the alignment
805 parent_context.new_paragraph(os);
809 // The single '=' is meant here.
810 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
811 newlayout->isEnvironment()) {
812 eat_whitespace(p, os, parent_context, false);
813 Context context(true, parent_context.textclass, newlayout,
814 parent_context.layout, parent_context.font);
815 if (parent_context.deeper_paragraph) {
816 // We are beginning a nested environment after a
817 // deeper paragraph inside the outer list environment.
818 // Therefore we don't need to output a "begin deeper".
819 context.need_end_deeper = true;
821 parent_context.check_end_layout(os);
822 switch (context.layout->latextype) {
823 case LATEX_LIST_ENVIRONMENT:
824 context.extra_stuff = "\\labelwidthstring "
825 + p.verbatim_item() + '\n';
828 case LATEX_BIB_ENVIRONMENT:
829 p.verbatim_item(); // swallow next arg
835 context.check_deeper(os);
836 parse_text(p, os, FLAG_END, outer, context);
837 context.check_end_layout(os);
838 if (parent_context.deeper_paragraph) {
839 // We must suppress the "end deeper" because we
840 // suppressed the "begin deeper" above.
841 context.need_end_deeper = false;
843 context.check_end_deeper(os);
844 parent_context.new_paragraph(os);
848 else if (name == "appendix") {
849 // This is no good latex style, but it works and is used in some documents...
850 eat_whitespace(p, os, parent_context, false);
851 parent_context.check_end_layout(os);
852 Context context(true, parent_context.textclass, parent_context.layout,
853 parent_context.layout, parent_context.font);
854 context.check_layout(os);
855 os << "\\start_of_appendix\n";
856 parse_text(p, os, FLAG_END, outer, context);
857 context.check_end_layout(os);
861 else if (known_environments.find(name) != known_environments.end()) {
862 vector<ArgumentType> arguments = known_environments[name];
863 // The last "argument" denotes wether we may translate the
864 // environment contents to LyX
865 // The default required if no argument is given makes us
866 // compatible with the reLyXre environment.
867 ArgumentType contents = arguments.empty() ?
870 if (!arguments.empty())
871 arguments.pop_back();
872 // See comment in parse_unknown_environment()
873 bool const specialfont =
874 (parent_context.font != parent_context.normalfont);
875 bool const new_layout_allowed =
876 parent_context.new_layout_allowed;
878 parent_context.new_layout_allowed = false;
879 parse_arguments("\\begin{" + name + "}", arguments, p, os,
880 outer, parent_context);
881 if (contents == verbatim)
882 handle_ert(os, p.verbatimEnvironment(name),
885 parse_text_snippet(p, os, FLAG_END, outer,
887 handle_ert(os, "\\end{" + name + "}", parent_context);
889 parent_context.new_layout_allowed = new_layout_allowed;
893 parse_unknown_environment(p, name, os, FLAG_END, outer,
896 active_environments.pop_back();
900 /// parses a comment and outputs it to \p os.
901 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
903 BOOST_ASSERT(t.cat() == catComment);
904 if (!t.cs().empty()) {
905 context.check_layout(os);
906 handle_comment(os, '%' + t.cs(), context);
907 if (p.next_token().cat() == catNewline) {
908 // A newline after a comment line starts a new
910 if (context.new_layout_allowed) {
911 if(!context.atParagraphStart())
912 // Only start a new paragraph if not already
913 // done (we might get called recursively)
914 context.new_paragraph(os);
916 handle_ert(os, "\n", context);
917 eat_whitespace(p, os, context, true);
927 * Reads spaces and comments until the first non-space, non-comment token.
928 * New paragraphs (double newlines or \\par) are handled like simple spaces
929 * if \p eatParagraph is true.
930 * Spaces are skipped, but comments are written to \p os.
932 void eat_whitespace(Parser & p, ostream & os, Context & context,
936 Token const & t = p.get_token();
937 if (t.cat() == catComment)
938 parse_comment(p, os, t, context);
939 else if ((! eatParagraph && p.isParagraph()) ||
940 (t.cat() != catSpace && t.cat() != catNewline)) {
949 * Set a font attribute, parse text and reset the font attribute.
950 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
951 * \param currentvalue Current value of the attribute. Is set to the new
952 * value during parsing.
953 * \param newvalue New value of the attribute
955 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
956 Context & context, string const & attribute,
957 string & currentvalue, string const & newvalue)
959 context.check_layout(os);
960 string const oldvalue = currentvalue;
961 currentvalue = newvalue;
962 os << '\n' << attribute << ' ' << newvalue << "\n";
963 parse_text_snippet(p, os, flags, outer, context);
964 context.check_layout(os);
965 os << '\n' << attribute << ' ' << oldvalue << "\n";
966 currentvalue = oldvalue;
970 /// get the arguments of a natbib or jurabib citation command
971 void get_cite_arguments(Parser & p, bool natbibOrder,
972 string & before, string & after)
974 // We need to distinguish "" and "[]", so we can't use p.getOpt().
976 // text before the citation
978 // text after the citation
979 after = p.getFullOpt();
981 if (!after.empty()) {
982 before = p.getFullOpt();
983 if (natbibOrder && !before.empty())
989 /// Convert filenames with TeX macros and/or quotes to something LyX
991 string const normalize_filename(string const & name)
993 Parser p(trim(name, "\""));
996 Token const & t = p.get_token();
997 if (t.cat() != catEscape)
999 else if (t.cs() == "lyxdot") {
1000 // This is used by LyX for simple dots in relative
1004 } else if (t.cs() == "space") {
1014 /// Convert \p name from TeX convention (relative to master file) to LyX
1015 /// convention (relative to .lyx file) if it is relative
1016 void fix_relative_filename(string & name)
1018 FileName fname(name);
1019 if (fname.isAbsolute())
1022 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1024 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1025 from_utf8(getParentFilePath())));
1029 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1030 void parse_noweb(Parser & p, ostream & os, Context & context)
1032 // assemble the rest of the keyword
1036 Token const & t = p.get_token();
1037 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1040 scrap = (p.good() && p.next_token().asInput() == "=");
1042 name += p.get_token().asInput();
1045 name += t.asInput();
1048 if (!scrap || !context.new_layout_allowed ||
1049 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1050 cerr << "Warning: Could not interpret '" << name
1051 << "'. Ignoring it." << endl;
1055 // We use new_paragraph instead of check_end_layout because the stuff
1056 // following the noweb chunk needs to start with a \begin_layout.
1057 // This may create a new paragraph even if there was none in the
1058 // noweb file, but the alternative is an invalid LyX file. Since
1059 // noweb code chunks are implemented with a layout style in LyX they
1060 // always must be in an own paragraph.
1061 context.new_paragraph(os);
1062 Context newcontext(true, context.textclass,
1063 context.textclass[from_ascii("Scrap")]);
1064 newcontext.check_layout(os);
1067 Token const & t = p.get_token();
1068 // We abuse the parser a bit, because this is no TeX syntax
1070 if (t.cat() == catEscape)
1071 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1073 os << subst(t.asInput(), "\n", "\n\\newline\n");
1074 // The scrap chunk is ended by an @ at the beginning of a line.
1075 // After the @ the line may contain a comment and/or
1076 // whitespace, but nothing else.
1077 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1078 (p.next_token().cat() == catSpace ||
1079 p.next_token().cat() == catNewline ||
1080 p.next_token().cat() == catComment)) {
1081 while (p.good() && p.next_token().cat() == catSpace)
1082 os << p.get_token().asInput();
1083 if (p.next_token().cat() == catComment)
1084 // The comment includes a final '\n'
1085 os << p.get_token().asInput();
1087 if (p.next_token().cat() == catNewline)
1094 newcontext.check_end_layout(os);
1097 } // anonymous namespace
1100 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1103 LayoutPtr newlayout;
1104 // store the current selectlanguage to be used after \foreignlanguage
1106 // Store the latest bibliographystyle (needed for bibtex inset)
1107 string bibliographystyle;
1108 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1109 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1111 Token const & t = p.get_token();
1114 cerr << "t: " << t << " flags: " << flags << "\n";
1117 if (flags & FLAG_ITEM) {
1118 if (t.cat() == catSpace)
1121 flags &= ~FLAG_ITEM;
1122 if (t.cat() == catBegin) {
1123 // skip the brace and collect everything to the next matching
1125 flags |= FLAG_BRACE_LAST;
1129 // handle only this single token, leave the loop if done
1130 flags |= FLAG_LEAVE;
1133 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1139 if (t.cat() == catMath) {
1140 // we are inside some text mode thingy, so opening new math is allowed
1141 context.check_layout(os);
1142 begin_inset(os, "Formula ");
1143 Token const & n = p.get_token();
1144 if (n.cat() == catMath && outer) {
1145 // TeX's $$...$$ syntax for displayed math
1147 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1149 p.get_token(); // skip the second '$' token
1151 // simple $...$ stuff
1154 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1160 else if (t.cat() == catSuper || t.cat() == catSub)
1161 cerr << "catcode " << t << " illegal in text mode\n";
1163 // Basic support for english quotes. This should be
1164 // extended to other quotes, but is not so easy (a
1165 // left english quote is the same as a right german
1167 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1168 context.check_layout(os);
1169 begin_inset(os, "Quotes ");
1175 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1176 context.check_layout(os);
1177 begin_inset(os, "Quotes ");
1184 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1185 context.check_layout(os);
1186 begin_inset(os, "Quotes ");
1193 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1194 context.check_layout(os);
1195 begin_inset(os, "Quotes ");
1202 else if (t.asInput() == "<"
1203 && p.next_token().asInput() == "<" && noweb_mode) {
1205 parse_noweb(p, os, context);
1208 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1209 check_space(p, os, context);
1211 else if (t.character() == '[' && noweb_mode &&
1212 p.next_token().character() == '[') {
1213 // These can contain underscores
1215 string const s = p.getFullOpt() + ']';
1216 if (p.next_token().character() == ']')
1219 cerr << "Warning: Inserting missing ']' in '"
1220 << s << "'." << endl;
1221 handle_ert(os, s, context);
1224 else if (t.cat() == catLetter ||
1225 t.cat() == catOther ||
1226 t.cat() == catAlign ||
1227 t.cat() == catParameter) {
1228 // This translates "&" to "\\&" which may be wrong...
1229 context.check_layout(os);
1230 os << t.character();
1233 else if (p.isParagraph()) {
1234 if (context.new_layout_allowed)
1235 context.new_paragraph(os);
1237 handle_ert(os, "\\par ", context);
1238 eat_whitespace(p, os, context, true);
1241 else if (t.cat() == catActive) {
1242 context.check_layout(os);
1243 if (t.character() == '~') {
1244 if (context.layout->free_spacing)
1247 os << "\\InsetSpace ~\n";
1249 os << t.character();
1252 else if (t.cat() == catBegin &&
1253 p.next_token().cat() == catEnd) {
1255 Token const prev = p.prev_token();
1257 if (p.next_token().character() == '`' ||
1258 (prev.character() == '-' &&
1259 p.next_token().character() == '-'))
1260 ; // ignore it in {}`` or -{}-
1262 handle_ert(os, "{}", context);
1266 else if (t.cat() == catBegin) {
1267 context.check_layout(os);
1268 // special handling of font attribute changes
1269 Token const prev = p.prev_token();
1270 Token const next = p.next_token();
1271 TeXFont const oldFont = context.font;
1272 if (next.character() == '[' ||
1273 next.character() == ']' ||
1274 next.character() == '*') {
1276 if (p.next_token().cat() == catEnd) {
1277 os << next.character();
1281 handle_ert(os, "{", context);
1282 parse_text_snippet(p, os,
1285 handle_ert(os, "}", context);
1287 } else if (! context.new_layout_allowed) {
1288 handle_ert(os, "{", context);
1289 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1291 handle_ert(os, "}", context);
1292 } else if (is_known(next.cs(), known_sizes)) {
1293 // next will change the size, so we must
1295 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1297 if (!context.atParagraphStart())
1299 << context.font.size << "\n";
1300 } else if (is_known(next.cs(), known_font_families)) {
1301 // next will change the font family, so we
1302 // must reset it here
1303 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1305 if (!context.atParagraphStart())
1307 << context.font.family << "\n";
1308 } else if (is_known(next.cs(), known_font_series)) {
1309 // next will change the font series, so we
1310 // must reset it here
1311 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1313 if (!context.atParagraphStart())
1315 << context.font.series << "\n";
1316 } else if (is_known(next.cs(), known_font_shapes)) {
1317 // next will change the font shape, so we
1318 // must reset it here
1319 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1321 if (!context.atParagraphStart())
1323 << context.font.shape << "\n";
1324 } else if (is_known(next.cs(), known_old_font_families) ||
1325 is_known(next.cs(), known_old_font_series) ||
1326 is_known(next.cs(), known_old_font_shapes)) {
1327 // next will change the font family, series
1328 // and shape, so we must reset it here
1329 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1331 if (!context.atParagraphStart())
1333 << context.font.family
1335 << context.font.series
1337 << context.font.shape << "\n";
1339 handle_ert(os, "{", context);
1340 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1342 handle_ert(os, "}", context);
1346 else if (t.cat() == catEnd) {
1347 if (flags & FLAG_BRACE_LAST) {
1350 cerr << "stray '}' in text\n";
1351 handle_ert(os, "}", context);
1354 else if (t.cat() == catComment)
1355 parse_comment(p, os, t, context);
1358 // control sequences
1361 else if (t.cs() == "(") {
1362 context.check_layout(os);
1363 begin_inset(os, "Formula");
1365 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1370 else if (t.cs() == "[") {
1371 context.check_layout(os);
1372 begin_inset(os, "Formula");
1374 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1379 else if (t.cs() == "begin")
1380 parse_environment(p, os, outer, context);
1382 else if (t.cs() == "end") {
1383 if (flags & FLAG_END) {
1384 // eat environment name
1385 string const name = p.getArg('{', '}');
1386 if (name != active_environment())
1387 cerr << "\\end{" + name + "} does not match \\begin{"
1388 + active_environment() + "}\n";
1391 p.error("found 'end' unexpectedly");
1394 else if (t.cs() == "item") {
1397 bool optarg = false;
1398 if (p.next_token().character() == '[') {
1399 p.get_token(); // eat '['
1400 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1405 context.check_layout(os);
1406 if (context.has_item) {
1407 // An item in an unknown list-like environment
1408 // FIXME: Do this in check_layout()!
1409 context.has_item = false;
1411 handle_ert(os, "\\item", context);
1413 handle_ert(os, "\\item ", context);
1416 if (context.layout->labeltype != LABEL_MANUAL) {
1417 // lyx does not support \item[\mybullet]
1418 // in itemize environments
1419 handle_ert(os, "[", context);
1421 handle_ert(os, "]", context);
1422 } else if (!s.empty()) {
1423 // The space is needed to separate the
1424 // item from the rest of the sentence.
1426 eat_whitespace(p, os, context, false);
1431 else if (t.cs() == "bibitem") {
1433 context.check_layout(os);
1436 os << '{' << p.verbatim_item() << '}' << "\n";
1439 else if (t.cs() == "def") {
1440 context.check_layout(os);
1441 eat_whitespace(p, os, context, false);
1442 string name = p.get_token().cs();
1443 eat_whitespace(p, os, context, false);
1449 while (p.next_token().cat() != catBegin) {
1450 if (p.next_token().cat() == catParameter) {
1455 // followed by number?
1456 if (p.next_token().cat() == catOther) {
1457 char c = p.getChar();
1459 // number = current arity + 1?
1460 if (c == arity + '0' + 1)
1465 paramtext += p.get_token().asString();
1467 paramtext += p.get_token().asString();
1472 // only output simple (i.e. compatible) macro as FormulaMacros
1473 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1475 context.check_layout(os);
1476 begin_inset(os, "FormulaMacro");
1480 handle_ert(os, ert, context);
1483 else if (t.cs() == "noindent") {
1485 context.add_extra_stuff("\\noindent\n");
1488 else if (t.cs() == "appendix") {
1489 context.add_extra_stuff("\\start_of_appendix\n");
1490 // We need to start a new paragraph. Otherwise the
1491 // appendix in 'bla\appendix\chapter{' would start
1493 context.new_paragraph(os);
1494 // We need to make sure that the paragraph is
1495 // generated even if it is empty. Otherwise the
1496 // appendix in '\par\appendix\par\chapter{' would
1498 context.check_layout(os);
1499 // FIXME: This is a hack to prevent paragraph
1500 // deletion if it is empty. Handle this better!
1502 "%dummy comment inserted by tex2lyx to "
1503 "ensure that this paragraph is not empty",
1505 // Both measures above may generate an additional
1506 // empty paragraph, but that does not hurt, because
1507 // whitespace does not matter here.
1508 eat_whitespace(p, os, context, true);
1511 // Must attempt to parse "Section*" before "Section".
1512 else if ((p.next_token().asInput() == "*") &&
1513 context.new_layout_allowed &&
1514 // The single '=' is meant here.
1515 (newlayout = findLayout(context.textclass,
1516 t.cs() + '*')).get() &&
1517 newlayout->isCommand()) {
1519 output_command_layout(os, p, outer, context, newlayout);
1523 // The single '=' is meant here.
1524 else if (context.new_layout_allowed &&
1525 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1526 newlayout->isCommand()) {
1527 output_command_layout(os, p, outer, context, newlayout);
1531 // Special handling for \caption
1532 // FIXME: remove this when InsetCaption is supported.
1533 else if (context.new_layout_allowed &&
1534 t.cs() == captionlayout->latexname()) {
1535 output_command_layout(os, p, outer, context,
1540 else if (t.cs() == "includegraphics") {
1541 bool const clip = p.next_token().asInput() == "*";
1544 map<string, string> opts = split_map(p.getArg('[', ']'));
1546 opts["clip"] = string();
1547 string name = normalize_filename(p.verbatim_item());
1549 string const path = getMasterFilePath();
1550 // We want to preserve relative / absolute filenames,
1551 // therefore path is only used for testing
1552 // FIXME UNICODE encoding of name and path may be
1553 // wrong (makeAbsPath expects utf8)
1554 if (!makeAbsPath(name, path).exists()) {
1555 // The file extension is probably missing.
1556 // Now try to find it out.
1557 string const dvips_name =
1558 find_file(name, path,
1559 known_dvips_graphics_formats);
1560 string const pdftex_name =
1561 find_file(name, path,
1562 known_pdftex_graphics_formats);
1563 if (!dvips_name.empty()) {
1564 if (!pdftex_name.empty()) {
1565 cerr << "This file contains the "
1567 "\"\\includegraphics{"
1569 "However, files\n\""
1570 << dvips_name << "\" and\n\""
1571 << pdftex_name << "\"\n"
1572 "both exist, so I had to make a "
1573 "choice and took the first one.\n"
1574 "Please move the unwanted one "
1575 "someplace else and try again\n"
1576 "if my choice was wrong."
1580 } else if (!pdftex_name.empty())
1584 // FIXME UNICODE encoding of name and path may be
1585 // wrong (makeAbsPath expects utf8)
1586 if (makeAbsPath(name, path).exists())
1587 fix_relative_filename(name);
1589 cerr << "Warning: Could not find graphics file '"
1590 << name << "'." << endl;
1592 context.check_layout(os);
1593 begin_inset(os, "Graphics ");
1594 os << "\n\tfilename " << name << '\n';
1595 if (opts.find("width") != opts.end())
1597 << translate_len(opts["width"]) << '\n';
1598 if (opts.find("height") != opts.end())
1600 << translate_len(opts["height"]) << '\n';
1601 if (opts.find("scale") != opts.end()) {
1602 istringstream iss(opts["scale"]);
1606 os << "\tscale " << val << '\n';
1608 if (opts.find("angle") != opts.end())
1609 os << "\trotateAngle "
1610 << opts["angle"] << '\n';
1611 if (opts.find("origin") != opts.end()) {
1613 string const opt = opts["origin"];
1614 if (opt.find('l') != string::npos) ss << "left";
1615 if (opt.find('r') != string::npos) ss << "right";
1616 if (opt.find('c') != string::npos) ss << "center";
1617 if (opt.find('t') != string::npos) ss << "Top";
1618 if (opt.find('b') != string::npos) ss << "Bottom";
1619 if (opt.find('B') != string::npos) ss << "Baseline";
1620 if (!ss.str().empty())
1621 os << "\trotateOrigin " << ss.str() << '\n';
1623 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1625 if (opts.find("keepaspectratio") != opts.end())
1626 os << "\tkeepAspectRatio\n";
1627 if (opts.find("clip") != opts.end())
1629 if (opts.find("draft") != opts.end())
1631 if (opts.find("bb") != opts.end())
1632 os << "\tBoundingBox "
1633 << opts["bb"] << '\n';
1634 int numberOfbbOptions = 0;
1635 if (opts.find("bbllx") != opts.end())
1636 numberOfbbOptions++;
1637 if (opts.find("bblly") != opts.end())
1638 numberOfbbOptions++;
1639 if (opts.find("bburx") != opts.end())
1640 numberOfbbOptions++;
1641 if (opts.find("bbury") != opts.end())
1642 numberOfbbOptions++;
1643 if (numberOfbbOptions == 4)
1644 os << "\tBoundingBox "
1645 << opts["bbllx"] << " " << opts["bblly"] << " "
1646 << opts["bburx"] << " " << opts["bbury"] << '\n';
1647 else if (numberOfbbOptions > 0)
1648 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1649 numberOfbbOptions = 0;
1650 if (opts.find("natwidth") != opts.end())
1651 numberOfbbOptions++;
1652 if (opts.find("natheight") != opts.end())
1653 numberOfbbOptions++;
1654 if (numberOfbbOptions == 2)
1655 os << "\tBoundingBox 0bp 0bp "
1656 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1657 else if (numberOfbbOptions > 0)
1658 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1659 ostringstream special;
1660 if (opts.find("hiresbb") != opts.end())
1661 special << "hiresbb,";
1662 if (opts.find("trim") != opts.end())
1664 if (opts.find("viewport") != opts.end())
1665 special << "viewport=" << opts["viewport"] << ',';
1666 if (opts.find("totalheight") != opts.end())
1667 special << "totalheight=" << opts["totalheight"] << ',';
1668 if (opts.find("type") != opts.end())
1669 special << "type=" << opts["type"] << ',';
1670 if (opts.find("ext") != opts.end())
1671 special << "ext=" << opts["ext"] << ',';
1672 if (opts.find("read") != opts.end())
1673 special << "read=" << opts["read"] << ',';
1674 if (opts.find("command") != opts.end())
1675 special << "command=" << opts["command"] << ',';
1676 string s_special = special.str();
1677 if (!s_special.empty()) {
1678 // We had special arguments. Remove the trailing ','.
1679 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1681 // TODO: Handle the unknown settings better.
1682 // Warn about invalid options.
1683 // Check whether some option was given twice.
1687 else if (t.cs() == "footnote" ||
1688 (t.cs() == "thanks" && context.layout->intitle)) {
1690 context.check_layout(os);
1691 begin_inset(os, "Foot\n");
1692 os << "status collapsed\n\n";
1693 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1697 else if (t.cs() == "marginpar") {
1699 context.check_layout(os);
1700 begin_inset(os, "Marginal\n");
1701 os << "status collapsed\n\n";
1702 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1706 else if (t.cs() == "ensuremath") {
1708 context.check_layout(os);
1709 string const s = p.verbatim_item();
1710 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1713 handle_ert(os, "\\ensuremath{" + s + "}",
1717 else if (t.cs() == "hfill") {
1718 context.check_layout(os);
1719 os << "\n\\hfill\n";
1724 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1725 // FIXME: Somehow prevent title layouts if
1726 // "maketitle" was not found
1728 skip_braces(p); // swallow this
1731 else if (t.cs() == "tableofcontents") {
1733 context.check_layout(os);
1734 begin_inset(os, "LatexCommand \\tableofcontents\n");
1736 skip_braces(p); // swallow this
1739 else if (t.cs() == "listoffigures") {
1741 context.check_layout(os);
1742 begin_inset(os, "FloatList figure\n");
1744 skip_braces(p); // swallow this
1747 else if (t.cs() == "listoftables") {
1749 context.check_layout(os);
1750 begin_inset(os, "FloatList table\n");
1752 skip_braces(p); // swallow this
1755 else if (t.cs() == "listof") {
1756 p.skip_spaces(true);
1757 string const name = p.get_token().asString();
1758 if (context.textclass.floats().typeExist(name)) {
1759 context.check_layout(os);
1760 begin_inset(os, "FloatList ");
1763 p.get_token(); // swallow second arg
1765 handle_ert(os, "\\listof{" + name + "}", context);
1768 else if (t.cs() == "textrm")
1769 parse_text_attributes(p, os, FLAG_ITEM, outer,
1770 context, "\\family",
1771 context.font.family, "roman");
1773 else if (t.cs() == "textsf")
1774 parse_text_attributes(p, os, FLAG_ITEM, outer,
1775 context, "\\family",
1776 context.font.family, "sans");
1778 else if (t.cs() == "texttt")
1779 parse_text_attributes(p, os, FLAG_ITEM, outer,
1780 context, "\\family",
1781 context.font.family, "typewriter");
1783 else if (t.cs() == "textmd")
1784 parse_text_attributes(p, os, FLAG_ITEM, outer,
1785 context, "\\series",
1786 context.font.series, "medium");
1788 else if (t.cs() == "textbf")
1789 parse_text_attributes(p, os, FLAG_ITEM, outer,
1790 context, "\\series",
1791 context.font.series, "bold");
1793 else if (t.cs() == "textup")
1794 parse_text_attributes(p, os, FLAG_ITEM, outer,
1796 context.font.shape, "up");
1798 else if (t.cs() == "textit")
1799 parse_text_attributes(p, os, FLAG_ITEM, outer,
1801 context.font.shape, "italic");
1803 else if (t.cs() == "textsl")
1804 parse_text_attributes(p, os, FLAG_ITEM, outer,
1806 context.font.shape, "slanted");
1808 else if (t.cs() == "textsc")
1809 parse_text_attributes(p, os, FLAG_ITEM, outer,
1811 context.font.shape, "smallcaps");
1813 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1814 context.check_layout(os);
1815 TeXFont oldFont = context.font;
1816 context.font.init();
1817 context.font.size = oldFont.size;
1818 os << "\n\\family " << context.font.family << "\n";
1819 os << "\n\\series " << context.font.series << "\n";
1820 os << "\n\\shape " << context.font.shape << "\n";
1821 if (t.cs() == "textnormal") {
1822 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1823 output_font_change(os, context.font, oldFont);
1824 context.font = oldFont;
1826 eat_whitespace(p, os, context, false);
1829 else if (t.cs() == "underbar") {
1830 // Do NOT handle \underline.
1831 // \underbar cuts through y, g, q, p etc.,
1832 // \underline does not.
1833 context.check_layout(os);
1834 os << "\n\\bar under\n";
1835 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1836 context.check_layout(os);
1837 os << "\n\\bar default\n";
1840 else if (t.cs() == "emph" || t.cs() == "noun") {
1841 context.check_layout(os);
1842 os << "\n\\" << t.cs() << " on\n";
1843 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1844 context.check_layout(os);
1845 os << "\n\\" << t.cs() << " default\n";
1848 else if (use_natbib &&
1849 is_known(t.cs(), known_natbib_commands) &&
1850 ((t.cs() != "citefullauthor" &&
1851 t.cs() != "citeyear" &&
1852 t.cs() != "citeyearpar") ||
1853 p.next_token().asInput() != "*")) {
1854 context.check_layout(os);
1856 // \citet[before][after]{a} \citet[after][before]{a}
1857 // \citet[before][]{a} \citet[][before]{a}
1858 // \citet[after]{a} \citet[after]{a}
1859 // \citet{a} \citet{a}
1860 string command = '\\' + t.cs();
1861 if (p.next_token().asInput() == "*") {
1865 if (command == "\\citefullauthor")
1866 // alternative name for "\\citeauthor*"
1867 command = "\\citeauthor*";
1869 // text before the citation
1871 // text after the citation
1873 get_cite_arguments(p, true, before, after);
1875 if (command == "\\cite") {
1876 // \cite without optional argument means
1877 // \citet, \cite with at least one optional
1878 // argument means \citep.
1879 if (before.empty() && after.empty())
1880 command = "\\citet";
1882 command = "\\citep";
1884 if (before.empty() && after == "[]")
1885 // avoid \citet[]{a}
1887 else if (before == "[]" && after == "[]") {
1888 // avoid \citet[][]{a}
1892 begin_inset(os, "LatexCommand ");
1893 os << command << after << before
1894 << '{' << p.verbatim_item() << "}\n";
1898 else if (use_jurabib &&
1899 is_known(t.cs(), known_jurabib_commands)) {
1900 context.check_layout(os);
1901 string const command = '\\' + t.cs();
1902 char argumentOrder = '\0';
1903 vector<string> const & options = used_packages["jurabib"];
1904 if (find(options.begin(), options.end(),
1905 "natbiborder") != options.end())
1906 argumentOrder = 'n';
1907 else if (find(options.begin(), options.end(),
1908 "jurabiborder") != options.end())
1909 argumentOrder = 'j';
1911 // text before the citation
1913 // text after the citation
1915 get_cite_arguments(p, argumentOrder != 'j', before, after);
1917 string const citation = p.verbatim_item();
1918 if (!before.empty() && argumentOrder == '\0') {
1919 cerr << "Warning: Assuming argument order "
1920 "of jurabib version 0.6 for\n'"
1921 << command << before << after << '{'
1922 << citation << "}'.\n"
1923 "Add 'jurabiborder' to the jurabib "
1924 "package options if you used an\n"
1925 "earlier jurabib version." << endl;
1927 begin_inset(os, "LatexCommand ");
1928 os << command << after << before
1929 << '{' << citation << "}\n";
1933 else if (is_known(t.cs(), known_latex_commands)) {
1934 // This needs to be after the check for natbib and
1935 // jurabib commands, because "cite" has different
1936 // arguments with natbib and jurabib.
1937 context.check_layout(os);
1938 begin_inset(os, "LatexCommand ");
1939 os << '\\' << t.cs();
1940 // lyx cannot handle newlines in a latex command
1941 // FIXME: Move the substitution into parser::getOpt()?
1942 os << subst(p.getOpt(), "\n", " ");
1943 os << subst(p.getOpt(), "\n", " ");
1944 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1948 else if (is_known(t.cs(), known_quotes)) {
1949 char const * const * where = is_known(t.cs(), known_quotes);
1950 context.check_layout(os);
1951 begin_inset(os, "Quotes ");
1952 os << known_coded_quotes[where - known_quotes];
1954 // LyX adds {} after the quote, so we have to eat
1955 // spaces here if there are any before a possible
1957 eat_whitespace(p, os, context, false);
1961 else if (is_known(t.cs(), known_sizes) &&
1962 context.new_layout_allowed) {
1963 char const * const * where = is_known(t.cs(), known_sizes);
1964 context.check_layout(os);
1965 TeXFont const oldFont = context.font;
1966 context.font.size = known_coded_sizes[where - known_sizes];
1967 output_font_change(os, oldFont, context.font);
1968 eat_whitespace(p, os, context, false);
1971 else if (is_known(t.cs(), known_font_families) &&
1972 context.new_layout_allowed) {
1973 char const * const * where =
1974 is_known(t.cs(), known_font_families);
1975 context.check_layout(os);
1976 TeXFont const oldFont = context.font;
1977 context.font.family =
1978 known_coded_font_families[where - known_font_families];
1979 output_font_change(os, oldFont, context.font);
1980 eat_whitespace(p, os, context, false);
1983 else if (is_known(t.cs(), known_font_series) &&
1984 context.new_layout_allowed) {
1985 char const * const * where =
1986 is_known(t.cs(), known_font_series);
1987 context.check_layout(os);
1988 TeXFont const oldFont = context.font;
1989 context.font.series =
1990 known_coded_font_series[where - known_font_series];
1991 output_font_change(os, oldFont, context.font);
1992 eat_whitespace(p, os, context, false);
1995 else if (is_known(t.cs(), known_font_shapes) &&
1996 context.new_layout_allowed) {
1997 char const * const * where =
1998 is_known(t.cs(), known_font_shapes);
1999 context.check_layout(os);
2000 TeXFont const oldFont = context.font;
2001 context.font.shape =
2002 known_coded_font_shapes[where - known_font_shapes];
2003 output_font_change(os, oldFont, context.font);
2004 eat_whitespace(p, os, context, false);
2006 else if (is_known(t.cs(), known_old_font_families) &&
2007 context.new_layout_allowed) {
2008 char const * const * where =
2009 is_known(t.cs(), known_old_font_families);
2010 context.check_layout(os);
2011 TeXFont const oldFont = context.font;
2012 context.font.init();
2013 context.font.size = oldFont.size;
2014 context.font.family =
2015 known_coded_font_families[where - known_old_font_families];
2016 output_font_change(os, oldFont, context.font);
2017 eat_whitespace(p, os, context, false);
2020 else if (is_known(t.cs(), known_old_font_series) &&
2021 context.new_layout_allowed) {
2022 char const * const * where =
2023 is_known(t.cs(), known_old_font_series);
2024 context.check_layout(os);
2025 TeXFont const oldFont = context.font;
2026 context.font.init();
2027 context.font.size = oldFont.size;
2028 context.font.series =
2029 known_coded_font_series[where - known_old_font_series];
2030 output_font_change(os, oldFont, context.font);
2031 eat_whitespace(p, os, context, false);
2034 else if (is_known(t.cs(), known_old_font_shapes) &&
2035 context.new_layout_allowed) {
2036 char const * const * where =
2037 is_known(t.cs(), known_old_font_shapes);
2038 context.check_layout(os);
2039 TeXFont const oldFont = context.font;
2040 context.font.init();
2041 context.font.size = oldFont.size;
2042 context.font.shape =
2043 known_coded_font_shapes[where - known_old_font_shapes];
2044 output_font_change(os, oldFont, context.font);
2045 eat_whitespace(p, os, context, false);
2048 else if (t.cs() == "selectlanguage") {
2049 context.check_layout(os);
2050 // save the language for the case that a \foreignlanguage is used
2051 selectlang = subst(p.verbatim_item(), "\n", " ");
2052 os << "\\lang " << selectlang << "\n";
2056 else if (t.cs() == "foreignlanguage") {
2057 context.check_layout(os);
2058 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2059 os << subst(p.verbatim_item(), "\n", " ");
2060 // set back to last selectlanguage
2061 os << "\n\\lang " << selectlang << "\n";
2064 else if (t.cs() == "inputencoding")
2065 // write nothing because this is done by LyX using the "\lang"
2066 // information given by selectlanguage and foreignlanguage
2067 subst(p.verbatim_item(), "\n", " ");
2069 else if (t.cs() == "LyX" || t.cs() == "TeX"
2070 || t.cs() == "LaTeX") {
2071 context.check_layout(os);
2073 skip_braces(p); // eat {}
2076 else if (t.cs() == "LaTeXe") {
2077 context.check_layout(os);
2079 skip_braces(p); // eat {}
2082 else if (t.cs() == "ldots") {
2083 context.check_layout(os);
2085 os << "\\SpecialChar \\ldots{}\n";
2088 else if (t.cs() == "lyxarrow") {
2089 context.check_layout(os);
2090 os << "\\SpecialChar \\menuseparator\n";
2094 else if (t.cs() == "textcompwordmark") {
2095 context.check_layout(os);
2096 os << "\\SpecialChar \\textcompwordmark{}\n";
2100 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2101 context.check_layout(os);
2102 os << "\\SpecialChar \\@.\n";
2106 else if (t.cs() == "-") {
2107 context.check_layout(os);
2108 os << "\\SpecialChar \\-\n";
2111 else if (t.cs() == "textasciitilde") {
2112 context.check_layout(os);
2117 else if (t.cs() == "textasciicircum") {
2118 context.check_layout(os);
2123 else if (t.cs() == "textbackslash") {
2124 context.check_layout(os);
2125 os << "\n\\backslash\n";
2129 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2130 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2132 context.check_layout(os);
2136 else if (t.cs() == "char") {
2137 context.check_layout(os);
2138 if (p.next_token().character() == '`') {
2140 if (p.next_token().cs() == "\"") {
2145 handle_ert(os, "\\char`", context);
2148 handle_ert(os, "\\char", context);
2152 else if (t.cs() == "verb") {
2153 context.check_layout(os);
2154 char const delimiter = p.next_token().character();
2155 string const arg = p.getArg(delimiter, delimiter);
2157 oss << "\\verb" << delimiter << arg << delimiter;
2158 handle_ert(os, oss.str(), context);
2161 else if (t.cs() == "\"") {
2162 context.check_layout(os);
2163 string const name = p.verbatim_item();
2164 if (name == "a") os << '\xe4';
2165 else if (name == "o") os << '\xf6';
2166 else if (name == "u") os << '\xfc';
2167 else if (name == "A") os << '\xc4';
2168 else if (name == "O") os << '\xd6';
2169 else if (name == "U") os << '\xdc';
2170 else handle_ert(os, "\"{" + name + "}", context);
2173 // Problem: \= creates a tabstop inside the tabbing environment
2174 // and else an accent. In the latter case we really would want
2175 // \={o} instead of \= o.
2176 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2177 handle_ert(os, t.asInput(), context);
2179 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2180 || t.cs() == "'" || t.cs() == "`"
2181 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2182 // we need the trim as the LyX parser chokes on such spaces
2183 // The argument of InsetLatexAccent is parsed as a
2184 // subset of LaTeX, so don't parse anything here,
2185 // but use the raw argument.
2186 // Otherwise we would convert \~{\i} wrongly.
2187 // This will of course not translate \~{\ss} to \~{ß},
2188 // but that does at least compile and does only look
2189 // strange on screen.
2190 context.check_layout(os);
2191 os << "\\i \\" << t.cs() << "{"
2192 << trim(p.verbatim_item(), " ")
2196 else if (t.cs() == "ss") {
2197 context.check_layout(os);
2199 skip_braces(p); // eat {}
2202 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2204 context.check_layout(os);
2205 os << "\\i \\" << t.cs() << "{}\n";
2206 skip_braces(p); // eat {}
2209 else if (t.cs() == "\\") {
2210 context.check_layout(os);
2211 string const next = p.next_token().asInput();
2213 handle_ert(os, "\\\\" + p.getOpt(), context);
2214 else if (next == "*") {
2216 handle_ert(os, "\\\\*" + p.getOpt(), context);
2219 os << "\n\\newline\n";
2223 else if (t.cs() == "newline" ||
2224 t.cs() == "linebreak") {
2225 context.check_layout(os);
2226 os << "\n\\" << t.cs() << "\n";
2227 skip_braces(p); // eat {}
2230 else if (t.cs() == "href") {
2231 context.check_layout(os);
2232 begin_inset(os, "CommandInset ");
2233 os << t.cs() << "\n";
2234 os << "LatexCommand " << t.cs() << "\n";
2237 // the first argument is "type:target", "type:" is optional
2238 // the second argument the name
2239 string href_target = subst(p.verbatim_item(), "\n", " ");
2240 string href_name = subst(p.verbatim_item(), "\n", " ");
2242 // serach for the ":" to divide type from target
2243 if ((pos = href_target.find(":", 0)) != string::npos){
2244 href_type = href_target;
2245 href_type.erase(pos + 1, href_type.length());
2246 href_target.erase(0, pos + 1);
2249 os << "name " << '"' << href_name << '"' << "\n";
2250 os << "target " << '"' << href_target << '"' << "\n";
2252 os << "type " << '"' << href_type << '"' << "\n";
2256 else if (t.cs() == "input" || t.cs() == "include"
2257 || t.cs() == "verbatiminput") {
2258 string name = '\\' + t.cs();
2259 if (t.cs() == "verbatiminput"
2260 && p.next_token().asInput() == "*")
2261 name += p.get_token().asInput();
2262 context.check_layout(os);
2263 begin_inset(os, "Include ");
2264 string filename(normalize_filename(p.getArg('{', '}')));
2265 string const path = getMasterFilePath();
2266 // We want to preserve relative / absolute filenames,
2267 // therefore path is only used for testing
2268 // FIXME UNICODE encoding of filename and path may be
2269 // wrong (makeAbsPath expects utf8)
2270 if ((t.cs() == "include" || t.cs() == "input") &&
2271 !makeAbsPath(filename, path).exists()) {
2272 // The file extension is probably missing.
2273 // Now try to find it out.
2274 string const tex_name =
2275 find_file(filename, path,
2276 known_tex_extensions);
2277 if (!tex_name.empty())
2278 filename = tex_name;
2280 // FIXME UNICODE encoding of filename and path may be
2281 // wrong (makeAbsPath expects utf8)
2282 if (makeAbsPath(filename, path).exists()) {
2283 string const abstexname =
2284 makeAbsPath(filename, path).absFilename();
2285 string const abslyxname =
2286 changeExtension(abstexname, ".lyx");
2287 fix_relative_filename(filename);
2288 string const lyxname =
2289 changeExtension(filename, ".lyx");
2290 if (t.cs() != "verbatiminput" &&
2291 tex2lyx(abstexname, FileName(abslyxname))) {
2292 os << name << '{' << lyxname << "}\n";
2294 os << name << '{' << filename << "}\n";
2297 cerr << "Warning: Could not find included file '"
2298 << filename << "'." << endl;
2299 os << name << '{' << filename << "}\n";
2301 os << "preview false\n";
2305 else if (t.cs() == "bibliographystyle") {
2306 // store new bibliographystyle
2307 bibliographystyle = p.verbatim_item();
2308 // output new bibliographystyle.
2309 // This is only necessary if used in some other macro than \bibliography.
2310 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2313 else if (t.cs() == "bibliography") {
2314 context.check_layout(os);
2315 begin_inset(os, "LatexCommand ");
2317 // Do we have a bibliographystyle set?
2318 if (!bibliographystyle.empty()) {
2319 os << '[' << bibliographystyle << ']';
2321 os << '{' << p.verbatim_item() << "}\n";
2325 else if (t.cs() == "parbox")
2326 parse_box(p, os, FLAG_ITEM, outer, context, true);
2328 else if (t.cs() == "smallskip" ||
2329 t.cs() == "medskip" ||
2330 t.cs() == "bigskip" ||
2331 t.cs() == "vfill") {
2332 context.check_layout(os);
2333 begin_inset(os, "VSpace ");
2339 else if (is_known(t.cs(), known_spaces)) {
2340 char const * const * where = is_known(t.cs(), known_spaces);
2341 context.check_layout(os);
2342 begin_inset(os, "InsetSpace ");
2343 os << '\\' << known_coded_spaces[where - known_spaces]
2345 // LaTeX swallows whitespace after all spaces except
2346 // "\\,". We have to do that here, too, because LyX
2347 // adds "{}" which would make the spaces significant.
2349 eat_whitespace(p, os, context, false);
2350 // LyX adds "{}" after all spaces except "\\ " and
2351 // "\\,", so we have to remove "{}".
2352 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2353 // remove the braces after "\\,", too.
2358 else if (t.cs() == "newpage" ||
2359 t.cs() == "pagebreak" ||
2360 t.cs() == "clearpage" ||
2361 t.cs() == "cleardoublepage") {
2362 context.check_layout(os);
2363 os << "\n\\" << t.cs() << "\n";
2364 skip_braces(p); // eat {}
2367 else if (t.cs() == "newcommand" ||
2368 t.cs() == "providecommand" ||
2369 t.cs() == "renewcommand" ||
2370 t.cs() == "newlyxcommand") {
2371 // these could be handled by parse_command(), but
2372 // we need to call add_known_command() here.
2373 string name = t.asInput();
2374 if (p.next_token().asInput() == "*") {
2375 // Starred form. Eat '*'
2379 string const command = p.verbatim_item();
2380 string const opt1 = p.getOpt();
2382 unsigned optionalsNum = 0;
2384 string const opt = p.getFullOpt();
2390 add_known_command(command, opt1, optionalsNum);
2391 string const ert = name + '{' + command + '}' + opt1
2392 + optionals + '{' + p.verbatim_item() + '}';
2394 context.check_layout(os);
2395 begin_inset(os, "FormulaMacro");
2400 else if (t.cs() == "vspace") {
2401 bool starred = false;
2402 if (p.next_token().asInput() == "*") {
2406 string const length = p.verbatim_item();
2409 bool valid = splitLatexLength(length, valstring, unit);
2410 bool known_vspace = false;
2411 bool known_unit = false;
2414 istringstream iss(valstring);
2417 if (unit == "\\smallskipamount") {
2419 known_vspace = true;
2420 } else if (unit == "\\medskipamount") {
2422 known_vspace = true;
2423 } else if (unit == "\\bigskipamount") {
2425 known_vspace = true;
2426 } else if (unit == "\\fill") {
2428 known_vspace = true;
2431 if (!known_vspace) {
2432 switch (unitFromString(unit)) {
2453 if (known_unit || known_vspace) {
2454 // Literal length or known variable
2455 context.check_layout(os);
2456 begin_inset(os, "VSpace ");
2464 // LyX can't handle other length variables in Inset VSpace
2465 string name = t.asInput();
2470 handle_ert(os, name + '{' + unit + '}', context);
2471 else if (value == -1.0)
2472 handle_ert(os, name + "{-" + unit + '}', context);
2474 handle_ert(os, name + '{' + valstring + unit + '}', context);
2476 handle_ert(os, name + '{' + length + '}', context);
2481 //cerr << "#: " << t << " mode: " << mode << endl;
2482 // heuristic: read up to next non-nested space
2484 string s = t.asInput();
2485 string z = p.verbatim_item();
2486 while (p.good() && z != " " && z.size()) {
2487 //cerr << "read: " << z << endl;
2489 z = p.verbatim_item();
2491 cerr << "found ERT: " << s << endl;
2492 handle_ert(os, s + ' ', context);
2494 string name = t.asInput();
2495 if (p.next_token().asInput() == "*") {
2496 // Starred commands like \vspace*{}
2497 p.get_token(); // Eat '*'
2500 if (! parse_command(name, p, os, outer, context))
2501 handle_ert(os, name, context);
2504 if (flags & FLAG_LEAVE) {
2505 flags &= ~FLAG_LEAVE;