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>
38 using namespace lyx::support;
43 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
44 Context const & context)
46 Context newcontext(true, context.textclass);
47 newcontext.font = context.font;
48 parse_text(p, os, flags, outer, newcontext);
49 newcontext.check_end_layout(os);
55 /// parses a paragraph snippet, useful for example for \\emph{...}
56 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
59 Context newcontext(context);
60 // Don't inherit the extra stuff
61 newcontext.extra_stuff.clear();
62 parse_text(p, os, flags, outer, newcontext);
63 // Make sure that we don't create invalid .lyx files
64 context.need_layout = newcontext.need_layout;
65 context.need_end_layout = newcontext.need_end_layout;
70 * Thin wrapper around parse_text_snippet() using a string.
72 * We completely ignore \c context.need_layout and \c context.need_end_layout,
73 * because our return value is not used directly (otherwise the stream version
74 * of parse_text_snippet() could be used). That means that the caller needs
75 * to do layout management manually.
76 * This is intended to parse text that does not create any layout changes.
78 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
81 Context newcontext(context);
82 newcontext.need_layout = false;
83 newcontext.need_end_layout = false;
84 newcontext.new_layout_allowed = false;
85 // Avoid warning by Context::~Context()
86 newcontext.extra_stuff.clear();
88 parse_text_snippet(p, os, flags, outer, newcontext);
93 char const * const known_latex_commands[] = { "ref", "cite", "nocite", "label",
94 "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
99 * We can't put these into known_latex_commands because the argument order
100 * is reversed in lyx if there are 2 arguments.
101 * The starred forms are also known.
103 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
104 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
105 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
109 * We can't put these into known_latex_commands because the argument order
110 * is reversed in lyx if there are 2 arguments.
111 * No starred form other than "cite*" known.
113 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
114 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
115 // jurabib commands not (yet) supported by LyX:
117 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
118 // "footciteauthor", "footciteyear", "footciteyearpar",
119 "citefield", "citetitle", "cite*", 0 };
121 /// LaTeX names for quotes
122 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
123 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
124 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
125 "guilsinglleft", "frq", "guilsinglright", 0};
127 /// the same as known_quotes with .lyx names
128 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
129 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
130 "gld", "grd", "gls", "ers", "fls",
131 "fls", "frs", "frs", 0};
133 /// LaTeX names for font sizes
134 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
135 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
137 /// the same as known_sizes with .lyx names
138 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
139 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
141 /// LaTeX 2.09 names for font families
142 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
144 /// LaTeX names for font families
145 char const * const known_font_families[] = { "rmfamily", "sffamily",
148 /// the same as known_old_font_families and known_font_families with .lyx names
149 char const * const known_coded_font_families[] = { "roman", "sans",
152 /// LaTeX 2.09 names for font series
153 char const * const known_old_font_series[] = { "bf", 0};
155 /// LaTeX names for font series
156 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
158 /// the same as known_old_font_series and known_font_series with .lyx names
159 char const * const known_coded_font_series[] = { "bold", "medium", 0};
161 /// LaTeX 2.09 names for font shapes
162 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
164 /// LaTeX names for font shapes
165 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
168 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
169 char const * const known_coded_font_shapes[] = { "italic", "slanted",
170 "smallcaps", "up", 0};
173 * Graphics file extensions known by the dvips driver of the graphics package.
174 * These extensions are used to complete the filename of an included
175 * graphics file if it does not contain an extension.
176 * The order must be the same that latex uses to find a file, because we
177 * will use the first extension that matches.
178 * This is only an approximation for the common cases. If we would want to
179 * do it right in all cases, we would need to know which graphics driver is
180 * used and know the extensions of every driver of the graphics package.
182 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
183 "ps.gz", "eps.Z", "ps.Z", 0};
186 * Graphics file extensions known by the pdftex driver of the graphics package.
187 * \sa known_dvips_graphics_formats
189 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
193 * Known file extensions for TeX files as used by \\include.
195 char const * const known_tex_extensions[] = {"tex", 0};
197 /// spaces known by InsetSpace
198 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
199 "qquad", "enspace", "enskip", "negthinspace", 0};
201 /// the same as known_spaces with .lyx names
202 char const * const known_coded_spaces[] = { "space{}", "space{}",
203 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
204 "negthinspace{}", 0};
207 /// splits "x=z, y=b" into a map
208 map<string, string> split_map(string const & s)
210 map<string, string> res;
213 for (size_t i = 0; i < v.size(); ++i) {
214 size_t const pos = v[i].find('=');
215 string const index = v[i].substr(0, pos);
216 string const value = v[i].substr(pos + 1, string::npos);
217 res[trim(index)] = trim(value);
224 * Split a LaTeX length into value and unit.
225 * The latter can be a real unit like "pt", or a latex length variable
226 * like "\textwidth". The unit may contain additional stuff like glue
227 * lengths, but we don't care, because such lengths are ERT anyway.
228 * \returns true if \p value and \p unit are valid.
230 bool splitLatexLength(string const & len, string & value, string & unit)
234 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
235 //'4,5' is a valid LaTeX length number. Change it to '4.5'
236 string const length = subst(len, ',', '.');
237 if (i == string::npos)
240 if (len[0] == '\\') {
241 // We had something like \textwidth without a factor
247 value = trim(string(length, 0, i));
251 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
252 if (contains(len, '\\'))
253 unit = trim(string(len, i));
255 unit = ascii_lowercase(trim(string(len, i)));
260 /// A simple function to translate a latex length to something lyx can
261 /// understand. Not perfect, but rather best-effort.
262 bool translate_len(string const & length, string & valstring, string & unit)
264 if (!splitLatexLength(length, valstring, unit))
266 // LyX uses percent values
268 istringstream iss(valstring);
273 string const percentval = oss.str();
275 if (unit.empty() || unit[0] != '\\')
277 string::size_type const i = unit.find(' ');
278 string const endlen = (i == string::npos) ? string() : string(unit, i);
279 if (unit == "\\textwidth") {
280 valstring = percentval;
281 unit = "text%" + endlen;
282 } else if (unit == "\\columnwidth") {
283 valstring = percentval;
284 unit = "col%" + endlen;
285 } else if (unit == "\\paperwidth") {
286 valstring = percentval;
287 unit = "page%" + endlen;
288 } else if (unit == "\\linewidth") {
289 valstring = percentval;
290 unit = "line%" + endlen;
291 } else if (unit == "\\paperheight") {
292 valstring = percentval;
293 unit = "pheight%" + endlen;
294 } else if (unit == "\\textheight") {
295 valstring = percentval;
296 unit = "theight%" + endlen;
304 string translate_len(string const & length)
308 if (translate_len(length, value, unit))
310 // If the input is invalid, return what we have.
318 * Translates a LaTeX length into \p value, \p unit and
319 * \p special parts suitable for a box inset.
320 * The difference from translate_len() is that a box inset knows about
321 * some special "units" that are stored in \p special.
323 void translate_box_len(string const & length, string & value, string & unit, string & special)
325 if (translate_len(length, value, unit)) {
326 if (unit == "\\height" || unit == "\\depth" ||
327 unit == "\\totalheight" || unit == "\\width") {
328 special = unit.substr(1);
329 // The unit is not used, but LyX requires a dummy setting
342 * Find a file with basename \p name in path \p path and an extension
345 string find_file(string const & name, string const & path,
346 char const * const * extensions)
348 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
350 for (char const * const * what = extensions; *what; ++what) {
351 string const trial = addExtension(name, *what);
352 if (makeAbsPath(trial, path).exists())
359 void begin_inset(ostream & os, string const & name)
361 os << "\n\\begin_inset " << name;
365 void end_inset(ostream & os)
367 os << "\n\\end_inset\n\n";
371 void skip_braces(Parser & p)
373 if (p.next_token().cat() != catBegin)
376 if (p.next_token().cat() == catEnd) {
384 void handle_ert(ostream & os, string const & s, Context & context)
386 // We must have a valid layout before outputting the ERT inset.
387 context.check_layout(os);
388 Context newcontext(true, context.textclass);
389 begin_inset(os, "ERT");
390 os << "\nstatus collapsed\n";
391 newcontext.check_layout(os);
392 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
394 os << "\n\\backslash\n";
395 else if (*it == '\n') {
396 newcontext.new_paragraph(os);
397 newcontext.check_layout(os);
401 newcontext.check_end_layout(os);
406 void handle_comment(ostream & os, string const & s, Context & context)
408 // TODO: Handle this better
409 Context newcontext(true, context.textclass);
410 begin_inset(os, "ERT");
411 os << "\nstatus collapsed\n";
412 newcontext.check_layout(os);
413 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
415 os << "\n\\backslash\n";
419 // make sure that our comment is the last thing on the line
420 newcontext.new_paragraph(os);
421 newcontext.check_layout(os);
422 newcontext.check_end_layout(os);
427 LayoutPtr findLayout(TextClass const & textclass, string const & name)
429 DocumentClass::const_iterator lit = textclass.begin();
430 DocumentClass::const_iterator len = textclass.end();
431 for (; lit != len; ++lit)
432 if (lit->latexname() == name)
438 void eat_whitespace(Parser &, ostream &, Context &, bool);
441 void output_command_layout(ostream & os, Parser & p, bool outer,
442 Context & parent_context,
445 parent_context.check_end_layout(os);
446 Context context(true, parent_context.textclass, newlayout,
447 parent_context.layout, parent_context.font);
448 if (parent_context.deeper_paragraph) {
449 // We are beginning a nested environment after a
450 // deeper paragraph inside the outer list environment.
451 // Therefore we don't need to output a "begin deeper".
452 context.need_end_deeper = true;
454 context.check_deeper(os);
455 context.check_layout(os);
456 if (context.layout->optionalargs > 0) {
457 eat_whitespace(p, os, context, false);
458 if (p.next_token().character() == '[') {
459 p.get_token(); // eat '['
460 begin_inset(os, "OptArg\n");
461 os << "status collapsed\n\n";
462 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
464 eat_whitespace(p, os, context, false);
467 parse_text(p, os, FLAG_ITEM, outer, context);
468 context.check_end_layout(os);
469 if (parent_context.deeper_paragraph) {
470 // We must suppress the "end deeper" because we
471 // suppressed the "begin deeper" above.
472 context.need_end_deeper = false;
474 context.check_end_deeper(os);
475 // We don't need really a new paragraph, but
476 // we must make sure that the next item gets a \begin_layout.
477 parent_context.new_paragraph(os);
482 * Output a space if necessary.
483 * This function gets called for every whitespace token.
485 * We have three cases here:
486 * 1. A space must be suppressed. Example: The lyxcode case below
487 * 2. A space may be suppressed. Example: Spaces before "\par"
488 * 3. A space must not be suppressed. Example: A space between two words
490 * We currently handle only 1. and 3 and from 2. only the case of
491 * spaces before newlines as a side effect.
493 * 2. could be used to suppress as many spaces as possible. This has two effects:
494 * - Reimporting LyX generated LaTeX files changes almost no whitespace
495 * - Superflous whitespace from non LyX generated LaTeX files is removed.
496 * The drawback is that the logic inside the function becomes
497 * complicated, and that is the reason why it is not implemented.
499 void check_space(Parser const & p, ostream & os, Context & context)
501 Token const next = p.next_token();
502 Token const curr = p.curr_token();
503 // A space before a single newline and vice versa must be ignored
504 // LyX emits a newline before \end{lyxcode}.
505 // This newline must be ignored,
506 // otherwise LyX will add an additional protected space.
507 if (next.cat() == catSpace ||
508 next.cat() == catNewline ||
509 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
512 context.check_layout(os);
518 * Parse all arguments of \p command
520 void parse_arguments(string const & command,
521 vector<ArgumentType> const & template_arguments,
522 Parser & p, ostream & os, bool outer, Context & context)
524 string ert = command;
525 size_t no_arguments = template_arguments.size();
526 for (size_t i = 0; i < no_arguments; ++i) {
527 switch (template_arguments[i]) {
529 // This argument contains regular LaTeX
530 handle_ert(os, ert + '{', context);
531 eat_whitespace(p, os, context, false);
532 parse_text(p, os, FLAG_ITEM, outer, context);
536 // This argument may contain special characters
537 ert += '{' + p.verbatim_item() + '}';
544 handle_ert(os, ert, context);
549 * Check whether \p command is a known command. If yes,
550 * handle the command with all arguments.
551 * \return true if the command was parsed, false otherwise.
553 bool parse_command(string const & command, Parser & p, ostream & os,
554 bool outer, Context & context)
556 if (known_commands.find(command) != known_commands.end()) {
557 parse_arguments(command, known_commands[command], p, os,
565 /// Parses a minipage or parbox
566 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
567 Context & parent_context, bool use_parbox)
571 // We need to set the height to the LaTeX default of 1\\totalheight
572 // for the case when no height argument is given
573 string height_value = "1";
574 string height_unit = "in";
575 string height_special = "totalheight";
577 if (p.next_token().asInput() == "[") {
578 position = p.getArg('[', ']');
579 if (position != "t" && position != "c" && position != "b") {
581 cerr << "invalid position for minipage/parbox" << endl;
583 if (p.next_token().asInput() == "[") {
584 latex_height = p.getArg('[', ']');
585 translate_box_len(latex_height, height_value, height_unit, height_special);
587 if (p.next_token().asInput() == "[") {
588 inner_pos = p.getArg('[', ']');
589 if (inner_pos != "c" && inner_pos != "t" &&
590 inner_pos != "b" && inner_pos != "s") {
591 inner_pos = position;
592 cerr << "invalid inner_pos for minipage/parbox"
600 string const latex_width = p.verbatim_item();
601 translate_len(latex_width, width_value, width_unit);
602 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
603 // LyX can't handle length variables
608 ss << "\\begin{minipage}";
609 if (!position.empty())
610 ss << '[' << position << ']';
611 if (!latex_height.empty())
612 ss << '[' << latex_height << ']';
613 if (!inner_pos.empty())
614 ss << '[' << inner_pos << ']';
615 ss << "{" << latex_width << "}";
618 handle_ert(os, ss.str(), parent_context);
619 parent_context.new_paragraph(os);
620 parse_text_in_inset(p, os, flags, outer, parent_context);
622 handle_ert(os, "}", parent_context);
624 handle_ert(os, "\\end{minipage}", parent_context);
626 // LyX does not like empty positions, so we have
627 // to set them to the LaTeX default values here.
628 if (position.empty())
630 if (inner_pos.empty())
631 inner_pos = position;
632 parent_context.check_layout(os);
633 begin_inset(os, "Box Frameless\n");
634 os << "position \"" << position << "\"\n";
635 os << "hor_pos \"c\"\n";
636 os << "has_inner_box 1\n";
637 os << "inner_pos \"" << inner_pos << "\"\n";
638 os << "use_parbox " << use_parbox << "\n";
639 os << "width \"" << width_value << width_unit << "\"\n";
640 os << "special \"none\"\n";
641 os << "height \"" << height_value << height_unit << "\"\n";
642 os << "height_special \"" << height_special << "\"\n";
643 os << "status open\n\n";
644 parse_text_in_inset(p, os, flags, outer, parent_context);
646 #ifdef PRESERVE_LAYOUT
647 // lyx puts a % after the end of the minipage
648 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
650 //handle_comment(os, "%dummy", parent_context);
653 parent_context.new_paragraph(os);
655 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
656 //handle_comment(os, "%dummy", parent_context);
659 // We add a protected space if something real follows
660 if (p.good() && p.next_token().cat() != catComment) {
661 os << "\\InsetSpace ~\n";
669 /// parse an unknown environment
670 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
671 unsigned flags, bool outer,
672 Context & parent_context)
674 if (name == "tabbing")
675 // We need to remember that we have to handle '\=' specially
676 flags |= FLAG_TABBING;
678 // We need to translate font changes and paragraphs inside the
679 // environment to ERT if we have a non standard font.
680 // Otherwise things like
681 // \large\begin{foo}\huge bar\end{foo}
683 bool const specialfont =
684 (parent_context.font != parent_context.normalfont);
685 bool const new_layout_allowed = parent_context.new_layout_allowed;
687 parent_context.new_layout_allowed = false;
688 handle_ert(os, "\\begin{" + name + "}", parent_context);
689 parse_text_snippet(p, os, flags, outer, parent_context);
690 handle_ert(os, "\\end{" + name + "}", parent_context);
692 parent_context.new_layout_allowed = new_layout_allowed;
696 void parse_environment(Parser & p, ostream & os, bool outer,
697 Context & parent_context)
700 string const name = p.getArg('{', '}');
701 const bool is_starred = suffixIs(name, '*');
702 string const unstarred_name = rtrim(name, "*");
703 active_environments.push_back(name);
705 if (is_math_env(name)) {
706 parent_context.check_layout(os);
707 begin_inset(os, "Formula ");
708 os << "\\begin{" << name << "}";
709 parse_math(p, os, FLAG_END, MATH_MODE);
710 os << "\\end{" << name << "}";
714 else if (name == "tabular" || name == "longtable") {
715 eat_whitespace(p, os, parent_context, false);
716 parent_context.check_layout(os);
717 begin_inset(os, "Tabular ");
718 handle_tabular(p, os, name == "longtable", parent_context);
723 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
724 eat_whitespace(p, os, parent_context, false);
725 parent_context.check_layout(os);
726 begin_inset(os, "Float " + unstarred_name + "\n");
727 if (p.next_token().asInput() == "[") {
728 os << "placement " << p.getArg('[', ']') << '\n';
730 os << "wide " << convert<string>(is_starred)
731 << "\nsideways false"
732 << "\nstatus open\n\n";
733 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
735 // We don't need really a new paragraph, but
736 // we must make sure that the next item gets a \begin_layout.
737 parent_context.new_paragraph(os);
741 else if (name == "minipage") {
742 eat_whitespace(p, os, parent_context, false);
743 parse_box(p, os, FLAG_END, outer, parent_context, false);
747 else if (name == "comment") {
748 eat_whitespace(p, os, parent_context, false);
749 parent_context.check_layout(os);
750 begin_inset(os, "Note Comment\n");
751 os << "status open\n";
752 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
757 else if (name == "lyxgreyedout") {
758 eat_whitespace(p, os, parent_context, false);
759 parent_context.check_layout(os);
760 begin_inset(os, "Note Greyedout\n");
761 os << "status open\n";
762 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
767 else if (name == "framed") {
768 eat_whitespace(p, os, parent_context, false);
769 parent_context.check_layout(os);
770 begin_inset(os, "Note Framed\n");
771 os << "status open\n";
772 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
777 else if (name == "shaded") {
778 eat_whitespace(p, os, parent_context, false);
779 parent_context.check_layout(os);
780 begin_inset(os, "Note Shaded\n");
781 os << "status open\n";
782 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
787 else if (!parent_context.new_layout_allowed)
788 parse_unknown_environment(p, name, os, FLAG_END, outer,
791 // Alignment settings
792 else if (name == "center" || name == "flushleft" || name == "flushright" ||
793 name == "centering" || name == "raggedright" || name == "raggedleft") {
794 eat_whitespace(p, os, parent_context, false);
795 // We must begin a new paragraph if not already done
796 if (! parent_context.atParagraphStart()) {
797 parent_context.check_end_layout(os);
798 parent_context.new_paragraph(os);
800 if (name == "flushleft" || name == "raggedright")
801 parent_context.add_extra_stuff("\\align left\n");
802 else if (name == "flushright" || name == "raggedleft")
803 parent_context.add_extra_stuff("\\align right\n");
805 parent_context.add_extra_stuff("\\align center\n");
806 parse_text(p, os, FLAG_END, outer, parent_context);
807 // Just in case the environment is empty ..
808 parent_context.extra_stuff.erase();
809 // We must begin a new paragraph to reset the alignment
810 parent_context.new_paragraph(os);
814 // The single '=' is meant here.
815 else if ((newlayout = findLayout(parent_context.textclass, name)) &&
816 newlayout->isEnvironment()) {
817 eat_whitespace(p, os, parent_context, false);
818 Context context(true, parent_context.textclass, newlayout,
819 parent_context.layout, parent_context.font);
820 if (parent_context.deeper_paragraph) {
821 // We are beginning a nested environment after a
822 // deeper paragraph inside the outer list environment.
823 // Therefore we don't need to output a "begin deeper".
824 context.need_end_deeper = true;
826 parent_context.check_end_layout(os);
827 switch (context.layout->latextype) {
828 case LATEX_LIST_ENVIRONMENT:
829 context.extra_stuff = "\\labelwidthstring "
830 + p.verbatim_item() + '\n';
833 case LATEX_BIB_ENVIRONMENT:
834 p.verbatim_item(); // swallow next arg
840 context.check_deeper(os);
841 parse_text(p, os, FLAG_END, outer, context);
842 context.check_end_layout(os);
843 if (parent_context.deeper_paragraph) {
844 // We must suppress the "end deeper" because we
845 // suppressed the "begin deeper" above.
846 context.need_end_deeper = false;
848 context.check_end_deeper(os);
849 parent_context.new_paragraph(os);
853 else if (name == "appendix") {
854 // This is no good latex style, but it works and is used in some documents...
855 eat_whitespace(p, os, parent_context, false);
856 parent_context.check_end_layout(os);
857 Context context(true, parent_context.textclass, parent_context.layout,
858 parent_context.layout, parent_context.font);
859 context.check_layout(os);
860 os << "\\start_of_appendix\n";
861 parse_text(p, os, FLAG_END, outer, context);
862 context.check_end_layout(os);
866 else if (known_environments.find(name) != known_environments.end()) {
867 vector<ArgumentType> arguments = known_environments[name];
868 // The last "argument" denotes wether we may translate the
869 // environment contents to LyX
870 // The default required if no argument is given makes us
871 // compatible with the reLyXre environment.
872 ArgumentType contents = arguments.empty() ?
875 if (!arguments.empty())
876 arguments.pop_back();
877 // See comment in parse_unknown_environment()
878 bool const specialfont =
879 (parent_context.font != parent_context.normalfont);
880 bool const new_layout_allowed =
881 parent_context.new_layout_allowed;
883 parent_context.new_layout_allowed = false;
884 parse_arguments("\\begin{" + name + "}", arguments, p, os,
885 outer, parent_context);
886 if (contents == verbatim)
887 handle_ert(os, p.verbatimEnvironment(name),
890 parse_text_snippet(p, os, FLAG_END, outer,
892 handle_ert(os, "\\end{" + name + "}", parent_context);
894 parent_context.new_layout_allowed = new_layout_allowed;
898 parse_unknown_environment(p, name, os, FLAG_END, outer,
901 active_environments.pop_back();
905 /// parses a comment and outputs it to \p os.
906 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
908 BOOST_ASSERT(t.cat() == catComment);
909 if (!t.cs().empty()) {
910 context.check_layout(os);
911 handle_comment(os, '%' + t.cs(), context);
912 if (p.next_token().cat() == catNewline) {
913 // A newline after a comment line starts a new
915 if (context.new_layout_allowed) {
916 if(!context.atParagraphStart())
917 // Only start a new paragraph if not already
918 // done (we might get called recursively)
919 context.new_paragraph(os);
921 handle_ert(os, "\n", context);
922 eat_whitespace(p, os, context, true);
932 * Reads spaces and comments until the first non-space, non-comment token.
933 * New paragraphs (double newlines or \\par) are handled like simple spaces
934 * if \p eatParagraph is true.
935 * Spaces are skipped, but comments are written to \p os.
937 void eat_whitespace(Parser & p, ostream & os, Context & context,
941 Token const & t = p.get_token();
942 if (t.cat() == catComment)
943 parse_comment(p, os, t, context);
944 else if ((! eatParagraph && p.isParagraph()) ||
945 (t.cat() != catSpace && t.cat() != catNewline)) {
954 * Set a font attribute, parse text and reset the font attribute.
955 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
956 * \param currentvalue Current value of the attribute. Is set to the new
957 * value during parsing.
958 * \param newvalue New value of the attribute
960 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
961 Context & context, string const & attribute,
962 string & currentvalue, string const & newvalue)
964 context.check_layout(os);
965 string const oldvalue = currentvalue;
966 currentvalue = newvalue;
967 os << '\n' << attribute << ' ' << newvalue << "\n";
968 parse_text_snippet(p, os, flags, outer, context);
969 context.check_layout(os);
970 os << '\n' << attribute << ' ' << oldvalue << "\n";
971 currentvalue = oldvalue;
975 /// get the arguments of a natbib or jurabib citation command
976 void get_cite_arguments(Parser & p, bool natbibOrder,
977 string & before, string & after)
979 // We need to distinguish "" and "[]", so we can't use p.getOpt().
981 // text before the citation
983 // text after the citation
984 after = p.getFullOpt();
986 if (!after.empty()) {
987 before = p.getFullOpt();
988 if (natbibOrder && !before.empty())
994 /// Convert filenames with TeX macros and/or quotes to something LyX
996 string const normalize_filename(string const & name)
998 Parser p(trim(name, "\""));
1001 Token const & t = p.get_token();
1002 if (t.cat() != catEscape)
1004 else if (t.cs() == "lyxdot") {
1005 // This is used by LyX for simple dots in relative
1009 } else if (t.cs() == "space") {
1019 /// Convert \p name from TeX convention (relative to master file) to LyX
1020 /// convention (relative to .lyx file) if it is relative
1021 void fix_relative_filename(string & name)
1023 FileName fname(name);
1024 if (fname.isAbsolute())
1027 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1029 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1030 from_utf8(getParentFilePath())));
1034 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1035 void parse_noweb(Parser & p, ostream & os, Context & context)
1037 // assemble the rest of the keyword
1041 Token const & t = p.get_token();
1042 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1045 scrap = (p.good() && p.next_token().asInput() == "=");
1047 name += p.get_token().asInput();
1050 name += t.asInput();
1053 if (!scrap || !context.new_layout_allowed ||
1054 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1055 cerr << "Warning: Could not interpret '" << name
1056 << "'. Ignoring it." << endl;
1060 // We use new_paragraph instead of check_end_layout because the stuff
1061 // following the noweb chunk needs to start with a \begin_layout.
1062 // This may create a new paragraph even if there was none in the
1063 // noweb file, but the alternative is an invalid LyX file. Since
1064 // noweb code chunks are implemented with a layout style in LyX they
1065 // always must be in an own paragraph.
1066 context.new_paragraph(os);
1067 Context newcontext(true, context.textclass,
1068 &context.textclass[from_ascii("Scrap")]);
1069 newcontext.check_layout(os);
1072 Token const & t = p.get_token();
1073 // We abuse the parser a bit, because this is no TeX syntax
1075 if (t.cat() == catEscape)
1076 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1078 os << subst(t.asInput(), "\n", "\n\\newline\n");
1079 // The scrap chunk is ended by an @ at the beginning of a line.
1080 // After the @ the line may contain a comment and/or
1081 // whitespace, but nothing else.
1082 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1083 (p.next_token().cat() == catSpace ||
1084 p.next_token().cat() == catNewline ||
1085 p.next_token().cat() == catComment)) {
1086 while (p.good() && p.next_token().cat() == catSpace)
1087 os << p.get_token().asInput();
1088 if (p.next_token().cat() == catComment)
1089 // The comment includes a final '\n'
1090 os << p.get_token().asInput();
1092 if (p.next_token().cat() == catNewline)
1099 newcontext.check_end_layout(os);
1102 } // anonymous namespace
1105 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1108 LayoutPtr newlayout;
1109 // store the current selectlanguage to be used after \foreignlanguage
1111 // Store the latest bibliographystyle (needed for bibtex inset)
1112 string bibliographystyle;
1113 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1114 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1116 Token const & t = p.get_token();
1119 cerr << "t: " << t << " flags: " << flags << "\n";
1122 if (flags & FLAG_ITEM) {
1123 if (t.cat() == catSpace)
1126 flags &= ~FLAG_ITEM;
1127 if (t.cat() == catBegin) {
1128 // skip the brace and collect everything to the next matching
1130 flags |= FLAG_BRACE_LAST;
1134 // handle only this single token, leave the loop if done
1135 flags |= FLAG_LEAVE;
1138 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1144 if (t.cat() == catMath) {
1145 // we are inside some text mode thingy, so opening new math is allowed
1146 context.check_layout(os);
1147 begin_inset(os, "Formula ");
1148 Token const & n = p.get_token();
1149 if (n.cat() == catMath && outer) {
1150 // TeX's $$...$$ syntax for displayed math
1152 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1154 p.get_token(); // skip the second '$' token
1156 // simple $...$ stuff
1159 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1165 else if (t.cat() == catSuper || t.cat() == catSub)
1166 cerr << "catcode " << t << " illegal in text mode\n";
1168 // Basic support for english quotes. This should be
1169 // extended to other quotes, but is not so easy (a
1170 // left english quote is the same as a right german
1172 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1173 context.check_layout(os);
1174 begin_inset(os, "Quotes ");
1180 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1181 context.check_layout(os);
1182 begin_inset(os, "Quotes ");
1189 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1190 context.check_layout(os);
1191 begin_inset(os, "Quotes ");
1198 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1199 context.check_layout(os);
1200 begin_inset(os, "Quotes ");
1207 else if (t.asInput() == "<"
1208 && p.next_token().asInput() == "<" && noweb_mode) {
1210 parse_noweb(p, os, context);
1213 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1214 check_space(p, os, context);
1216 else if (t.character() == '[' && noweb_mode &&
1217 p.next_token().character() == '[') {
1218 // These can contain underscores
1220 string const s = p.getFullOpt() + ']';
1221 if (p.next_token().character() == ']')
1224 cerr << "Warning: Inserting missing ']' in '"
1225 << s << "'." << endl;
1226 handle_ert(os, s, context);
1229 else if (t.cat() == catLetter ||
1230 t.cat() == catOther ||
1231 t.cat() == catAlign ||
1232 t.cat() == catParameter) {
1233 // This translates "&" to "\\&" which may be wrong...
1234 context.check_layout(os);
1235 os << t.character();
1238 else if (p.isParagraph()) {
1239 if (context.new_layout_allowed)
1240 context.new_paragraph(os);
1242 handle_ert(os, "\\par ", context);
1243 eat_whitespace(p, os, context, true);
1246 else if (t.cat() == catActive) {
1247 context.check_layout(os);
1248 if (t.character() == '~') {
1249 if (context.layout->free_spacing)
1252 os << "\\InsetSpace ~\n";
1254 os << t.character();
1257 else if (t.cat() == catBegin &&
1258 p.next_token().cat() == catEnd) {
1260 Token const prev = p.prev_token();
1262 if (p.next_token().character() == '`' ||
1263 (prev.character() == '-' &&
1264 p.next_token().character() == '-'))
1265 ; // ignore it in {}`` or -{}-
1267 handle_ert(os, "{}", context);
1271 else if (t.cat() == catBegin) {
1272 context.check_layout(os);
1273 // special handling of font attribute changes
1274 Token const prev = p.prev_token();
1275 Token const next = p.next_token();
1276 TeXFont const oldFont = context.font;
1277 if (next.character() == '[' ||
1278 next.character() == ']' ||
1279 next.character() == '*') {
1281 if (p.next_token().cat() == catEnd) {
1282 os << next.character();
1286 handle_ert(os, "{", context);
1287 parse_text_snippet(p, os,
1290 handle_ert(os, "}", context);
1292 } else if (! context.new_layout_allowed) {
1293 handle_ert(os, "{", context);
1294 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1296 handle_ert(os, "}", context);
1297 } else if (is_known(next.cs(), known_sizes)) {
1298 // next will change the size, so we must
1300 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1302 if (!context.atParagraphStart())
1304 << context.font.size << "\n";
1305 } else if (is_known(next.cs(), known_font_families)) {
1306 // next will change the font family, so we
1307 // must reset it here
1308 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1310 if (!context.atParagraphStart())
1312 << context.font.family << "\n";
1313 } else if (is_known(next.cs(), known_font_series)) {
1314 // next will change the font series, so we
1315 // must reset it here
1316 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1318 if (!context.atParagraphStart())
1320 << context.font.series << "\n";
1321 } else if (is_known(next.cs(), known_font_shapes)) {
1322 // next will change the font shape, so we
1323 // must reset it here
1324 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1326 if (!context.atParagraphStart())
1328 << context.font.shape << "\n";
1329 } else if (is_known(next.cs(), known_old_font_families) ||
1330 is_known(next.cs(), known_old_font_series) ||
1331 is_known(next.cs(), known_old_font_shapes)) {
1332 // next will change the font family, series
1333 // and shape, so we must reset it here
1334 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1336 if (!context.atParagraphStart())
1338 << context.font.family
1340 << context.font.series
1342 << context.font.shape << "\n";
1344 handle_ert(os, "{", context);
1345 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1347 handle_ert(os, "}", context);
1351 else if (t.cat() == catEnd) {
1352 if (flags & FLAG_BRACE_LAST) {
1355 cerr << "stray '}' in text\n";
1356 handle_ert(os, "}", context);
1359 else if (t.cat() == catComment)
1360 parse_comment(p, os, t, context);
1363 // control sequences
1366 else if (t.cs() == "(") {
1367 context.check_layout(os);
1368 begin_inset(os, "Formula");
1370 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1375 else if (t.cs() == "[") {
1376 context.check_layout(os);
1377 begin_inset(os, "Formula");
1379 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1384 else if (t.cs() == "begin")
1385 parse_environment(p, os, outer, context);
1387 else if (t.cs() == "end") {
1388 if (flags & FLAG_END) {
1389 // eat environment name
1390 string const name = p.getArg('{', '}');
1391 if (name != active_environment())
1392 cerr << "\\end{" + name + "} does not match \\begin{"
1393 + active_environment() + "}\n";
1396 p.error("found 'end' unexpectedly");
1399 else if (t.cs() == "item") {
1402 bool optarg = false;
1403 if (p.next_token().character() == '[') {
1404 p.get_token(); // eat '['
1405 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1410 context.check_layout(os);
1411 if (context.has_item) {
1412 // An item in an unknown list-like environment
1413 // FIXME: Do this in check_layout()!
1414 context.has_item = false;
1416 handle_ert(os, "\\item", context);
1418 handle_ert(os, "\\item ", context);
1421 if (context.layout->labeltype != LABEL_MANUAL) {
1422 // lyx does not support \item[\mybullet]
1423 // in itemize environments
1424 handle_ert(os, "[", context);
1426 handle_ert(os, "]", context);
1427 } else if (!s.empty()) {
1428 // The space is needed to separate the
1429 // item from the rest of the sentence.
1431 eat_whitespace(p, os, context, false);
1436 else if (t.cs() == "bibitem") {
1438 context.check_layout(os);
1441 os << '{' << p.verbatim_item() << '}' << "\n";
1444 else if (t.cs() == "def") {
1445 context.check_layout(os);
1446 eat_whitespace(p, os, context, false);
1447 string name = p.get_token().cs();
1448 eat_whitespace(p, os, context, false);
1454 while (p.next_token().cat() != catBegin) {
1455 if (p.next_token().cat() == catParameter) {
1460 // followed by number?
1461 if (p.next_token().cat() == catOther) {
1462 char c = p.getChar();
1464 // number = current arity + 1?
1465 if (c == arity + '0' + 1)
1470 paramtext += p.get_token().asString();
1472 paramtext += p.get_token().asString();
1477 // only output simple (i.e. compatible) macro as FormulaMacros
1478 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1480 context.check_layout(os);
1481 begin_inset(os, "FormulaMacro");
1485 handle_ert(os, ert, context);
1488 else if (t.cs() == "noindent") {
1490 context.add_extra_stuff("\\noindent\n");
1493 else if (t.cs() == "appendix") {
1494 context.add_extra_stuff("\\start_of_appendix\n");
1495 // We need to start a new paragraph. Otherwise the
1496 // appendix in 'bla\appendix\chapter{' would start
1498 context.new_paragraph(os);
1499 // We need to make sure that the paragraph is
1500 // generated even if it is empty. Otherwise the
1501 // appendix in '\par\appendix\par\chapter{' would
1503 context.check_layout(os);
1504 // FIXME: This is a hack to prevent paragraph
1505 // deletion if it is empty. Handle this better!
1507 "%dummy comment inserted by tex2lyx to "
1508 "ensure that this paragraph is not empty",
1510 // Both measures above may generate an additional
1511 // empty paragraph, but that does not hurt, because
1512 // whitespace does not matter here.
1513 eat_whitespace(p, os, context, true);
1516 // Must attempt to parse "Section*" before "Section".
1517 else if ((p.next_token().asInput() == "*") &&
1518 context.new_layout_allowed &&
1519 // The single '=' is meant here.
1520 (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1521 newlayout->isCommand()) {
1523 output_command_layout(os, p, outer, context, newlayout);
1527 // The single '=' is meant here.
1528 else if (context.new_layout_allowed &&
1529 (newlayout = findLayout(context.textclass, t.cs())) &&
1530 newlayout->isCommand()) {
1531 output_command_layout(os, p, outer, context, newlayout);
1535 // Special handling for \caption
1536 // FIXME: remove this when InsetCaption is supported.
1537 else if (context.new_layout_allowed &&
1538 t.cs() == captionlayout->latexname()) {
1539 output_command_layout(os, p, outer, context,
1544 else if (t.cs() == "includegraphics") {
1545 bool const clip = p.next_token().asInput() == "*";
1548 map<string, string> opts = split_map(p.getArg('[', ']'));
1550 opts["clip"] = string();
1551 string name = normalize_filename(p.verbatim_item());
1553 string const path = getMasterFilePath();
1554 // We want to preserve relative / absolute filenames,
1555 // therefore path is only used for testing
1556 // FIXME UNICODE encoding of name and path may be
1557 // wrong (makeAbsPath expects utf8)
1558 if (!makeAbsPath(name, path).exists()) {
1559 // The file extension is probably missing.
1560 // Now try to find it out.
1561 string const dvips_name =
1562 find_file(name, path,
1563 known_dvips_graphics_formats);
1564 string const pdftex_name =
1565 find_file(name, path,
1566 known_pdftex_graphics_formats);
1567 if (!dvips_name.empty()) {
1568 if (!pdftex_name.empty()) {
1569 cerr << "This file contains the "
1571 "\"\\includegraphics{"
1573 "However, files\n\""
1574 << dvips_name << "\" and\n\""
1575 << pdftex_name << "\"\n"
1576 "both exist, so I had to make a "
1577 "choice and took the first one.\n"
1578 "Please move the unwanted one "
1579 "someplace else and try again\n"
1580 "if my choice was wrong."
1584 } else if (!pdftex_name.empty())
1588 // FIXME UNICODE encoding of name and path may be
1589 // wrong (makeAbsPath expects utf8)
1590 if (makeAbsPath(name, path).exists())
1591 fix_relative_filename(name);
1593 cerr << "Warning: Could not find graphics file '"
1594 << name << "'." << endl;
1596 context.check_layout(os);
1597 begin_inset(os, "Graphics ");
1598 os << "\n\tfilename " << name << '\n';
1599 if (opts.find("width") != opts.end())
1601 << translate_len(opts["width"]) << '\n';
1602 if (opts.find("height") != opts.end())
1604 << translate_len(opts["height"]) << '\n';
1605 if (opts.find("scale") != opts.end()) {
1606 istringstream iss(opts["scale"]);
1610 os << "\tscale " << val << '\n';
1612 if (opts.find("angle") != opts.end())
1613 os << "\trotateAngle "
1614 << opts["angle"] << '\n';
1615 if (opts.find("origin") != opts.end()) {
1617 string const opt = opts["origin"];
1618 if (opt.find('l') != string::npos) ss << "left";
1619 if (opt.find('r') != string::npos) ss << "right";
1620 if (opt.find('c') != string::npos) ss << "center";
1621 if (opt.find('t') != string::npos) ss << "Top";
1622 if (opt.find('b') != string::npos) ss << "Bottom";
1623 if (opt.find('B') != string::npos) ss << "Baseline";
1624 if (!ss.str().empty())
1625 os << "\trotateOrigin " << ss.str() << '\n';
1627 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1629 if (opts.find("keepaspectratio") != opts.end())
1630 os << "\tkeepAspectRatio\n";
1631 if (opts.find("clip") != opts.end())
1633 if (opts.find("draft") != opts.end())
1635 if (opts.find("bb") != opts.end())
1636 os << "\tBoundingBox "
1637 << opts["bb"] << '\n';
1638 int numberOfbbOptions = 0;
1639 if (opts.find("bbllx") != opts.end())
1640 numberOfbbOptions++;
1641 if (opts.find("bblly") != opts.end())
1642 numberOfbbOptions++;
1643 if (opts.find("bburx") != opts.end())
1644 numberOfbbOptions++;
1645 if (opts.find("bbury") != opts.end())
1646 numberOfbbOptions++;
1647 if (numberOfbbOptions == 4)
1648 os << "\tBoundingBox "
1649 << opts["bbllx"] << " " << opts["bblly"] << " "
1650 << opts["bburx"] << " " << opts["bbury"] << '\n';
1651 else if (numberOfbbOptions > 0)
1652 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1653 numberOfbbOptions = 0;
1654 if (opts.find("natwidth") != opts.end())
1655 numberOfbbOptions++;
1656 if (opts.find("natheight") != opts.end())
1657 numberOfbbOptions++;
1658 if (numberOfbbOptions == 2)
1659 os << "\tBoundingBox 0bp 0bp "
1660 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1661 else if (numberOfbbOptions > 0)
1662 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1663 ostringstream special;
1664 if (opts.find("hiresbb") != opts.end())
1665 special << "hiresbb,";
1666 if (opts.find("trim") != opts.end())
1668 if (opts.find("viewport") != opts.end())
1669 special << "viewport=" << opts["viewport"] << ',';
1670 if (opts.find("totalheight") != opts.end())
1671 special << "totalheight=" << opts["totalheight"] << ',';
1672 if (opts.find("type") != opts.end())
1673 special << "type=" << opts["type"] << ',';
1674 if (opts.find("ext") != opts.end())
1675 special << "ext=" << opts["ext"] << ',';
1676 if (opts.find("read") != opts.end())
1677 special << "read=" << opts["read"] << ',';
1678 if (opts.find("command") != opts.end())
1679 special << "command=" << opts["command"] << ',';
1680 string s_special = special.str();
1681 if (!s_special.empty()) {
1682 // We had special arguments. Remove the trailing ','.
1683 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1685 // TODO: Handle the unknown settings better.
1686 // Warn about invalid options.
1687 // Check whether some option was given twice.
1691 else if (t.cs() == "footnote" ||
1692 (t.cs() == "thanks" && context.layout->intitle)) {
1694 context.check_layout(os);
1695 begin_inset(os, "Foot\n");
1696 os << "status collapsed\n\n";
1697 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1701 else if (t.cs() == "marginpar") {
1703 context.check_layout(os);
1704 begin_inset(os, "Marginal\n");
1705 os << "status collapsed\n\n";
1706 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1710 else if (t.cs() == "ensuremath") {
1712 context.check_layout(os);
1713 string const s = p.verbatim_item();
1714 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1717 handle_ert(os, "\\ensuremath{" + s + "}",
1721 else if (t.cs() == "hfill") {
1722 context.check_layout(os);
1723 os << "\n\\hfill\n";
1728 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1729 // FIXME: Somehow prevent title layouts if
1730 // "maketitle" was not found
1732 skip_braces(p); // swallow this
1735 else if (t.cs() == "tableofcontents") {
1737 context.check_layout(os);
1738 begin_inset(os, "LatexCommand \\tableofcontents\n");
1740 skip_braces(p); // swallow this
1743 else if (t.cs() == "listoffigures") {
1745 context.check_layout(os);
1746 begin_inset(os, "FloatList figure\n");
1748 skip_braces(p); // swallow this
1751 else if (t.cs() == "listoftables") {
1753 context.check_layout(os);
1754 begin_inset(os, "FloatList table\n");
1756 skip_braces(p); // swallow this
1759 else if (t.cs() == "listof") {
1760 p.skip_spaces(true);
1761 string const name = p.get_token().asString();
1762 if (context.textclass.floats().typeExist(name)) {
1763 context.check_layout(os);
1764 begin_inset(os, "FloatList ");
1767 p.get_token(); // swallow second arg
1769 handle_ert(os, "\\listof{" + name + "}", context);
1772 else if (t.cs() == "textrm")
1773 parse_text_attributes(p, os, FLAG_ITEM, outer,
1774 context, "\\family",
1775 context.font.family, "roman");
1777 else if (t.cs() == "textsf")
1778 parse_text_attributes(p, os, FLAG_ITEM, outer,
1779 context, "\\family",
1780 context.font.family, "sans");
1782 else if (t.cs() == "texttt")
1783 parse_text_attributes(p, os, FLAG_ITEM, outer,
1784 context, "\\family",
1785 context.font.family, "typewriter");
1787 else if (t.cs() == "textmd")
1788 parse_text_attributes(p, os, FLAG_ITEM, outer,
1789 context, "\\series",
1790 context.font.series, "medium");
1792 else if (t.cs() == "textbf")
1793 parse_text_attributes(p, os, FLAG_ITEM, outer,
1794 context, "\\series",
1795 context.font.series, "bold");
1797 else if (t.cs() == "textup")
1798 parse_text_attributes(p, os, FLAG_ITEM, outer,
1800 context.font.shape, "up");
1802 else if (t.cs() == "textit")
1803 parse_text_attributes(p, os, FLAG_ITEM, outer,
1805 context.font.shape, "italic");
1807 else if (t.cs() == "textsl")
1808 parse_text_attributes(p, os, FLAG_ITEM, outer,
1810 context.font.shape, "slanted");
1812 else if (t.cs() == "textsc")
1813 parse_text_attributes(p, os, FLAG_ITEM, outer,
1815 context.font.shape, "smallcaps");
1817 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1818 context.check_layout(os);
1819 TeXFont oldFont = context.font;
1820 context.font.init();
1821 context.font.size = oldFont.size;
1822 os << "\n\\family " << context.font.family << "\n";
1823 os << "\n\\series " << context.font.series << "\n";
1824 os << "\n\\shape " << context.font.shape << "\n";
1825 if (t.cs() == "textnormal") {
1826 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1827 output_font_change(os, context.font, oldFont);
1828 context.font = oldFont;
1830 eat_whitespace(p, os, context, false);
1833 else if (t.cs() == "underbar") {
1834 // Do NOT handle \underline.
1835 // \underbar cuts through y, g, q, p etc.,
1836 // \underline does not.
1837 context.check_layout(os);
1838 os << "\n\\bar under\n";
1839 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1840 context.check_layout(os);
1841 os << "\n\\bar default\n";
1844 else if (t.cs() == "emph" || t.cs() == "noun") {
1845 context.check_layout(os);
1846 os << "\n\\" << t.cs() << " on\n";
1847 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1848 context.check_layout(os);
1849 os << "\n\\" << t.cs() << " default\n";
1852 else if (use_natbib &&
1853 is_known(t.cs(), known_natbib_commands) &&
1854 ((t.cs() != "citefullauthor" &&
1855 t.cs() != "citeyear" &&
1856 t.cs() != "citeyearpar") ||
1857 p.next_token().asInput() != "*")) {
1858 context.check_layout(os);
1860 // \citet[before][after]{a} \citet[after][before]{a}
1861 // \citet[before][]{a} \citet[][before]{a}
1862 // \citet[after]{a} \citet[after]{a}
1863 // \citet{a} \citet{a}
1864 string command = '\\' + t.cs();
1865 if (p.next_token().asInput() == "*") {
1869 if (command == "\\citefullauthor")
1870 // alternative name for "\\citeauthor*"
1871 command = "\\citeauthor*";
1873 // text before the citation
1875 // text after the citation
1877 get_cite_arguments(p, true, before, after);
1879 if (command == "\\cite") {
1880 // \cite without optional argument means
1881 // \citet, \cite with at least one optional
1882 // argument means \citep.
1883 if (before.empty() && after.empty())
1884 command = "\\citet";
1886 command = "\\citep";
1888 if (before.empty() && after == "[]")
1889 // avoid \citet[]{a}
1891 else if (before == "[]" && after == "[]") {
1892 // avoid \citet[][]{a}
1896 begin_inset(os, "LatexCommand ");
1897 os << command << after << before
1898 << '{' << p.verbatim_item() << "}\n";
1902 else if (use_jurabib &&
1903 is_known(t.cs(), known_jurabib_commands)) {
1904 context.check_layout(os);
1905 string const command = '\\' + t.cs();
1906 char argumentOrder = '\0';
1907 vector<string> const & options = used_packages["jurabib"];
1908 if (find(options.begin(), options.end(),
1909 "natbiborder") != options.end())
1910 argumentOrder = 'n';
1911 else if (find(options.begin(), options.end(),
1912 "jurabiborder") != options.end())
1913 argumentOrder = 'j';
1915 // text before the citation
1917 // text after the citation
1919 get_cite_arguments(p, argumentOrder != 'j', before, after);
1921 string const citation = p.verbatim_item();
1922 if (!before.empty() && argumentOrder == '\0') {
1923 cerr << "Warning: Assuming argument order "
1924 "of jurabib version 0.6 for\n'"
1925 << command << before << after << '{'
1926 << citation << "}'.\n"
1927 "Add 'jurabiborder' to the jurabib "
1928 "package options if you used an\n"
1929 "earlier jurabib version." << endl;
1931 begin_inset(os, "LatexCommand ");
1932 os << command << after << before
1933 << '{' << citation << "}\n";
1937 else if (is_known(t.cs(), known_latex_commands)) {
1938 // This needs to be after the check for natbib and
1939 // jurabib commands, because "cite" has different
1940 // arguments with natbib and jurabib.
1941 context.check_layout(os);
1942 begin_inset(os, "LatexCommand ");
1943 os << '\\' << t.cs();
1944 // lyx cannot handle newlines in a latex command
1945 // FIXME: Move the substitution into parser::getOpt()?
1946 os << subst(p.getOpt(), "\n", " ");
1947 os << subst(p.getOpt(), "\n", " ");
1948 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1952 else if (is_known(t.cs(), known_quotes)) {
1953 char const * const * where = is_known(t.cs(), known_quotes);
1954 context.check_layout(os);
1955 begin_inset(os, "Quotes ");
1956 os << known_coded_quotes[where - known_quotes];
1958 // LyX adds {} after the quote, so we have to eat
1959 // spaces here if there are any before a possible
1961 eat_whitespace(p, os, context, false);
1965 else if (is_known(t.cs(), known_sizes) &&
1966 context.new_layout_allowed) {
1967 char const * const * where = is_known(t.cs(), known_sizes);
1968 context.check_layout(os);
1969 TeXFont const oldFont = context.font;
1970 context.font.size = known_coded_sizes[where - known_sizes];
1971 output_font_change(os, oldFont, context.font);
1972 eat_whitespace(p, os, context, false);
1975 else if (is_known(t.cs(), known_font_families) &&
1976 context.new_layout_allowed) {
1977 char const * const * where =
1978 is_known(t.cs(), known_font_families);
1979 context.check_layout(os);
1980 TeXFont const oldFont = context.font;
1981 context.font.family =
1982 known_coded_font_families[where - known_font_families];
1983 output_font_change(os, oldFont, context.font);
1984 eat_whitespace(p, os, context, false);
1987 else if (is_known(t.cs(), known_font_series) &&
1988 context.new_layout_allowed) {
1989 char const * const * where =
1990 is_known(t.cs(), known_font_series);
1991 context.check_layout(os);
1992 TeXFont const oldFont = context.font;
1993 context.font.series =
1994 known_coded_font_series[where - known_font_series];
1995 output_font_change(os, oldFont, context.font);
1996 eat_whitespace(p, os, context, false);
1999 else if (is_known(t.cs(), known_font_shapes) &&
2000 context.new_layout_allowed) {
2001 char const * const * where =
2002 is_known(t.cs(), known_font_shapes);
2003 context.check_layout(os);
2004 TeXFont const oldFont = context.font;
2005 context.font.shape =
2006 known_coded_font_shapes[where - known_font_shapes];
2007 output_font_change(os, oldFont, context.font);
2008 eat_whitespace(p, os, context, false);
2010 else if (is_known(t.cs(), known_old_font_families) &&
2011 context.new_layout_allowed) {
2012 char const * const * where =
2013 is_known(t.cs(), known_old_font_families);
2014 context.check_layout(os);
2015 TeXFont const oldFont = context.font;
2016 context.font.init();
2017 context.font.size = oldFont.size;
2018 context.font.family =
2019 known_coded_font_families[where - known_old_font_families];
2020 output_font_change(os, oldFont, context.font);
2021 eat_whitespace(p, os, context, false);
2024 else if (is_known(t.cs(), known_old_font_series) &&
2025 context.new_layout_allowed) {
2026 char const * const * where =
2027 is_known(t.cs(), known_old_font_series);
2028 context.check_layout(os);
2029 TeXFont const oldFont = context.font;
2030 context.font.init();
2031 context.font.size = oldFont.size;
2032 context.font.series =
2033 known_coded_font_series[where - known_old_font_series];
2034 output_font_change(os, oldFont, context.font);
2035 eat_whitespace(p, os, context, false);
2038 else if (is_known(t.cs(), known_old_font_shapes) &&
2039 context.new_layout_allowed) {
2040 char const * const * where =
2041 is_known(t.cs(), known_old_font_shapes);
2042 context.check_layout(os);
2043 TeXFont const oldFont = context.font;
2044 context.font.init();
2045 context.font.size = oldFont.size;
2046 context.font.shape =
2047 known_coded_font_shapes[where - known_old_font_shapes];
2048 output_font_change(os, oldFont, context.font);
2049 eat_whitespace(p, os, context, false);
2052 else if (t.cs() == "selectlanguage") {
2053 context.check_layout(os);
2054 // save the language for the case that a \foreignlanguage is used
2055 selectlang = subst(p.verbatim_item(), "\n", " ");
2056 os << "\\lang " << selectlang << "\n";
2060 else if (t.cs() == "foreignlanguage") {
2061 context.check_layout(os);
2062 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2063 os << subst(p.verbatim_item(), "\n", " ");
2064 // set back to last selectlanguage
2065 os << "\n\\lang " << selectlang << "\n";
2068 else if (t.cs() == "inputencoding")
2069 // write nothing because this is done by LyX using the "\lang"
2070 // information given by selectlanguage and foreignlanguage
2071 subst(p.verbatim_item(), "\n", " ");
2073 else if (t.cs() == "LyX" || t.cs() == "TeX"
2074 || t.cs() == "LaTeX") {
2075 context.check_layout(os);
2077 skip_braces(p); // eat {}
2080 else if (t.cs() == "LaTeXe") {
2081 context.check_layout(os);
2083 skip_braces(p); // eat {}
2086 else if (t.cs() == "ldots") {
2087 context.check_layout(os);
2089 os << "\\SpecialChar \\ldots{}\n";
2092 else if (t.cs() == "lyxarrow") {
2093 context.check_layout(os);
2094 os << "\\SpecialChar \\menuseparator\n";
2098 else if (t.cs() == "textcompwordmark") {
2099 context.check_layout(os);
2100 os << "\\SpecialChar \\textcompwordmark{}\n";
2104 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2105 context.check_layout(os);
2106 os << "\\SpecialChar \\@.\n";
2110 else if (t.cs() == "-") {
2111 context.check_layout(os);
2112 os << "\\SpecialChar \\-\n";
2115 else if (t.cs() == "textasciitilde") {
2116 context.check_layout(os);
2121 else if (t.cs() == "textasciicircum") {
2122 context.check_layout(os);
2127 else if (t.cs() == "textbackslash") {
2128 context.check_layout(os);
2129 os << "\n\\backslash\n";
2133 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2134 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2136 context.check_layout(os);
2140 else if (t.cs() == "char") {
2141 context.check_layout(os);
2142 if (p.next_token().character() == '`') {
2144 if (p.next_token().cs() == "\"") {
2149 handle_ert(os, "\\char`", context);
2152 handle_ert(os, "\\char", context);
2156 else if (t.cs() == "verb") {
2157 context.check_layout(os);
2158 char const delimiter = p.next_token().character();
2159 string const arg = p.getArg(delimiter, delimiter);
2161 oss << "\\verb" << delimiter << arg << delimiter;
2162 handle_ert(os, oss.str(), context);
2165 else if (t.cs() == "\"") {
2166 context.check_layout(os);
2167 string const name = p.verbatim_item();
2168 if (name == "a") os << '\xe4';
2169 else if (name == "o") os << '\xf6';
2170 else if (name == "u") os << '\xfc';
2171 else if (name == "A") os << '\xc4';
2172 else if (name == "O") os << '\xd6';
2173 else if (name == "U") os << '\xdc';
2174 else handle_ert(os, "\"{" + name + "}", context);
2177 // Problem: \= creates a tabstop inside the tabbing environment
2178 // and else an accent. In the latter case we really would want
2179 // \={o} instead of \= o.
2180 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2181 handle_ert(os, t.asInput(), context);
2183 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2184 || t.cs() == "'" || t.cs() == "`"
2185 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2186 // we need the trim as the LyX parser chokes on such spaces
2187 // The argument of InsetLatexAccent is parsed as a
2188 // subset of LaTeX, so don't parse anything here,
2189 // but use the raw argument.
2190 // Otherwise we would convert \~{\i} wrongly.
2191 // This will of course not translate \~{\ss} to \~{ß},
2192 // but that does at least compile and does only look
2193 // strange on screen.
2194 context.check_layout(os);
2195 os << "\\i \\" << t.cs() << "{"
2196 << trim(p.verbatim_item(), " ")
2200 else if (t.cs() == "ss") {
2201 context.check_layout(os);
2203 skip_braces(p); // eat {}
2206 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2208 context.check_layout(os);
2209 os << "\\i \\" << t.cs() << "{}\n";
2210 skip_braces(p); // eat {}
2213 else if (t.cs() == "\\") {
2214 context.check_layout(os);
2215 string const next = p.next_token().asInput();
2217 handle_ert(os, "\\\\" + p.getOpt(), context);
2218 else if (next == "*") {
2220 handle_ert(os, "\\\\*" + p.getOpt(), context);
2223 os << "\n\\newline\n";
2227 else if (t.cs() == "newline" ||
2228 t.cs() == "linebreak") {
2229 context.check_layout(os);
2230 os << "\n\\" << t.cs() << "\n";
2231 skip_braces(p); // eat {}
2234 else if (t.cs() == "href") {
2235 context.check_layout(os);
2236 begin_inset(os, "CommandInset ");
2237 os << t.cs() << "\n";
2238 os << "LatexCommand " << t.cs() << "\n";
2241 // the first argument is "type:target", "type:" is optional
2242 // the second argument the name
2243 string href_target = subst(p.verbatim_item(), "\n", " ");
2244 string href_name = subst(p.verbatim_item(), "\n", " ");
2246 // serach for the ":" to divide type from target
2247 if ((pos = href_target.find(":", 0)) != string::npos){
2248 href_type = href_target;
2249 href_type.erase(pos + 1, href_type.length());
2250 href_target.erase(0, pos + 1);
2253 os << "name " << '"' << href_name << '"' << "\n";
2254 os << "target " << '"' << href_target << '"' << "\n";
2256 os << "type " << '"' << href_type << '"' << "\n";
2260 else if (t.cs() == "input" || t.cs() == "include"
2261 || t.cs() == "verbatiminput") {
2262 string name = '\\' + t.cs();
2263 if (t.cs() == "verbatiminput"
2264 && p.next_token().asInput() == "*")
2265 name += p.get_token().asInput();
2266 context.check_layout(os);
2267 begin_inset(os, "Include ");
2268 string filename(normalize_filename(p.getArg('{', '}')));
2269 string const path = getMasterFilePath();
2270 // We want to preserve relative / absolute filenames,
2271 // therefore path is only used for testing
2272 // FIXME UNICODE encoding of filename and path may be
2273 // wrong (makeAbsPath expects utf8)
2274 if ((t.cs() == "include" || t.cs() == "input") &&
2275 !makeAbsPath(filename, path).exists()) {
2276 // The file extension is probably missing.
2277 // Now try to find it out.
2278 string const tex_name =
2279 find_file(filename, path,
2280 known_tex_extensions);
2281 if (!tex_name.empty())
2282 filename = tex_name;
2284 // FIXME UNICODE encoding of filename and path may be
2285 // wrong (makeAbsPath expects utf8)
2286 if (makeAbsPath(filename, path).exists()) {
2287 string const abstexname =
2288 makeAbsPath(filename, path).absFilename();
2289 string const abslyxname =
2290 changeExtension(abstexname, ".lyx");
2291 fix_relative_filename(filename);
2292 string const lyxname =
2293 changeExtension(filename, ".lyx");
2294 if (t.cs() != "verbatiminput" &&
2295 tex2lyx(abstexname, FileName(abslyxname))) {
2296 os << name << '{' << lyxname << "}\n";
2298 os << name << '{' << filename << "}\n";
2301 cerr << "Warning: Could not find included file '"
2302 << filename << "'." << endl;
2303 os << name << '{' << filename << "}\n";
2305 os << "preview false\n";
2309 else if (t.cs() == "bibliographystyle") {
2310 // store new bibliographystyle
2311 bibliographystyle = p.verbatim_item();
2312 // output new bibliographystyle.
2313 // This is only necessary if used in some other macro than \bibliography.
2314 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2317 else if (t.cs() == "bibliography") {
2318 context.check_layout(os);
2319 begin_inset(os, "LatexCommand ");
2321 // Do we have a bibliographystyle set?
2322 if (!bibliographystyle.empty()) {
2323 os << '[' << bibliographystyle << ']';
2325 os << '{' << p.verbatim_item() << "}\n";
2329 else if (t.cs() == "parbox")
2330 parse_box(p, os, FLAG_ITEM, outer, context, true);
2332 else if (t.cs() == "smallskip" ||
2333 t.cs() == "medskip" ||
2334 t.cs() == "bigskip" ||
2335 t.cs() == "vfill") {
2336 context.check_layout(os);
2337 begin_inset(os, "VSpace ");
2343 else if (is_known(t.cs(), known_spaces)) {
2344 char const * const * where = is_known(t.cs(), known_spaces);
2345 context.check_layout(os);
2346 begin_inset(os, "InsetSpace ");
2347 os << '\\' << known_coded_spaces[where - known_spaces]
2349 // LaTeX swallows whitespace after all spaces except
2350 // "\\,". We have to do that here, too, because LyX
2351 // adds "{}" which would make the spaces significant.
2353 eat_whitespace(p, os, context, false);
2354 // LyX adds "{}" after all spaces except "\\ " and
2355 // "\\,", so we have to remove "{}".
2356 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2357 // remove the braces after "\\,", too.
2362 else if (t.cs() == "newpage" ||
2363 t.cs() == "pagebreak" ||
2364 t.cs() == "clearpage" ||
2365 t.cs() == "cleardoublepage") {
2366 context.check_layout(os);
2367 os << "\n\\" << t.cs() << "\n";
2368 skip_braces(p); // eat {}
2371 else if (t.cs() == "newcommand" ||
2372 t.cs() == "providecommand" ||
2373 t.cs() == "renewcommand" ||
2374 t.cs() == "newlyxcommand") {
2375 // these could be handled by parse_command(), but
2376 // we need to call add_known_command() here.
2377 string name = t.asInput();
2378 if (p.next_token().asInput() == "*") {
2379 // Starred form. Eat '*'
2383 string const command = p.verbatim_item();
2384 string const opt1 = p.getOpt();
2386 unsigned optionalsNum = 0;
2388 string const opt = p.getFullOpt();
2394 add_known_command(command, opt1, optionalsNum);
2395 string const ert = name + '{' + command + '}' + opt1
2396 + optionals + '{' + p.verbatim_item() + '}';
2398 context.check_layout(os);
2399 begin_inset(os, "FormulaMacro");
2404 else if (t.cs() == "vspace") {
2405 bool starred = false;
2406 if (p.next_token().asInput() == "*") {
2410 string const length = p.verbatim_item();
2413 bool valid = splitLatexLength(length, valstring, unit);
2414 bool known_vspace = false;
2415 bool known_unit = false;
2418 istringstream iss(valstring);
2421 if (unit == "\\smallskipamount") {
2423 known_vspace = true;
2424 } else if (unit == "\\medskipamount") {
2426 known_vspace = true;
2427 } else if (unit == "\\bigskipamount") {
2429 known_vspace = true;
2430 } else if (unit == "\\fill") {
2432 known_vspace = true;
2435 if (!known_vspace) {
2436 switch (unitFromString(unit)) {
2457 if (known_unit || known_vspace) {
2458 // Literal length or known variable
2459 context.check_layout(os);
2460 begin_inset(os, "VSpace ");
2468 // LyX can't handle other length variables in Inset VSpace
2469 string name = t.asInput();
2474 handle_ert(os, name + '{' + unit + '}', context);
2475 else if (value == -1.0)
2476 handle_ert(os, name + "{-" + unit + '}', context);
2478 handle_ert(os, name + '{' + valstring + unit + '}', context);
2480 handle_ert(os, name + '{' + length + '}', context);
2485 //cerr << "#: " << t << " mode: " << mode << endl;
2486 // heuristic: read up to next non-nested space
2488 string s = t.asInput();
2489 string z = p.verbatim_item();
2490 while (p.good() && z != " " && z.size()) {
2491 //cerr << "read: " << z << endl;
2493 z = p.verbatim_item();
2495 cerr << "found ERT: " << s << endl;
2496 handle_ert(os, s + ' ', context);
2498 string name = t.asInput();
2499 if (p.next_token().asInput() == "*") {
2500 // Starred commands like \vspace*{}
2501 p.get_token(); // Eat '*'
2504 if (! parse_command(name, p, os, outer, context))
2505 handle_ert(os, name, context);
2508 if (flags & FLAG_LEAVE) {
2509 flags &= ~FLAG_LEAVE;