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"
29 #include <boost/assert.hpp>
37 using namespace lyx::support;
42 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
43 Context const & context)
45 Context newcontext(true, context.textclass);
46 newcontext.font = context.font;
47 parse_text(p, os, flags, outer, newcontext);
48 newcontext.check_end_layout(os);
54 /// parses a paragraph snippet, useful for example for \\emph{...}
55 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
58 Context newcontext(context);
59 // Don't inherit the extra stuff
60 newcontext.extra_stuff.clear();
61 parse_text(p, os, flags, outer, newcontext);
62 // Make sure that we don't create invalid .lyx files
63 context.need_layout = newcontext.need_layout;
64 context.need_end_layout = newcontext.need_end_layout;
69 * Thin wrapper around parse_text_snippet() using a string.
71 * We completely ignore \c context.need_layout and \c context.need_end_layout,
72 * because our return value is not used directly (otherwise the stream version
73 * of parse_text_snippet() could be used). That means that the caller needs
74 * to do layout management manually.
75 * This is intended to parse text that does not create any layout changes.
77 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
80 Context newcontext(context);
81 newcontext.need_layout = false;
82 newcontext.need_end_layout = false;
83 newcontext.new_layout_allowed = false;
84 // Avoid warning by Context::~Context()
85 newcontext.extra_stuff.clear();
87 parse_text_snippet(p, os, flags, outer, newcontext);
92 char const * const known_latex_commands[] = { "ref", "cite", "nocite", "label",
93 "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
98 * We can't put these into known_latex_commands because the argument order
99 * is reversed in lyx if there are 2 arguments.
100 * The starred forms are also known.
102 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
103 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
104 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
108 * We can't put these into known_latex_commands because the argument order
109 * is reversed in lyx if there are 2 arguments.
110 * No starred form other than "cite*" known.
112 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
113 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
114 // jurabib commands not (yet) supported by LyX:
116 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
117 // "footciteauthor", "footciteyear", "footciteyearpar",
118 "citefield", "citetitle", "cite*", 0 };
120 /// LaTeX names for quotes
121 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
122 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
123 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
124 "guilsinglleft", "frq", "guilsinglright", 0};
126 /// the same as known_quotes with .lyx names
127 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
128 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
129 "gld", "grd", "gls", "ers", "fls",
130 "fls", "frs", "frs", 0};
132 /// LaTeX names for font sizes
133 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
134 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
136 /// the same as known_sizes with .lyx names
137 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
138 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
140 /// LaTeX 2.09 names for font families
141 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
143 /// LaTeX names for font families
144 char const * const known_font_families[] = { "rmfamily", "sffamily",
147 /// the same as known_old_font_families and known_font_families with .lyx names
148 char const * const known_coded_font_families[] = { "roman", "sans",
151 /// LaTeX 2.09 names for font series
152 char const * const known_old_font_series[] = { "bf", 0};
154 /// LaTeX names for font series
155 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
157 /// the same as known_old_font_series and known_font_series with .lyx names
158 char const * const known_coded_font_series[] = { "bold", "medium", 0};
160 /// LaTeX 2.09 names for font shapes
161 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
163 /// LaTeX names for font shapes
164 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
167 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
168 char const * const known_coded_font_shapes[] = { "italic", "slanted",
169 "smallcaps", "up", 0};
172 * Graphics file extensions known by the dvips driver of the graphics package.
173 * These extensions are used to complete the filename of an included
174 * graphics file if it does not contain an extension.
175 * The order must be the same that latex uses to find a file, because we
176 * will use the first extension that matches.
177 * This is only an approximation for the common cases. If we would want to
178 * do it right in all cases, we would need to know which graphics driver is
179 * used and know the extensions of every driver of the graphics package.
181 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
182 "ps.gz", "eps.Z", "ps.Z", 0};
185 * Graphics file extensions known by the pdftex driver of the graphics package.
186 * \sa known_dvips_graphics_formats
188 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
192 * Known file extensions for TeX files as used by \\include.
194 char const * const known_tex_extensions[] = {"tex", 0};
196 /// spaces known by InsetSpace
197 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
198 "qquad", "enspace", "enskip", "negthinspace", 0};
200 /// the same as known_spaces with .lyx names
201 char const * const known_coded_spaces[] = { "space{}", "space{}",
202 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
203 "negthinspace{}", 0};
206 /// splits "x=z, y=b" into a map
207 map<string, string> split_map(string const & s)
209 map<string, string> res;
212 for (size_t i = 0; i < v.size(); ++i) {
213 size_t const pos = v[i].find('=');
214 string const index = v[i].substr(0, pos);
215 string const value = v[i].substr(pos + 1, string::npos);
216 res[trim(index)] = trim(value);
223 * Split a LaTeX length into value and unit.
224 * The latter can be a real unit like "pt", or a latex length variable
225 * like "\textwidth". The unit may contain additional stuff like glue
226 * lengths, but we don't care, because such lengths are ERT anyway.
227 * \returns true if \p value and \p unit are valid.
229 bool splitLatexLength(string const & len, string & value, string & unit)
233 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
234 //'4,5' is a valid LaTeX length number. Change it to '4.5'
235 string const length = subst(len, ',', '.');
236 if (i == string::npos)
239 if (len[0] == '\\') {
240 // We had something like \textwidth without a factor
246 value = trim(string(length, 0, i));
250 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
251 if (contains(len, '\\'))
252 unit = trim(string(len, i));
254 unit = ascii_lowercase(trim(string(len, i)));
259 /// A simple function to translate a latex length to something lyx can
260 /// understand. Not perfect, but rather best-effort.
261 bool translate_len(string const & length, string & valstring, string & unit)
263 if (!splitLatexLength(length, valstring, unit))
265 // LyX uses percent values
267 istringstream iss(valstring);
272 string const percentval = oss.str();
274 if (unit.empty() || unit[0] != '\\')
276 string::size_type const i = unit.find(' ');
277 string const endlen = (i == string::npos) ? string() : string(unit, i);
278 if (unit == "\\textwidth") {
279 valstring = percentval;
280 unit = "text%" + endlen;
281 } else if (unit == "\\columnwidth") {
282 valstring = percentval;
283 unit = "col%" + endlen;
284 } else if (unit == "\\paperwidth") {
285 valstring = percentval;
286 unit = "page%" + endlen;
287 } else if (unit == "\\linewidth") {
288 valstring = percentval;
289 unit = "line%" + endlen;
290 } else if (unit == "\\paperheight") {
291 valstring = percentval;
292 unit = "pheight%" + endlen;
293 } else if (unit == "\\textheight") {
294 valstring = percentval;
295 unit = "theight%" + endlen;
303 string translate_len(string const & length)
307 if (translate_len(length, value, unit))
309 // If the input is invalid, return what we have.
317 * Translates a LaTeX length into \p value, \p unit and
318 * \p special parts suitable for a box inset.
319 * The difference from translate_len() is that a box inset knows about
320 * some special "units" that are stored in \p special.
322 void translate_box_len(string const & length, string & value, string & unit, string & special)
324 if (translate_len(length, value, unit)) {
325 if (unit == "\\height" || unit == "\\depth" ||
326 unit == "\\totalheight" || unit == "\\width") {
327 special = unit.substr(1);
328 // The unit is not used, but LyX requires a dummy setting
341 * Find a file with basename \p name in path \p path and an extension
344 string find_file(string const & name, string const & path,
345 char const * const * extensions)
347 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
349 for (char const * const * what = extensions; *what; ++what) {
350 string const trial = addExtension(name, *what);
351 if (makeAbsPath(trial, path).exists())
358 void begin_inset(ostream & os, string const & name)
360 os << "\n\\begin_inset " << name;
364 void end_inset(ostream & os)
366 os << "\n\\end_inset\n\n";
370 void skip_braces(Parser & p)
372 if (p.next_token().cat() != catBegin)
375 if (p.next_token().cat() == catEnd) {
383 void handle_ert(ostream & os, string const & s, Context & context)
385 // We must have a valid layout before outputting the ERT inset.
386 context.check_layout(os);
387 Context newcontext(true, context.textclass);
388 begin_inset(os, "ERT");
389 os << "\nstatus collapsed\n";
390 newcontext.check_layout(os);
391 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
393 os << "\n\\backslash\n";
394 else if (*it == '\n') {
395 newcontext.new_paragraph(os);
396 newcontext.check_layout(os);
400 newcontext.check_end_layout(os);
405 void handle_comment(ostream & os, string const & s, Context & context)
407 // TODO: Handle this better
408 Context newcontext(true, context.textclass);
409 begin_inset(os, "ERT");
410 os << "\nstatus collapsed\n";
411 newcontext.check_layout(os);
412 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
414 os << "\n\\backslash\n";
418 // make sure that our comment is the last thing on the line
419 newcontext.new_paragraph(os);
420 newcontext.check_layout(os);
421 newcontext.check_end_layout(os);
426 LayoutPtr findLayout(TextClass const & textclass, string const & name)
428 DocumentClass::const_iterator lit = textclass.begin();
429 DocumentClass::const_iterator len = textclass.end();
430 for (; lit != len; ++lit)
431 if (lit->latexname() == name)
437 void eat_whitespace(Parser &, ostream &, Context &, bool);
440 void output_command_layout(ostream & os, Parser & p, bool outer,
441 Context & parent_context,
444 parent_context.check_end_layout(os);
445 Context context(true, parent_context.textclass, newlayout,
446 parent_context.layout, parent_context.font);
447 if (parent_context.deeper_paragraph) {
448 // We are beginning a nested environment after a
449 // deeper paragraph inside the outer list environment.
450 // Therefore we don't need to output a "begin deeper".
451 context.need_end_deeper = true;
453 context.check_deeper(os);
454 context.check_layout(os);
455 if (context.layout->optionalargs > 0) {
456 eat_whitespace(p, os, context, false);
457 if (p.next_token().character() == '[') {
458 p.get_token(); // eat '['
459 begin_inset(os, "OptArg\n");
460 os << "status collapsed\n\n";
461 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
463 eat_whitespace(p, os, context, false);
466 parse_text(p, os, FLAG_ITEM, outer, context);
467 context.check_end_layout(os);
468 if (parent_context.deeper_paragraph) {
469 // We must suppress the "end deeper" because we
470 // suppressed the "begin deeper" above.
471 context.need_end_deeper = false;
473 context.check_end_deeper(os);
474 // We don't need really a new paragraph, but
475 // we must make sure that the next item gets a \begin_layout.
476 parent_context.new_paragraph(os);
481 * Output a space if necessary.
482 * This function gets called for every whitespace token.
484 * We have three cases here:
485 * 1. A space must be suppressed. Example: The lyxcode case below
486 * 2. A space may be suppressed. Example: Spaces before "\par"
487 * 3. A space must not be suppressed. Example: A space between two words
489 * We currently handle only 1. and 3 and from 2. only the case of
490 * spaces before newlines as a side effect.
492 * 2. could be used to suppress as many spaces as possible. This has two effects:
493 * - Reimporting LyX generated LaTeX files changes almost no whitespace
494 * - Superflous whitespace from non LyX generated LaTeX files is removed.
495 * The drawback is that the logic inside the function becomes
496 * complicated, and that is the reason why it is not implemented.
498 void check_space(Parser const & p, ostream & os, Context & context)
500 Token const next = p.next_token();
501 Token const curr = p.curr_token();
502 // A space before a single newline and vice versa must be ignored
503 // LyX emits a newline before \end{lyxcode}.
504 // This newline must be ignored,
505 // otherwise LyX will add an additional protected space.
506 if (next.cat() == catSpace ||
507 next.cat() == catNewline ||
508 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
511 context.check_layout(os);
517 * Parse all arguments of \p command
519 void parse_arguments(string const & command,
520 vector<ArgumentType> const & template_arguments,
521 Parser & p, ostream & os, bool outer, Context & context)
523 string ert = command;
524 size_t no_arguments = template_arguments.size();
525 for (size_t i = 0; i < no_arguments; ++i) {
526 switch (template_arguments[i]) {
528 // This argument contains regular LaTeX
529 handle_ert(os, ert + '{', context);
530 eat_whitespace(p, os, context, false);
531 parse_text(p, os, FLAG_ITEM, outer, context);
535 // This argument may contain special characters
536 ert += '{' + p.verbatim_item() + '}';
543 handle_ert(os, ert, context);
548 * Check whether \p command is a known command. If yes,
549 * handle the command with all arguments.
550 * \return true if the command was parsed, false otherwise.
552 bool parse_command(string const & command, Parser & p, ostream & os,
553 bool outer, Context & context)
555 if (known_commands.find(command) != known_commands.end()) {
556 parse_arguments(command, known_commands[command], p, os,
564 /// Parses a minipage or parbox
565 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
566 Context & parent_context, bool use_parbox)
570 // We need to set the height to the LaTeX default of 1\\totalheight
571 // for the case when no height argument is given
572 string height_value = "1";
573 string height_unit = "in";
574 string height_special = "totalheight";
576 if (p.next_token().asInput() == "[") {
577 position = p.getArg('[', ']');
578 if (position != "t" && position != "c" && position != "b") {
580 cerr << "invalid position for minipage/parbox" << endl;
582 if (p.next_token().asInput() == "[") {
583 latex_height = p.getArg('[', ']');
584 translate_box_len(latex_height, height_value, height_unit, height_special);
586 if (p.next_token().asInput() == "[") {
587 inner_pos = p.getArg('[', ']');
588 if (inner_pos != "c" && inner_pos != "t" &&
589 inner_pos != "b" && inner_pos != "s") {
590 inner_pos = position;
591 cerr << "invalid inner_pos for minipage/parbox"
599 string const latex_width = p.verbatim_item();
600 translate_len(latex_width, width_value, width_unit);
601 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
602 // LyX can't handle length variables
607 ss << "\\begin{minipage}";
608 if (!position.empty())
609 ss << '[' << position << ']';
610 if (!latex_height.empty())
611 ss << '[' << latex_height << ']';
612 if (!inner_pos.empty())
613 ss << '[' << inner_pos << ']';
614 ss << "{" << latex_width << "}";
617 handle_ert(os, ss.str(), parent_context);
618 parent_context.new_paragraph(os);
619 parse_text_in_inset(p, os, flags, outer, parent_context);
621 handle_ert(os, "}", parent_context);
623 handle_ert(os, "\\end{minipage}", parent_context);
625 // LyX does not like empty positions, so we have
626 // to set them to the LaTeX default values here.
627 if (position.empty())
629 if (inner_pos.empty())
630 inner_pos = position;
631 parent_context.check_layout(os);
632 begin_inset(os, "Box Frameless\n");
633 os << "position \"" << position << "\"\n";
634 os << "hor_pos \"c\"\n";
635 os << "has_inner_box 1\n";
636 os << "inner_pos \"" << inner_pos << "\"\n";
637 os << "use_parbox " << use_parbox << "\n";
638 os << "width \"" << width_value << width_unit << "\"\n";
639 os << "special \"none\"\n";
640 os << "height \"" << height_value << height_unit << "\"\n";
641 os << "height_special \"" << height_special << "\"\n";
642 os << "status open\n\n";
643 parse_text_in_inset(p, os, flags, outer, parent_context);
645 #ifdef PRESERVE_LAYOUT
646 // lyx puts a % after the end of the minipage
647 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
649 //handle_comment(os, "%dummy", parent_context);
652 parent_context.new_paragraph(os);
654 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
655 //handle_comment(os, "%dummy", parent_context);
658 // We add a protected space if something real follows
659 if (p.good() && p.next_token().cat() != catComment) {
660 os << "\\InsetSpace ~\n";
668 /// parse an unknown environment
669 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
670 unsigned flags, bool outer,
671 Context & parent_context)
673 if (name == "tabbing")
674 // We need to remember that we have to handle '\=' specially
675 flags |= FLAG_TABBING;
677 // We need to translate font changes and paragraphs inside the
678 // environment to ERT if we have a non standard font.
679 // Otherwise things like
680 // \large\begin{foo}\huge bar\end{foo}
682 bool const specialfont =
683 (parent_context.font != parent_context.normalfont);
684 bool const new_layout_allowed = parent_context.new_layout_allowed;
686 parent_context.new_layout_allowed = false;
687 handle_ert(os, "\\begin{" + name + "}", parent_context);
688 parse_text_snippet(p, os, flags, outer, parent_context);
689 handle_ert(os, "\\end{" + name + "}", parent_context);
691 parent_context.new_layout_allowed = new_layout_allowed;
695 void parse_environment(Parser & p, ostream & os, bool outer,
696 Context & parent_context)
699 string const name = p.getArg('{', '}');
700 const bool is_starred = suffixIs(name, '*');
701 string const unstarred_name = rtrim(name, "*");
702 active_environments.push_back(name);
704 if (is_math_env(name)) {
705 parent_context.check_layout(os);
706 begin_inset(os, "Formula ");
707 os << "\\begin{" << name << "}";
708 parse_math(p, os, FLAG_END, MATH_MODE);
709 os << "\\end{" << name << "}";
713 else if (name == "tabular" || name == "longtable") {
714 eat_whitespace(p, os, parent_context, false);
715 parent_context.check_layout(os);
716 begin_inset(os, "Tabular ");
717 handle_tabular(p, os, name == "longtable", parent_context);
722 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
723 eat_whitespace(p, os, parent_context, false);
724 parent_context.check_layout(os);
725 begin_inset(os, "Float " + unstarred_name + "\n");
726 if (p.next_token().asInput() == "[") {
727 os << "placement " << p.getArg('[', ']') << '\n';
729 os << "wide " << convert<string>(is_starred)
730 << "\nsideways false"
731 << "\nstatus open\n\n";
732 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
734 // We don't need really a new paragraph, but
735 // we must make sure that the next item gets a \begin_layout.
736 parent_context.new_paragraph(os);
740 else if (name == "minipage") {
741 eat_whitespace(p, os, parent_context, false);
742 parse_box(p, os, FLAG_END, outer, parent_context, false);
746 else if (name == "comment") {
747 eat_whitespace(p, os, parent_context, false);
748 parent_context.check_layout(os);
749 begin_inset(os, "Note Comment\n");
750 os << "status open\n";
751 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
756 else if (name == "lyxgreyedout") {
757 eat_whitespace(p, os, parent_context, false);
758 parent_context.check_layout(os);
759 begin_inset(os, "Note Greyedout\n");
760 os << "status open\n";
761 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
766 else if (name == "framed") {
767 eat_whitespace(p, os, parent_context, false);
768 parent_context.check_layout(os);
769 begin_inset(os, "Note Framed\n");
770 os << "status open\n";
771 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
776 else if (name == "shaded") {
777 eat_whitespace(p, os, parent_context, false);
778 parent_context.check_layout(os);
779 begin_inset(os, "Note Shaded\n");
780 os << "status open\n";
781 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
786 else if (!parent_context.new_layout_allowed)
787 parse_unknown_environment(p, name, os, FLAG_END, outer,
790 // Alignment settings
791 else if (name == "center" || name == "flushleft" || name == "flushright" ||
792 name == "centering" || name == "raggedright" || name == "raggedleft") {
793 eat_whitespace(p, os, parent_context, false);
794 // We must begin a new paragraph if not already done
795 if (! parent_context.atParagraphStart()) {
796 parent_context.check_end_layout(os);
797 parent_context.new_paragraph(os);
799 if (name == "flushleft" || name == "raggedright")
800 parent_context.add_extra_stuff("\\align left\n");
801 else if (name == "flushright" || name == "raggedleft")
802 parent_context.add_extra_stuff("\\align right\n");
804 parent_context.add_extra_stuff("\\align center\n");
805 parse_text(p, os, FLAG_END, outer, parent_context);
806 // Just in case the environment is empty ..
807 parent_context.extra_stuff.erase();
808 // We must begin a new paragraph to reset the alignment
809 parent_context.new_paragraph(os);
813 // The single '=' is meant here.
814 else if ((newlayout = findLayout(parent_context.textclass, name)) &&
815 newlayout->isEnvironment()) {
816 eat_whitespace(p, os, parent_context, false);
817 Context context(true, parent_context.textclass, newlayout,
818 parent_context.layout, parent_context.font);
819 if (parent_context.deeper_paragraph) {
820 // We are beginning a nested environment after a
821 // deeper paragraph inside the outer list environment.
822 // Therefore we don't need to output a "begin deeper".
823 context.need_end_deeper = true;
825 parent_context.check_end_layout(os);
826 switch (context.layout->latextype) {
827 case LATEX_LIST_ENVIRONMENT:
828 context.extra_stuff = "\\labelwidthstring "
829 + p.verbatim_item() + '\n';
832 case LATEX_BIB_ENVIRONMENT:
833 p.verbatim_item(); // swallow next arg
839 context.check_deeper(os);
840 parse_text(p, os, FLAG_END, outer, context);
841 context.check_end_layout(os);
842 if (parent_context.deeper_paragraph) {
843 // We must suppress the "end deeper" because we
844 // suppressed the "begin deeper" above.
845 context.need_end_deeper = false;
847 context.check_end_deeper(os);
848 parent_context.new_paragraph(os);
852 else if (name == "appendix") {
853 // This is no good latex style, but it works and is used in some documents...
854 eat_whitespace(p, os, parent_context, false);
855 parent_context.check_end_layout(os);
856 Context context(true, parent_context.textclass, parent_context.layout,
857 parent_context.layout, parent_context.font);
858 context.check_layout(os);
859 os << "\\start_of_appendix\n";
860 parse_text(p, os, FLAG_END, outer, context);
861 context.check_end_layout(os);
865 else if (known_environments.find(name) != known_environments.end()) {
866 vector<ArgumentType> arguments = known_environments[name];
867 // The last "argument" denotes wether we may translate the
868 // environment contents to LyX
869 // The default required if no argument is given makes us
870 // compatible with the reLyXre environment.
871 ArgumentType contents = arguments.empty() ?
874 if (!arguments.empty())
875 arguments.pop_back();
876 // See comment in parse_unknown_environment()
877 bool const specialfont =
878 (parent_context.font != parent_context.normalfont);
879 bool const new_layout_allowed =
880 parent_context.new_layout_allowed;
882 parent_context.new_layout_allowed = false;
883 parse_arguments("\\begin{" + name + "}", arguments, p, os,
884 outer, parent_context);
885 if (contents == verbatim)
886 handle_ert(os, p.verbatimEnvironment(name),
889 parse_text_snippet(p, os, FLAG_END, outer,
891 handle_ert(os, "\\end{" + name + "}", parent_context);
893 parent_context.new_layout_allowed = new_layout_allowed;
897 parse_unknown_environment(p, name, os, FLAG_END, outer,
900 active_environments.pop_back();
904 /// parses a comment and outputs it to \p os.
905 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
907 BOOST_ASSERT(t.cat() == catComment);
908 if (!t.cs().empty()) {
909 context.check_layout(os);
910 handle_comment(os, '%' + t.cs(), context);
911 if (p.next_token().cat() == catNewline) {
912 // A newline after a comment line starts a new
914 if (context.new_layout_allowed) {
915 if(!context.atParagraphStart())
916 // Only start a new paragraph if not already
917 // done (we might get called recursively)
918 context.new_paragraph(os);
920 handle_ert(os, "\n", context);
921 eat_whitespace(p, os, context, true);
931 * Reads spaces and comments until the first non-space, non-comment token.
932 * New paragraphs (double newlines or \\par) are handled like simple spaces
933 * if \p eatParagraph is true.
934 * Spaces are skipped, but comments are written to \p os.
936 void eat_whitespace(Parser & p, ostream & os, Context & context,
940 Token const & t = p.get_token();
941 if (t.cat() == catComment)
942 parse_comment(p, os, t, context);
943 else if ((! eatParagraph && p.isParagraph()) ||
944 (t.cat() != catSpace && t.cat() != catNewline)) {
953 * Set a font attribute, parse text and reset the font attribute.
954 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
955 * \param currentvalue Current value of the attribute. Is set to the new
956 * value during parsing.
957 * \param newvalue New value of the attribute
959 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
960 Context & context, string const & attribute,
961 string & currentvalue, string const & newvalue)
963 context.check_layout(os);
964 string const oldvalue = currentvalue;
965 currentvalue = newvalue;
966 os << '\n' << attribute << ' ' << newvalue << "\n";
967 parse_text_snippet(p, os, flags, outer, context);
968 context.check_layout(os);
969 os << '\n' << attribute << ' ' << oldvalue << "\n";
970 currentvalue = oldvalue;
974 /// get the arguments of a natbib or jurabib citation command
975 void get_cite_arguments(Parser & p, bool natbibOrder,
976 string & before, string & after)
978 // We need to distinguish "" and "[]", so we can't use p.getOpt().
980 // text before the citation
982 // text after the citation
983 after = p.getFullOpt();
985 if (!after.empty()) {
986 before = p.getFullOpt();
987 if (natbibOrder && !before.empty())
993 /// Convert filenames with TeX macros and/or quotes to something LyX
995 string const normalize_filename(string const & name)
997 Parser p(trim(name, "\""));
1000 Token const & t = p.get_token();
1001 if (t.cat() != catEscape)
1003 else if (t.cs() == "lyxdot") {
1004 // This is used by LyX for simple dots in relative
1008 } else if (t.cs() == "space") {
1018 /// Convert \p name from TeX convention (relative to master file) to LyX
1019 /// convention (relative to .lyx file) if it is relative
1020 void fix_relative_filename(string & name)
1022 FileName fname(name);
1023 if (fname.isAbsolute())
1026 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1028 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1029 from_utf8(getParentFilePath())));
1033 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1034 void parse_noweb(Parser & p, ostream & os, Context & context)
1036 // assemble the rest of the keyword
1040 Token const & t = p.get_token();
1041 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1044 scrap = (p.good() && p.next_token().asInput() == "=");
1046 name += p.get_token().asInput();
1049 name += t.asInput();
1052 if (!scrap || !context.new_layout_allowed ||
1053 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1054 cerr << "Warning: Could not interpret '" << name
1055 << "'. Ignoring it." << endl;
1059 // We use new_paragraph instead of check_end_layout because the stuff
1060 // following the noweb chunk needs to start with a \begin_layout.
1061 // This may create a new paragraph even if there was none in the
1062 // noweb file, but the alternative is an invalid LyX file. Since
1063 // noweb code chunks are implemented with a layout style in LyX they
1064 // always must be in an own paragraph.
1065 context.new_paragraph(os);
1066 Context newcontext(true, context.textclass,
1067 &context.textclass[from_ascii("Scrap")]);
1068 newcontext.check_layout(os);
1071 Token const & t = p.get_token();
1072 // We abuse the parser a bit, because this is no TeX syntax
1074 if (t.cat() == catEscape)
1075 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1077 os << subst(t.asInput(), "\n", "\n\\newline\n");
1078 // The scrap chunk is ended by an @ at the beginning of a line.
1079 // After the @ the line may contain a comment and/or
1080 // whitespace, but nothing else.
1081 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1082 (p.next_token().cat() == catSpace ||
1083 p.next_token().cat() == catNewline ||
1084 p.next_token().cat() == catComment)) {
1085 while (p.good() && p.next_token().cat() == catSpace)
1086 os << p.get_token().asInput();
1087 if (p.next_token().cat() == catComment)
1088 // The comment includes a final '\n'
1089 os << p.get_token().asInput();
1091 if (p.next_token().cat() == catNewline)
1098 newcontext.check_end_layout(os);
1101 } // anonymous namespace
1104 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1107 LayoutPtr newlayout;
1108 // store the current selectlanguage to be used after \foreignlanguage
1110 // Store the latest bibliographystyle (needed for bibtex inset)
1111 string bibliographystyle;
1112 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1113 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1115 Token const & t = p.get_token();
1118 cerr << "t: " << t << " flags: " << flags << "\n";
1121 if (flags & FLAG_ITEM) {
1122 if (t.cat() == catSpace)
1125 flags &= ~FLAG_ITEM;
1126 if (t.cat() == catBegin) {
1127 // skip the brace and collect everything to the next matching
1129 flags |= FLAG_BRACE_LAST;
1133 // handle only this single token, leave the loop if done
1134 flags |= FLAG_LEAVE;
1137 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1143 if (t.cat() == catMath) {
1144 // we are inside some text mode thingy, so opening new math is allowed
1145 context.check_layout(os);
1146 begin_inset(os, "Formula ");
1147 Token const & n = p.get_token();
1148 if (n.cat() == catMath && outer) {
1149 // TeX's $$...$$ syntax for displayed math
1151 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1153 p.get_token(); // skip the second '$' token
1155 // simple $...$ stuff
1158 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1164 else if (t.cat() == catSuper || t.cat() == catSub)
1165 cerr << "catcode " << t << " illegal in text mode\n";
1167 // Basic support for english quotes. This should be
1168 // extended to other quotes, but is not so easy (a
1169 // left english quote is the same as a right german
1171 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1172 context.check_layout(os);
1173 begin_inset(os, "Quotes ");
1179 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1180 context.check_layout(os);
1181 begin_inset(os, "Quotes ");
1188 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1189 context.check_layout(os);
1190 begin_inset(os, "Quotes ");
1197 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1198 context.check_layout(os);
1199 begin_inset(os, "Quotes ");
1206 else if (t.asInput() == "<"
1207 && p.next_token().asInput() == "<" && noweb_mode) {
1209 parse_noweb(p, os, context);
1212 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1213 check_space(p, os, context);
1215 else if (t.character() == '[' && noweb_mode &&
1216 p.next_token().character() == '[') {
1217 // These can contain underscores
1219 string const s = p.getFullOpt() + ']';
1220 if (p.next_token().character() == ']')
1223 cerr << "Warning: Inserting missing ']' in '"
1224 << s << "'." << endl;
1225 handle_ert(os, s, context);
1228 else if (t.cat() == catLetter ||
1229 t.cat() == catOther ||
1230 t.cat() == catAlign ||
1231 t.cat() == catParameter) {
1232 // This translates "&" to "\\&" which may be wrong...
1233 context.check_layout(os);
1234 os << t.character();
1237 else if (p.isParagraph()) {
1238 if (context.new_layout_allowed)
1239 context.new_paragraph(os);
1241 handle_ert(os, "\\par ", context);
1242 eat_whitespace(p, os, context, true);
1245 else if (t.cat() == catActive) {
1246 context.check_layout(os);
1247 if (t.character() == '~') {
1248 if (context.layout->free_spacing)
1251 os << "\\InsetSpace ~\n";
1253 os << t.character();
1256 else if (t.cat() == catBegin &&
1257 p.next_token().cat() == catEnd) {
1259 Token const prev = p.prev_token();
1261 if (p.next_token().character() == '`' ||
1262 (prev.character() == '-' &&
1263 p.next_token().character() == '-'))
1264 ; // ignore it in {}`` or -{}-
1266 handle_ert(os, "{}", context);
1270 else if (t.cat() == catBegin) {
1271 context.check_layout(os);
1272 // special handling of font attribute changes
1273 Token const prev = p.prev_token();
1274 Token const next = p.next_token();
1275 TeXFont const oldFont = context.font;
1276 if (next.character() == '[' ||
1277 next.character() == ']' ||
1278 next.character() == '*') {
1280 if (p.next_token().cat() == catEnd) {
1281 os << next.character();
1285 handle_ert(os, "{", context);
1286 parse_text_snippet(p, os,
1289 handle_ert(os, "}", context);
1291 } else if (! context.new_layout_allowed) {
1292 handle_ert(os, "{", context);
1293 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1295 handle_ert(os, "}", context);
1296 } else if (is_known(next.cs(), known_sizes)) {
1297 // next will change the size, so we must
1299 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1301 if (!context.atParagraphStart())
1303 << context.font.size << "\n";
1304 } else if (is_known(next.cs(), known_font_families)) {
1305 // next will change the font family, so we
1306 // must reset it here
1307 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1309 if (!context.atParagraphStart())
1311 << context.font.family << "\n";
1312 } else if (is_known(next.cs(), known_font_series)) {
1313 // next will change the font series, so we
1314 // must reset it here
1315 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1317 if (!context.atParagraphStart())
1319 << context.font.series << "\n";
1320 } else if (is_known(next.cs(), known_font_shapes)) {
1321 // next will change the font shape, so we
1322 // must reset it here
1323 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1325 if (!context.atParagraphStart())
1327 << context.font.shape << "\n";
1328 } else if (is_known(next.cs(), known_old_font_families) ||
1329 is_known(next.cs(), known_old_font_series) ||
1330 is_known(next.cs(), known_old_font_shapes)) {
1331 // next will change the font family, series
1332 // and shape, so we must reset it here
1333 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1335 if (!context.atParagraphStart())
1337 << context.font.family
1339 << context.font.series
1341 << context.font.shape << "\n";
1343 handle_ert(os, "{", context);
1344 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1346 handle_ert(os, "}", context);
1350 else if (t.cat() == catEnd) {
1351 if (flags & FLAG_BRACE_LAST) {
1354 cerr << "stray '}' in text\n";
1355 handle_ert(os, "}", context);
1358 else if (t.cat() == catComment)
1359 parse_comment(p, os, t, context);
1362 // control sequences
1365 else if (t.cs() == "(") {
1366 context.check_layout(os);
1367 begin_inset(os, "Formula");
1369 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1374 else if (t.cs() == "[") {
1375 context.check_layout(os);
1376 begin_inset(os, "Formula");
1378 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1383 else if (t.cs() == "begin")
1384 parse_environment(p, os, outer, context);
1386 else if (t.cs() == "end") {
1387 if (flags & FLAG_END) {
1388 // eat environment name
1389 string const name = p.getArg('{', '}');
1390 if (name != active_environment())
1391 cerr << "\\end{" + name + "} does not match \\begin{"
1392 + active_environment() + "}\n";
1395 p.error("found 'end' unexpectedly");
1398 else if (t.cs() == "item") {
1401 bool optarg = false;
1402 if (p.next_token().character() == '[') {
1403 p.get_token(); // eat '['
1404 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1409 context.check_layout(os);
1410 if (context.has_item) {
1411 // An item in an unknown list-like environment
1412 // FIXME: Do this in check_layout()!
1413 context.has_item = false;
1415 handle_ert(os, "\\item", context);
1417 handle_ert(os, "\\item ", context);
1420 if (context.layout->labeltype != LABEL_MANUAL) {
1421 // lyx does not support \item[\mybullet]
1422 // in itemize environments
1423 handle_ert(os, "[", context);
1425 handle_ert(os, "]", context);
1426 } else if (!s.empty()) {
1427 // The space is needed to separate the
1428 // item from the rest of the sentence.
1430 eat_whitespace(p, os, context, false);
1435 else if (t.cs() == "bibitem") {
1437 context.check_layout(os);
1440 os << '{' << p.verbatim_item() << '}' << "\n";
1443 else if (t.cs() == "def") {
1444 context.check_layout(os);
1445 eat_whitespace(p, os, context, false);
1446 string name = p.get_token().cs();
1447 eat_whitespace(p, os, context, false);
1453 while (p.next_token().cat() != catBegin) {
1454 if (p.next_token().cat() == catParameter) {
1459 // followed by number?
1460 if (p.next_token().cat() == catOther) {
1461 char c = p.getChar();
1463 // number = current arity + 1?
1464 if (c == arity + '0' + 1)
1469 paramtext += p.get_token().asString();
1471 paramtext += p.get_token().asString();
1476 // only output simple (i.e. compatible) macro as FormulaMacros
1477 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1479 context.check_layout(os);
1480 begin_inset(os, "FormulaMacro");
1484 handle_ert(os, ert, context);
1487 else if (t.cs() == "noindent") {
1489 context.add_extra_stuff("\\noindent\n");
1492 else if (t.cs() == "appendix") {
1493 context.add_extra_stuff("\\start_of_appendix\n");
1494 // We need to start a new paragraph. Otherwise the
1495 // appendix in 'bla\appendix\chapter{' would start
1497 context.new_paragraph(os);
1498 // We need to make sure that the paragraph is
1499 // generated even if it is empty. Otherwise the
1500 // appendix in '\par\appendix\par\chapter{' would
1502 context.check_layout(os);
1503 // FIXME: This is a hack to prevent paragraph
1504 // deletion if it is empty. Handle this better!
1506 "%dummy comment inserted by tex2lyx to "
1507 "ensure that this paragraph is not empty",
1509 // Both measures above may generate an additional
1510 // empty paragraph, but that does not hurt, because
1511 // whitespace does not matter here.
1512 eat_whitespace(p, os, context, true);
1515 // Must attempt to parse "Section*" before "Section".
1516 else if ((p.next_token().asInput() == "*") &&
1517 context.new_layout_allowed &&
1518 // The single '=' is meant here.
1519 (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1520 newlayout->isCommand()) {
1522 output_command_layout(os, p, outer, context, newlayout);
1526 // The single '=' is meant here.
1527 else if (context.new_layout_allowed &&
1528 (newlayout = findLayout(context.textclass, t.cs())) &&
1529 newlayout->isCommand()) {
1530 output_command_layout(os, p, outer, context, newlayout);
1534 // Special handling for \caption
1535 // FIXME: remove this when InsetCaption is supported.
1536 else if (context.new_layout_allowed &&
1537 t.cs() == captionlayout->latexname()) {
1538 output_command_layout(os, p, outer, context,
1543 else if (t.cs() == "includegraphics") {
1544 bool const clip = p.next_token().asInput() == "*";
1547 map<string, string> opts = split_map(p.getArg('[', ']'));
1549 opts["clip"] = string();
1550 string name = normalize_filename(p.verbatim_item());
1552 string const path = getMasterFilePath();
1553 // We want to preserve relative / absolute filenames,
1554 // therefore path is only used for testing
1555 // FIXME UNICODE encoding of name and path may be
1556 // wrong (makeAbsPath expects utf8)
1557 if (!makeAbsPath(name, path).exists()) {
1558 // The file extension is probably missing.
1559 // Now try to find it out.
1560 string const dvips_name =
1561 find_file(name, path,
1562 known_dvips_graphics_formats);
1563 string const pdftex_name =
1564 find_file(name, path,
1565 known_pdftex_graphics_formats);
1566 if (!dvips_name.empty()) {
1567 if (!pdftex_name.empty()) {
1568 cerr << "This file contains the "
1570 "\"\\includegraphics{"
1572 "However, files\n\""
1573 << dvips_name << "\" and\n\""
1574 << pdftex_name << "\"\n"
1575 "both exist, so I had to make a "
1576 "choice and took the first one.\n"
1577 "Please move the unwanted one "
1578 "someplace else and try again\n"
1579 "if my choice was wrong."
1583 } else if (!pdftex_name.empty())
1587 // FIXME UNICODE encoding of name and path may be
1588 // wrong (makeAbsPath expects utf8)
1589 if (makeAbsPath(name, path).exists())
1590 fix_relative_filename(name);
1592 cerr << "Warning: Could not find graphics file '"
1593 << name << "'." << endl;
1595 context.check_layout(os);
1596 begin_inset(os, "Graphics ");
1597 os << "\n\tfilename " << name << '\n';
1598 if (opts.find("width") != opts.end())
1600 << translate_len(opts["width"]) << '\n';
1601 if (opts.find("height") != opts.end())
1603 << translate_len(opts["height"]) << '\n';
1604 if (opts.find("scale") != opts.end()) {
1605 istringstream iss(opts["scale"]);
1609 os << "\tscale " << val << '\n';
1611 if (opts.find("angle") != opts.end())
1612 os << "\trotateAngle "
1613 << opts["angle"] << '\n';
1614 if (opts.find("origin") != opts.end()) {
1616 string const opt = opts["origin"];
1617 if (opt.find('l') != string::npos) ss << "left";
1618 if (opt.find('r') != string::npos) ss << "right";
1619 if (opt.find('c') != string::npos) ss << "center";
1620 if (opt.find('t') != string::npos) ss << "Top";
1621 if (opt.find('b') != string::npos) ss << "Bottom";
1622 if (opt.find('B') != string::npos) ss << "Baseline";
1623 if (!ss.str().empty())
1624 os << "\trotateOrigin " << ss.str() << '\n';
1626 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1628 if (opts.find("keepaspectratio") != opts.end())
1629 os << "\tkeepAspectRatio\n";
1630 if (opts.find("clip") != opts.end())
1632 if (opts.find("draft") != opts.end())
1634 if (opts.find("bb") != opts.end())
1635 os << "\tBoundingBox "
1636 << opts["bb"] << '\n';
1637 int numberOfbbOptions = 0;
1638 if (opts.find("bbllx") != opts.end())
1639 numberOfbbOptions++;
1640 if (opts.find("bblly") != opts.end())
1641 numberOfbbOptions++;
1642 if (opts.find("bburx") != opts.end())
1643 numberOfbbOptions++;
1644 if (opts.find("bbury") != opts.end())
1645 numberOfbbOptions++;
1646 if (numberOfbbOptions == 4)
1647 os << "\tBoundingBox "
1648 << opts["bbllx"] << " " << opts["bblly"] << " "
1649 << opts["bburx"] << " " << opts["bbury"] << '\n';
1650 else if (numberOfbbOptions > 0)
1651 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1652 numberOfbbOptions = 0;
1653 if (opts.find("natwidth") != opts.end())
1654 numberOfbbOptions++;
1655 if (opts.find("natheight") != opts.end())
1656 numberOfbbOptions++;
1657 if (numberOfbbOptions == 2)
1658 os << "\tBoundingBox 0bp 0bp "
1659 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1660 else if (numberOfbbOptions > 0)
1661 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1662 ostringstream special;
1663 if (opts.find("hiresbb") != opts.end())
1664 special << "hiresbb,";
1665 if (opts.find("trim") != opts.end())
1667 if (opts.find("viewport") != opts.end())
1668 special << "viewport=" << opts["viewport"] << ',';
1669 if (opts.find("totalheight") != opts.end())
1670 special << "totalheight=" << opts["totalheight"] << ',';
1671 if (opts.find("type") != opts.end())
1672 special << "type=" << opts["type"] << ',';
1673 if (opts.find("ext") != opts.end())
1674 special << "ext=" << opts["ext"] << ',';
1675 if (opts.find("read") != opts.end())
1676 special << "read=" << opts["read"] << ',';
1677 if (opts.find("command") != opts.end())
1678 special << "command=" << opts["command"] << ',';
1679 string s_special = special.str();
1680 if (!s_special.empty()) {
1681 // We had special arguments. Remove the trailing ','.
1682 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1684 // TODO: Handle the unknown settings better.
1685 // Warn about invalid options.
1686 // Check whether some option was given twice.
1690 else if (t.cs() == "footnote" ||
1691 (t.cs() == "thanks" && context.layout->intitle)) {
1693 context.check_layout(os);
1694 begin_inset(os, "Foot\n");
1695 os << "status collapsed\n\n";
1696 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1700 else if (t.cs() == "marginpar") {
1702 context.check_layout(os);
1703 begin_inset(os, "Marginal\n");
1704 os << "status collapsed\n\n";
1705 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1709 else if (t.cs() == "ensuremath") {
1711 context.check_layout(os);
1712 string const s = p.verbatim_item();
1713 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1716 handle_ert(os, "\\ensuremath{" + s + "}",
1720 else if (t.cs() == "hfill") {
1721 context.check_layout(os);
1722 os << "\n\\hfill\n";
1727 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1728 // FIXME: Somehow prevent title layouts if
1729 // "maketitle" was not found
1731 skip_braces(p); // swallow this
1734 else if (t.cs() == "tableofcontents") {
1736 context.check_layout(os);
1737 begin_inset(os, "LatexCommand \\tableofcontents\n");
1739 skip_braces(p); // swallow this
1742 else if (t.cs() == "listoffigures") {
1744 context.check_layout(os);
1745 begin_inset(os, "FloatList figure\n");
1747 skip_braces(p); // swallow this
1750 else if (t.cs() == "listoftables") {
1752 context.check_layout(os);
1753 begin_inset(os, "FloatList table\n");
1755 skip_braces(p); // swallow this
1758 else if (t.cs() == "listof") {
1759 p.skip_spaces(true);
1760 string const name = p.get_token().asString();
1761 if (context.textclass.floats().typeExist(name)) {
1762 context.check_layout(os);
1763 begin_inset(os, "FloatList ");
1766 p.get_token(); // swallow second arg
1768 handle_ert(os, "\\listof{" + name + "}", context);
1771 else if (t.cs() == "textrm")
1772 parse_text_attributes(p, os, FLAG_ITEM, outer,
1773 context, "\\family",
1774 context.font.family, "roman");
1776 else if (t.cs() == "textsf")
1777 parse_text_attributes(p, os, FLAG_ITEM, outer,
1778 context, "\\family",
1779 context.font.family, "sans");
1781 else if (t.cs() == "texttt")
1782 parse_text_attributes(p, os, FLAG_ITEM, outer,
1783 context, "\\family",
1784 context.font.family, "typewriter");
1786 else if (t.cs() == "textmd")
1787 parse_text_attributes(p, os, FLAG_ITEM, outer,
1788 context, "\\series",
1789 context.font.series, "medium");
1791 else if (t.cs() == "textbf")
1792 parse_text_attributes(p, os, FLAG_ITEM, outer,
1793 context, "\\series",
1794 context.font.series, "bold");
1796 else if (t.cs() == "textup")
1797 parse_text_attributes(p, os, FLAG_ITEM, outer,
1799 context.font.shape, "up");
1801 else if (t.cs() == "textit")
1802 parse_text_attributes(p, os, FLAG_ITEM, outer,
1804 context.font.shape, "italic");
1806 else if (t.cs() == "textsl")
1807 parse_text_attributes(p, os, FLAG_ITEM, outer,
1809 context.font.shape, "slanted");
1811 else if (t.cs() == "textsc")
1812 parse_text_attributes(p, os, FLAG_ITEM, outer,
1814 context.font.shape, "smallcaps");
1816 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1817 context.check_layout(os);
1818 TeXFont oldFont = context.font;
1819 context.font.init();
1820 context.font.size = oldFont.size;
1821 os << "\n\\family " << context.font.family << "\n";
1822 os << "\n\\series " << context.font.series << "\n";
1823 os << "\n\\shape " << context.font.shape << "\n";
1824 if (t.cs() == "textnormal") {
1825 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1826 output_font_change(os, context.font, oldFont);
1827 context.font = oldFont;
1829 eat_whitespace(p, os, context, false);
1832 else if (t.cs() == "underbar") {
1833 // Do NOT handle \underline.
1834 // \underbar cuts through y, g, q, p etc.,
1835 // \underline does not.
1836 context.check_layout(os);
1837 os << "\n\\bar under\n";
1838 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1839 context.check_layout(os);
1840 os << "\n\\bar default\n";
1843 else if (t.cs() == "emph" || t.cs() == "noun") {
1844 context.check_layout(os);
1845 os << "\n\\" << t.cs() << " on\n";
1846 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1847 context.check_layout(os);
1848 os << "\n\\" << t.cs() << " default\n";
1851 else if (use_natbib &&
1852 is_known(t.cs(), known_natbib_commands) &&
1853 ((t.cs() != "citefullauthor" &&
1854 t.cs() != "citeyear" &&
1855 t.cs() != "citeyearpar") ||
1856 p.next_token().asInput() != "*")) {
1857 context.check_layout(os);
1859 // \citet[before][after]{a} \citet[after][before]{a}
1860 // \citet[before][]{a} \citet[][before]{a}
1861 // \citet[after]{a} \citet[after]{a}
1862 // \citet{a} \citet{a}
1863 string command = '\\' + t.cs();
1864 if (p.next_token().asInput() == "*") {
1868 if (command == "\\citefullauthor")
1869 // alternative name for "\\citeauthor*"
1870 command = "\\citeauthor*";
1872 // text before the citation
1874 // text after the citation
1876 get_cite_arguments(p, true, before, after);
1878 if (command == "\\cite") {
1879 // \cite without optional argument means
1880 // \citet, \cite with at least one optional
1881 // argument means \citep.
1882 if (before.empty() && after.empty())
1883 command = "\\citet";
1885 command = "\\citep";
1887 if (before.empty() && after == "[]")
1888 // avoid \citet[]{a}
1890 else if (before == "[]" && after == "[]") {
1891 // avoid \citet[][]{a}
1895 begin_inset(os, "LatexCommand ");
1896 os << command << after << before
1897 << '{' << p.verbatim_item() << "}\n";
1901 else if (use_jurabib &&
1902 is_known(t.cs(), known_jurabib_commands)) {
1903 context.check_layout(os);
1904 string const command = '\\' + t.cs();
1905 char argumentOrder = '\0';
1906 vector<string> const & options = used_packages["jurabib"];
1907 if (find(options.begin(), options.end(),
1908 "natbiborder") != options.end())
1909 argumentOrder = 'n';
1910 else if (find(options.begin(), options.end(),
1911 "jurabiborder") != options.end())
1912 argumentOrder = 'j';
1914 // text before the citation
1916 // text after the citation
1918 get_cite_arguments(p, argumentOrder != 'j', before, after);
1920 string const citation = p.verbatim_item();
1921 if (!before.empty() && argumentOrder == '\0') {
1922 cerr << "Warning: Assuming argument order "
1923 "of jurabib version 0.6 for\n'"
1924 << command << before << after << '{'
1925 << citation << "}'.\n"
1926 "Add 'jurabiborder' to the jurabib "
1927 "package options if you used an\n"
1928 "earlier jurabib version." << endl;
1930 begin_inset(os, "LatexCommand ");
1931 os << command << after << before
1932 << '{' << citation << "}\n";
1936 else if (is_known(t.cs(), known_latex_commands)) {
1937 // This needs to be after the check for natbib and
1938 // jurabib commands, because "cite" has different
1939 // arguments with natbib and jurabib.
1940 context.check_layout(os);
1941 begin_inset(os, "LatexCommand ");
1942 os << '\\' << t.cs();
1943 // lyx cannot handle newlines in a latex command
1944 // FIXME: Move the substitution into parser::getOpt()?
1945 os << subst(p.getOpt(), "\n", " ");
1946 os << subst(p.getOpt(), "\n", " ");
1947 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1951 else if (is_known(t.cs(), known_quotes)) {
1952 char const * const * where = is_known(t.cs(), known_quotes);
1953 context.check_layout(os);
1954 begin_inset(os, "Quotes ");
1955 os << known_coded_quotes[where - known_quotes];
1957 // LyX adds {} after the quote, so we have to eat
1958 // spaces here if there are any before a possible
1960 eat_whitespace(p, os, context, false);
1964 else if (is_known(t.cs(), known_sizes) &&
1965 context.new_layout_allowed) {
1966 char const * const * where = is_known(t.cs(), known_sizes);
1967 context.check_layout(os);
1968 TeXFont const oldFont = context.font;
1969 context.font.size = known_coded_sizes[where - known_sizes];
1970 output_font_change(os, oldFont, context.font);
1971 eat_whitespace(p, os, context, false);
1974 else if (is_known(t.cs(), known_font_families) &&
1975 context.new_layout_allowed) {
1976 char const * const * where =
1977 is_known(t.cs(), known_font_families);
1978 context.check_layout(os);
1979 TeXFont const oldFont = context.font;
1980 context.font.family =
1981 known_coded_font_families[where - known_font_families];
1982 output_font_change(os, oldFont, context.font);
1983 eat_whitespace(p, os, context, false);
1986 else if (is_known(t.cs(), known_font_series) &&
1987 context.new_layout_allowed) {
1988 char const * const * where =
1989 is_known(t.cs(), known_font_series);
1990 context.check_layout(os);
1991 TeXFont const oldFont = context.font;
1992 context.font.series =
1993 known_coded_font_series[where - known_font_series];
1994 output_font_change(os, oldFont, context.font);
1995 eat_whitespace(p, os, context, false);
1998 else if (is_known(t.cs(), known_font_shapes) &&
1999 context.new_layout_allowed) {
2000 char const * const * where =
2001 is_known(t.cs(), known_font_shapes);
2002 context.check_layout(os);
2003 TeXFont const oldFont = context.font;
2004 context.font.shape =
2005 known_coded_font_shapes[where - known_font_shapes];
2006 output_font_change(os, oldFont, context.font);
2007 eat_whitespace(p, os, context, false);
2009 else if (is_known(t.cs(), known_old_font_families) &&
2010 context.new_layout_allowed) {
2011 char const * const * where =
2012 is_known(t.cs(), known_old_font_families);
2013 context.check_layout(os);
2014 TeXFont const oldFont = context.font;
2015 context.font.init();
2016 context.font.size = oldFont.size;
2017 context.font.family =
2018 known_coded_font_families[where - known_old_font_families];
2019 output_font_change(os, oldFont, context.font);
2020 eat_whitespace(p, os, context, false);
2023 else if (is_known(t.cs(), known_old_font_series) &&
2024 context.new_layout_allowed) {
2025 char const * const * where =
2026 is_known(t.cs(), known_old_font_series);
2027 context.check_layout(os);
2028 TeXFont const oldFont = context.font;
2029 context.font.init();
2030 context.font.size = oldFont.size;
2031 context.font.series =
2032 known_coded_font_series[where - known_old_font_series];
2033 output_font_change(os, oldFont, context.font);
2034 eat_whitespace(p, os, context, false);
2037 else if (is_known(t.cs(), known_old_font_shapes) &&
2038 context.new_layout_allowed) {
2039 char const * const * where =
2040 is_known(t.cs(), known_old_font_shapes);
2041 context.check_layout(os);
2042 TeXFont const oldFont = context.font;
2043 context.font.init();
2044 context.font.size = oldFont.size;
2045 context.font.shape =
2046 known_coded_font_shapes[where - known_old_font_shapes];
2047 output_font_change(os, oldFont, context.font);
2048 eat_whitespace(p, os, context, false);
2051 else if (t.cs() == "selectlanguage") {
2052 context.check_layout(os);
2053 // save the language for the case that a \foreignlanguage is used
2054 selectlang = subst(p.verbatim_item(), "\n", " ");
2055 os << "\\lang " << selectlang << "\n";
2059 else if (t.cs() == "foreignlanguage") {
2060 context.check_layout(os);
2061 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2062 os << subst(p.verbatim_item(), "\n", " ");
2063 // set back to last selectlanguage
2064 os << "\n\\lang " << selectlang << "\n";
2067 else if (t.cs() == "inputencoding")
2068 // write nothing because this is done by LyX using the "\lang"
2069 // information given by selectlanguage and foreignlanguage
2070 subst(p.verbatim_item(), "\n", " ");
2072 else if (t.cs() == "LyX" || t.cs() == "TeX"
2073 || t.cs() == "LaTeX") {
2074 context.check_layout(os);
2076 skip_braces(p); // eat {}
2079 else if (t.cs() == "LaTeXe") {
2080 context.check_layout(os);
2082 skip_braces(p); // eat {}
2085 else if (t.cs() == "ldots") {
2086 context.check_layout(os);
2088 os << "\\SpecialChar \\ldots{}\n";
2091 else if (t.cs() == "lyxarrow") {
2092 context.check_layout(os);
2093 os << "\\SpecialChar \\menuseparator\n";
2097 else if (t.cs() == "textcompwordmark") {
2098 context.check_layout(os);
2099 os << "\\SpecialChar \\textcompwordmark{}\n";
2103 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2104 context.check_layout(os);
2105 os << "\\SpecialChar \\@.\n";
2109 else if (t.cs() == "-") {
2110 context.check_layout(os);
2111 os << "\\SpecialChar \\-\n";
2114 else if (t.cs() == "textasciitilde") {
2115 context.check_layout(os);
2120 else if (t.cs() == "textasciicircum") {
2121 context.check_layout(os);
2126 else if (t.cs() == "textbackslash") {
2127 context.check_layout(os);
2128 os << "\n\\backslash\n";
2132 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2133 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2135 context.check_layout(os);
2139 else if (t.cs() == "char") {
2140 context.check_layout(os);
2141 if (p.next_token().character() == '`') {
2143 if (p.next_token().cs() == "\"") {
2148 handle_ert(os, "\\char`", context);
2151 handle_ert(os, "\\char", context);
2155 else if (t.cs() == "verb") {
2156 context.check_layout(os);
2157 char const delimiter = p.next_token().character();
2158 string const arg = p.getArg(delimiter, delimiter);
2160 oss << "\\verb" << delimiter << arg << delimiter;
2161 handle_ert(os, oss.str(), context);
2164 else if (t.cs() == "\"") {
2165 context.check_layout(os);
2166 string const name = p.verbatim_item();
2167 if (name == "a") os << '\xe4';
2168 else if (name == "o") os << '\xf6';
2169 else if (name == "u") os << '\xfc';
2170 else if (name == "A") os << '\xc4';
2171 else if (name == "O") os << '\xd6';
2172 else if (name == "U") os << '\xdc';
2173 else handle_ert(os, "\"{" + name + "}", context);
2176 // Problem: \= creates a tabstop inside the tabbing environment
2177 // and else an accent. In the latter case we really would want
2178 // \={o} instead of \= o.
2179 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2180 handle_ert(os, t.asInput(), context);
2182 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2183 || t.cs() == "'" || t.cs() == "`"
2184 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2185 // we need the trim as the LyX parser chokes on such spaces
2186 // The argument of InsetLatexAccent is parsed as a
2187 // subset of LaTeX, so don't parse anything here,
2188 // but use the raw argument.
2189 // Otherwise we would convert \~{\i} wrongly.
2190 // This will of course not translate \~{\ss} to \~{ß},
2191 // but that does at least compile and does only look
2192 // strange on screen.
2193 context.check_layout(os);
2194 os << "\\i \\" << t.cs() << "{"
2195 << trim(p.verbatim_item(), " ")
2199 else if (t.cs() == "ss") {
2200 context.check_layout(os);
2202 skip_braces(p); // eat {}
2205 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2207 context.check_layout(os);
2208 os << "\\i \\" << t.cs() << "{}\n";
2209 skip_braces(p); // eat {}
2212 else if (t.cs() == "\\") {
2213 context.check_layout(os);
2214 string const next = p.next_token().asInput();
2216 handle_ert(os, "\\\\" + p.getOpt(), context);
2217 else if (next == "*") {
2219 handle_ert(os, "\\\\*" + p.getOpt(), context);
2222 os << "\n\\newline\n";
2226 else if (t.cs() == "newline" ||
2227 t.cs() == "linebreak") {
2228 context.check_layout(os);
2229 os << "\n\\" << t.cs() << "\n";
2230 skip_braces(p); // eat {}
2233 else if (t.cs() == "href") {
2234 context.check_layout(os);
2235 begin_inset(os, "CommandInset ");
2236 os << t.cs() << "\n";
2237 os << "LatexCommand " << t.cs() << "\n";
2240 // the first argument is "type:target", "type:" is optional
2241 // the second argument the name
2242 string href_target = subst(p.verbatim_item(), "\n", " ");
2243 string href_name = subst(p.verbatim_item(), "\n", " ");
2245 // serach for the ":" to divide type from target
2246 if ((pos = href_target.find(":", 0)) != string::npos){
2247 href_type = href_target;
2248 href_type.erase(pos + 1, href_type.length());
2249 href_target.erase(0, pos + 1);
2252 os << "name " << '"' << href_name << '"' << "\n";
2253 os << "target " << '"' << href_target << '"' << "\n";
2255 os << "type " << '"' << href_type << '"' << "\n";
2259 else if (t.cs() == "input" || t.cs() == "include"
2260 || t.cs() == "verbatiminput") {
2261 string name = '\\' + t.cs();
2262 if (t.cs() == "verbatiminput"
2263 && p.next_token().asInput() == "*")
2264 name += p.get_token().asInput();
2265 context.check_layout(os);
2266 begin_inset(os, "Include ");
2267 string filename(normalize_filename(p.getArg('{', '}')));
2268 string const path = getMasterFilePath();
2269 // We want to preserve relative / absolute filenames,
2270 // therefore path is only used for testing
2271 // FIXME UNICODE encoding of filename and path may be
2272 // wrong (makeAbsPath expects utf8)
2273 if ((t.cs() == "include" || t.cs() == "input") &&
2274 !makeAbsPath(filename, path).exists()) {
2275 // The file extension is probably missing.
2276 // Now try to find it out.
2277 string const tex_name =
2278 find_file(filename, path,
2279 known_tex_extensions);
2280 if (!tex_name.empty())
2281 filename = tex_name;
2283 // FIXME UNICODE encoding of filename and path may be
2284 // wrong (makeAbsPath expects utf8)
2285 if (makeAbsPath(filename, path).exists()) {
2286 string const abstexname =
2287 makeAbsPath(filename, path).absFilename();
2288 string const abslyxname =
2289 changeExtension(abstexname, ".lyx");
2290 fix_relative_filename(filename);
2291 string const lyxname =
2292 changeExtension(filename, ".lyx");
2293 if (t.cs() != "verbatiminput" &&
2294 tex2lyx(abstexname, FileName(abslyxname))) {
2295 os << name << '{' << lyxname << "}\n";
2297 os << name << '{' << filename << "}\n";
2300 cerr << "Warning: Could not find included file '"
2301 << filename << "'." << endl;
2302 os << name << '{' << filename << "}\n";
2304 os << "preview false\n";
2308 else if (t.cs() == "bibliographystyle") {
2309 // store new bibliographystyle
2310 bibliographystyle = p.verbatim_item();
2311 // output new bibliographystyle.
2312 // This is only necessary if used in some other macro than \bibliography.
2313 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2316 else if (t.cs() == "bibliography") {
2317 context.check_layout(os);
2318 begin_inset(os, "LatexCommand ");
2320 // Do we have a bibliographystyle set?
2321 if (!bibliographystyle.empty()) {
2322 os << '[' << bibliographystyle << ']';
2324 os << '{' << p.verbatim_item() << "}\n";
2328 else if (t.cs() == "parbox")
2329 parse_box(p, os, FLAG_ITEM, outer, context, true);
2331 else if (t.cs() == "smallskip" ||
2332 t.cs() == "medskip" ||
2333 t.cs() == "bigskip" ||
2334 t.cs() == "vfill") {
2335 context.check_layout(os);
2336 begin_inset(os, "VSpace ");
2342 else if (is_known(t.cs(), known_spaces)) {
2343 char const * const * where = is_known(t.cs(), known_spaces);
2344 context.check_layout(os);
2345 begin_inset(os, "InsetSpace ");
2346 os << '\\' << known_coded_spaces[where - known_spaces]
2348 // LaTeX swallows whitespace after all spaces except
2349 // "\\,". We have to do that here, too, because LyX
2350 // adds "{}" which would make the spaces significant.
2352 eat_whitespace(p, os, context, false);
2353 // LyX adds "{}" after all spaces except "\\ " and
2354 // "\\,", so we have to remove "{}".
2355 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2356 // remove the braces after "\\,", too.
2361 else if (t.cs() == "newpage" ||
2362 t.cs() == "pagebreak" ||
2363 t.cs() == "clearpage" ||
2364 t.cs() == "cleardoublepage") {
2365 context.check_layout(os);
2366 os << "\n\\" << t.cs() << "\n";
2367 skip_braces(p); // eat {}
2370 else if (t.cs() == "newcommand" ||
2371 t.cs() == "providecommand" ||
2372 t.cs() == "renewcommand" ||
2373 t.cs() == "newlyxcommand") {
2374 // these could be handled by parse_command(), but
2375 // we need to call add_known_command() here.
2376 string name = t.asInput();
2377 if (p.next_token().asInput() == "*") {
2378 // Starred form. Eat '*'
2382 string const command = p.verbatim_item();
2383 string const opt1 = p.getOpt();
2385 unsigned optionalsNum = 0;
2387 string const opt = p.getFullOpt();
2393 add_known_command(command, opt1, optionalsNum);
2394 string const ert = name + '{' + command + '}' + opt1
2395 + optionals + '{' + p.verbatim_item() + '}';
2397 context.check_layout(os);
2398 begin_inset(os, "FormulaMacro");
2403 else if (t.cs() == "vspace") {
2404 bool starred = false;
2405 if (p.next_token().asInput() == "*") {
2409 string const length = p.verbatim_item();
2412 bool valid = splitLatexLength(length, valstring, unit);
2413 bool known_vspace = false;
2414 bool known_unit = false;
2417 istringstream iss(valstring);
2420 if (unit == "\\smallskipamount") {
2422 known_vspace = true;
2423 } else if (unit == "\\medskipamount") {
2425 known_vspace = true;
2426 } else if (unit == "\\bigskipamount") {
2428 known_vspace = true;
2429 } else if (unit == "\\fill") {
2431 known_vspace = true;
2434 if (!known_vspace) {
2435 switch (unitFromString(unit)) {
2456 if (known_unit || known_vspace) {
2457 // Literal length or known variable
2458 context.check_layout(os);
2459 begin_inset(os, "VSpace ");
2467 // LyX can't handle other length variables in Inset VSpace
2468 string name = t.asInput();
2473 handle_ert(os, name + '{' + unit + '}', context);
2474 else if (value == -1.0)
2475 handle_ert(os, name + "{-" + unit + '}', context);
2477 handle_ert(os, name + '{' + valstring + unit + '}', context);
2479 handle_ert(os, name + '{' + length + '}', context);
2484 //cerr << "#: " << t << " mode: " << mode << endl;
2485 // heuristic: read up to next non-nested space
2487 string s = t.asInput();
2488 string z = p.verbatim_item();
2489 while (p.good() && z != " " && z.size()) {
2490 //cerr << "read: " << z << endl;
2492 z = p.verbatim_item();
2494 cerr << "found ERT: " << s << endl;
2495 handle_ert(os, s + ' ', context);
2497 string name = t.asInput();
2498 if (p.next_token().asInput() == "*") {
2499 // Starred commands like \vspace*{}
2500 p.get_token(); // Eat '*'
2503 if (! parse_command(name, p, os, outer, context))
2504 handle_ert(os, name, context);
2507 if (flags & FLAG_LEAVE) {
2508 flags &= ~FLAG_LEAVE;