2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
20 #include "FloatList.h"
24 #include "support/convert.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/lstrings.h"
35 using namespace lyx::support;
40 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
41 Context const & context)
43 Context newcontext(true, context.textclass);
44 newcontext.font = context.font;
45 parse_text(p, os, flags, outer, newcontext);
46 newcontext.check_end_layout(os);
52 /// parses a paragraph snippet, useful for example for \\emph{...}
53 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
56 Context newcontext(context);
57 // Don't inherit the extra stuff
58 newcontext.extra_stuff.clear();
59 parse_text(p, os, flags, outer, newcontext);
60 // Make sure that we don't create invalid .lyx files
61 context.need_layout = newcontext.need_layout;
62 context.need_end_layout = newcontext.need_end_layout;
67 * Thin wrapper around parse_text_snippet() using a string.
69 * We completely ignore \c context.need_layout and \c context.need_end_layout,
70 * because our return value is not used directly (otherwise the stream version
71 * of parse_text_snippet() could be used). That means that the caller needs
72 * to do layout management manually.
73 * This is intended to parse text that does not create any layout changes.
75 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
78 Context newcontext(context);
79 newcontext.need_layout = false;
80 newcontext.need_end_layout = false;
81 newcontext.new_layout_allowed = false;
82 // Avoid warning by Context::~Context()
83 newcontext.extra_stuff.clear();
85 parse_text_snippet(p, os, flags, outer, newcontext);
90 char const * const known_latex_commands[] = { "ref", "cite", "nocite", "label",
91 "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
96 * We can't put these into known_latex_commands because the argument order
97 * is reversed in lyx if there are 2 arguments.
98 * The starred forms are also known.
100 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
101 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
102 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
106 * We can't put these into known_latex_commands because the argument order
107 * is reversed in lyx if there are 2 arguments.
108 * No starred form other than "cite*" known.
110 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
111 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
112 // jurabib commands not (yet) supported by LyX:
114 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
115 // "footciteauthor", "footciteyear", "footciteyearpar",
116 "citefield", "citetitle", "cite*", 0 };
118 /// LaTeX names for quotes
119 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
120 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
121 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
122 "guilsinglleft", "frq", "guilsinglright", 0};
124 /// the same as known_quotes with .lyx names
125 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
126 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
127 "gld", "grd", "gls", "ers", "fls",
128 "fls", "frs", "frs", 0};
130 /// LaTeX names for font sizes
131 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
132 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
134 /// the same as known_sizes with .lyx names
135 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
136 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
138 /// LaTeX 2.09 names for font families
139 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
141 /// LaTeX names for font families
142 char const * const known_font_families[] = { "rmfamily", "sffamily",
145 /// the same as known_old_font_families and known_font_families with .lyx names
146 char const * const known_coded_font_families[] = { "roman", "sans",
149 /// LaTeX 2.09 names for font series
150 char const * const known_old_font_series[] = { "bf", 0};
152 /// LaTeX names for font series
153 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
155 /// the same as known_old_font_series and known_font_series with .lyx names
156 char const * const known_coded_font_series[] = { "bold", "medium", 0};
158 /// LaTeX 2.09 names for font shapes
159 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
161 /// LaTeX names for font shapes
162 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
165 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
166 char const * const known_coded_font_shapes[] = { "italic", "slanted",
167 "smallcaps", "up", 0};
170 * Graphics file extensions known by the dvips driver of the graphics package.
171 * These extensions are used to complete the filename of an included
172 * graphics file if it does not contain an extension.
173 * The order must be the same that latex uses to find a file, because we
174 * will use the first extension that matches.
175 * This is only an approximation for the common cases. If we would want to
176 * do it right in all cases, we would need to know which graphics driver is
177 * used and know the extensions of every driver of the graphics package.
179 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
180 "ps.gz", "eps.Z", "ps.Z", 0};
183 * Graphics file extensions known by the pdftex driver of the graphics package.
184 * \sa known_dvips_graphics_formats
186 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
190 * Known file extensions for TeX files as used by \\include.
192 char const * const known_tex_extensions[] = {"tex", 0};
194 /// spaces known by InsetSpace
195 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
196 "qquad", "enspace", "enskip", "negthinspace", 0};
198 /// the same as known_spaces with .lyx names
199 char const * const known_coded_spaces[] = { "space{}", "space{}",
200 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
201 "negthinspace{}", 0};
204 /// splits "x=z, y=b" into a map
205 map<string, string> split_map(string const & s)
207 map<string, string> res;
210 for (size_t i = 0; i < v.size(); ++i) {
211 size_t const pos = v[i].find('=');
212 string const index = v[i].substr(0, pos);
213 string const value = v[i].substr(pos + 1, string::npos);
214 res[trim(index)] = trim(value);
221 * Split a LaTeX length into value and unit.
222 * The latter can be a real unit like "pt", or a latex length variable
223 * like "\textwidth". The unit may contain additional stuff like glue
224 * lengths, but we don't care, because such lengths are ERT anyway.
225 * \returns true if \p value and \p unit are valid.
227 bool splitLatexLength(string const & len, string & value, string & unit)
231 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
232 //'4,5' is a valid LaTeX length number. Change it to '4.5'
233 string const length = subst(len, ',', '.');
234 if (i == string::npos)
237 if (len[0] == '\\') {
238 // We had something like \textwidth without a factor
244 value = trim(string(length, 0, i));
248 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
249 if (contains(len, '\\'))
250 unit = trim(string(len, i));
252 unit = ascii_lowercase(trim(string(len, i)));
257 /// A simple function to translate a latex length to something lyx can
258 /// understand. Not perfect, but rather best-effort.
259 bool translate_len(string const & length, string & valstring, string & unit)
261 if (!splitLatexLength(length, valstring, unit))
263 // LyX uses percent values
265 istringstream iss(valstring);
270 string const percentval = oss.str();
272 if (unit.empty() || unit[0] != '\\')
274 string::size_type const i = unit.find(' ');
275 string const endlen = (i == string::npos) ? string() : string(unit, i);
276 if (unit == "\\textwidth") {
277 valstring = percentval;
278 unit = "text%" + endlen;
279 } else if (unit == "\\columnwidth") {
280 valstring = percentval;
281 unit = "col%" + endlen;
282 } else if (unit == "\\paperwidth") {
283 valstring = percentval;
284 unit = "page%" + endlen;
285 } else if (unit == "\\linewidth") {
286 valstring = percentval;
287 unit = "line%" + endlen;
288 } else if (unit == "\\paperheight") {
289 valstring = percentval;
290 unit = "pheight%" + endlen;
291 } else if (unit == "\\textheight") {
292 valstring = percentval;
293 unit = "theight%" + endlen;
301 string translate_len(string const & length)
305 if (translate_len(length, value, unit))
307 // If the input is invalid, return what we have.
315 * Translates a LaTeX length into \p value, \p unit and
316 * \p special parts suitable for a box inset.
317 * The difference from translate_len() is that a box inset knows about
318 * some special "units" that are stored in \p special.
320 void translate_box_len(string const & length, string & value, string & unit, string & special)
322 if (translate_len(length, value, unit)) {
323 if (unit == "\\height" || unit == "\\depth" ||
324 unit == "\\totalheight" || unit == "\\width") {
325 special = unit.substr(1);
326 // The unit is not used, but LyX requires a dummy setting
339 * Find a file with basename \p name in path \p path and an extension
342 string find_file(string const & name, string const & path,
343 char const * const * extensions)
345 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
347 for (char const * const * what = extensions; *what; ++what) {
348 string const trial = addExtension(name, *what);
349 if (makeAbsPath(trial, path).exists())
356 void begin_inset(ostream & os, string const & name)
358 os << "\n\\begin_inset " << name;
362 void end_inset(ostream & os)
364 os << "\n\\end_inset\n\n";
368 void skip_braces(Parser & p)
370 if (p.next_token().cat() != catBegin)
373 if (p.next_token().cat() == catEnd) {
381 void handle_ert(ostream & os, string const & s, Context & context)
383 // We must have a valid layout before outputting the ERT inset.
384 context.check_layout(os);
385 Context newcontext(true, context.textclass);
386 begin_inset(os, "ERT");
387 os << "\nstatus collapsed\n";
388 newcontext.check_layout(os);
389 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
391 os << "\n\\backslash\n";
392 else if (*it == '\n') {
393 newcontext.new_paragraph(os);
394 newcontext.check_layout(os);
398 newcontext.check_end_layout(os);
403 void handle_comment(ostream & os, string const & s, Context & context)
405 // TODO: Handle this better
406 Context newcontext(true, context.textclass);
407 begin_inset(os, "ERT");
408 os << "\nstatus collapsed\n";
409 newcontext.check_layout(os);
410 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
412 os << "\n\\backslash\n";
416 // make sure that our comment is the last thing on the line
417 newcontext.new_paragraph(os);
418 newcontext.check_layout(os);
419 newcontext.check_end_layout(os);
424 class isLayout : public unary_function<LayoutPtr, bool> {
426 isLayout(string const name) : name_(name) {}
427 bool operator()(LayoutPtr const & ptr) const {
428 return ptr->latexname() == name_;
435 LayoutPtr findLayout(TextClass const & textclass,
438 TextClass::const_iterator beg = textclass.begin();
439 TextClass::const_iterator end = textclass.end();
441 TextClass::const_iterator
442 it = find_if(beg, end, isLayout(name));
444 return (it == end) ? LayoutPtr() : *it;
448 void eat_whitespace(Parser &, ostream &, Context &, bool);
451 void output_command_layout(ostream & os, Parser & p, bool outer,
452 Context & parent_context,
455 parent_context.check_end_layout(os);
456 Context context(true, parent_context.textclass, newlayout,
457 parent_context.layout, parent_context.font);
458 if (parent_context.deeper_paragraph) {
459 // We are beginning a nested environment after a
460 // deeper paragraph inside the outer list environment.
461 // Therefore we don't need to output a "begin deeper".
462 context.need_end_deeper = true;
464 context.check_deeper(os);
465 context.check_layout(os);
466 if (context.layout->optionalargs > 0) {
467 eat_whitespace(p, os, context, false);
468 if (p.next_token().character() == '[') {
469 p.get_token(); // eat '['
470 begin_inset(os, "OptArg\n");
471 os << "status collapsed\n\n";
472 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
474 eat_whitespace(p, os, context, false);
477 parse_text(p, os, FLAG_ITEM, outer, context);
478 context.check_end_layout(os);
479 if (parent_context.deeper_paragraph) {
480 // We must suppress the "end deeper" because we
481 // suppressed the "begin deeper" above.
482 context.need_end_deeper = false;
484 context.check_end_deeper(os);
485 // We don't need really a new paragraph, but
486 // we must make sure that the next item gets a \begin_layout.
487 parent_context.new_paragraph(os);
492 * Output a space if necessary.
493 * This function gets called for every whitespace token.
495 * We have three cases here:
496 * 1. A space must be suppressed. Example: The lyxcode case below
497 * 2. A space may be suppressed. Example: Spaces before "\par"
498 * 3. A space must not be suppressed. Example: A space between two words
500 * We currently handle only 1. and 3 and from 2. only the case of
501 * spaces before newlines as a side effect.
503 * 2. could be used to suppress as many spaces as possible. This has two effects:
504 * - Reimporting LyX generated LaTeX files changes almost no whitespace
505 * - Superflous whitespace from non LyX generated LaTeX files is removed.
506 * The drawback is that the logic inside the function becomes
507 * complicated, and that is the reason why it is not implemented.
509 void check_space(Parser const & p, ostream & os, Context & context)
511 Token const next = p.next_token();
512 Token const curr = p.curr_token();
513 // A space before a single newline and vice versa must be ignored
514 // LyX emits a newline before \end{lyxcode}.
515 // This newline must be ignored,
516 // otherwise LyX will add an additional protected space.
517 if (next.cat() == catSpace ||
518 next.cat() == catNewline ||
519 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
522 context.check_layout(os);
528 * Parse all arguments of \p command
530 void parse_arguments(string const & command,
531 vector<ArgumentType> const & template_arguments,
532 Parser & p, ostream & os, bool outer, Context & context)
534 string ert = command;
535 size_t no_arguments = template_arguments.size();
536 for (size_t i = 0; i < no_arguments; ++i) {
537 switch (template_arguments[i]) {
539 // This argument contains regular LaTeX
540 handle_ert(os, ert + '{', context);
541 eat_whitespace(p, os, context, false);
542 parse_text(p, os, FLAG_ITEM, outer, context);
546 // This argument may contain special characters
547 ert += '{' + p.verbatim_item() + '}';
554 handle_ert(os, ert, context);
559 * Check whether \p command is a known command. If yes,
560 * handle the command with all arguments.
561 * \return true if the command was parsed, false otherwise.
563 bool parse_command(string const & command, Parser & p, ostream & os,
564 bool outer, Context & context)
566 if (known_commands.find(command) != known_commands.end()) {
567 parse_arguments(command, known_commands[command], p, os,
575 /// Parses a minipage or parbox
576 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
577 Context & parent_context, bool use_parbox)
581 // We need to set the height to the LaTeX default of 1\\totalheight
582 // for the case when no height argument is given
583 string height_value = "1";
584 string height_unit = "in";
585 string height_special = "totalheight";
587 if (p.next_token().asInput() == "[") {
588 position = p.getArg('[', ']');
589 if (position != "t" && position != "c" && position != "b") {
591 cerr << "invalid position for minipage/parbox" << endl;
593 if (p.next_token().asInput() == "[") {
594 latex_height = p.getArg('[', ']');
595 translate_box_len(latex_height, height_value, height_unit, height_special);
597 if (p.next_token().asInput() == "[") {
598 inner_pos = p.getArg('[', ']');
599 if (inner_pos != "c" && inner_pos != "t" &&
600 inner_pos != "b" && inner_pos != "s") {
601 inner_pos = position;
602 cerr << "invalid inner_pos for minipage/parbox"
610 string const latex_width = p.verbatim_item();
611 translate_len(latex_width, width_value, width_unit);
612 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
613 // LyX can't handle length variables
618 ss << "\\begin{minipage}";
619 if (!position.empty())
620 ss << '[' << position << ']';
621 if (!latex_height.empty())
622 ss << '[' << latex_height << ']';
623 if (!inner_pos.empty())
624 ss << '[' << inner_pos << ']';
625 ss << "{" << latex_width << "}";
628 handle_ert(os, ss.str(), parent_context);
629 parent_context.new_paragraph(os);
630 parse_text_in_inset(p, os, flags, outer, parent_context);
632 handle_ert(os, "}", parent_context);
634 handle_ert(os, "\\end{minipage}", parent_context);
636 // LyX does not like empty positions, so we have
637 // to set them to the LaTeX default values here.
638 if (position.empty())
640 if (inner_pos.empty())
641 inner_pos = position;
642 parent_context.check_layout(os);
643 begin_inset(os, "Box Frameless\n");
644 os << "position \"" << position << "\"\n";
645 os << "hor_pos \"c\"\n";
646 os << "has_inner_box 1\n";
647 os << "inner_pos \"" << inner_pos << "\"\n";
648 os << "use_parbox " << use_parbox << "\n";
649 os << "width \"" << width_value << width_unit << "\"\n";
650 os << "special \"none\"\n";
651 os << "height \"" << height_value << height_unit << "\"\n";
652 os << "height_special \"" << height_special << "\"\n";
653 os << "status open\n\n";
654 parse_text_in_inset(p, os, flags, outer, parent_context);
656 #ifdef PRESERVE_LAYOUT
657 // lyx puts a % after the end of the minipage
658 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
660 //handle_comment(os, "%dummy", parent_context);
663 parent_context.new_paragraph(os);
665 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
666 //handle_comment(os, "%dummy", parent_context);
669 // We add a protected space if something real follows
670 if (p.good() && p.next_token().cat() != catComment) {
671 os << "\\InsetSpace ~\n";
679 /// parse an unknown environment
680 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
681 unsigned flags, bool outer,
682 Context & parent_context)
684 if (name == "tabbing")
685 // We need to remember that we have to handle '\=' specially
686 flags |= FLAG_TABBING;
688 // We need to translate font changes and paragraphs inside the
689 // environment to ERT if we have a non standard font.
690 // Otherwise things like
691 // \large\begin{foo}\huge bar\end{foo}
693 bool const specialfont =
694 (parent_context.font != parent_context.normalfont);
695 bool const new_layout_allowed = parent_context.new_layout_allowed;
697 parent_context.new_layout_allowed = false;
698 handle_ert(os, "\\begin{" + name + "}", parent_context);
699 parse_text_snippet(p, os, flags, outer, parent_context);
700 handle_ert(os, "\\end{" + name + "}", parent_context);
702 parent_context.new_layout_allowed = new_layout_allowed;
706 void parse_environment(Parser & p, ostream & os, bool outer,
707 Context & parent_context)
710 string const name = p.getArg('{', '}');
711 const bool is_starred = suffixIs(name, '*');
712 string const unstarred_name = rtrim(name, "*");
713 active_environments.push_back(name);
715 if (is_math_env(name)) {
716 parent_context.check_layout(os);
717 begin_inset(os, "Formula ");
718 os << "\\begin{" << name << "}";
719 parse_math(p, os, FLAG_END, MATH_MODE);
720 os << "\\end{" << name << "}";
724 else if (name == "tabular" || name == "longtable") {
725 eat_whitespace(p, os, parent_context, false);
726 parent_context.check_layout(os);
727 begin_inset(os, "Tabular ");
728 handle_tabular(p, os, name == "longtable", parent_context);
733 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
734 eat_whitespace(p, os, parent_context, false);
735 parent_context.check_layout(os);
736 begin_inset(os, "Float " + unstarred_name + "\n");
737 if (p.next_token().asInput() == "[") {
738 os << "placement " << p.getArg('[', ']') << '\n';
740 os << "wide " << convert<string>(is_starred)
741 << "\nsideways false"
742 << "\nstatus open\n\n";
743 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
745 // We don't need really a new paragraph, but
746 // we must make sure that the next item gets a \begin_layout.
747 parent_context.new_paragraph(os);
751 else if (name == "minipage") {
752 eat_whitespace(p, os, parent_context, false);
753 parse_box(p, os, FLAG_END, outer, parent_context, false);
757 else if (name == "comment") {
758 eat_whitespace(p, os, parent_context, false);
759 parent_context.check_layout(os);
760 begin_inset(os, "Note Comment\n");
761 os << "status open\n";
762 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
767 else if (name == "lyxgreyedout") {
768 eat_whitespace(p, os, parent_context, false);
769 parent_context.check_layout(os);
770 begin_inset(os, "Note Greyedout\n");
771 os << "status open\n";
772 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
777 else if (name == "framed") {
778 eat_whitespace(p, os, parent_context, false);
779 parent_context.check_layout(os);
780 begin_inset(os, "Note Framed\n");
781 os << "status open\n";
782 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
787 else if (name == "shaded") {
788 eat_whitespace(p, os, parent_context, false);
789 parent_context.check_layout(os);
790 begin_inset(os, "Note Shaded\n");
791 os << "status open\n";
792 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
797 else if (!parent_context.new_layout_allowed)
798 parse_unknown_environment(p, name, os, FLAG_END, outer,
801 // Alignment settings
802 else if (name == "center" || name == "flushleft" || name == "flushright" ||
803 name == "centering" || name == "raggedright" || name == "raggedleft") {
804 eat_whitespace(p, os, parent_context, false);
805 // We must begin a new paragraph if not already done
806 if (! parent_context.atParagraphStart()) {
807 parent_context.check_end_layout(os);
808 parent_context.new_paragraph(os);
810 if (name == "flushleft" || name == "raggedright")
811 parent_context.add_extra_stuff("\\align left\n");
812 else if (name == "flushright" || name == "raggedleft")
813 parent_context.add_extra_stuff("\\align right\n");
815 parent_context.add_extra_stuff("\\align center\n");
816 parse_text(p, os, FLAG_END, outer, parent_context);
817 // Just in case the environment is empty ..
818 parent_context.extra_stuff.erase();
819 // We must begin a new paragraph to reset the alignment
820 parent_context.new_paragraph(os);
824 // The single '=' is meant here.
825 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
826 newlayout->isEnvironment()) {
827 eat_whitespace(p, os, parent_context, false);
828 Context context(true, parent_context.textclass, newlayout,
829 parent_context.layout, parent_context.font);
830 if (parent_context.deeper_paragraph) {
831 // We are beginning a nested environment after a
832 // deeper paragraph inside the outer list environment.
833 // Therefore we don't need to output a "begin deeper".
834 context.need_end_deeper = true;
836 parent_context.check_end_layout(os);
837 switch (context.layout->latextype) {
838 case LATEX_LIST_ENVIRONMENT:
839 context.extra_stuff = "\\labelwidthstring "
840 + p.verbatim_item() + '\n';
843 case LATEX_BIB_ENVIRONMENT:
844 p.verbatim_item(); // swallow next arg
850 context.check_deeper(os);
851 parse_text(p, os, FLAG_END, outer, context);
852 context.check_end_layout(os);
853 if (parent_context.deeper_paragraph) {
854 // We must suppress the "end deeper" because we
855 // suppressed the "begin deeper" above.
856 context.need_end_deeper = false;
858 context.check_end_deeper(os);
859 parent_context.new_paragraph(os);
863 else if (name == "appendix") {
864 // This is no good latex style, but it works and is used in some documents...
865 eat_whitespace(p, os, parent_context, false);
866 parent_context.check_end_layout(os);
867 Context context(true, parent_context.textclass, parent_context.layout,
868 parent_context.layout, parent_context.font);
869 context.check_layout(os);
870 os << "\\start_of_appendix\n";
871 parse_text(p, os, FLAG_END, outer, context);
872 context.check_end_layout(os);
876 else if (known_environments.find(name) != known_environments.end()) {
877 vector<ArgumentType> arguments = known_environments[name];
878 // The last "argument" denotes wether we may translate the
879 // environment contents to LyX
880 // The default required if no argument is given makes us
881 // compatible with the reLyXre environment.
882 ArgumentType contents = arguments.empty() ?
885 if (!arguments.empty())
886 arguments.pop_back();
887 // See comment in parse_unknown_environment()
888 bool const specialfont =
889 (parent_context.font != parent_context.normalfont);
890 bool const new_layout_allowed =
891 parent_context.new_layout_allowed;
893 parent_context.new_layout_allowed = false;
894 parse_arguments("\\begin{" + name + "}", arguments, p, os,
895 outer, parent_context);
896 if (contents == verbatim)
897 handle_ert(os, p.verbatimEnvironment(name),
900 parse_text_snippet(p, os, FLAG_END, outer,
902 handle_ert(os, "\\end{" + name + "}", parent_context);
904 parent_context.new_layout_allowed = new_layout_allowed;
908 parse_unknown_environment(p, name, os, FLAG_END, outer,
911 active_environments.pop_back();
915 /// parses a comment and outputs it to \p os.
916 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
918 BOOST_ASSERT(t.cat() == catComment);
919 if (!t.cs().empty()) {
920 context.check_layout(os);
921 handle_comment(os, '%' + t.cs(), context);
922 if (p.next_token().cat() == catNewline) {
923 // A newline after a comment line starts a new
925 if (context.new_layout_allowed) {
926 if(!context.atParagraphStart())
927 // Only start a new paragraph if not already
928 // done (we might get called recursively)
929 context.new_paragraph(os);
931 handle_ert(os, "\n", context);
932 eat_whitespace(p, os, context, true);
942 * Reads spaces and comments until the first non-space, non-comment token.
943 * New paragraphs (double newlines or \\par) are handled like simple spaces
944 * if \p eatParagraph is true.
945 * Spaces are skipped, but comments are written to \p os.
947 void eat_whitespace(Parser & p, ostream & os, Context & context,
951 Token const & t = p.get_token();
952 if (t.cat() == catComment)
953 parse_comment(p, os, t, context);
954 else if ((! eatParagraph && p.isParagraph()) ||
955 (t.cat() != catSpace && t.cat() != catNewline)) {
964 * Set a font attribute, parse text and reset the font attribute.
965 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
966 * \param currentvalue Current value of the attribute. Is set to the new
967 * value during parsing.
968 * \param newvalue New value of the attribute
970 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
971 Context & context, string const & attribute,
972 string & currentvalue, string const & newvalue)
974 context.check_layout(os);
975 string const oldvalue = currentvalue;
976 currentvalue = newvalue;
977 os << '\n' << attribute << ' ' << newvalue << "\n";
978 parse_text_snippet(p, os, flags, outer, context);
979 context.check_layout(os);
980 os << '\n' << attribute << ' ' << oldvalue << "\n";
981 currentvalue = oldvalue;
985 /// get the arguments of a natbib or jurabib citation command
986 void get_cite_arguments(Parser & p, bool natbibOrder,
987 string & before, string & after)
989 // We need to distinguish "" and "[]", so we can't use p.getOpt().
991 // text before the citation
993 // text after the citation
994 after = p.getFullOpt();
996 if (!after.empty()) {
997 before = p.getFullOpt();
998 if (natbibOrder && !before.empty())
1004 /// Convert filenames with TeX macros and/or quotes to something LyX
1006 string const normalize_filename(string const & name)
1008 Parser p(trim(name, "\""));
1011 Token const & t = p.get_token();
1012 if (t.cat() != catEscape)
1014 else if (t.cs() == "lyxdot") {
1015 // This is used by LyX for simple dots in relative
1019 } else if (t.cs() == "space") {
1029 /// Convert \p name from TeX convention (relative to master file) to LyX
1030 /// convention (relative to .lyx file) if it is relative
1031 void fix_relative_filename(string & name)
1033 FileName fname(name);
1034 if (fname.isAbsolute())
1037 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1039 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1040 from_utf8(getParentFilePath())));
1044 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1045 void parse_noweb(Parser & p, ostream & os, Context & context)
1047 // assemble the rest of the keyword
1051 Token const & t = p.get_token();
1052 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1055 scrap = (p.good() && p.next_token().asInput() == "=");
1057 name += p.get_token().asInput();
1060 name += t.asInput();
1063 if (!scrap || !context.new_layout_allowed ||
1064 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1065 cerr << "Warning: Could not interpret '" << name
1066 << "'. Ignoring it." << endl;
1070 // We use new_paragraph instead of check_end_layout because the stuff
1071 // following the noweb chunk needs to start with a \begin_layout.
1072 // This may create a new paragraph even if there was none in the
1073 // noweb file, but the alternative is an invalid LyX file. Since
1074 // noweb code chunks are implemented with a layout style in LyX they
1075 // always must be in an own paragraph.
1076 context.new_paragraph(os);
1077 Context newcontext(true, context.textclass,
1078 context.textclass[from_ascii("Scrap")]);
1079 newcontext.check_layout(os);
1082 Token const & t = p.get_token();
1083 // We abuse the parser a bit, because this is no TeX syntax
1085 if (t.cat() == catEscape)
1086 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1088 os << subst(t.asInput(), "\n", "\n\\newline\n");
1089 // The scrap chunk is ended by an @ at the beginning of a line.
1090 // After the @ the line may contain a comment and/or
1091 // whitespace, but nothing else.
1092 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1093 (p.next_token().cat() == catSpace ||
1094 p.next_token().cat() == catNewline ||
1095 p.next_token().cat() == catComment)) {
1096 while (p.good() && p.next_token().cat() == catSpace)
1097 os << p.get_token().asInput();
1098 if (p.next_token().cat() == catComment)
1099 // The comment includes a final '\n'
1100 os << p.get_token().asInput();
1102 if (p.next_token().cat() == catNewline)
1109 newcontext.check_end_layout(os);
1112 } // anonymous namespace
1115 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1118 LayoutPtr newlayout;
1119 // store the current selectlanguage to be used after \foreignlanguage
1121 // Store the latest bibliographystyle (needed for bibtex inset)
1122 string bibliographystyle;
1123 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1124 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1126 Token const & t = p.get_token();
1129 cerr << "t: " << t << " flags: " << flags << "\n";
1132 if (flags & FLAG_ITEM) {
1133 if (t.cat() == catSpace)
1136 flags &= ~FLAG_ITEM;
1137 if (t.cat() == catBegin) {
1138 // skip the brace and collect everything to the next matching
1140 flags |= FLAG_BRACE_LAST;
1144 // handle only this single token, leave the loop if done
1145 flags |= FLAG_LEAVE;
1148 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1154 if (t.cat() == catMath) {
1155 // we are inside some text mode thingy, so opening new math is allowed
1156 context.check_layout(os);
1157 begin_inset(os, "Formula ");
1158 Token const & n = p.get_token();
1159 if (n.cat() == catMath && outer) {
1160 // TeX's $$...$$ syntax for displayed math
1162 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1164 p.get_token(); // skip the second '$' token
1166 // simple $...$ stuff
1169 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1175 else if (t.cat() == catSuper || t.cat() == catSub)
1176 cerr << "catcode " << t << " illegal in text mode\n";
1178 // Basic support for english quotes. This should be
1179 // extended to other quotes, but is not so easy (a
1180 // left english quote is the same as a right german
1182 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1183 context.check_layout(os);
1184 begin_inset(os, "Quotes ");
1190 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1191 context.check_layout(os);
1192 begin_inset(os, "Quotes ");
1199 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1200 context.check_layout(os);
1201 begin_inset(os, "Quotes ");
1208 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1209 context.check_layout(os);
1210 begin_inset(os, "Quotes ");
1217 else if (t.asInput() == "<"
1218 && p.next_token().asInput() == "<" && noweb_mode) {
1220 parse_noweb(p, os, context);
1223 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1224 check_space(p, os, context);
1226 else if (t.character() == '[' && noweb_mode &&
1227 p.next_token().character() == '[') {
1228 // These can contain underscores
1230 string const s = p.getFullOpt() + ']';
1231 if (p.next_token().character() == ']')
1234 cerr << "Warning: Inserting missing ']' in '"
1235 << s << "'." << endl;
1236 handle_ert(os, s, context);
1239 else if (t.cat() == catLetter ||
1240 t.cat() == catOther ||
1241 t.cat() == catAlign ||
1242 t.cat() == catParameter) {
1243 // This translates "&" to "\\&" which may be wrong...
1244 context.check_layout(os);
1245 os << t.character();
1248 else if (p.isParagraph()) {
1249 if (context.new_layout_allowed)
1250 context.new_paragraph(os);
1252 handle_ert(os, "\\par ", context);
1253 eat_whitespace(p, os, context, true);
1256 else if (t.cat() == catActive) {
1257 context.check_layout(os);
1258 if (t.character() == '~') {
1259 if (context.layout->free_spacing)
1262 os << "\\InsetSpace ~\n";
1264 os << t.character();
1267 else if (t.cat() == catBegin &&
1268 p.next_token().cat() == catEnd) {
1270 Token const prev = p.prev_token();
1272 if (p.next_token().character() == '`' ||
1273 (prev.character() == '-' &&
1274 p.next_token().character() == '-'))
1275 ; // ignore it in {}`` or -{}-
1277 handle_ert(os, "{}", context);
1281 else if (t.cat() == catBegin) {
1282 context.check_layout(os);
1283 // special handling of font attribute changes
1284 Token const prev = p.prev_token();
1285 Token const next = p.next_token();
1286 TeXFont const oldFont = context.font;
1287 if (next.character() == '[' ||
1288 next.character() == ']' ||
1289 next.character() == '*') {
1291 if (p.next_token().cat() == catEnd) {
1292 os << next.character();
1296 handle_ert(os, "{", context);
1297 parse_text_snippet(p, os,
1300 handle_ert(os, "}", context);
1302 } else if (! context.new_layout_allowed) {
1303 handle_ert(os, "{", context);
1304 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1306 handle_ert(os, "}", context);
1307 } else if (is_known(next.cs(), known_sizes)) {
1308 // next will change the size, so we must
1310 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1312 if (!context.atParagraphStart())
1314 << context.font.size << "\n";
1315 } else if (is_known(next.cs(), known_font_families)) {
1316 // next will change the font family, so we
1317 // must reset it here
1318 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1320 if (!context.atParagraphStart())
1322 << context.font.family << "\n";
1323 } else if (is_known(next.cs(), known_font_series)) {
1324 // next will change the font series, so we
1325 // must reset it here
1326 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1328 if (!context.atParagraphStart())
1330 << context.font.series << "\n";
1331 } else if (is_known(next.cs(), known_font_shapes)) {
1332 // next will change the font shape, so we
1333 // must reset it here
1334 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1336 if (!context.atParagraphStart())
1338 << context.font.shape << "\n";
1339 } else if (is_known(next.cs(), known_old_font_families) ||
1340 is_known(next.cs(), known_old_font_series) ||
1341 is_known(next.cs(), known_old_font_shapes)) {
1342 // next will change the font family, series
1343 // and shape, so we must reset it here
1344 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1346 if (!context.atParagraphStart())
1348 << context.font.family
1350 << context.font.series
1352 << context.font.shape << "\n";
1354 handle_ert(os, "{", context);
1355 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1357 handle_ert(os, "}", context);
1361 else if (t.cat() == catEnd) {
1362 if (flags & FLAG_BRACE_LAST) {
1365 cerr << "stray '}' in text\n";
1366 handle_ert(os, "}", context);
1369 else if (t.cat() == catComment)
1370 parse_comment(p, os, t, context);
1373 // control sequences
1376 else if (t.cs() == "(") {
1377 context.check_layout(os);
1378 begin_inset(os, "Formula");
1380 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1385 else if (t.cs() == "[") {
1386 context.check_layout(os);
1387 begin_inset(os, "Formula");
1389 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1394 else if (t.cs() == "begin")
1395 parse_environment(p, os, outer, context);
1397 else if (t.cs() == "end") {
1398 if (flags & FLAG_END) {
1399 // eat environment name
1400 string const name = p.getArg('{', '}');
1401 if (name != active_environment())
1402 cerr << "\\end{" + name + "} does not match \\begin{"
1403 + active_environment() + "}\n";
1406 p.error("found 'end' unexpectedly");
1409 else if (t.cs() == "item") {
1412 bool optarg = false;
1413 if (p.next_token().character() == '[') {
1414 p.get_token(); // eat '['
1415 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1420 context.check_layout(os);
1421 if (context.has_item) {
1422 // An item in an unknown list-like environment
1423 // FIXME: Do this in check_layout()!
1424 context.has_item = false;
1426 handle_ert(os, "\\item", context);
1428 handle_ert(os, "\\item ", context);
1431 if (context.layout->labeltype != LABEL_MANUAL) {
1432 // lyx does not support \item[\mybullet]
1433 // in itemize environments
1434 handle_ert(os, "[", context);
1436 handle_ert(os, "]", context);
1437 } else if (!s.empty()) {
1438 // The space is needed to separate the
1439 // item from the rest of the sentence.
1441 eat_whitespace(p, os, context, false);
1446 else if (t.cs() == "bibitem") {
1448 context.check_layout(os);
1451 os << '{' << p.verbatim_item() << '}' << "\n";
1454 else if (t.cs() == "def") {
1455 context.check_layout(os);
1456 eat_whitespace(p, os, context, false);
1457 string name = p.get_token().cs();
1458 eat_whitespace(p, os, context, false);
1464 while (p.next_token().cat() != catBegin) {
1465 if (p.next_token().cat() == catParameter) {
1470 // followed by number?
1471 if (p.next_token().cat() == catOther) {
1472 char c = p.getChar();
1474 // number = current arity + 1?
1475 if (c == arity + '0' + 1)
1480 paramtext += p.get_token().asString();
1482 paramtext += p.get_token().asString();
1487 // only output simple (i.e. compatible) macro as FormulaMacros
1488 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1490 context.check_layout(os);
1491 begin_inset(os, "FormulaMacro");
1495 handle_ert(os, ert, context);
1498 else if (t.cs() == "noindent") {
1500 context.add_extra_stuff("\\noindent\n");
1503 else if (t.cs() == "appendix") {
1504 context.add_extra_stuff("\\start_of_appendix\n");
1505 // We need to start a new paragraph. Otherwise the
1506 // appendix in 'bla\appendix\chapter{' would start
1508 context.new_paragraph(os);
1509 // We need to make sure that the paragraph is
1510 // generated even if it is empty. Otherwise the
1511 // appendix in '\par\appendix\par\chapter{' would
1513 context.check_layout(os);
1514 // FIXME: This is a hack to prevent paragraph
1515 // deletion if it is empty. Handle this better!
1517 "%dummy comment inserted by tex2lyx to "
1518 "ensure that this paragraph is not empty",
1520 // Both measures above may generate an additional
1521 // empty paragraph, but that does not hurt, because
1522 // whitespace does not matter here.
1523 eat_whitespace(p, os, context, true);
1526 // Must attempt to parse "Section*" before "Section".
1527 else if ((p.next_token().asInput() == "*") &&
1528 context.new_layout_allowed &&
1529 // The single '=' is meant here.
1530 (newlayout = findLayout(context.textclass,
1531 t.cs() + '*')).get() &&
1532 newlayout->isCommand()) {
1534 output_command_layout(os, p, outer, context, newlayout);
1538 // The single '=' is meant here.
1539 else if (context.new_layout_allowed &&
1540 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1541 newlayout->isCommand()) {
1542 output_command_layout(os, p, outer, context, newlayout);
1546 // Special handling for \caption
1547 // FIXME: remove this when InsetCaption is supported.
1548 else if (context.new_layout_allowed &&
1549 t.cs() == captionlayout->latexname()) {
1550 output_command_layout(os, p, outer, context,
1555 else if (t.cs() == "includegraphics") {
1556 bool const clip = p.next_token().asInput() == "*";
1559 map<string, string> opts = split_map(p.getArg('[', ']'));
1561 opts["clip"] = string();
1562 string name = normalize_filename(p.verbatim_item());
1564 string const path = getMasterFilePath();
1565 // We want to preserve relative / absolute filenames,
1566 // therefore path is only used for testing
1567 // FIXME UNICODE encoding of name and path may be
1568 // wrong (makeAbsPath expects utf8)
1569 if (!makeAbsPath(name, path).exists()) {
1570 // The file extension is probably missing.
1571 // Now try to find it out.
1572 string const dvips_name =
1573 find_file(name, path,
1574 known_dvips_graphics_formats);
1575 string const pdftex_name =
1576 find_file(name, path,
1577 known_pdftex_graphics_formats);
1578 if (!dvips_name.empty()) {
1579 if (!pdftex_name.empty()) {
1580 cerr << "This file contains the "
1582 "\"\\includegraphics{"
1584 "However, files\n\""
1585 << dvips_name << "\" and\n\""
1586 << pdftex_name << "\"\n"
1587 "both exist, so I had to make a "
1588 "choice and took the first one.\n"
1589 "Please move the unwanted one "
1590 "someplace else and try again\n"
1591 "if my choice was wrong."
1595 } else if (!pdftex_name.empty())
1599 // FIXME UNICODE encoding of name and path may be
1600 // wrong (makeAbsPath expects utf8)
1601 if (makeAbsPath(name, path).exists())
1602 fix_relative_filename(name);
1604 cerr << "Warning: Could not find graphics file '"
1605 << name << "'." << endl;
1607 context.check_layout(os);
1608 begin_inset(os, "Graphics ");
1609 os << "\n\tfilename " << name << '\n';
1610 if (opts.find("width") != opts.end())
1612 << translate_len(opts["width"]) << '\n';
1613 if (opts.find("height") != opts.end())
1615 << translate_len(opts["height"]) << '\n';
1616 if (opts.find("scale") != opts.end()) {
1617 istringstream iss(opts["scale"]);
1621 os << "\tscale " << val << '\n';
1623 if (opts.find("angle") != opts.end())
1624 os << "\trotateAngle "
1625 << opts["angle"] << '\n';
1626 if (opts.find("origin") != opts.end()) {
1628 string const opt = opts["origin"];
1629 if (opt.find('l') != string::npos) ss << "left";
1630 if (opt.find('r') != string::npos) ss << "right";
1631 if (opt.find('c') != string::npos) ss << "center";
1632 if (opt.find('t') != string::npos) ss << "Top";
1633 if (opt.find('b') != string::npos) ss << "Bottom";
1634 if (opt.find('B') != string::npos) ss << "Baseline";
1635 if (!ss.str().empty())
1636 os << "\trotateOrigin " << ss.str() << '\n';
1638 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1640 if (opts.find("keepaspectratio") != opts.end())
1641 os << "\tkeepAspectRatio\n";
1642 if (opts.find("clip") != opts.end())
1644 if (opts.find("draft") != opts.end())
1646 if (opts.find("bb") != opts.end())
1647 os << "\tBoundingBox "
1648 << opts["bb"] << '\n';
1649 int numberOfbbOptions = 0;
1650 if (opts.find("bbllx") != opts.end())
1651 numberOfbbOptions++;
1652 if (opts.find("bblly") != opts.end())
1653 numberOfbbOptions++;
1654 if (opts.find("bburx") != opts.end())
1655 numberOfbbOptions++;
1656 if (opts.find("bbury") != opts.end())
1657 numberOfbbOptions++;
1658 if (numberOfbbOptions == 4)
1659 os << "\tBoundingBox "
1660 << opts["bbllx"] << " " << opts["bblly"] << " "
1661 << opts["bburx"] << " " << opts["bbury"] << '\n';
1662 else if (numberOfbbOptions > 0)
1663 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1664 numberOfbbOptions = 0;
1665 if (opts.find("natwidth") != opts.end())
1666 numberOfbbOptions++;
1667 if (opts.find("natheight") != opts.end())
1668 numberOfbbOptions++;
1669 if (numberOfbbOptions == 2)
1670 os << "\tBoundingBox 0bp 0bp "
1671 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1672 else if (numberOfbbOptions > 0)
1673 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1674 ostringstream special;
1675 if (opts.find("hiresbb") != opts.end())
1676 special << "hiresbb,";
1677 if (opts.find("trim") != opts.end())
1679 if (opts.find("viewport") != opts.end())
1680 special << "viewport=" << opts["viewport"] << ',';
1681 if (opts.find("totalheight") != opts.end())
1682 special << "totalheight=" << opts["totalheight"] << ',';
1683 if (opts.find("type") != opts.end())
1684 special << "type=" << opts["type"] << ',';
1685 if (opts.find("ext") != opts.end())
1686 special << "ext=" << opts["ext"] << ',';
1687 if (opts.find("read") != opts.end())
1688 special << "read=" << opts["read"] << ',';
1689 if (opts.find("command") != opts.end())
1690 special << "command=" << opts["command"] << ',';
1691 string s_special = special.str();
1692 if (!s_special.empty()) {
1693 // We had special arguments. Remove the trailing ','.
1694 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1696 // TODO: Handle the unknown settings better.
1697 // Warn about invalid options.
1698 // Check whether some option was given twice.
1702 else if (t.cs() == "footnote" ||
1703 (t.cs() == "thanks" && context.layout->intitle)) {
1705 context.check_layout(os);
1706 begin_inset(os, "Foot\n");
1707 os << "status collapsed\n\n";
1708 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1712 else if (t.cs() == "marginpar") {
1714 context.check_layout(os);
1715 begin_inset(os, "Marginal\n");
1716 os << "status collapsed\n\n";
1717 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1721 else if (t.cs() == "ensuremath") {
1723 context.check_layout(os);
1724 string const s = p.verbatim_item();
1725 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1728 handle_ert(os, "\\ensuremath{" + s + "}",
1732 else if (t.cs() == "hfill") {
1733 context.check_layout(os);
1734 os << "\n\\hfill\n";
1739 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1740 // FIXME: Somehow prevent title layouts if
1741 // "maketitle" was not found
1743 skip_braces(p); // swallow this
1746 else if (t.cs() == "tableofcontents") {
1748 context.check_layout(os);
1749 begin_inset(os, "LatexCommand \\tableofcontents\n");
1751 skip_braces(p); // swallow this
1754 else if (t.cs() == "listoffigures") {
1756 context.check_layout(os);
1757 begin_inset(os, "FloatList figure\n");
1759 skip_braces(p); // swallow this
1762 else if (t.cs() == "listoftables") {
1764 context.check_layout(os);
1765 begin_inset(os, "FloatList table\n");
1767 skip_braces(p); // swallow this
1770 else if (t.cs() == "listof") {
1771 p.skip_spaces(true);
1772 string const name = p.get_token().asString();
1773 if (context.textclass.floats().typeExist(name)) {
1774 context.check_layout(os);
1775 begin_inset(os, "FloatList ");
1778 p.get_token(); // swallow second arg
1780 handle_ert(os, "\\listof{" + name + "}", context);
1783 else if (t.cs() == "textrm")
1784 parse_text_attributes(p, os, FLAG_ITEM, outer,
1785 context, "\\family",
1786 context.font.family, "roman");
1788 else if (t.cs() == "textsf")
1789 parse_text_attributes(p, os, FLAG_ITEM, outer,
1790 context, "\\family",
1791 context.font.family, "sans");
1793 else if (t.cs() == "texttt")
1794 parse_text_attributes(p, os, FLAG_ITEM, outer,
1795 context, "\\family",
1796 context.font.family, "typewriter");
1798 else if (t.cs() == "textmd")
1799 parse_text_attributes(p, os, FLAG_ITEM, outer,
1800 context, "\\series",
1801 context.font.series, "medium");
1803 else if (t.cs() == "textbf")
1804 parse_text_attributes(p, os, FLAG_ITEM, outer,
1805 context, "\\series",
1806 context.font.series, "bold");
1808 else if (t.cs() == "textup")
1809 parse_text_attributes(p, os, FLAG_ITEM, outer,
1811 context.font.shape, "up");
1813 else if (t.cs() == "textit")
1814 parse_text_attributes(p, os, FLAG_ITEM, outer,
1816 context.font.shape, "italic");
1818 else if (t.cs() == "textsl")
1819 parse_text_attributes(p, os, FLAG_ITEM, outer,
1821 context.font.shape, "slanted");
1823 else if (t.cs() == "textsc")
1824 parse_text_attributes(p, os, FLAG_ITEM, outer,
1826 context.font.shape, "smallcaps");
1828 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1829 context.check_layout(os);
1830 TeXFont oldFont = context.font;
1831 context.font.init();
1832 context.font.size = oldFont.size;
1833 os << "\n\\family " << context.font.family << "\n";
1834 os << "\n\\series " << context.font.series << "\n";
1835 os << "\n\\shape " << context.font.shape << "\n";
1836 if (t.cs() == "textnormal") {
1837 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1838 output_font_change(os, context.font, oldFont);
1839 context.font = oldFont;
1841 eat_whitespace(p, os, context, false);
1844 else if (t.cs() == "underbar") {
1845 // Do NOT handle \underline.
1846 // \underbar cuts through y, g, q, p etc.,
1847 // \underline does not.
1848 context.check_layout(os);
1849 os << "\n\\bar under\n";
1850 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1851 context.check_layout(os);
1852 os << "\n\\bar default\n";
1855 else if (t.cs() == "emph" || t.cs() == "noun") {
1856 context.check_layout(os);
1857 os << "\n\\" << t.cs() << " on\n";
1858 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1859 context.check_layout(os);
1860 os << "\n\\" << t.cs() << " default\n";
1863 else if (use_natbib &&
1864 is_known(t.cs(), known_natbib_commands) &&
1865 ((t.cs() != "citefullauthor" &&
1866 t.cs() != "citeyear" &&
1867 t.cs() != "citeyearpar") ||
1868 p.next_token().asInput() != "*")) {
1869 context.check_layout(os);
1871 // \citet[before][after]{a} \citet[after][before]{a}
1872 // \citet[before][]{a} \citet[][before]{a}
1873 // \citet[after]{a} \citet[after]{a}
1874 // \citet{a} \citet{a}
1875 string command = '\\' + t.cs();
1876 if (p.next_token().asInput() == "*") {
1880 if (command == "\\citefullauthor")
1881 // alternative name for "\\citeauthor*"
1882 command = "\\citeauthor*";
1884 // text before the citation
1886 // text after the citation
1888 get_cite_arguments(p, true, before, after);
1890 if (command == "\\cite") {
1891 // \cite without optional argument means
1892 // \citet, \cite with at least one optional
1893 // argument means \citep.
1894 if (before.empty() && after.empty())
1895 command = "\\citet";
1897 command = "\\citep";
1899 if (before.empty() && after == "[]")
1900 // avoid \citet[]{a}
1902 else if (before == "[]" && after == "[]") {
1903 // avoid \citet[][]{a}
1907 begin_inset(os, "LatexCommand ");
1908 os << command << after << before
1909 << '{' << p.verbatim_item() << "}\n";
1913 else if (use_jurabib &&
1914 is_known(t.cs(), known_jurabib_commands)) {
1915 context.check_layout(os);
1916 string const command = '\\' + t.cs();
1917 char argumentOrder = '\0';
1918 vector<string> const & options = used_packages["jurabib"];
1919 if (find(options.begin(), options.end(),
1920 "natbiborder") != options.end())
1921 argumentOrder = 'n';
1922 else if (find(options.begin(), options.end(),
1923 "jurabiborder") != options.end())
1924 argumentOrder = 'j';
1926 // text before the citation
1928 // text after the citation
1930 get_cite_arguments(p, argumentOrder != 'j', before, after);
1932 string const citation = p.verbatim_item();
1933 if (!before.empty() && argumentOrder == '\0') {
1934 cerr << "Warning: Assuming argument order "
1935 "of jurabib version 0.6 for\n'"
1936 << command << before << after << '{'
1937 << citation << "}'.\n"
1938 "Add 'jurabiborder' to the jurabib "
1939 "package options if you used an\n"
1940 "earlier jurabib version." << endl;
1942 begin_inset(os, "LatexCommand ");
1943 os << command << after << before
1944 << '{' << citation << "}\n";
1948 else if (is_known(t.cs(), known_latex_commands)) {
1949 // This needs to be after the check for natbib and
1950 // jurabib commands, because "cite" has different
1951 // arguments with natbib and jurabib.
1952 context.check_layout(os);
1953 begin_inset(os, "LatexCommand ");
1954 os << '\\' << t.cs();
1955 // lyx cannot handle newlines in a latex command
1956 // FIXME: Move the substitution into parser::getOpt()?
1957 os << subst(p.getOpt(), "\n", " ");
1958 os << subst(p.getOpt(), "\n", " ");
1959 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1963 else if (is_known(t.cs(), known_quotes)) {
1964 char const * const * where = is_known(t.cs(), known_quotes);
1965 context.check_layout(os);
1966 begin_inset(os, "Quotes ");
1967 os << known_coded_quotes[where - known_quotes];
1969 // LyX adds {} after the quote, so we have to eat
1970 // spaces here if there are any before a possible
1972 eat_whitespace(p, os, context, false);
1976 else if (is_known(t.cs(), known_sizes) &&
1977 context.new_layout_allowed) {
1978 char const * const * where = is_known(t.cs(), known_sizes);
1979 context.check_layout(os);
1980 TeXFont const oldFont = context.font;
1981 context.font.size = known_coded_sizes[where - known_sizes];
1982 output_font_change(os, oldFont, context.font);
1983 eat_whitespace(p, os, context, false);
1986 else if (is_known(t.cs(), known_font_families) &&
1987 context.new_layout_allowed) {
1988 char const * const * where =
1989 is_known(t.cs(), known_font_families);
1990 context.check_layout(os);
1991 TeXFont const oldFont = context.font;
1992 context.font.family =
1993 known_coded_font_families[where - known_font_families];
1994 output_font_change(os, oldFont, context.font);
1995 eat_whitespace(p, os, context, false);
1998 else if (is_known(t.cs(), known_font_series) &&
1999 context.new_layout_allowed) {
2000 char const * const * where =
2001 is_known(t.cs(), known_font_series);
2002 context.check_layout(os);
2003 TeXFont const oldFont = context.font;
2004 context.font.series =
2005 known_coded_font_series[where - known_font_series];
2006 output_font_change(os, oldFont, context.font);
2007 eat_whitespace(p, os, context, false);
2010 else if (is_known(t.cs(), known_font_shapes) &&
2011 context.new_layout_allowed) {
2012 char const * const * where =
2013 is_known(t.cs(), known_font_shapes);
2014 context.check_layout(os);
2015 TeXFont const oldFont = context.font;
2016 context.font.shape =
2017 known_coded_font_shapes[where - known_font_shapes];
2018 output_font_change(os, oldFont, context.font);
2019 eat_whitespace(p, os, context, false);
2021 else if (is_known(t.cs(), known_old_font_families) &&
2022 context.new_layout_allowed) {
2023 char const * const * where =
2024 is_known(t.cs(), known_old_font_families);
2025 context.check_layout(os);
2026 TeXFont const oldFont = context.font;
2027 context.font.init();
2028 context.font.size = oldFont.size;
2029 context.font.family =
2030 known_coded_font_families[where - known_old_font_families];
2031 output_font_change(os, oldFont, context.font);
2032 eat_whitespace(p, os, context, false);
2035 else if (is_known(t.cs(), known_old_font_series) &&
2036 context.new_layout_allowed) {
2037 char const * const * where =
2038 is_known(t.cs(), known_old_font_series);
2039 context.check_layout(os);
2040 TeXFont const oldFont = context.font;
2041 context.font.init();
2042 context.font.size = oldFont.size;
2043 context.font.series =
2044 known_coded_font_series[where - known_old_font_series];
2045 output_font_change(os, oldFont, context.font);
2046 eat_whitespace(p, os, context, false);
2049 else if (is_known(t.cs(), known_old_font_shapes) &&
2050 context.new_layout_allowed) {
2051 char const * const * where =
2052 is_known(t.cs(), known_old_font_shapes);
2053 context.check_layout(os);
2054 TeXFont const oldFont = context.font;
2055 context.font.init();
2056 context.font.size = oldFont.size;
2057 context.font.shape =
2058 known_coded_font_shapes[where - known_old_font_shapes];
2059 output_font_change(os, oldFont, context.font);
2060 eat_whitespace(p, os, context, false);
2063 else if (t.cs() == "selectlanguage") {
2064 context.check_layout(os);
2065 // save the language for the case that a \foreignlanguage is used
2066 selectlang = subst(p.verbatim_item(), "\n", " ");
2067 os << "\\lang " << selectlang << "\n";
2071 else if (t.cs() == "foreignlanguage") {
2072 context.check_layout(os);
2073 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2074 os << subst(p.verbatim_item(), "\n", " ");
2075 // set back to last selectlanguage
2076 os << "\n\\lang " << selectlang << "\n";
2079 else if (t.cs() == "inputencoding")
2080 // write nothing because this is done by LyX using the "\lang"
2081 // information given by selectlanguage and foreignlanguage
2082 subst(p.verbatim_item(), "\n", " ");
2084 else if (t.cs() == "LyX" || t.cs() == "TeX"
2085 || t.cs() == "LaTeX") {
2086 context.check_layout(os);
2088 skip_braces(p); // eat {}
2091 else if (t.cs() == "LaTeXe") {
2092 context.check_layout(os);
2094 skip_braces(p); // eat {}
2097 else if (t.cs() == "ldots") {
2098 context.check_layout(os);
2100 os << "\\SpecialChar \\ldots{}\n";
2103 else if (t.cs() == "lyxarrow") {
2104 context.check_layout(os);
2105 os << "\\SpecialChar \\menuseparator\n";
2109 else if (t.cs() == "textcompwordmark") {
2110 context.check_layout(os);
2111 os << "\\SpecialChar \\textcompwordmark{}\n";
2115 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2116 context.check_layout(os);
2117 os << "\\SpecialChar \\@.\n";
2121 else if (t.cs() == "-") {
2122 context.check_layout(os);
2123 os << "\\SpecialChar \\-\n";
2126 else if (t.cs() == "textasciitilde") {
2127 context.check_layout(os);
2132 else if (t.cs() == "textasciicircum") {
2133 context.check_layout(os);
2138 else if (t.cs() == "textbackslash") {
2139 context.check_layout(os);
2140 os << "\n\\backslash\n";
2144 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2145 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2147 context.check_layout(os);
2151 else if (t.cs() == "char") {
2152 context.check_layout(os);
2153 if (p.next_token().character() == '`') {
2155 if (p.next_token().cs() == "\"") {
2160 handle_ert(os, "\\char`", context);
2163 handle_ert(os, "\\char", context);
2167 else if (t.cs() == "verb") {
2168 context.check_layout(os);
2169 char const delimiter = p.next_token().character();
2170 string const arg = p.getArg(delimiter, delimiter);
2172 oss << "\\verb" << delimiter << arg << delimiter;
2173 handle_ert(os, oss.str(), context);
2176 else if (t.cs() == "\"") {
2177 context.check_layout(os);
2178 string const name = p.verbatim_item();
2179 if (name == "a") os << '\xe4';
2180 else if (name == "o") os << '\xf6';
2181 else if (name == "u") os << '\xfc';
2182 else if (name == "A") os << '\xc4';
2183 else if (name == "O") os << '\xd6';
2184 else if (name == "U") os << '\xdc';
2185 else handle_ert(os, "\"{" + name + "}", context);
2188 // Problem: \= creates a tabstop inside the tabbing environment
2189 // and else an accent. In the latter case we really would want
2190 // \={o} instead of \= o.
2191 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2192 handle_ert(os, t.asInput(), context);
2194 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2195 || t.cs() == "'" || t.cs() == "`"
2196 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2197 // we need the trim as the LyX parser chokes on such spaces
2198 // The argument of InsetLatexAccent is parsed as a
2199 // subset of LaTeX, so don't parse anything here,
2200 // but use the raw argument.
2201 // Otherwise we would convert \~{\i} wrongly.
2202 // This will of course not translate \~{\ss} to \~{ß},
2203 // but that does at least compile and does only look
2204 // strange on screen.
2205 context.check_layout(os);
2206 os << "\\i \\" << t.cs() << "{"
2207 << trim(p.verbatim_item(), " ")
2211 else if (t.cs() == "ss") {
2212 context.check_layout(os);
2214 skip_braces(p); // eat {}
2217 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2219 context.check_layout(os);
2220 os << "\\i \\" << t.cs() << "{}\n";
2221 skip_braces(p); // eat {}
2224 else if (t.cs() == "\\") {
2225 context.check_layout(os);
2226 string const next = p.next_token().asInput();
2228 handle_ert(os, "\\\\" + p.getOpt(), context);
2229 else if (next == "*") {
2231 handle_ert(os, "\\\\*" + p.getOpt(), context);
2234 os << "\n\\newline\n";
2238 else if (t.cs() == "newline" ||
2239 t.cs() == "linebreak") {
2240 context.check_layout(os);
2241 os << "\n\\" << t.cs() << "\n";
2242 skip_braces(p); // eat {}
2245 else if (t.cs() == "href") {
2246 context.check_layout(os);
2247 begin_inset(os, "CommandInset ");
2248 os << t.cs() << "\n";
2249 os << "LatexCommand " << t.cs() << "\n";
2252 // the first argument is "type:target", "type:" is optional
2253 // the second argument the name
2254 string href_target = subst(p.verbatim_item(), "\n", " ");
2255 string href_name = subst(p.verbatim_item(), "\n", " ");
2257 // serach for the ":" to divide type from target
2258 if ((pos = href_target.find(":", 0)) != string::npos){
2259 href_type = href_target;
2260 href_type.erase(pos + 1, href_type.length());
2261 href_target.erase(0, pos + 1);
2264 os << "name " << '"' << href_name << '"' << "\n";
2265 os << "target " << '"' << href_target << '"' << "\n";
2267 os << "type " << '"' << href_type << '"' << "\n";
2271 else if (t.cs() == "input" || t.cs() == "include"
2272 || t.cs() == "verbatiminput") {
2273 string name = '\\' + t.cs();
2274 if (t.cs() == "verbatiminput"
2275 && p.next_token().asInput() == "*")
2276 name += p.get_token().asInput();
2277 context.check_layout(os);
2278 begin_inset(os, "Include ");
2279 string filename(normalize_filename(p.getArg('{', '}')));
2280 string const path = getMasterFilePath();
2281 // We want to preserve relative / absolute filenames,
2282 // therefore path is only used for testing
2283 // FIXME UNICODE encoding of filename and path may be
2284 // wrong (makeAbsPath expects utf8)
2285 if ((t.cs() == "include" || t.cs() == "input") &&
2286 !makeAbsPath(filename, path).exists()) {
2287 // The file extension is probably missing.
2288 // Now try to find it out.
2289 string const tex_name =
2290 find_file(filename, path,
2291 known_tex_extensions);
2292 if (!tex_name.empty())
2293 filename = tex_name;
2295 // FIXME UNICODE encoding of filename and path may be
2296 // wrong (makeAbsPath expects utf8)
2297 if (makeAbsPath(filename, path).exists()) {
2298 string const abstexname =
2299 makeAbsPath(filename, path).absFilename();
2300 string const abslyxname =
2301 changeExtension(abstexname, ".lyx");
2302 fix_relative_filename(filename);
2303 string const lyxname =
2304 changeExtension(filename, ".lyx");
2305 if (t.cs() != "verbatiminput" &&
2306 tex2lyx(abstexname, FileName(abslyxname))) {
2307 os << name << '{' << lyxname << "}\n";
2309 os << name << '{' << filename << "}\n";
2312 cerr << "Warning: Could not find included file '"
2313 << filename << "'." << endl;
2314 os << name << '{' << filename << "}\n";
2316 os << "preview false\n";
2320 else if (t.cs() == "bibliographystyle") {
2321 // store new bibliographystyle
2322 bibliographystyle = p.verbatim_item();
2323 // output new bibliographystyle.
2324 // This is only necessary if used in some other macro than \bibliography.
2325 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2328 else if (t.cs() == "bibliography") {
2329 context.check_layout(os);
2330 begin_inset(os, "LatexCommand ");
2332 // Do we have a bibliographystyle set?
2333 if (!bibliographystyle.empty()) {
2334 os << '[' << bibliographystyle << ']';
2336 os << '{' << p.verbatim_item() << "}\n";
2340 else if (t.cs() == "parbox")
2341 parse_box(p, os, FLAG_ITEM, outer, context, true);
2343 else if (t.cs() == "smallskip" ||
2344 t.cs() == "medskip" ||
2345 t.cs() == "bigskip" ||
2346 t.cs() == "vfill") {
2347 context.check_layout(os);
2348 begin_inset(os, "VSpace ");
2354 else if (is_known(t.cs(), known_spaces)) {
2355 char const * const * where = is_known(t.cs(), known_spaces);
2356 context.check_layout(os);
2357 begin_inset(os, "InsetSpace ");
2358 os << '\\' << known_coded_spaces[where - known_spaces]
2360 // LaTeX swallows whitespace after all spaces except
2361 // "\\,". We have to do that here, too, because LyX
2362 // adds "{}" which would make the spaces significant.
2364 eat_whitespace(p, os, context, false);
2365 // LyX adds "{}" after all spaces except "\\ " and
2366 // "\\,", so we have to remove "{}".
2367 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2368 // remove the braces after "\\,", too.
2373 else if (t.cs() == "newpage" ||
2374 t.cs() == "pagebreak" ||
2375 t.cs() == "clearpage" ||
2376 t.cs() == "cleardoublepage") {
2377 context.check_layout(os);
2378 os << "\n\\" << t.cs() << "\n";
2379 skip_braces(p); // eat {}
2382 else if (t.cs() == "newcommand" ||
2383 t.cs() == "providecommand" ||
2384 t.cs() == "renewcommand" ||
2385 t.cs() == "newlyxcommand") {
2386 // these could be handled by parse_command(), but
2387 // we need to call add_known_command() here.
2388 string name = t.asInput();
2389 if (p.next_token().asInput() == "*") {
2390 // Starred form. Eat '*'
2394 string const command = p.verbatim_item();
2395 string const opt1 = p.getOpt();
2397 unsigned optionalsNum = 0;
2399 string const opt = p.getFullOpt();
2405 add_known_command(command, opt1, optionalsNum);
2406 string const ert = name + '{' + command + '}' + opt1
2407 + optionals + '{' + p.verbatim_item() + '}';
2409 context.check_layout(os);
2410 begin_inset(os, "FormulaMacro");
2415 else if (t.cs() == "vspace") {
2416 bool starred = false;
2417 if (p.next_token().asInput() == "*") {
2421 string const length = p.verbatim_item();
2424 bool valid = splitLatexLength(length, valstring, unit);
2425 bool known_vspace = false;
2426 bool known_unit = false;
2429 istringstream iss(valstring);
2432 if (unit == "\\smallskipamount") {
2434 known_vspace = true;
2435 } else if (unit == "\\medskipamount") {
2437 known_vspace = true;
2438 } else if (unit == "\\bigskipamount") {
2440 known_vspace = true;
2441 } else if (unit == "\\fill") {
2443 known_vspace = true;
2446 if (!known_vspace) {
2447 switch (unitFromString(unit)) {
2468 if (known_unit || known_vspace) {
2469 // Literal length or known variable
2470 context.check_layout(os);
2471 begin_inset(os, "VSpace ");
2479 // LyX can't handle other length variables in Inset VSpace
2480 string name = t.asInput();
2485 handle_ert(os, name + '{' + unit + '}', context);
2486 else if (value == -1.0)
2487 handle_ert(os, name + "{-" + unit + '}', context);
2489 handle_ert(os, name + '{' + valstring + unit + '}', context);
2491 handle_ert(os, name + '{' + length + '}', context);
2496 //cerr << "#: " << t << " mode: " << mode << endl;
2497 // heuristic: read up to next non-nested space
2499 string s = t.asInput();
2500 string z = p.verbatim_item();
2501 while (p.good() && z != " " && z.size()) {
2502 //cerr << "read: " << z << endl;
2504 z = p.verbatim_item();
2506 cerr << "found ERT: " << s << endl;
2507 handle_ert(os, s + ' ', context);
2509 string name = t.asInput();
2510 if (p.next_token().asInput() == "*") {
2511 // Starred commands like \vspace*{}
2512 p.get_token(); // Eat '*'
2515 if (! parse_command(name, p, os, outer, context))
2516 handle_ert(os, name, context);
2519 if (flags & FLAG_LEAVE) {
2520 flags &= ~FLAG_LEAVE;