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
9 * Full author contact details are available in file CREDITS.
19 #include "FloatList.h"
20 #include "lengthcommon.h"
21 #include "support/lstrings.h"
22 #include "support/convert.h"
23 #include "support/filetools.h"
25 #include <boost/filesystem/operations.hpp>
26 #include <boost/tuple/tuple.hpp>
38 using std::ostringstream;
39 using std::istringstream;
45 using support::addExtension;
46 using support::changeExtension;
47 using support::FileName;
48 using support::makeAbsPath;
49 using support::makeRelPath;
51 using support::suffixIs;
52 using support::contains;
55 namespace fs = boost::filesystem;
58 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
59 Context const & context)
61 Context newcontext(true, context.textclass);
62 newcontext.font = context.font;
63 parse_text(p, os, flags, outer, newcontext);
64 newcontext.check_end_layout(os);
70 /// parses a paragraph snippet, useful for example for \\emph{...}
71 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
74 Context newcontext(context);
75 // Don't inherit the extra stuff
76 newcontext.extra_stuff.clear();
77 parse_text(p, os, flags, outer, newcontext);
78 // Make sure that we don't create invalid .lyx files
79 context.need_layout = newcontext.need_layout;
80 context.need_end_layout = newcontext.need_end_layout;
85 * Thin wrapper around parse_text_snippet() using a string.
87 * We completely ignore \c context.need_layout and \c context.need_end_layout,
88 * because our return value is not used directly (otherwise the stream version
89 * of parse_text_snippet() could be used). That means that the caller needs
90 * to do layout management manually.
91 * This is intended to parse text that does not create any layout changes.
93 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
96 Context newcontext(context);
97 newcontext.need_layout = false;
98 newcontext.need_end_layout = false;
99 newcontext.new_layout_allowed = false;
100 // Avoid warning by Context::~Context()
101 newcontext.extra_stuff.clear();
103 parse_text_snippet(p, os, flags, outer, newcontext);
108 char const * const known_latex_commands[] = { "ref", "cite", "label", "href",
109 "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
114 * We can't put these into known_latex_commands because the argument order
115 * is reversed in lyx if there are 2 arguments.
116 * The starred forms are also known.
118 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
119 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
120 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
124 * We can't put these into known_latex_commands because the argument order
125 * is reversed in lyx if there are 2 arguments.
126 * No starred form other than "cite*" known.
128 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
129 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
130 // jurabib commands not (yet) supported by LyX:
132 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
133 // "footciteauthor", "footciteyear", "footciteyearpar",
134 "citefield", "citetitle", "cite*", 0 };
136 /// LaTeX names for quotes
137 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
138 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
140 /// the same as known_quotes with .lyx names
141 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
142 "grd", "gls", "fls", "frs", 0};
144 /// LaTeX names for font sizes
145 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
146 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
148 /// the same as known_sizes with .lyx names
149 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
150 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
152 /// LaTeX 2.09 names for font families
153 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
155 /// LaTeX names for font families
156 char const * const known_font_families[] = { "rmfamily", "sffamily",
159 /// the same as known_old_font_families and known_font_families with .lyx names
160 char const * const known_coded_font_families[] = { "roman", "sans",
163 /// LaTeX 2.09 names for font series
164 char const * const known_old_font_series[] = { "bf", 0};
166 /// LaTeX names for font series
167 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
169 /// the same as known_old_font_series and known_font_series with .lyx names
170 char const * const known_coded_font_series[] = { "bold", "medium", 0};
172 /// LaTeX 2.09 names for font shapes
173 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
175 /// LaTeX names for font shapes
176 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
179 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
180 char const * const known_coded_font_shapes[] = { "italic", "slanted",
181 "smallcaps", "up", 0};
184 * Graphics file extensions known by the dvips driver of the graphics package.
185 * These extensions are used to complete the filename of an included
186 * graphics file if it does not contain an extension.
187 * The order must be the same that latex uses to find a file, because we
188 * will use the first extension that matches.
189 * This is only an approximation for the common cases. If we would want to
190 * do it right in all cases, we would need to know which graphics driver is
191 * used and know the extensions of every driver of the graphics package.
193 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
194 "ps.gz", "eps.Z", "ps.Z", 0};
197 * Graphics file extensions known by the pdftex driver of the graphics package.
198 * \sa known_dvips_graphics_formats
200 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
204 * Known file extensions for TeX files as used by \\include.
206 char const * const known_tex_extensions[] = {"tex", 0};
208 /// spaces known by InsetSpace
209 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
210 "qquad", "enspace", "enskip", "negthinspace", 0};
212 /// the same as known_spaces with .lyx names
213 char const * const known_coded_spaces[] = { "space{}", "space{}",
214 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
215 "negthinspace{}", 0};
218 /// splits "x=z, y=b" into a map
219 map<string, string> split_map(string const & s)
221 map<string, string> res;
224 for (size_t i = 0; i < v.size(); ++i) {
225 size_t const pos = v[i].find('=');
226 string const index = v[i].substr(0, pos);
227 string const value = v[i].substr(pos + 1, string::npos);
228 res[trim(index)] = trim(value);
235 * Split a LaTeX length into value and unit.
236 * The latter can be a real unit like "pt", or a latex length variable
237 * like "\textwidth". The unit may contain additional stuff like glue
238 * lengths, but we don't care, because such lengths are ERT anyway.
239 * \returns true if \p value and \p unit are valid.
241 bool splitLatexLength(string const & len, string & value, string & unit)
245 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
246 //'4,5' is a valid LaTeX length number. Change it to '4.5'
247 string const length = subst(len, ',', '.');
248 if (i == string::npos)
251 if (len[0] == '\\') {
252 // We had something like \textwidth without a factor
258 value = trim(string(length, 0, i));
262 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
263 if (contains(len, '\\'))
264 unit = trim(string(len, i));
266 unit = support::ascii_lowercase(trim(string(len, i)));
271 /// A simple function to translate a latex length to something lyx can
272 /// understand. Not perfect, but rather best-effort.
273 bool translate_len(string const & length, string & valstring, string & unit)
275 if (!splitLatexLength(length, valstring, unit))
277 // LyX uses percent values
279 istringstream iss(valstring);
284 string const percentval = oss.str();
286 if (unit.empty() || unit[0] != '\\')
288 string::size_type const i = unit.find(' ');
289 string const endlen = (i == string::npos) ? string() : string(unit, i);
290 if (unit == "\\textwidth") {
291 valstring = percentval;
292 unit = "text%" + endlen;
293 } else if (unit == "\\columnwidth") {
294 valstring = percentval;
295 unit = "col%" + endlen;
296 } else if (unit == "\\paperwidth") {
297 valstring = percentval;
298 unit = "page%" + endlen;
299 } else if (unit == "\\linewidth") {
300 valstring = percentval;
301 unit = "line%" + endlen;
302 } else if (unit == "\\paperheight") {
303 valstring = percentval;
304 unit = "pheight%" + endlen;
305 } else if (unit == "\\textheight") {
306 valstring = percentval;
307 unit = "theight%" + endlen;
315 string translate_len(string const & length)
319 if (translate_len(length, value, unit))
321 // If the input is invalid, return what we have.
329 * Translates a LaTeX length into \p value, \p unit and
330 * \p special parts suitable for a box inset.
331 * The difference from translate_len() is that a box inset knows about
332 * some special "units" that are stored in \p special.
334 void translate_box_len(string const & length, string & value, string & unit, string & special)
336 if (translate_len(length, value, unit)) {
337 if (unit == "\\height" || unit == "\\depth" ||
338 unit == "\\totalheight" || unit == "\\width") {
339 special = unit.substr(1);
340 // The unit is not used, but LyX requires a dummy setting
353 * Find a file with basename \p name in path \p path and an extension
356 string find_file(string const & name, string const & path,
357 char const * const * extensions)
359 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
361 for (char const * const * what = extensions; *what; ++what) {
362 string const trial = addExtension(name, *what);
363 if (fs::exists(makeAbsPath(trial, path).toFilesystemEncoding()))
370 void begin_inset(ostream & os, string const & name)
372 os << "\n\\begin_inset " << name;
376 void end_inset(ostream & os)
378 os << "\n\\end_inset\n\n";
382 void skip_braces(Parser & p)
384 if (p.next_token().cat() != catBegin)
387 if (p.next_token().cat() == catEnd) {
395 void handle_ert(ostream & os, string const & s, Context & context)
397 // We must have a valid layout before outputting the ERT inset.
398 context.check_layout(os);
399 Context newcontext(true, context.textclass);
400 begin_inset(os, "ERT");
401 os << "\nstatus collapsed\n";
402 newcontext.check_layout(os);
403 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
405 os << "\n\\backslash\n";
406 else if (*it == '\n') {
407 newcontext.new_paragraph(os);
408 newcontext.check_layout(os);
412 newcontext.check_end_layout(os);
417 void handle_comment(ostream & os, string const & s, Context & context)
419 // TODO: Handle this better
420 Context newcontext(true, context.textclass);
421 begin_inset(os, "ERT");
422 os << "\nstatus collapsed\n";
423 newcontext.check_layout(os);
424 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
426 os << "\n\\backslash\n";
430 // make sure that our comment is the last thing on the line
431 newcontext.new_paragraph(os);
432 newcontext.check_layout(os);
433 newcontext.check_end_layout(os);
438 class isLayout : public std::unary_function<LayoutPtr, bool> {
440 isLayout(string const name) : name_(name) {}
441 bool operator()(LayoutPtr const & ptr) const {
442 return ptr->latexname() == name_;
449 LayoutPtr findLayout(TextClass const & textclass,
452 TextClass::const_iterator beg = textclass.begin();
453 TextClass::const_iterator end = textclass.end();
455 TextClass::const_iterator
456 it = std::find_if(beg, end, isLayout(name));
458 return (it == end) ? LayoutPtr() : *it;
462 void eat_whitespace(Parser &, ostream &, Context &, bool);
465 void output_command_layout(ostream & os, Parser & p, bool outer,
466 Context & parent_context,
469 parent_context.check_end_layout(os);
470 Context context(true, parent_context.textclass, newlayout,
471 parent_context.layout, parent_context.font);
472 if (parent_context.deeper_paragraph) {
473 // We are beginning a nested environment after a
474 // deeper paragraph inside the outer list environment.
475 // Therefore we don't need to output a "begin deeper".
476 context.need_end_deeper = true;
478 context.check_deeper(os);
479 context.check_layout(os);
480 if (context.layout->optionalargs > 0) {
481 eat_whitespace(p, os, context, false);
482 if (p.next_token().character() == '[') {
483 p.get_token(); // eat '['
484 begin_inset(os, "OptArg\n");
485 os << "status collapsed\n\n";
486 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
488 eat_whitespace(p, os, context, false);
491 parse_text(p, os, FLAG_ITEM, outer, context);
492 context.check_end_layout(os);
493 if (parent_context.deeper_paragraph) {
494 // We must suppress the "end deeper" because we
495 // suppressed the "begin deeper" above.
496 context.need_end_deeper = false;
498 context.check_end_deeper(os);
499 // We don't need really a new paragraph, but
500 // we must make sure that the next item gets a \begin_layout.
501 parent_context.new_paragraph(os);
506 * Output a space if necessary.
507 * This function gets called for every whitespace token.
509 * We have three cases here:
510 * 1. A space must be suppressed. Example: The lyxcode case below
511 * 2. A space may be suppressed. Example: Spaces before "\par"
512 * 3. A space must not be suppressed. Example: A space between two words
514 * We currently handle only 1. and 3 and from 2. only the case of
515 * spaces before newlines as a side effect.
517 * 2. could be used to suppress as many spaces as possible. This has two effects:
518 * - Reimporting LyX generated LaTeX files changes almost no whitespace
519 * - Superflous whitespace from non LyX generated LaTeX files is removed.
520 * The drawback is that the logic inside the function becomes
521 * complicated, and that is the reason why it is not implemented.
523 void check_space(Parser const & p, ostream & os, Context & context)
525 Token const next = p.next_token();
526 Token const curr = p.curr_token();
527 // A space before a single newline and vice versa must be ignored
528 // LyX emits a newline before \end{lyxcode}.
529 // This newline must be ignored,
530 // otherwise LyX will add an additional protected space.
531 if (next.cat() == catSpace ||
532 next.cat() == catNewline ||
533 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
536 context.check_layout(os);
542 * Parse all arguments of \p command
544 void parse_arguments(string const & command,
545 vector<ArgumentType> const & template_arguments,
546 Parser & p, ostream & os, bool outer, Context & context)
548 string ert = command;
549 size_t no_arguments = template_arguments.size();
550 for (size_t i = 0; i < no_arguments; ++i) {
551 switch (template_arguments[i]) {
553 // This argument contains regular LaTeX
554 handle_ert(os, ert + '{', context);
555 eat_whitespace(p, os, context, false);
556 parse_text(p, os, FLAG_ITEM, outer, context);
560 // This argument may contain special characters
561 ert += '{' + p.verbatim_item() + '}';
568 handle_ert(os, ert, context);
573 * Check whether \p command is a known command. If yes,
574 * handle the command with all arguments.
575 * \return true if the command was parsed, false otherwise.
577 bool parse_command(string const & command, Parser & p, ostream & os,
578 bool outer, Context & context)
580 if (known_commands.find(command) != known_commands.end()) {
581 parse_arguments(command, known_commands[command], p, os,
589 /// Parses a minipage or parbox
590 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
591 Context & parent_context, bool use_parbox)
595 // We need to set the height to the LaTeX default of 1\\totalheight
596 // for the case when no height argument is given
597 string height_value = "1";
598 string height_unit = "in";
599 string height_special = "totalheight";
601 if (p.next_token().asInput() == "[") {
602 position = p.getArg('[', ']');
603 if (position != "t" && position != "c" && position != "b") {
605 cerr << "invalid position for minipage/parbox" << endl;
607 if (p.next_token().asInput() == "[") {
608 latex_height = p.getArg('[', ']');
609 translate_box_len(latex_height, height_value, height_unit, height_special);
611 if (p.next_token().asInput() == "[") {
612 inner_pos = p.getArg('[', ']');
613 if (inner_pos != "c" && inner_pos != "t" &&
614 inner_pos != "b" && inner_pos != "s") {
615 inner_pos = position;
616 cerr << "invalid inner_pos for minipage/parbox"
624 string const latex_width = p.verbatim_item();
625 translate_len(latex_width, width_value, width_unit);
626 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
627 // LyX can't handle length variables
632 ss << "\\begin{minipage}";
633 if (!position.empty())
634 ss << '[' << position << ']';
635 if (!latex_height.empty())
636 ss << '[' << latex_height << ']';
637 if (!inner_pos.empty())
638 ss << '[' << inner_pos << ']';
639 ss << "{" << latex_width << "}";
642 handle_ert(os, ss.str(), parent_context);
643 parent_context.new_paragraph(os);
644 parse_text_in_inset(p, os, flags, outer, parent_context);
646 handle_ert(os, "}", parent_context);
648 handle_ert(os, "\\end{minipage}", parent_context);
650 // LyX does not like empty positions, so we have
651 // to set them to the LaTeX default values here.
652 if (position.empty())
654 if (inner_pos.empty())
655 inner_pos = position;
656 parent_context.check_layout(os);
657 begin_inset(os, "Box Frameless\n");
658 os << "position \"" << position << "\"\n";
659 os << "hor_pos \"c\"\n";
660 os << "has_inner_box 1\n";
661 os << "inner_pos \"" << inner_pos << "\"\n";
662 os << "use_parbox " << use_parbox << "\n";
663 os << "width \"" << width_value << width_unit << "\"\n";
664 os << "special \"none\"\n";
665 os << "height \"" << height_value << height_unit << "\"\n";
666 os << "height_special \"" << height_special << "\"\n";
667 os << "status open\n\n";
668 parse_text_in_inset(p, os, flags, outer, parent_context);
670 #ifdef PRESERVE_LAYOUT
671 // lyx puts a % after the end of the minipage
672 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
674 //handle_comment(os, "%dummy", parent_context);
677 parent_context.new_paragraph(os);
679 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
680 //handle_comment(os, "%dummy", parent_context);
683 // We add a protected space if something real follows
684 if (p.good() && p.next_token().cat() != catComment) {
685 os << "\\InsetSpace ~\n";
693 /// parse an unknown environment
694 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
695 unsigned flags, bool outer,
696 Context & parent_context)
698 if (name == "tabbing")
699 // We need to remember that we have to handle '\=' specially
700 flags |= FLAG_TABBING;
702 // We need to translate font changes and paragraphs inside the
703 // environment to ERT if we have a non standard font.
704 // Otherwise things like
705 // \large\begin{foo}\huge bar\end{foo}
707 bool const specialfont =
708 (parent_context.font != parent_context.normalfont);
709 bool const new_layout_allowed = parent_context.new_layout_allowed;
711 parent_context.new_layout_allowed = false;
712 handle_ert(os, "\\begin{" + name + "}", parent_context);
713 parse_text_snippet(p, os, flags, outer, parent_context);
714 handle_ert(os, "\\end{" + name + "}", parent_context);
716 parent_context.new_layout_allowed = new_layout_allowed;
720 void parse_environment(Parser & p, ostream & os, bool outer,
721 Context & parent_context)
724 string const name = p.getArg('{', '}');
725 const bool is_starred = suffixIs(name, '*');
726 string const unstarred_name = rtrim(name, "*");
727 active_environments.push_back(name);
729 if (is_math_env(name)) {
730 parent_context.check_layout(os);
731 begin_inset(os, "Formula ");
732 os << "\\begin{" << name << "}";
733 parse_math(p, os, FLAG_END, MATH_MODE);
734 os << "\\end{" << name << "}";
738 else if (name == "tabular" || name == "longtable") {
739 eat_whitespace(p, os, parent_context, false);
740 parent_context.check_layout(os);
741 begin_inset(os, "Tabular ");
742 handle_tabular(p, os, name == "longtable", parent_context);
747 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
748 eat_whitespace(p, os, parent_context, false);
749 parent_context.check_layout(os);
750 begin_inset(os, "Float " + unstarred_name + "\n");
751 if (p.next_token().asInput() == "[") {
752 os << "placement " << p.getArg('[', ']') << '\n';
754 os << "wide " << convert<string>(is_starred)
755 << "\nsideways false"
756 << "\nstatus open\n\n";
757 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
759 // We don't need really a new paragraph, but
760 // we must make sure that the next item gets a \begin_layout.
761 parent_context.new_paragraph(os);
765 else if (name == "minipage") {
766 eat_whitespace(p, os, parent_context, false);
767 parse_box(p, os, FLAG_END, outer, parent_context, false);
771 else if (name == "comment") {
772 eat_whitespace(p, os, parent_context, false);
773 parent_context.check_layout(os);
774 begin_inset(os, "Note Comment\n");
775 os << "status open\n";
776 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
781 else if (name == "lyxgreyedout") {
782 eat_whitespace(p, os, parent_context, false);
783 parent_context.check_layout(os);
784 begin_inset(os, "Note Greyedout\n");
785 os << "status open\n";
786 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
791 else if (!parent_context.new_layout_allowed)
792 parse_unknown_environment(p, name, os, FLAG_END, outer,
795 // Alignment settings
796 else if (name == "center" || name == "flushleft" || name == "flushright" ||
797 name == "centering" || name == "raggedright" || name == "raggedleft") {
798 eat_whitespace(p, os, parent_context, false);
799 // We must begin a new paragraph if not already done
800 if (! parent_context.atParagraphStart()) {
801 parent_context.check_end_layout(os);
802 parent_context.new_paragraph(os);
804 if (name == "flushleft" || name == "raggedright")
805 parent_context.add_extra_stuff("\\align left\n");
806 else if (name == "flushright" || name == "raggedleft")
807 parent_context.add_extra_stuff("\\align right\n");
809 parent_context.add_extra_stuff("\\align center\n");
810 parse_text(p, os, FLAG_END, outer, parent_context);
811 // Just in case the environment is empty ..
812 parent_context.extra_stuff.erase();
813 // We must begin a new paragraph to reset the alignment
814 parent_context.new_paragraph(os);
818 // The single '=' is meant here.
819 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
820 newlayout->isEnvironment()) {
821 eat_whitespace(p, os, parent_context, false);
822 Context context(true, parent_context.textclass, newlayout,
823 parent_context.layout, parent_context.font);
824 if (parent_context.deeper_paragraph) {
825 // We are beginning a nested environment after a
826 // deeper paragraph inside the outer list environment.
827 // Therefore we don't need to output a "begin deeper".
828 context.need_end_deeper = true;
830 parent_context.check_end_layout(os);
831 switch (context.layout->latextype) {
832 case LATEX_LIST_ENVIRONMENT:
833 context.extra_stuff = "\\labelwidthstring "
834 + p.verbatim_item() + '\n';
837 case LATEX_BIB_ENVIRONMENT:
838 p.verbatim_item(); // swallow next arg
844 context.check_deeper(os);
845 parse_text(p, os, FLAG_END, outer, context);
846 context.check_end_layout(os);
847 if (parent_context.deeper_paragraph) {
848 // We must suppress the "end deeper" because we
849 // suppressed the "begin deeper" above.
850 context.need_end_deeper = false;
852 context.check_end_deeper(os);
853 parent_context.new_paragraph(os);
857 else if (name == "appendix") {
858 // This is no good latex style, but it works and is used in some documents...
859 eat_whitespace(p, os, parent_context, false);
860 parent_context.check_end_layout(os);
861 Context context(true, parent_context.textclass, parent_context.layout,
862 parent_context.layout, parent_context.font);
863 context.check_layout(os);
864 os << "\\start_of_appendix\n";
865 parse_text(p, os, FLAG_END, outer, context);
866 context.check_end_layout(os);
870 else if (known_environments.find(name) != known_environments.end()) {
871 vector<ArgumentType> arguments = known_environments[name];
872 // The last "argument" denotes wether we may translate the
873 // environment contents to LyX
874 // The default required if no argument is given makes us
875 // compatible with the reLyXre environment.
876 ArgumentType contents = arguments.empty() ?
879 if (!arguments.empty())
880 arguments.pop_back();
881 // See comment in parse_unknown_environment()
882 bool const specialfont =
883 (parent_context.font != parent_context.normalfont);
884 bool const new_layout_allowed =
885 parent_context.new_layout_allowed;
887 parent_context.new_layout_allowed = false;
888 parse_arguments("\\begin{" + name + "}", arguments, p, os,
889 outer, parent_context);
890 if (contents == verbatim)
891 handle_ert(os, p.verbatimEnvironment(name),
894 parse_text_snippet(p, os, FLAG_END, outer,
896 handle_ert(os, "\\end{" + name + "}", parent_context);
898 parent_context.new_layout_allowed = new_layout_allowed;
902 parse_unknown_environment(p, name, os, FLAG_END, outer,
905 active_environments.pop_back();
909 /// parses a comment and outputs it to \p os.
910 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
912 BOOST_ASSERT(t.cat() == catComment);
913 if (!t.cs().empty()) {
914 context.check_layout(os);
915 handle_comment(os, '%' + t.cs(), context);
916 if (p.next_token().cat() == catNewline) {
917 // A newline after a comment line starts a new
919 if (context.new_layout_allowed) {
920 if(!context.atParagraphStart())
921 // Only start a new paragraph if not already
922 // done (we might get called recursively)
923 context.new_paragraph(os);
925 handle_ert(os, "\n", context);
926 eat_whitespace(p, os, context, true);
936 * Reads spaces and comments until the first non-space, non-comment token.
937 * New paragraphs (double newlines or \\par) are handled like simple spaces
938 * if \p eatParagraph is true.
939 * Spaces are skipped, but comments are written to \p os.
941 void eat_whitespace(Parser & p, ostream & os, Context & context,
945 Token const & t = p.get_token();
946 if (t.cat() == catComment)
947 parse_comment(p, os, t, context);
948 else if ((! eatParagraph && p.isParagraph()) ||
949 (t.cat() != catSpace && t.cat() != catNewline)) {
958 * Set a font attribute, parse text and reset the font attribute.
959 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
960 * \param currentvalue Current value of the attribute. Is set to the new
961 * value during parsing.
962 * \param newvalue New value of the attribute
964 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
965 Context & context, string const & attribute,
966 string & currentvalue, string const & newvalue)
968 context.check_layout(os);
969 string const oldvalue = currentvalue;
970 currentvalue = newvalue;
971 os << '\n' << attribute << ' ' << newvalue << "\n";
972 parse_text_snippet(p, os, flags, outer, context);
973 context.check_layout(os);
974 os << '\n' << attribute << ' ' << oldvalue << "\n";
975 currentvalue = oldvalue;
979 /// get the arguments of a natbib or jurabib citation command
980 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
982 // We need to distinguish "" and "[]", so we can't use p.getOpt().
984 // text before the citation
986 // text after the citation
987 string after = p.getFullOpt();
989 if (!after.empty()) {
990 before = p.getFullOpt();
991 if (natbibOrder && !before.empty())
992 std::swap(before, after);
994 return std::make_pair(before, after);
998 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
999 string const normalize_filename(string const & name)
1001 Parser p(trim(name, "\""));
1004 Token const & t = p.get_token();
1005 if (t.cat() != catEscape)
1007 else if (t.cs() == "lyxdot") {
1008 // This is used by LyX for simple dots in relative
1012 } else if (t.cs() == "space") {
1022 /// Convert \p name from TeX convention (relative to master file) to LyX
1023 /// convention (relative to .lyx file) if it is relative
1024 void fix_relative_filename(string & name)
1026 if (lyx::support::absolutePath(name))
1028 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1030 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1031 from_utf8(getParentFilePath())));
1035 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1036 void parse_noweb(Parser & p, ostream & os, Context & context)
1038 // assemble the rest of the keyword
1042 Token const & t = p.get_token();
1043 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1046 scrap = (p.good() && p.next_token().asInput() == "=");
1048 name += p.get_token().asInput();
1051 name += t.asInput();
1054 if (!scrap || !context.new_layout_allowed ||
1055 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1056 cerr << "Warning: Could not interpret '" << name
1057 << "'. Ignoring it." << endl;
1061 // We use new_paragraph instead of check_end_layout because the stuff
1062 // following the noweb chunk needs to start with a \begin_layout.
1063 // This may create a new paragraph even if there was none in the
1064 // noweb file, but the alternative is an invalid LyX file. Since
1065 // noweb code chunks are implemented with a layout style in LyX they
1066 // always must be in an own paragraph.
1067 context.new_paragraph(os);
1068 Context newcontext(true, context.textclass,
1069 context.textclass[from_ascii("Scrap")]);
1070 newcontext.check_layout(os);
1073 Token const & t = p.get_token();
1074 // We abuse the parser a bit, because this is no TeX syntax
1076 if (t.cat() == catEscape)
1077 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1079 os << subst(t.asInput(), "\n", "\n\\newline\n");
1080 // The scrap chunk is ended by an @ at the beginning of a line.
1081 // After the @ the line may contain a comment and/or
1082 // whitespace, but nothing else.
1083 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1084 (p.next_token().cat() == catSpace ||
1085 p.next_token().cat() == catNewline ||
1086 p.next_token().cat() == catComment)) {
1087 while (p.good() && p.next_token().cat() == catSpace)
1088 os << p.get_token().asInput();
1089 if (p.next_token().cat() == catComment)
1090 // The comment includes a final '\n'
1091 os << p.get_token().asInput();
1093 if (p.next_token().cat() == catNewline)
1100 newcontext.check_end_layout(os);
1103 } // anonymous namespace
1106 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1109 LayoutPtr newlayout;
1110 // Store the latest bibliographystyle (needed for bibtex inset)
1111 string bibliographystyle;
1112 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1113 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1115 Token const & t = p.get_token();
1118 cerr << "t: " << t << " flags: " << flags << "\n";
1121 if (flags & FLAG_ITEM) {
1122 if (t.cat() == catSpace)
1125 flags &= ~FLAG_ITEM;
1126 if (t.cat() == catBegin) {
1127 // skip the brace and collect everything to the next matching
1129 flags |= FLAG_BRACE_LAST;
1133 // handle only this single token, leave the loop if done
1134 flags |= FLAG_LEAVE;
1137 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1143 if (t.cat() == catMath) {
1144 // we are inside some text mode thingy, so opening new math is allowed
1145 context.check_layout(os);
1146 begin_inset(os, "Formula ");
1147 Token const & n = p.get_token();
1148 if (n.cat() == catMath && outer) {
1149 // TeX's $$...$$ syntax for displayed math
1151 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1153 p.get_token(); // skip the second '$' token
1155 // simple $...$ stuff
1158 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1164 else if (t.cat() == catSuper || t.cat() == catSub)
1165 cerr << "catcode " << t << " illegal in text mode\n";
1167 // Basic support for english quotes. This should be
1168 // extended to other quotes, but is not so easy (a
1169 // left english quote is the same as a right german
1171 else if (t.asInput() == "`"
1172 && p.next_token().asInput() == "`") {
1173 context.check_layout(os);
1174 begin_inset(os, "Quotes ");
1180 else if (t.asInput() == "'"
1181 && p.next_token().asInput() == "'") {
1182 context.check_layout(os);
1183 begin_inset(os, "Quotes ");
1190 else if (t.asInput() == "<"
1191 && p.next_token().asInput() == "<" && noweb_mode) {
1193 parse_noweb(p, os, context);
1196 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1197 check_space(p, os, context);
1199 else if (t.character() == '[' && noweb_mode &&
1200 p.next_token().character() == '[') {
1201 // These can contain underscores
1203 string const s = p.getFullOpt() + ']';
1204 if (p.next_token().character() == ']')
1207 cerr << "Warning: Inserting missing ']' in '"
1208 << s << "'." << endl;
1209 handle_ert(os, s, context);
1212 else if (t.cat() == catLetter ||
1213 t.cat() == catOther ||
1214 t.cat() == catAlign ||
1215 t.cat() == catParameter) {
1216 // This translates "&" to "\\&" which may be wrong...
1217 context.check_layout(os);
1218 os << t.character();
1221 else if (p.isParagraph()) {
1222 if (context.new_layout_allowed)
1223 context.new_paragraph(os);
1225 handle_ert(os, "\\par ", context);
1226 eat_whitespace(p, os, context, true);
1229 else if (t.cat() == catActive) {
1230 context.check_layout(os);
1231 if (t.character() == '~') {
1232 if (context.layout->free_spacing)
1235 os << "\\InsetSpace ~\n";
1237 os << t.character();
1240 else if (t.cat() == catBegin &&
1241 p.next_token().cat() == catEnd) {
1243 Token const prev = p.prev_token();
1245 if (p.next_token().character() == '`' ||
1246 (prev.character() == '-' &&
1247 p.next_token().character() == '-'))
1248 ; // ignore it in {}`` or -{}-
1250 handle_ert(os, "{}", context);
1254 else if (t.cat() == catBegin) {
1255 context.check_layout(os);
1256 // special handling of font attribute changes
1257 Token const prev = p.prev_token();
1258 Token const next = p.next_token();
1259 TeXFont const oldFont = context.font;
1260 if (next.character() == '[' ||
1261 next.character() == ']' ||
1262 next.character() == '*') {
1264 if (p.next_token().cat() == catEnd) {
1265 os << next.character();
1269 handle_ert(os, "{", context);
1270 parse_text_snippet(p, os,
1273 handle_ert(os, "}", context);
1275 } else if (! context.new_layout_allowed) {
1276 handle_ert(os, "{", context);
1277 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1279 handle_ert(os, "}", context);
1280 } else if (is_known(next.cs(), known_sizes)) {
1281 // next will change the size, so we must
1283 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1285 if (!context.atParagraphStart())
1287 << context.font.size << "\n";
1288 } else if (is_known(next.cs(), known_font_families)) {
1289 // next will change the font family, so we
1290 // must reset it here
1291 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1293 if (!context.atParagraphStart())
1295 << context.font.family << "\n";
1296 } else if (is_known(next.cs(), known_font_series)) {
1297 // next will change the font series, so we
1298 // must reset it here
1299 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1301 if (!context.atParagraphStart())
1303 << context.font.series << "\n";
1304 } else if (is_known(next.cs(), known_font_shapes)) {
1305 // next will change the font shape, so we
1306 // must reset it here
1307 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1309 if (!context.atParagraphStart())
1311 << context.font.shape << "\n";
1312 } else if (is_known(next.cs(), known_old_font_families) ||
1313 is_known(next.cs(), known_old_font_series) ||
1314 is_known(next.cs(), known_old_font_shapes)) {
1315 // next will change the font family, series
1316 // and shape, so we must reset it here
1317 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1319 if (!context.atParagraphStart())
1321 << context.font.family
1323 << context.font.series
1325 << context.font.shape << "\n";
1327 handle_ert(os, "{", context);
1328 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1330 handle_ert(os, "}", context);
1334 else if (t.cat() == catEnd) {
1335 if (flags & FLAG_BRACE_LAST) {
1338 cerr << "stray '}' in text\n";
1339 handle_ert(os, "}", context);
1342 else if (t.cat() == catComment)
1343 parse_comment(p, os, t, context);
1346 // control sequences
1349 else if (t.cs() == "(") {
1350 context.check_layout(os);
1351 begin_inset(os, "Formula");
1353 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1358 else if (t.cs() == "[") {
1359 context.check_layout(os);
1360 begin_inset(os, "Formula");
1362 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1367 else if (t.cs() == "begin")
1368 parse_environment(p, os, outer, context);
1370 else if (t.cs() == "end") {
1371 if (flags & FLAG_END) {
1372 // eat environment name
1373 string const name = p.getArg('{', '}');
1374 if (name != active_environment())
1375 cerr << "\\end{" + name + "} does not match \\begin{"
1376 + active_environment() + "}\n";
1379 p.error("found 'end' unexpectedly");
1382 else if (t.cs() == "item") {
1385 bool optarg = false;
1386 if (p.next_token().character() == '[') {
1387 p.get_token(); // eat '['
1388 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1393 context.check_layout(os);
1394 if (context.has_item) {
1395 // An item in an unknown list-like environment
1396 // FIXME: Do this in check_layout()!
1397 context.has_item = false;
1399 handle_ert(os, "\\item", context);
1401 handle_ert(os, "\\item ", context);
1404 if (context.layout->labeltype != LABEL_MANUAL) {
1405 // lyx does not support \item[\mybullet]
1406 // in itemize environments
1407 handle_ert(os, "[", context);
1409 handle_ert(os, "]", context);
1410 } else if (!s.empty()) {
1411 // The space is needed to separate the
1412 // item from the rest of the sentence.
1414 eat_whitespace(p, os, context, false);
1419 else if (t.cs() == "bibitem") {
1421 context.check_layout(os);
1424 os << '{' << p.verbatim_item() << '}' << "\n";
1427 else if (t.cs() == "def") {
1428 context.check_layout(os);
1429 eat_whitespace(p, os, context, false);
1430 string name = p.get_token().cs();
1431 eat_whitespace(p, os, context, false);
1437 while (p.next_token().cat() != catBegin) {
1438 if (p.next_token().cat() == catParameter) {
1443 // followed by number?
1444 if (p.next_token().cat() == catOther) {
1445 char c = p.getChar();
1447 // number = current arity + 1?
1448 if (c == arity + '0' + 1)
1453 paramtext += p.get_token().asString();
1455 paramtext += p.get_token().asString();
1460 // only output simple (i.e. compatible) macro as FormulaMacros
1461 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1463 context.check_layout(os);
1464 begin_inset(os, "FormulaMacro");
1468 handle_ert(os, ert, context);
1471 else if (t.cs() == "noindent") {
1473 context.add_extra_stuff("\\noindent\n");
1476 else if (t.cs() == "appendix") {
1477 context.add_extra_stuff("\\start_of_appendix\n");
1478 // We need to start a new paragraph. Otherwise the
1479 // appendix in 'bla\appendix\chapter{' would start
1481 context.new_paragraph(os);
1482 // We need to make sure that the paragraph is
1483 // generated even if it is empty. Otherwise the
1484 // appendix in '\par\appendix\par\chapter{' would
1486 context.check_layout(os);
1487 // FIXME: This is a hack to prevent paragraph
1488 // deletion if it is empty. Handle this better!
1490 "%dummy comment inserted by tex2lyx to "
1491 "ensure that this paragraph is not empty",
1493 // Both measures above may generate an additional
1494 // empty paragraph, but that does not hurt, because
1495 // whitespace does not matter here.
1496 eat_whitespace(p, os, context, true);
1499 // Must attempt to parse "Section*" before "Section".
1500 else if ((p.next_token().asInput() == "*") &&
1501 context.new_layout_allowed &&
1502 // The single '=' is meant here.
1503 (newlayout = findLayout(context.textclass,
1504 t.cs() + '*')).get() &&
1505 newlayout->isCommand()) {
1507 output_command_layout(os, p, outer, context, newlayout);
1511 // The single '=' is meant here.
1512 else if (context.new_layout_allowed &&
1513 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1514 newlayout->isCommand()) {
1515 output_command_layout(os, p, outer, context, newlayout);
1519 // Special handling for \caption
1520 // FIXME: remove this when InsetCaption is supported.
1521 else if (context.new_layout_allowed &&
1522 t.cs() == captionlayout->latexname()) {
1523 output_command_layout(os, p, outer, context,
1528 else if (t.cs() == "includegraphics") {
1529 bool const clip = p.next_token().asInput() == "*";
1532 map<string, string> opts = split_map(p.getArg('[', ']'));
1534 opts["clip"] = string();
1535 string name = normalize_filename(p.verbatim_item());
1537 string const path = getMasterFilePath();
1538 // We want to preserve relative / absolute filenames,
1539 // therefore path is only used for testing
1540 // FIXME UNICODE encoding of name and path may be
1541 // wrong (makeAbsPath expects utf8)
1542 if (!fs::exists(makeAbsPath(name, path).toFilesystemEncoding())) {
1543 // The file extension is probably missing.
1544 // Now try to find it out.
1545 string const dvips_name =
1546 find_file(name, path,
1547 known_dvips_graphics_formats);
1548 string const pdftex_name =
1549 find_file(name, path,
1550 known_pdftex_graphics_formats);
1551 if (!dvips_name.empty()) {
1552 if (!pdftex_name.empty()) {
1553 cerr << "This file contains the "
1555 "\"\\includegraphics{"
1557 "However, files\n\""
1558 << dvips_name << "\" and\n\""
1559 << pdftex_name << "\"\n"
1560 "both exist, so I had to make a "
1561 "choice and took the first one.\n"
1562 "Please move the unwanted one "
1563 "someplace else and try again\n"
1564 "if my choice was wrong."
1568 } else if (!pdftex_name.empty())
1572 // FIXME UNICODE encoding of name and path may be
1573 // wrong (makeAbsPath expects utf8)
1574 if (fs::exists(makeAbsPath(name, path).toFilesystemEncoding()))
1575 fix_relative_filename(name);
1577 cerr << "Warning: Could not find graphics file '"
1578 << name << "'." << endl;
1580 context.check_layout(os);
1581 begin_inset(os, "Graphics ");
1582 os << "\n\tfilename " << name << '\n';
1583 if (opts.find("width") != opts.end())
1585 << translate_len(opts["width"]) << '\n';
1586 if (opts.find("height") != opts.end())
1588 << translate_len(opts["height"]) << '\n';
1589 if (opts.find("scale") != opts.end()) {
1590 istringstream iss(opts["scale"]);
1594 os << "\tscale " << val << '\n';
1596 if (opts.find("angle") != opts.end())
1597 os << "\trotateAngle "
1598 << opts["angle"] << '\n';
1599 if (opts.find("origin") != opts.end()) {
1601 string const opt = opts["origin"];
1602 if (opt.find('l') != string::npos) ss << "left";
1603 if (opt.find('r') != string::npos) ss << "right";
1604 if (opt.find('c') != string::npos) ss << "center";
1605 if (opt.find('t') != string::npos) ss << "Top";
1606 if (opt.find('b') != string::npos) ss << "Bottom";
1607 if (opt.find('B') != string::npos) ss << "Baseline";
1608 if (!ss.str().empty())
1609 os << "\trotateOrigin " << ss.str() << '\n';
1611 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1613 if (opts.find("keepaspectratio") != opts.end())
1614 os << "\tkeepAspectRatio\n";
1615 if (opts.find("clip") != opts.end())
1617 if (opts.find("draft") != opts.end())
1619 if (opts.find("bb") != opts.end())
1620 os << "\tBoundingBox "
1621 << opts["bb"] << '\n';
1622 int numberOfbbOptions = 0;
1623 if (opts.find("bbllx") != opts.end())
1624 numberOfbbOptions++;
1625 if (opts.find("bblly") != opts.end())
1626 numberOfbbOptions++;
1627 if (opts.find("bburx") != opts.end())
1628 numberOfbbOptions++;
1629 if (opts.find("bbury") != opts.end())
1630 numberOfbbOptions++;
1631 if (numberOfbbOptions == 4)
1632 os << "\tBoundingBox "
1633 << opts["bbllx"] << opts["bblly"]
1634 << opts["bburx"] << opts["bbury"] << '\n';
1635 else if (numberOfbbOptions > 0)
1636 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1637 numberOfbbOptions = 0;
1638 if (opts.find("natwidth") != opts.end())
1639 numberOfbbOptions++;
1640 if (opts.find("natheight") != opts.end())
1641 numberOfbbOptions++;
1642 if (numberOfbbOptions == 2)
1643 os << "\tBoundingBox 0bp 0bp "
1644 << opts["natwidth"] << opts["natheight"] << '\n';
1645 else if (numberOfbbOptions > 0)
1646 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1647 ostringstream special;
1648 if (opts.find("hiresbb") != opts.end())
1649 special << "hiresbb,";
1650 if (opts.find("trim") != opts.end())
1652 if (opts.find("viewport") != opts.end())
1653 special << "viewport=" << opts["viewport"] << ',';
1654 if (opts.find("totalheight") != opts.end())
1655 special << "totalheight=" << opts["totalheight"] << ',';
1656 if (opts.find("type") != opts.end())
1657 special << "type=" << opts["type"] << ',';
1658 if (opts.find("ext") != opts.end())
1659 special << "ext=" << opts["ext"] << ',';
1660 if (opts.find("read") != opts.end())
1661 special << "read=" << opts["read"] << ',';
1662 if (opts.find("command") != opts.end())
1663 special << "command=" << opts["command"] << ',';
1664 string s_special = special.str();
1665 if (!s_special.empty()) {
1666 // We had special arguments. Remove the trailing ','.
1667 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1669 // TODO: Handle the unknown settings better.
1670 // Warn about invalid options.
1671 // Check whether some option was given twice.
1675 else if (t.cs() == "footnote" ||
1676 (t.cs() == "thanks" && context.layout->intitle)) {
1678 context.check_layout(os);
1679 begin_inset(os, "Foot\n");
1680 os << "status collapsed\n\n";
1681 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1685 else if (t.cs() == "marginpar") {
1687 context.check_layout(os);
1688 begin_inset(os, "Marginal\n");
1689 os << "status collapsed\n\n";
1690 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1694 else if (t.cs() == "ensuremath") {
1696 context.check_layout(os);
1697 string const s = p.verbatim_item();
1698 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1701 handle_ert(os, "\\ensuremath{" + s + "}",
1705 else if (t.cs() == "hfill") {
1706 context.check_layout(os);
1707 os << "\n\\hfill\n";
1712 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1713 // FIXME: Somehow prevent title layouts if
1714 // "maketitle" was not found
1716 skip_braces(p); // swallow this
1719 else if (t.cs() == "tableofcontents") {
1721 context.check_layout(os);
1722 begin_inset(os, "LatexCommand \\tableofcontents\n");
1724 skip_braces(p); // swallow this
1727 else if (t.cs() == "listoffigures") {
1729 context.check_layout(os);
1730 begin_inset(os, "FloatList figure\n");
1732 skip_braces(p); // swallow this
1735 else if (t.cs() == "listoftables") {
1737 context.check_layout(os);
1738 begin_inset(os, "FloatList table\n");
1740 skip_braces(p); // swallow this
1743 else if (t.cs() == "listof") {
1744 p.skip_spaces(true);
1745 string const name = p.get_token().asString();
1746 if (context.textclass.floats().typeExist(name)) {
1747 context.check_layout(os);
1748 begin_inset(os, "FloatList ");
1751 p.get_token(); // swallow second arg
1753 handle_ert(os, "\\listof{" + name + "}", context);
1756 else if (t.cs() == "textrm")
1757 parse_text_attributes(p, os, FLAG_ITEM, outer,
1758 context, "\\family",
1759 context.font.family, "roman");
1761 else if (t.cs() == "textsf")
1762 parse_text_attributes(p, os, FLAG_ITEM, outer,
1763 context, "\\family",
1764 context.font.family, "sans");
1766 else if (t.cs() == "texttt")
1767 parse_text_attributes(p, os, FLAG_ITEM, outer,
1768 context, "\\family",
1769 context.font.family, "typewriter");
1771 else if (t.cs() == "textmd")
1772 parse_text_attributes(p, os, FLAG_ITEM, outer,
1773 context, "\\series",
1774 context.font.series, "medium");
1776 else if (t.cs() == "textbf")
1777 parse_text_attributes(p, os, FLAG_ITEM, outer,
1778 context, "\\series",
1779 context.font.series, "bold");
1781 else if (t.cs() == "textup")
1782 parse_text_attributes(p, os, FLAG_ITEM, outer,
1784 context.font.shape, "up");
1786 else if (t.cs() == "textit")
1787 parse_text_attributes(p, os, FLAG_ITEM, outer,
1789 context.font.shape, "italic");
1791 else if (t.cs() == "textsl")
1792 parse_text_attributes(p, os, FLAG_ITEM, outer,
1794 context.font.shape, "slanted");
1796 else if (t.cs() == "textsc")
1797 parse_text_attributes(p, os, FLAG_ITEM, outer,
1799 context.font.shape, "smallcaps");
1801 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1802 context.check_layout(os);
1803 TeXFont oldFont = context.font;
1804 context.font.init();
1805 context.font.size = oldFont.size;
1806 os << "\n\\family " << context.font.family << "\n";
1807 os << "\n\\series " << context.font.series << "\n";
1808 os << "\n\\shape " << context.font.shape << "\n";
1809 if (t.cs() == "textnormal") {
1810 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1811 output_font_change(os, context.font, oldFont);
1812 context.font = oldFont;
1814 eat_whitespace(p, os, context, false);
1817 else if (t.cs() == "underbar") {
1818 // Do NOT handle \underline.
1819 // \underbar cuts through y, g, q, p etc.,
1820 // \underline does not.
1821 context.check_layout(os);
1822 os << "\n\\bar under\n";
1823 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1824 context.check_layout(os);
1825 os << "\n\\bar default\n";
1828 else if (t.cs() == "emph" || t.cs() == "noun") {
1829 context.check_layout(os);
1830 os << "\n\\" << t.cs() << " on\n";
1831 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1832 context.check_layout(os);
1833 os << "\n\\" << t.cs() << " default\n";
1836 else if (use_natbib &&
1837 is_known(t.cs(), known_natbib_commands) &&
1838 ((t.cs() != "citefullauthor" &&
1839 t.cs() != "citeyear" &&
1840 t.cs() != "citeyearpar") ||
1841 p.next_token().asInput() != "*")) {
1842 context.check_layout(os);
1844 // \citet[before][after]{a} \citet[after][before]{a}
1845 // \citet[before][]{a} \citet[][before]{a}
1846 // \citet[after]{a} \citet[after]{a}
1847 // \citet{a} \citet{a}
1848 string command = '\\' + t.cs();
1849 if (p.next_token().asInput() == "*") {
1853 if (command == "\\citefullauthor")
1854 // alternative name for "\\citeauthor*"
1855 command = "\\citeauthor*";
1857 // text before the citation
1859 // text after the citation
1862 boost::tie(before, after) = getCiteArguments(p, true);
1863 if (command == "\\cite") {
1864 // \cite without optional argument means
1865 // \citet, \cite with at least one optional
1866 // argument means \citep.
1867 if (before.empty() && after.empty())
1868 command = "\\citet";
1870 command = "\\citep";
1872 if (before.empty() && after == "[]")
1873 // avoid \citet[]{a}
1875 else if (before == "[]" && after == "[]") {
1876 // avoid \citet[][]{a}
1880 begin_inset(os, "LatexCommand ");
1881 os << command << after << before
1882 << '{' << p.verbatim_item() << "}\n";
1886 else if (use_jurabib &&
1887 is_known(t.cs(), known_jurabib_commands)) {
1888 context.check_layout(os);
1889 string const command = '\\' + t.cs();
1890 char argumentOrder = '\0';
1891 vector<string> const & options = used_packages["jurabib"];
1892 if (std::find(options.begin(), options.end(),
1893 "natbiborder") != options.end())
1894 argumentOrder = 'n';
1895 else if (std::find(options.begin(), options.end(),
1896 "jurabiborder") != options.end())
1897 argumentOrder = 'j';
1899 // text before the citation
1901 // text after the citation
1904 boost::tie(before, after) =
1905 getCiteArguments(p, argumentOrder != 'j');
1906 string const citation = p.verbatim_item();
1907 if (!before.empty() && argumentOrder == '\0') {
1908 cerr << "Warning: Assuming argument order "
1909 "of jurabib version 0.6 for\n'"
1910 << command << before << after << '{'
1911 << citation << "}'.\n"
1912 "Add 'jurabiborder' to the jurabib "
1913 "package options if you used an\n"
1914 "earlier jurabib version." << endl;
1916 begin_inset(os, "LatexCommand ");
1917 os << command << after << before
1918 << '{' << citation << "}\n";
1922 else if (is_known(t.cs(), known_latex_commands)) {
1923 // This needs to be after the check for natbib and
1924 // jurabib commands, because "cite" has different
1925 // arguments with natbib and jurabib.
1926 context.check_layout(os);
1927 begin_inset(os, "LatexCommand ");
1928 os << '\\' << t.cs();
1929 // lyx cannot handle newlines in a latex command
1930 // FIXME: Move the substitution into parser::getOpt()?
1931 os << subst(p.getOpt(), "\n", " ");
1932 os << subst(p.getOpt(), "\n", " ");
1933 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1937 else if (is_known(t.cs(), known_quotes)) {
1938 char const * const * where = is_known(t.cs(), known_quotes);
1939 context.check_layout(os);
1940 begin_inset(os, "Quotes ");
1941 os << known_coded_quotes[where - known_quotes];
1943 // LyX adds {} after the quote, so we have to eat
1944 // spaces here if there are any before a possible
1946 eat_whitespace(p, os, context, false);
1950 else if (is_known(t.cs(), known_sizes) &&
1951 context.new_layout_allowed) {
1952 char const * const * where = is_known(t.cs(), known_sizes);
1953 context.check_layout(os);
1954 TeXFont const oldFont = context.font;
1955 context.font.size = known_coded_sizes[where - known_sizes];
1956 output_font_change(os, oldFont, context.font);
1957 eat_whitespace(p, os, context, false);
1960 else if (is_known(t.cs(), known_font_families) &&
1961 context.new_layout_allowed) {
1962 char const * const * where =
1963 is_known(t.cs(), known_font_families);
1964 context.check_layout(os);
1965 TeXFont const oldFont = context.font;
1966 context.font.family =
1967 known_coded_font_families[where - known_font_families];
1968 output_font_change(os, oldFont, context.font);
1969 eat_whitespace(p, os, context, false);
1972 else if (is_known(t.cs(), known_font_series) &&
1973 context.new_layout_allowed) {
1974 char const * const * where =
1975 is_known(t.cs(), known_font_series);
1976 context.check_layout(os);
1977 TeXFont const oldFont = context.font;
1978 context.font.series =
1979 known_coded_font_series[where - known_font_series];
1980 output_font_change(os, oldFont, context.font);
1981 eat_whitespace(p, os, context, false);
1984 else if (is_known(t.cs(), known_font_shapes) &&
1985 context.new_layout_allowed) {
1986 char const * const * where =
1987 is_known(t.cs(), known_font_shapes);
1988 context.check_layout(os);
1989 TeXFont const oldFont = context.font;
1990 context.font.shape =
1991 known_coded_font_shapes[where - known_font_shapes];
1992 output_font_change(os, oldFont, context.font);
1993 eat_whitespace(p, os, context, false);
1995 else if (is_known(t.cs(), known_old_font_families) &&
1996 context.new_layout_allowed) {
1997 char const * const * where =
1998 is_known(t.cs(), known_old_font_families);
1999 context.check_layout(os);
2000 TeXFont const oldFont = context.font;
2001 context.font.init();
2002 context.font.size = oldFont.size;
2003 context.font.family =
2004 known_coded_font_families[where - known_old_font_families];
2005 output_font_change(os, oldFont, context.font);
2006 eat_whitespace(p, os, context, false);
2009 else if (is_known(t.cs(), known_old_font_series) &&
2010 context.new_layout_allowed) {
2011 char const * const * where =
2012 is_known(t.cs(), known_old_font_series);
2013 context.check_layout(os);
2014 TeXFont const oldFont = context.font;
2015 context.font.init();
2016 context.font.size = oldFont.size;
2017 context.font.series =
2018 known_coded_font_series[where - known_old_font_series];
2019 output_font_change(os, oldFont, context.font);
2020 eat_whitespace(p, os, context, false);
2023 else if (is_known(t.cs(), known_old_font_shapes) &&
2024 context.new_layout_allowed) {
2025 char const * const * where =
2026 is_known(t.cs(), known_old_font_shapes);
2027 context.check_layout(os);
2028 TeXFont const oldFont = context.font;
2029 context.font.init();
2030 context.font.size = oldFont.size;
2031 context.font.shape =
2032 known_coded_font_shapes[where - known_old_font_shapes];
2033 output_font_change(os, oldFont, context.font);
2034 eat_whitespace(p, os, context, false);
2037 else if (t.cs() == "LyX" || t.cs() == "TeX"
2038 || t.cs() == "LaTeX") {
2039 context.check_layout(os);
2041 skip_braces(p); // eat {}
2044 else if (t.cs() == "LaTeXe") {
2045 context.check_layout(os);
2047 skip_braces(p); // eat {}
2050 else if (t.cs() == "ldots") {
2051 context.check_layout(os);
2053 os << "\\SpecialChar \\ldots{}\n";
2056 else if (t.cs() == "lyxarrow") {
2057 context.check_layout(os);
2058 os << "\\SpecialChar \\menuseparator\n";
2062 else if (t.cs() == "textcompwordmark") {
2063 context.check_layout(os);
2064 os << "\\SpecialChar \\textcompwordmark{}\n";
2068 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2069 context.check_layout(os);
2070 os << "\\SpecialChar \\@.\n";
2074 else if (t.cs() == "-") {
2075 context.check_layout(os);
2076 os << "\\SpecialChar \\-\n";
2079 else if (t.cs() == "textasciitilde") {
2080 context.check_layout(os);
2085 else if (t.cs() == "textasciicircum") {
2086 context.check_layout(os);
2091 else if (t.cs() == "textbackslash") {
2092 context.check_layout(os);
2093 os << "\n\\backslash\n";
2097 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2098 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2100 context.check_layout(os);
2104 else if (t.cs() == "char") {
2105 context.check_layout(os);
2106 if (p.next_token().character() == '`') {
2108 if (p.next_token().cs() == "\"") {
2113 handle_ert(os, "\\char`", context);
2116 handle_ert(os, "\\char", context);
2120 else if (t.cs() == "verb") {
2121 context.check_layout(os);
2122 char const delimiter = p.next_token().character();
2123 string const arg = p.getArg(delimiter, delimiter);
2125 oss << "\\verb" << delimiter << arg << delimiter;
2126 handle_ert(os, oss.str(), context);
2129 else if (t.cs() == "\"") {
2130 context.check_layout(os);
2131 string const name = p.verbatim_item();
2132 if (name == "a") os << '\xe4';
2133 else if (name == "o") os << '\xf6';
2134 else if (name == "u") os << '\xfc';
2135 else if (name == "A") os << '\xc4';
2136 else if (name == "O") os << '\xd6';
2137 else if (name == "U") os << '\xdc';
2138 else handle_ert(os, "\"{" + name + "}", context);
2141 // Problem: \= creates a tabstop inside the tabbing environment
2142 // and else an accent. In the latter case we really would want
2143 // \={o} instead of \= o.
2144 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2145 handle_ert(os, t.asInput(), context);
2147 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2148 || t.cs() == "'" || t.cs() == "`"
2149 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2150 // we need the trim as the LyX parser chokes on such spaces
2151 // The argument of InsetLatexAccent is parsed as a
2152 // subset of LaTeX, so don't parse anything here,
2153 // but use the raw argument.
2154 // Otherwise we would convert \~{\i} wrongly.
2155 // This will of course not translate \~{\ss} to \~{ß},
2156 // but that does at least compile and does only look
2157 // strange on screen.
2158 context.check_layout(os);
2159 os << "\\i \\" << t.cs() << "{"
2160 << trim(p.verbatim_item(), " ")
2164 else if (t.cs() == "ss") {
2165 context.check_layout(os);
2167 skip_braces(p); // eat {}
2170 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2172 context.check_layout(os);
2173 os << "\\i \\" << t.cs() << "{}\n";
2174 skip_braces(p); // eat {}
2177 else if (t.cs() == "\\") {
2178 context.check_layout(os);
2179 string const next = p.next_token().asInput();
2181 handle_ert(os, "\\\\" + p.getOpt(), context);
2182 else if (next == "*") {
2184 handle_ert(os, "\\\\*" + p.getOpt(), context);
2187 os << "\n\\newline\n";
2191 else if (t.cs() == "input" || t.cs() == "include"
2192 || t.cs() == "verbatiminput") {
2193 string name = '\\' + t.cs();
2194 if (t.cs() == "verbatiminput"
2195 && p.next_token().asInput() == "*")
2196 name += p.get_token().asInput();
2197 context.check_layout(os);
2198 begin_inset(os, "Include ");
2199 string filename(normalize_filename(p.getArg('{', '}')));
2200 string const path = getMasterFilePath();
2201 // We want to preserve relative / absolute filenames,
2202 // therefore path is only used for testing
2203 // FIXME UNICODE encoding of filename and path may be
2204 // wrong (makeAbsPath expects utf8)
2205 if ((t.cs() == "include" || t.cs() == "input") &&
2206 !fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2207 // The file extension is probably missing.
2208 // Now try to find it out.
2209 string const tex_name =
2210 find_file(filename, path,
2211 known_tex_extensions);
2212 if (!tex_name.empty())
2213 filename = tex_name;
2215 // FIXME UNICODE encoding of filename and path may be
2216 // wrong (makeAbsPath expects utf8)
2217 if (fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2218 string const abstexname =
2219 makeAbsPath(filename, path).absFilename();
2220 string const abslyxname =
2221 changeExtension(abstexname, ".lyx");
2222 fix_relative_filename(filename);
2223 string const lyxname =
2224 changeExtension(filename, ".lyx");
2225 if (t.cs() != "verbatiminput" &&
2226 tex2lyx(abstexname, FileName(abslyxname))) {
2227 os << name << '{' << lyxname << "}\n";
2229 os << name << '{' << filename << "}\n";
2232 cerr << "Warning: Could not find included file '"
2233 << filename << "'." << endl;
2234 os << name << '{' << filename << "}\n";
2236 os << "preview false\n";
2240 else if (t.cs() == "bibliographystyle") {
2241 // store new bibliographystyle
2242 bibliographystyle = p.verbatim_item();
2243 // output new bibliographystyle.
2244 // This is only necessary if used in some other macro than \bibliography.
2245 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2248 else if (t.cs() == "bibliography") {
2249 context.check_layout(os);
2250 begin_inset(os, "LatexCommand ");
2252 // Do we have a bibliographystyle set?
2253 if (!bibliographystyle.empty()) {
2254 os << '[' << bibliographystyle << ']';
2256 os << '{' << p.verbatim_item() << "}\n";
2260 else if (t.cs() == "parbox")
2261 parse_box(p, os, FLAG_ITEM, outer, context, true);
2263 else if (t.cs() == "smallskip" ||
2264 t.cs() == "medskip" ||
2265 t.cs() == "bigskip" ||
2266 t.cs() == "vfill") {
2267 context.check_layout(os);
2268 begin_inset(os, "VSpace ");
2274 else if (is_known(t.cs(), known_spaces)) {
2275 char const * const * where = is_known(t.cs(), known_spaces);
2276 context.check_layout(os);
2277 begin_inset(os, "InsetSpace ");
2278 os << '\\' << known_coded_spaces[where - known_spaces]
2280 // LaTeX swallows whitespace after all spaces except
2281 // "\\,". We have to do that here, too, because LyX
2282 // adds "{}" which would make the spaces significant.
2284 eat_whitespace(p, os, context, false);
2285 // LyX adds "{}" after all spaces except "\\ " and
2286 // "\\,", so we have to remove "{}".
2287 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2288 // remove the braces after "\\,", too.
2293 else if (t.cs() == "newpage" ||
2294 t.cs() == "clearpage" ||
2295 t.cs() == "cleardoublepage") {
2296 context.check_layout(os);
2297 // FIXME: what about \\pagebreak?
2298 os << "\n\\" << t.cs() << "\n";
2299 skip_braces(p); // eat {}
2302 else if (t.cs() == "newcommand" ||
2303 t.cs() == "providecommand" ||
2304 t.cs() == "renewcommand") {
2305 // these could be handled by parse_command(), but
2306 // we need to call add_known_command() here.
2307 string name = t.asInput();
2308 if (p.next_token().asInput() == "*") {
2309 // Starred form. Eat '*'
2313 string const command = p.verbatim_item();
2314 string const opt1 = p.getOpt();
2315 string const opt2 = p.getFullOpt();
2316 add_known_command(command, opt1, !opt2.empty());
2317 string const ert = name + '{' + command + '}' +
2319 '{' + p.verbatim_item() + '}';
2322 context.check_layout(os);
2323 begin_inset(os, "FormulaMacro");
2327 // we cannot handle optional argument, so only output ERT
2328 handle_ert(os, ert, context);
2331 else if (t.cs() == "vspace") {
2332 bool starred = false;
2333 if (p.next_token().asInput() == "*") {
2337 string const length = p.verbatim_item();
2340 bool valid = splitLatexLength(length, valstring, unit);
2341 bool known_vspace = false;
2342 bool known_unit = false;
2345 istringstream iss(valstring);
2348 if (unit == "\\smallskipamount") {
2350 known_vspace = true;
2351 } else if (unit == "\\medskipamount") {
2353 known_vspace = true;
2354 } else if (unit == "\\bigskipamount") {
2356 known_vspace = true;
2357 } else if (unit == "\\fill") {
2359 known_vspace = true;
2362 if (!known_vspace) {
2363 switch (unitFromString(unit)) {
2384 if (known_unit || known_vspace) {
2385 // Literal length or known variable
2386 context.check_layout(os);
2387 begin_inset(os, "VSpace ");
2395 // LyX can't handle other length variables in Inset VSpace
2396 string name = t.asInput();
2401 handle_ert(os, name + '{' + unit + '}', context);
2402 else if (value == -1.0)
2403 handle_ert(os, name + "{-" + unit + '}', context);
2405 handle_ert(os, name + '{' + valstring + unit + '}', context);
2407 handle_ert(os, name + '{' + length + '}', context);
2412 //cerr << "#: " << t << " mode: " << mode << endl;
2413 // heuristic: read up to next non-nested space
2415 string s = t.asInput();
2416 string z = p.verbatim_item();
2417 while (p.good() && z != " " && z.size()) {
2418 //cerr << "read: " << z << endl;
2420 z = p.verbatim_item();
2422 cerr << "found ERT: " << s << endl;
2423 handle_ert(os, s + ' ', context);
2425 string name = t.asInput();
2426 if (p.next_token().asInput() == "*") {
2427 // Starred commands like \vspace*{}
2428 p.get_token(); // Eat '*'
2431 if (! parse_command(name, p, os, outer, context))
2432 handle_ert(os, name, context);
2435 if (flags & FLAG_LEAVE) {
2436 flags &= ~FLAG_LEAVE;