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.
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/convert.h"
22 #include "support/filetools.h"
24 #include <boost/filesystem/operations.hpp>
25 #include <boost/tuple/tuple.hpp>
35 using support::addExtension;
36 using support::changeExtension;
37 using support::FileName;
38 using support::makeAbsPath;
39 using support::makeRelPath;
41 using support::suffixIs;
42 using support::contains;
50 using std::ostringstream;
51 using std::istringstream;
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", "index",
109 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
113 * We can't put these into known_latex_commands because the argument order
114 * is reversed in lyx if there are 2 arguments.
115 * The starred forms are also known.
117 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
118 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
119 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
123 * We can't put these into known_latex_commands because the argument order
124 * is reversed in lyx if there are 2 arguments.
125 * No starred form other than "cite*" known.
127 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
128 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
129 // jurabib commands not (yet) supported by LyX:
131 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
132 // "footciteauthor", "footciteyear", "footciteyearpar",
133 "citefield", "citetitle", "cite*", 0 };
135 /// LaTeX names for quotes
136 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
137 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
139 /// the same as known_quotes with .lyx names
140 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
141 "grd", "gls", "fls", "frs", 0};
143 /// LaTeX names for font sizes
144 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
145 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
147 /// the same as known_sizes with .lyx names
148 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
149 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
151 /// LaTeX 2.09 names for font families
152 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
154 /// LaTeX names for font families
155 char const * const known_font_families[] = { "rmfamily", "sffamily",
158 /// the same as known_old_font_families and known_font_families with .lyx names
159 char const * const known_coded_font_families[] = { "roman", "sans",
162 /// LaTeX 2.09 names for font series
163 char const * const known_old_font_series[] = { "bf", 0};
165 /// LaTeX names for font series
166 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
168 /// the same as known_old_font_series and known_font_series with .lyx names
169 char const * const known_coded_font_series[] = { "bold", "medium", 0};
171 /// LaTeX 2.09 names for font shapes
172 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
174 /// LaTeX names for font shapes
175 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
178 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
179 char const * const known_coded_font_shapes[] = { "italic", "slanted",
180 "smallcaps", "up", 0};
183 * Graphics file extensions known by the dvips driver of the graphics package.
184 * These extensions are used to complete the filename of an included
185 * graphics file if it does not contain an extension.
186 * The order must be the same that latex uses to find a file, because we
187 * will use the first extension that matches.
188 * This is only an approximation for the common cases. If we would want to
189 * do it right in all cases, we would need to know which graphics driver is
190 * used and know the extensions of every driver of the graphics package.
192 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
193 "ps.gz", "eps.Z", "ps.Z", 0};
196 * Graphics file extensions known by the pdftex driver of the graphics package.
197 * \sa known_dvips_graphics_formats
199 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
203 * Known file extensions for TeX files as used by \\include.
205 char const * const known_tex_extensions[] = {"tex", 0};
207 /// spaces known by InsetSpace
208 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
209 "qquad", "enspace", "enskip", "negthinspace", 0};
211 /// the same as known_spaces with .lyx names
212 char const * const known_coded_spaces[] = { "space{}", "space{}",
213 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
214 "negthinspace{}", 0};
217 /// splits "x=z, y=b" into a map
218 map<string, string> split_map(string const & s)
220 map<string, string> res;
223 for (size_t i = 0; i < v.size(); ++i) {
224 size_t const pos = v[i].find('=');
225 string const index = v[i].substr(0, pos);
226 string const value = v[i].substr(pos + 1, string::npos);
227 res[trim(index)] = trim(value);
234 * Split a LaTeX length into value and unit.
235 * The latter can be a real unit like "pt", or a latex length variable
236 * like "\textwidth". The unit may contain additional stuff like glue
237 * lengths, but we don't care, because such lengths are ERT anyway.
238 * \returns true if \p value and \p unit are valid.
240 bool splitLatexLength(string const & len, string & value, string & unit)
244 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
245 //'4,5' is a valid LaTeX length number. Change it to '4.5'
246 string const length = subst(len, ',', '.');
247 if (i == string::npos)
250 if (len[0] == '\\') {
251 // We had something like \textwidth without a factor
257 value = trim(string(length, 0, i));
261 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
262 if (contains(len, '\\'))
263 unit = trim(string(len, i));
265 unit = support::ascii_lowercase(trim(string(len, i)));
270 /// A simple function to translate a latex length to something lyx can
271 /// understand. Not perfect, but rather best-effort.
272 bool translate_len(string const & length, string & valstring, string & unit)
274 if (!splitLatexLength(length, valstring, unit))
276 // LyX uses percent values
278 istringstream iss(valstring);
283 string const percentval = oss.str();
285 if (unit.empty() || unit[0] != '\\')
287 string::size_type const i = unit.find(' ');
288 string const endlen = (i == string::npos) ? string() : string(unit, i);
289 if (unit == "\\textwidth") {
290 valstring = percentval;
291 unit = "text%" + endlen;
292 } else if (unit == "\\columnwidth") {
293 valstring = percentval;
294 unit = "col%" + endlen;
295 } else if (unit == "\\paperwidth") {
296 valstring = percentval;
297 unit = "page%" + endlen;
298 } else if (unit == "\\linewidth") {
299 valstring = percentval;
300 unit = "line%" + endlen;
301 } else if (unit == "\\paperheight") {
302 valstring = percentval;
303 unit = "pheight%" + endlen;
304 } else if (unit == "\\textheight") {
305 valstring = percentval;
306 unit = "theight%" + endlen;
314 string translate_len(string const & length)
318 if (translate_len(length, value, unit))
320 // If the input is invalid, return what we have.
328 * Translates a LaTeX length into \p value, \p unit and
329 * \p special parts suitable for a box inset.
330 * The difference from translate_len() is that a box inset knows about
331 * some special "units" that are stored in \p special.
333 void translate_box_len(string const & length, string & value, string & unit, string & special)
335 if (translate_len(length, value, unit)) {
336 if (unit == "\\height" || unit == "\\depth" ||
337 unit == "\\totalheight" || unit == "\\width") {
338 special = unit.substr(1);
339 // The unit is not used, but LyX requires a dummy setting
352 * Find a file with basename \p name in path \p path and an extension
355 string find_file(string const & name, string const & path,
356 char const * const * extensions)
358 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
360 for (char const * const * what = extensions; *what; ++what) {
361 string const trial = addExtension(name, *what);
362 if (fs::exists(makeAbsPath(trial, path).toFilesystemEncoding()))
369 void begin_inset(ostream & os, string const & name)
371 os << "\n\\begin_inset " << name;
375 void end_inset(ostream & os)
377 os << "\n\\end_inset\n\n";
381 void skip_braces(Parser & p)
383 if (p.next_token().cat() != catBegin)
386 if (p.next_token().cat() == catEnd) {
394 void handle_ert(ostream & os, string const & s, Context & context)
396 // We must have a valid layout before outputting the ERT inset.
397 context.check_layout(os);
398 Context newcontext(true, context.textclass);
399 begin_inset(os, "ERT");
400 os << "\nstatus collapsed\n";
401 newcontext.check_layout(os);
402 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
404 os << "\n\\backslash\n";
405 else if (*it == '\n') {
406 newcontext.new_paragraph(os);
407 newcontext.check_layout(os);
411 newcontext.check_end_layout(os);
416 void handle_comment(ostream & os, string const & s, Context & context)
418 // TODO: Handle this better
419 Context newcontext(true, context.textclass);
420 begin_inset(os, "ERT");
421 os << "\nstatus collapsed\n";
422 newcontext.check_layout(os);
423 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
425 os << "\n\\backslash\n";
429 // make sure that our comment is the last thing on the line
430 newcontext.new_paragraph(os);
431 newcontext.check_layout(os);
432 newcontext.check_end_layout(os);
437 class isLayout : public std::unary_function<Layout_ptr, bool> {
439 isLayout(string const name) : name_(name) {}
440 bool operator()(Layout_ptr const & ptr) const {
441 return ptr->latexname() == name_;
448 Layout_ptr findLayout(TextClass const & textclass,
451 TextClass::const_iterator beg = textclass.begin();
452 TextClass::const_iterator end = textclass.end();
454 TextClass::const_iterator
455 it = std::find_if(beg, end, isLayout(name));
457 return (it == end) ? Layout_ptr() : *it;
461 void eat_whitespace(Parser &, ostream &, Context &, bool);
464 void output_command_layout(ostream & os, Parser & p, bool outer,
465 Context & parent_context,
466 Layout_ptr newlayout)
468 parent_context.check_end_layout(os);
469 Context context(true, parent_context.textclass, newlayout,
470 parent_context.layout, parent_context.font);
471 if (parent_context.deeper_paragraph) {
472 // We are beginning a nested environment after a
473 // deeper paragraph inside the outer list environment.
474 // Therefore we don't need to output a "begin deeper".
475 context.need_end_deeper = true;
477 context.check_deeper(os);
478 context.check_layout(os);
479 if (context.layout->optionalargs > 0) {
480 eat_whitespace(p, os, context, false);
481 if (p.next_token().character() == '[') {
482 p.get_token(); // eat '['
483 begin_inset(os, "OptArg\n");
484 os << "status collapsed\n\n";
485 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
487 eat_whitespace(p, os, context, false);
490 parse_text(p, os, FLAG_ITEM, outer, context);
491 context.check_end_layout(os);
492 if (parent_context.deeper_paragraph) {
493 // We must suppress the "end deeper" because we
494 // suppressed the "begin deeper" above.
495 context.need_end_deeper = false;
497 context.check_end_deeper(os);
498 // We don't need really a new paragraph, but
499 // we must make sure that the next item gets a \begin_layout.
500 parent_context.new_paragraph(os);
505 * Output a space if necessary.
506 * This function gets called for every whitespace token.
508 * We have three cases here:
509 * 1. A space must be suppressed. Example: The lyxcode case below
510 * 2. A space may be suppressed. Example: Spaces before "\par"
511 * 3. A space must not be suppressed. Example: A space between two words
513 * We currently handle only 1. and 3 and from 2. only the case of
514 * spaces before newlines as a side effect.
516 * 2. could be used to suppress as many spaces as possible. This has two effects:
517 * - Reimporting LyX generated LaTeX files changes almost no whitespace
518 * - Superflous whitespace from non LyX generated LaTeX files is removed.
519 * The drawback is that the logic inside the function becomes
520 * complicated, and that is the reason why it is not implemented.
522 void check_space(Parser const & p, ostream & os, Context & context)
524 Token const next = p.next_token();
525 Token const curr = p.curr_token();
526 // A space before a single newline and vice versa must be ignored
527 // LyX emits a newline before \end{lyxcode}.
528 // This newline must be ignored,
529 // otherwise LyX will add an additional protected space.
530 if (next.cat() == catSpace ||
531 next.cat() == catNewline ||
532 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
535 context.check_layout(os);
541 * Parse all arguments of \p command
543 void parse_arguments(string const & command,
544 vector<ArgumentType> const & template_arguments,
545 Parser & p, ostream & os, bool outer, Context & context)
547 string ert = command;
548 size_t no_arguments = template_arguments.size();
549 for (size_t i = 0; i < no_arguments; ++i) {
550 switch (template_arguments[i]) {
552 // This argument contains regular LaTeX
553 handle_ert(os, ert + '{', context);
554 eat_whitespace(p, os, context, false);
555 parse_text(p, os, FLAG_ITEM, outer, context);
559 // This argument may contain special characters
560 ert += '{' + p.verbatim_item() + '}';
567 handle_ert(os, ert, context);
572 * Check whether \p command is a known command. If yes,
573 * handle the command with all arguments.
574 * \return true if the command was parsed, false otherwise.
576 bool parse_command(string const & command, Parser & p, ostream & os,
577 bool outer, Context & context)
579 if (known_commands.find(command) != known_commands.end()) {
580 parse_arguments(command, known_commands[command], p, os,
588 /// Parses a minipage or parbox
589 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
590 Context & parent_context, bool use_parbox)
594 string height_value = "0";
595 string height_unit = "pt";
596 string height_special = "none";
598 if (p.next_token().asInput() == "[") {
599 position = p.getArg('[', ']');
600 if (position != "t" && position != "c" && position != "b") {
602 cerr << "invalid position for minipage/parbox" << endl;
604 if (p.next_token().asInput() == "[") {
605 latex_height = p.getArg('[', ']');
606 translate_box_len(latex_height, height_value, height_unit, height_special);
608 if (p.next_token().asInput() == "[") {
609 inner_pos = p.getArg('[', ']');
610 if (inner_pos != "c" && inner_pos != "t" &&
611 inner_pos != "b" && inner_pos != "s") {
612 inner_pos = position;
613 cerr << "invalid inner_pos for minipage/parbox"
621 string const latex_width = p.verbatim_item();
622 translate_len(latex_width, width_value, width_unit);
623 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
624 // LyX can't handle length variables
629 ss << "\\begin{minipage}";
630 if (!position.empty())
631 ss << '[' << position << ']';
632 if (!latex_height.empty())
633 ss << '[' << latex_height << ']';
634 if (!inner_pos.empty())
635 ss << '[' << inner_pos << ']';
636 ss << "{" << latex_width << "}";
639 handle_ert(os, ss.str(), parent_context);
640 parent_context.new_paragraph(os);
641 parse_text_in_inset(p, os, flags, outer, parent_context);
643 handle_ert(os, "}", parent_context);
645 handle_ert(os, "\\end{minipage}", parent_context);
647 // LyX does not like empty positions, so we have
648 // to set them to the LaTeX default values here.
649 if (position.empty())
651 if (inner_pos.empty())
652 inner_pos = position;
653 parent_context.check_layout(os);
654 begin_inset(os, "Box Frameless\n");
655 os << "position \"" << position << "\"\n";
656 os << "hor_pos \"c\"\n";
657 os << "has_inner_box 1\n";
658 os << "inner_pos \"" << inner_pos << "\"\n";
659 os << "use_parbox " << use_parbox << "\n";
660 os << "width \"" << width_value << width_unit << "\"\n";
661 os << "special \"none\"\n";
662 os << "height \"" << height_value << height_unit << "\"\n";
663 os << "height_special \"" << height_special << "\"\n";
664 os << "status open\n\n";
665 parse_text_in_inset(p, os, flags, outer, parent_context);
667 #ifdef PRESERVE_LAYOUT
668 // lyx puts a % after the end of the minipage
669 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
671 //handle_comment(os, "%dummy", parent_context);
674 parent_context.new_paragraph(os);
676 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
677 //handle_comment(os, "%dummy", parent_context);
680 // We add a protected space if something real follows
681 if (p.good() && p.next_token().cat() != catComment) {
682 os << "\\InsetSpace ~\n";
690 /// parse an unknown environment
691 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
692 unsigned flags, bool outer,
693 Context & parent_context)
695 if (name == "tabbing")
696 // We need to remember that we have to handle '\=' specially
697 flags |= FLAG_TABBING;
699 // We need to translate font changes and paragraphs inside the
700 // environment to ERT if we have a non standard font.
701 // Otherwise things like
702 // \large\begin{foo}\huge bar\end{foo}
704 bool const specialfont =
705 (parent_context.font != parent_context.normalfont);
706 bool const new_layout_allowed = parent_context.new_layout_allowed;
708 parent_context.new_layout_allowed = false;
709 handle_ert(os, "\\begin{" + name + "}", parent_context);
710 parse_text_snippet(p, os, flags, outer, parent_context);
711 handle_ert(os, "\\end{" + name + "}", parent_context);
713 parent_context.new_layout_allowed = new_layout_allowed;
717 void parse_environment(Parser & p, ostream & os, bool outer,
718 Context & parent_context)
720 Layout_ptr newlayout;
721 string const name = p.getArg('{', '}');
722 const bool is_starred = suffixIs(name, '*');
723 string const unstarred_name = rtrim(name, "*");
724 active_environments.push_back(name);
726 if (is_math_env(name)) {
727 parent_context.check_layout(os);
728 begin_inset(os, "Formula ");
729 os << "\\begin{" << name << "}";
730 parse_math(p, os, FLAG_END, MATH_MODE);
731 os << "\\end{" << name << "}";
735 else if (name == "tabular" || name == "longtable") {
736 eat_whitespace(p, os, parent_context, false);
737 parent_context.check_layout(os);
738 begin_inset(os, "Tabular ");
739 handle_tabular(p, os, name == "longtable", parent_context);
744 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
745 eat_whitespace(p, os, parent_context, false);
746 parent_context.check_layout(os);
747 begin_inset(os, "Float " + unstarred_name + "\n");
748 if (p.next_token().asInput() == "[") {
749 os << "placement " << p.getArg('[', ']') << '\n';
751 os << "wide " << convert<string>(is_starred)
752 << "\nsideways false"
753 << "\nstatus open\n\n";
754 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
756 // We don't need really a new paragraph, but
757 // we must make sure that the next item gets a \begin_layout.
758 parent_context.new_paragraph(os);
762 else if (name == "minipage") {
763 eat_whitespace(p, os, parent_context, false);
764 parse_box(p, os, FLAG_END, outer, parent_context, false);
768 else if (name == "comment") {
769 eat_whitespace(p, os, parent_context, false);
770 parent_context.check_layout(os);
771 begin_inset(os, "Note Comment\n");
772 os << "status open\n";
773 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
778 else if (name == "lyxgreyedout") {
779 eat_whitespace(p, os, parent_context, false);
780 parent_context.check_layout(os);
781 begin_inset(os, "Note Greyedout\n");
782 os << "status open\n";
783 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
788 else if (!parent_context.new_layout_allowed)
789 parse_unknown_environment(p, name, os, FLAG_END, outer,
792 // Alignment settings
793 else if (name == "center" || name == "flushleft" || name == "flushright" ||
794 name == "centering" || name == "raggedright" || name == "raggedleft") {
795 eat_whitespace(p, os, parent_context, false);
796 // We must begin a new paragraph if not already done
797 if (! parent_context.atParagraphStart()) {
798 parent_context.check_end_layout(os);
799 parent_context.new_paragraph(os);
801 if (name == "flushleft" || name == "raggedright")
802 parent_context.add_extra_stuff("\\align left\n");
803 else if (name == "flushright" || name == "raggedleft")
804 parent_context.add_extra_stuff("\\align right\n");
806 parent_context.add_extra_stuff("\\align center\n");
807 parse_text(p, os, FLAG_END, outer, parent_context);
808 // Just in case the environment is empty ..
809 parent_context.extra_stuff.erase();
810 // We must begin a new paragraph to reset the alignment
811 parent_context.new_paragraph(os);
815 // The single '=' is meant here.
816 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
817 newlayout->isEnvironment()) {
818 eat_whitespace(p, os, parent_context, false);
819 Context context(true, parent_context.textclass, newlayout,
820 parent_context.layout, parent_context.font);
821 if (parent_context.deeper_paragraph) {
822 // We are beginning a nested environment after a
823 // deeper paragraph inside the outer list environment.
824 // Therefore we don't need to output a "begin deeper".
825 context.need_end_deeper = true;
827 parent_context.check_end_layout(os);
828 switch (context.layout->latextype) {
829 case LATEX_LIST_ENVIRONMENT:
830 context.extra_stuff = "\\labelwidthstring "
831 + p.verbatim_item() + '\n';
834 case LATEX_BIB_ENVIRONMENT:
835 p.verbatim_item(); // swallow next arg
841 context.check_deeper(os);
842 parse_text(p, os, FLAG_END, outer, context);
843 context.check_end_layout(os);
844 if (parent_context.deeper_paragraph) {
845 // We must suppress the "end deeper" because we
846 // suppressed the "begin deeper" above.
847 context.need_end_deeper = false;
849 context.check_end_deeper(os);
850 parent_context.new_paragraph(os);
854 else if (name == "appendix") {
855 // This is no good latex style, but it works and is used in some documents...
856 eat_whitespace(p, os, parent_context, false);
857 parent_context.check_end_layout(os);
858 Context context(true, parent_context.textclass, parent_context.layout,
859 parent_context.layout, parent_context.font);
860 context.check_layout(os);
861 os << "\\start_of_appendix\n";
862 parse_text(p, os, FLAG_END, outer, context);
863 context.check_end_layout(os);
867 else if (known_environments.find(name) != known_environments.end()) {
868 vector<ArgumentType> arguments = known_environments[name];
869 // The last "argument" denotes wether we may translate the
870 // environment contents to LyX
871 // The default required if no argument is given makes us
872 // compatible with the reLyXre environment.
873 ArgumentType contents = arguments.empty() ?
876 if (!arguments.empty())
877 arguments.pop_back();
878 // See comment in parse_unknown_environment()
879 bool const specialfont =
880 (parent_context.font != parent_context.normalfont);
881 bool const new_layout_allowed =
882 parent_context.new_layout_allowed;
884 parent_context.new_layout_allowed = false;
885 parse_arguments("\\begin{" + name + "}", arguments, p, os,
886 outer, parent_context);
887 if (contents == verbatim)
888 handle_ert(os, p.verbatimEnvironment(name),
891 parse_text_snippet(p, os, FLAG_END, outer,
893 handle_ert(os, "\\end{" + name + "}", parent_context);
895 parent_context.new_layout_allowed = new_layout_allowed;
899 parse_unknown_environment(p, name, os, FLAG_END, outer,
902 active_environments.pop_back();
906 /// parses a comment and outputs it to \p os.
907 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
909 BOOST_ASSERT(t.cat() == catComment);
910 if (!t.cs().empty()) {
911 context.check_layout(os);
912 handle_comment(os, '%' + t.cs(), context);
913 if (p.next_token().cat() == catNewline) {
914 // A newline after a comment line starts a new
916 if (context.new_layout_allowed) {
917 if(!context.atParagraphStart())
918 // Only start a new paragraph if not already
919 // done (we might get called recursively)
920 context.new_paragraph(os);
922 handle_ert(os, "\n", context);
923 eat_whitespace(p, os, context, true);
933 * Reads spaces and comments until the first non-space, non-comment token.
934 * New paragraphs (double newlines or \\par) are handled like simple spaces
935 * if \p eatParagraph is true.
936 * Spaces are skipped, but comments are written to \p os.
938 void eat_whitespace(Parser & p, ostream & os, Context & context,
942 Token const & t = p.get_token();
943 if (t.cat() == catComment)
944 parse_comment(p, os, t, context);
945 else if ((! eatParagraph && p.isParagraph()) ||
946 (t.cat() != catSpace && t.cat() != catNewline)) {
955 * Set a font attribute, parse text and reset the font attribute.
956 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
957 * \param currentvalue Current value of the attribute. Is set to the new
958 * value during parsing.
959 * \param newvalue New value of the attribute
961 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
962 Context & context, string const & attribute,
963 string & currentvalue, string const & newvalue)
965 context.check_layout(os);
966 string const oldvalue = currentvalue;
967 currentvalue = newvalue;
968 os << '\n' << attribute << ' ' << newvalue << "\n";
969 parse_text_snippet(p, os, flags, outer, context);
970 context.check_layout(os);
971 os << '\n' << attribute << ' ' << oldvalue << "\n";
972 currentvalue = oldvalue;
976 /// get the arguments of a natbib or jurabib citation command
977 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
979 // We need to distinguish "" and "[]", so we can't use p.getOpt().
981 // text before the citation
983 // text after the citation
984 string after = p.getFullOpt();
986 if (!after.empty()) {
987 before = p.getFullOpt();
988 if (natbibOrder && !before.empty())
989 std::swap(before, after);
991 return std::make_pair(before, after);
995 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
996 string const normalize_filename(string const & name)
998 Parser p(trim(name, "\""));
1001 Token const & t = p.get_token();
1002 if (t.cat() != catEscape)
1004 else if (t.cs() == "lyxdot") {
1005 // This is used by LyX for simple dots in relative
1009 } else if (t.cs() == "space") {
1019 /// Convert \p name from TeX convention (relative to master file) to LyX
1020 /// convention (relative to .lyx file) if it is relative
1021 void fix_relative_filename(string & name)
1023 if (lyx::support::absolutePath(name))
1025 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1027 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1028 from_utf8(getParentFilePath())));
1032 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1033 void parse_noweb(Parser & p, ostream & os, Context & context)
1035 // assemble the rest of the keyword
1039 Token const & t = p.get_token();
1040 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1043 scrap = (p.good() && p.next_token().asInput() == "=");
1045 name += p.get_token().asInput();
1048 name += t.asInput();
1051 if (!scrap || !context.new_layout_allowed ||
1052 !context.textclass.hasLayout("Scrap")) {
1053 cerr << "Warning: Could not interpret '" << name
1054 << "'. Ignoring it." << endl;
1058 // We use new_paragraph instead of check_end_layout because the stuff
1059 // following the noweb chunk needs to start with a \begin_layout.
1060 // This may create a new paragraph even if there was none in the
1061 // noweb file, but the alternative is an invalid LyX file. Since
1062 // noweb code chunks are implemented with a layout style in LyX they
1063 // always must be in an own paragraph.
1064 context.new_paragraph(os);
1065 Context newcontext(true, context.textclass, context.textclass["Scrap"]);
1066 newcontext.check_layout(os);
1069 Token const & t = p.get_token();
1070 // We abuse the parser a bit, because this is no TeX syntax
1072 if (t.cat() == catEscape)
1073 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1075 os << subst(t.asInput(), "\n", "\n\\newline\n");
1076 // The scrap chunk is ended by an @ at the beginning of a line.
1077 // After the @ the line may contain a comment and/or
1078 // whitespace, but nothing else.
1079 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1080 (p.next_token().cat() == catSpace ||
1081 p.next_token().cat() == catNewline ||
1082 p.next_token().cat() == catComment)) {
1083 while (p.good() && p.next_token().cat() == catSpace)
1084 os << p.get_token().asInput();
1085 if (p.next_token().cat() == catComment)
1086 // The comment includes a final '\n'
1087 os << p.get_token().asInput();
1089 if (p.next_token().cat() == catNewline)
1096 newcontext.check_end_layout(os);
1099 } // anonymous namespace
1102 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1105 Layout_ptr newlayout;
1106 // Store the latest bibliographystyle (needed for bibtex inset)
1107 string bibliographystyle;
1108 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1109 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1111 Token const & t = p.get_token();
1114 cerr << "t: " << t << " flags: " << flags << "\n";
1117 if (flags & FLAG_ITEM) {
1118 if (t.cat() == catSpace)
1121 flags &= ~FLAG_ITEM;
1122 if (t.cat() == catBegin) {
1123 // skip the brace and collect everything to the next matching
1125 flags |= FLAG_BRACE_LAST;
1129 // handle only this single token, leave the loop if done
1130 flags |= FLAG_LEAVE;
1133 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1139 if (t.cat() == catMath) {
1140 // we are inside some text mode thingy, so opening new math is allowed
1141 context.check_layout(os);
1142 begin_inset(os, "Formula ");
1143 Token const & n = p.get_token();
1144 if (n.cat() == catMath && outer) {
1145 // TeX's $$...$$ syntax for displayed math
1147 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1149 p.get_token(); // skip the second '$' token
1151 // simple $...$ stuff
1154 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1160 else if (t.cat() == catSuper || t.cat() == catSub)
1161 cerr << "catcode " << t << " illegal in text mode\n";
1163 // Basic support for english quotes. This should be
1164 // extended to other quotes, but is not so easy (a
1165 // left english quote is the same as a right german
1167 else if (t.asInput() == "`"
1168 && p.next_token().asInput() == "`") {
1169 context.check_layout(os);
1170 begin_inset(os, "Quotes ");
1176 else if (t.asInput() == "'"
1177 && p.next_token().asInput() == "'") {
1178 context.check_layout(os);
1179 begin_inset(os, "Quotes ");
1186 else if (t.asInput() == "<"
1187 && p.next_token().asInput() == "<" && noweb_mode) {
1189 parse_noweb(p, os, context);
1192 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1193 check_space(p, os, context);
1195 else if (t.character() == '[' && noweb_mode &&
1196 p.next_token().character() == '[') {
1197 // These can contain underscores
1199 string const s = p.getFullOpt() + ']';
1200 if (p.next_token().character() == ']')
1203 cerr << "Warning: Inserting missing ']' in '"
1204 << s << "'." << endl;
1205 handle_ert(os, s, context);
1208 else if (t.cat() == catLetter ||
1209 t.cat() == catOther ||
1210 t.cat() == catAlign ||
1211 t.cat() == catParameter) {
1212 // This translates "&" to "\\&" which may be wrong...
1213 context.check_layout(os);
1214 os << t.character();
1217 else if (p.isParagraph()) {
1218 if (context.new_layout_allowed)
1219 context.new_paragraph(os);
1221 handle_ert(os, "\\par ", context);
1222 eat_whitespace(p, os, context, true);
1225 else if (t.cat() == catActive) {
1226 context.check_layout(os);
1227 if (t.character() == '~') {
1228 if (context.layout->free_spacing)
1231 os << "\\InsetSpace ~\n";
1233 os << t.character();
1236 else if (t.cat() == catBegin &&
1237 p.next_token().cat() == catEnd) {
1239 Token const prev = p.prev_token();
1241 if (p.next_token().character() == '`' ||
1242 (prev.character() == '-' &&
1243 p.next_token().character() == '-'))
1244 ; // ignore it in {}`` or -{}-
1246 handle_ert(os, "{}", context);
1250 else if (t.cat() == catBegin) {
1251 context.check_layout(os);
1252 // special handling of font attribute changes
1253 Token const prev = p.prev_token();
1254 Token const next = p.next_token();
1255 TeXFont const oldFont = context.font;
1256 if (next.character() == '[' ||
1257 next.character() == ']' ||
1258 next.character() == '*') {
1260 if (p.next_token().cat() == catEnd) {
1261 os << next.character();
1265 handle_ert(os, "{", context);
1266 parse_text_snippet(p, os,
1269 handle_ert(os, "}", context);
1271 } else if (! context.new_layout_allowed) {
1272 handle_ert(os, "{", context);
1273 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1275 handle_ert(os, "}", context);
1276 } else if (is_known(next.cs(), known_sizes)) {
1277 // next will change the size, so we must
1279 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1281 if (!context.atParagraphStart())
1283 << context.font.size << "\n";
1284 } else if (is_known(next.cs(), known_font_families)) {
1285 // next will change the font family, so we
1286 // must reset it here
1287 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1289 if (!context.atParagraphStart())
1291 << context.font.family << "\n";
1292 } else if (is_known(next.cs(), known_font_series)) {
1293 // next will change the font series, so we
1294 // must reset it here
1295 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1297 if (!context.atParagraphStart())
1299 << context.font.series << "\n";
1300 } else if (is_known(next.cs(), known_font_shapes)) {
1301 // next will change the font shape, so we
1302 // must reset it here
1303 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1305 if (!context.atParagraphStart())
1307 << context.font.shape << "\n";
1308 } else if (is_known(next.cs(), known_old_font_families) ||
1309 is_known(next.cs(), known_old_font_series) ||
1310 is_known(next.cs(), known_old_font_shapes)) {
1311 // next will change the font family, series
1312 // and shape, so we must reset it here
1313 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1315 if (!context.atParagraphStart())
1317 << context.font.family
1319 << context.font.series
1321 << context.font.shape << "\n";
1323 handle_ert(os, "{", context);
1324 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1326 handle_ert(os, "}", context);
1330 else if (t.cat() == catEnd) {
1331 if (flags & FLAG_BRACE_LAST) {
1334 cerr << "stray '}' in text\n";
1335 handle_ert(os, "}", context);
1338 else if (t.cat() == catComment)
1339 parse_comment(p, os, t, context);
1342 // control sequences
1345 else if (t.cs() == "(") {
1346 context.check_layout(os);
1347 begin_inset(os, "Formula");
1349 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1354 else if (t.cs() == "[") {
1355 context.check_layout(os);
1356 begin_inset(os, "Formula");
1358 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1363 else if (t.cs() == "begin")
1364 parse_environment(p, os, outer, context);
1366 else if (t.cs() == "end") {
1367 if (flags & FLAG_END) {
1368 // eat environment name
1369 string const name = p.getArg('{', '}');
1370 if (name != active_environment())
1371 cerr << "\\end{" + name + "} does not match \\begin{"
1372 + active_environment() + "}\n";
1375 p.error("found 'end' unexpectedly");
1378 else if (t.cs() == "item") {
1381 bool optarg = false;
1382 if (p.next_token().character() == '[') {
1383 p.get_token(); // eat '['
1384 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1389 context.check_layout(os);
1390 if (context.has_item) {
1391 // An item in an unknown list-like environment
1392 // FIXME: Do this in check_layout()!
1393 context.has_item = false;
1395 handle_ert(os, "\\item", context);
1397 handle_ert(os, "\\item ", context);
1400 if (context.layout->labeltype != LABEL_MANUAL) {
1401 // lyx does not support \item[\mybullet]
1402 // in itemize environments
1403 handle_ert(os, "[", context);
1405 handle_ert(os, "]", context);
1406 } else if (!s.empty()) {
1407 // The space is needed to separate the
1408 // item from the rest of the sentence.
1410 eat_whitespace(p, os, context, false);
1415 else if (t.cs() == "bibitem") {
1417 context.check_layout(os);
1420 os << '{' << p.verbatim_item() << '}' << "\n";
1423 else if (t.cs() == "def") {
1424 context.check_layout(os);
1425 eat_whitespace(p, os, context, false);
1426 string name = p.get_token().cs();
1427 eat_whitespace(p, os, context, false);
1433 while (p.next_token().cat() != catBegin) {
1434 if (p.next_token().cat() == catParameter) {
1439 // followed by number?
1440 if (p.next_token().cat() == catOther) {
1441 char c = p.getChar();
1443 // number = current arity + 1?
1444 if (c == arity + '0' + 1)
1449 paramtext += p.get_token().asString();
1451 paramtext += p.get_token().asString();
1456 // only output simple (i.e. compatible) macro as FormulaMacros
1457 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1459 context.check_layout(os);
1460 begin_inset(os, "FormulaMacro");
1464 handle_ert(os, ert, context);
1467 else if (t.cs() == "noindent") {
1469 context.add_extra_stuff("\\noindent\n");
1472 else if (t.cs() == "appendix") {
1473 context.add_extra_stuff("\\start_of_appendix\n");
1474 // We need to start a new paragraph. Otherwise the
1475 // appendix in 'bla\appendix\chapter{' would start
1477 context.new_paragraph(os);
1478 // We need to make sure that the paragraph is
1479 // generated even if it is empty. Otherwise the
1480 // appendix in '\par\appendix\par\chapter{' would
1482 context.check_layout(os);
1483 // FIXME: This is a hack to prevent paragraph
1484 // deletion if it is empty. Handle this better!
1486 "%dummy comment inserted by tex2lyx to "
1487 "ensure that this paragraph is not empty",
1489 // Both measures above may generate an additional
1490 // empty paragraph, but that does not hurt, because
1491 // whitespace does not matter here.
1492 eat_whitespace(p, os, context, true);
1495 // Must attempt to parse "Section*" before "Section".
1496 else if ((p.next_token().asInput() == "*") &&
1497 context.new_layout_allowed &&
1498 // The single '=' is meant here.
1499 (newlayout = findLayout(context.textclass,
1500 t.cs() + '*')).get() &&
1501 newlayout->isCommand()) {
1503 output_command_layout(os, p, outer, context, newlayout);
1507 // The single '=' is meant here.
1508 else if (context.new_layout_allowed &&
1509 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1510 newlayout->isCommand()) {
1511 output_command_layout(os, p, outer, context, newlayout);
1515 else if (t.cs() == "includegraphics") {
1516 bool const clip = p.next_token().asInput() == "*";
1519 map<string, string> opts = split_map(p.getArg('[', ']'));
1521 opts["clip"] = string();
1522 string name = normalize_filename(p.verbatim_item());
1524 string const path = getMasterFilePath();
1525 // We want to preserve relative / absolute filenames,
1526 // therefore path is only used for testing
1527 // FIXME UNICODE encoding of name and path may be
1528 // wrong (makeAbsPath expects utf8)
1529 if (!fs::exists(makeAbsPath(name, path).toFilesystemEncoding())) {
1530 // The file extension is probably missing.
1531 // Now try to find it out.
1532 string const dvips_name =
1533 find_file(name, path,
1534 known_dvips_graphics_formats);
1535 string const pdftex_name =
1536 find_file(name, path,
1537 known_pdftex_graphics_formats);
1538 if (!dvips_name.empty()) {
1539 if (!pdftex_name.empty()) {
1540 cerr << "This file contains the "
1542 "\"\\includegraphics{"
1544 "However, files\n\""
1545 << dvips_name << "\" and\n\""
1546 << pdftex_name << "\"\n"
1547 "both exist, so I had to make a "
1548 "choice and took the first one.\n"
1549 "Please move the unwanted one "
1550 "someplace else and try again\n"
1551 "if my choice was wrong."
1555 } else if (!pdftex_name.empty())
1559 // FIXME UNICODE encoding of name and path may be
1560 // wrong (makeAbsPath expects utf8)
1561 if (fs::exists(makeAbsPath(name, path).toFilesystemEncoding()))
1562 fix_relative_filename(name);
1564 cerr << "Warning: Could not find graphics file '"
1565 << name << "'." << endl;
1567 context.check_layout(os);
1568 begin_inset(os, "Graphics ");
1569 os << "\n\tfilename " << name << '\n';
1570 if (opts.find("width") != opts.end())
1572 << translate_len(opts["width"]) << '\n';
1573 if (opts.find("height") != opts.end())
1575 << translate_len(opts["height"]) << '\n';
1576 if (opts.find("scale") != opts.end()) {
1577 istringstream iss(opts["scale"]);
1581 os << "\tscale " << val << '\n';
1583 if (opts.find("angle") != opts.end())
1584 os << "\trotateAngle "
1585 << opts["angle"] << '\n';
1586 if (opts.find("origin") != opts.end()) {
1588 string const opt = opts["origin"];
1589 if (opt.find('l') != string::npos) ss << "left";
1590 if (opt.find('r') != string::npos) ss << "right";
1591 if (opt.find('c') != string::npos) ss << "center";
1592 if (opt.find('t') != string::npos) ss << "Top";
1593 if (opt.find('b') != string::npos) ss << "Bottom";
1594 if (opt.find('B') != string::npos) ss << "Baseline";
1595 if (!ss.str().empty())
1596 os << "\trotateOrigin " << ss.str() << '\n';
1598 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1600 if (opts.find("keepaspectratio") != opts.end())
1601 os << "\tkeepAspectRatio\n";
1602 if (opts.find("clip") != opts.end())
1604 if (opts.find("draft") != opts.end())
1606 if (opts.find("bb") != opts.end())
1607 os << "\tBoundingBox "
1608 << opts["bb"] << '\n';
1609 int numberOfbbOptions = 0;
1610 if (opts.find("bbllx") != opts.end())
1611 numberOfbbOptions++;
1612 if (opts.find("bblly") != opts.end())
1613 numberOfbbOptions++;
1614 if (opts.find("bburx") != opts.end())
1615 numberOfbbOptions++;
1616 if (opts.find("bbury") != opts.end())
1617 numberOfbbOptions++;
1618 if (numberOfbbOptions == 4)
1619 os << "\tBoundingBox "
1620 << opts["bbllx"] << opts["bblly"]
1621 << opts["bburx"] << opts["bbury"] << '\n';
1622 else if (numberOfbbOptions > 0)
1623 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1624 numberOfbbOptions = 0;
1625 if (opts.find("natwidth") != opts.end())
1626 numberOfbbOptions++;
1627 if (opts.find("natheight") != opts.end())
1628 numberOfbbOptions++;
1629 if (numberOfbbOptions == 2)
1630 os << "\tBoundingBox 0bp 0bp "
1631 << opts["natwidth"] << opts["natheight"] << '\n';
1632 else if (numberOfbbOptions > 0)
1633 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1634 ostringstream special;
1635 if (opts.find("hiresbb") != opts.end())
1636 special << "hiresbb,";
1637 if (opts.find("trim") != opts.end())
1639 if (opts.find("viewport") != opts.end())
1640 special << "viewport=" << opts["viewport"] << ',';
1641 if (opts.find("totalheight") != opts.end())
1642 special << "totalheight=" << opts["totalheight"] << ',';
1643 if (opts.find("type") != opts.end())
1644 special << "type=" << opts["type"] << ',';
1645 if (opts.find("ext") != opts.end())
1646 special << "ext=" << opts["ext"] << ',';
1647 if (opts.find("read") != opts.end())
1648 special << "read=" << opts["read"] << ',';
1649 if (opts.find("command") != opts.end())
1650 special << "command=" << opts["command"] << ',';
1651 string s_special = special.str();
1652 if (!s_special.empty()) {
1653 // We had special arguments. Remove the trailing ','.
1654 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1656 // TODO: Handle the unknown settings better.
1657 // Warn about invalid options.
1658 // Check whether some option was given twice.
1662 else if (t.cs() == "footnote" ||
1663 (t.cs() == "thanks" && context.layout->intitle)) {
1665 context.check_layout(os);
1666 begin_inset(os, "Foot\n");
1667 os << "status collapsed\n\n";
1668 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1672 else if (t.cs() == "marginpar") {
1674 context.check_layout(os);
1675 begin_inset(os, "Marginal\n");
1676 os << "status collapsed\n\n";
1677 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1681 else if (t.cs() == "ensuremath") {
1683 context.check_layout(os);
1684 string const s = p.verbatim_item();
1685 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1688 handle_ert(os, "\\ensuremath{" + s + "}",
1692 else if (t.cs() == "hfill") {
1693 context.check_layout(os);
1694 os << "\n\\hfill\n";
1699 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1700 // FIXME: Somehow prevent title layouts if
1701 // "maketitle" was not found
1703 skip_braces(p); // swallow this
1706 else if (t.cs() == "tableofcontents") {
1708 context.check_layout(os);
1709 begin_inset(os, "LatexCommand \\tableofcontents\n");
1711 skip_braces(p); // swallow this
1714 else if (t.cs() == "listoffigures") {
1716 context.check_layout(os);
1717 begin_inset(os, "FloatList figure\n");
1719 skip_braces(p); // swallow this
1722 else if (t.cs() == "listoftables") {
1724 context.check_layout(os);
1725 begin_inset(os, "FloatList table\n");
1727 skip_braces(p); // swallow this
1730 else if (t.cs() == "listof") {
1731 p.skip_spaces(true);
1732 string const name = p.get_token().asString();
1733 if (context.textclass.floats().typeExist(name)) {
1734 context.check_layout(os);
1735 begin_inset(os, "FloatList ");
1738 p.get_token(); // swallow second arg
1740 handle_ert(os, "\\listof{" + name + "}", context);
1743 else if (t.cs() == "textrm")
1744 parse_text_attributes(p, os, FLAG_ITEM, outer,
1745 context, "\\family",
1746 context.font.family, "roman");
1748 else if (t.cs() == "textsf")
1749 parse_text_attributes(p, os, FLAG_ITEM, outer,
1750 context, "\\family",
1751 context.font.family, "sans");
1753 else if (t.cs() == "texttt")
1754 parse_text_attributes(p, os, FLAG_ITEM, outer,
1755 context, "\\family",
1756 context.font.family, "typewriter");
1758 else if (t.cs() == "textmd")
1759 parse_text_attributes(p, os, FLAG_ITEM, outer,
1760 context, "\\series",
1761 context.font.series, "medium");
1763 else if (t.cs() == "textbf")
1764 parse_text_attributes(p, os, FLAG_ITEM, outer,
1765 context, "\\series",
1766 context.font.series, "bold");
1768 else if (t.cs() == "textup")
1769 parse_text_attributes(p, os, FLAG_ITEM, outer,
1771 context.font.shape, "up");
1773 else if (t.cs() == "textit")
1774 parse_text_attributes(p, os, FLAG_ITEM, outer,
1776 context.font.shape, "italic");
1778 else if (t.cs() == "textsl")
1779 parse_text_attributes(p, os, FLAG_ITEM, outer,
1781 context.font.shape, "slanted");
1783 else if (t.cs() == "textsc")
1784 parse_text_attributes(p, os, FLAG_ITEM, outer,
1786 context.font.shape, "smallcaps");
1788 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1789 context.check_layout(os);
1790 TeXFont oldFont = context.font;
1791 context.font.init();
1792 context.font.size = oldFont.size;
1793 os << "\n\\family " << context.font.family << "\n";
1794 os << "\n\\series " << context.font.series << "\n";
1795 os << "\n\\shape " << context.font.shape << "\n";
1796 if (t.cs() == "textnormal") {
1797 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1798 output_font_change(os, context.font, oldFont);
1799 context.font = oldFont;
1801 eat_whitespace(p, os, context, false);
1804 else if (t.cs() == "underbar") {
1805 // Do NOT handle \underline.
1806 // \underbar cuts through y, g, q, p etc.,
1807 // \underline does not.
1808 context.check_layout(os);
1809 os << "\n\\bar under\n";
1810 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1811 context.check_layout(os);
1812 os << "\n\\bar default\n";
1815 else if (t.cs() == "emph" || t.cs() == "noun") {
1816 context.check_layout(os);
1817 os << "\n\\" << t.cs() << " on\n";
1818 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1819 context.check_layout(os);
1820 os << "\n\\" << t.cs() << " default\n";
1823 else if (use_natbib &&
1824 is_known(t.cs(), known_natbib_commands) &&
1825 ((t.cs() != "citefullauthor" &&
1826 t.cs() != "citeyear" &&
1827 t.cs() != "citeyearpar") ||
1828 p.next_token().asInput() != "*")) {
1829 context.check_layout(os);
1831 // \citet[before][after]{a} \citet[after][before]{a}
1832 // \citet[before][]{a} \citet[][before]{a}
1833 // \citet[after]{a} \citet[after]{a}
1834 // \citet{a} \citet{a}
1835 string command = '\\' + t.cs();
1836 if (p.next_token().asInput() == "*") {
1840 if (command == "\\citefullauthor")
1841 // alternative name for "\\citeauthor*"
1842 command = "\\citeauthor*";
1844 // text before the citation
1846 // text after the citation
1849 boost::tie(before, after) = getCiteArguments(p, true);
1850 if (command == "\\cite") {
1851 // \cite without optional argument means
1852 // \citet, \cite with at least one optional
1853 // argument means \citep.
1854 if (before.empty() && after.empty())
1855 command = "\\citet";
1857 command = "\\citep";
1859 if (before.empty() && after == "[]")
1860 // avoid \citet[]{a}
1862 else if (before == "[]" && after == "[]") {
1863 // avoid \citet[][]{a}
1867 begin_inset(os, "LatexCommand ");
1868 os << command << after << before
1869 << '{' << p.verbatim_item() << "}\n";
1873 else if (use_jurabib &&
1874 is_known(t.cs(), known_jurabib_commands)) {
1875 context.check_layout(os);
1876 string const command = '\\' + t.cs();
1877 char argumentOrder = '\0';
1878 vector<string> const & options = used_packages["jurabib"];
1879 if (std::find(options.begin(), options.end(),
1880 "natbiborder") != options.end())
1881 argumentOrder = 'n';
1882 else if (std::find(options.begin(), options.end(),
1883 "jurabiborder") != options.end())
1884 argumentOrder = 'j';
1886 // text before the citation
1888 // text after the citation
1891 boost::tie(before, after) =
1892 getCiteArguments(p, argumentOrder != 'j');
1893 string const citation = p.verbatim_item();
1894 if (!before.empty() && argumentOrder == '\0') {
1895 cerr << "Warning: Assuming argument order "
1896 "of jurabib version 0.6 for\n'"
1897 << command << before << after << '{'
1898 << citation << "}'.\n"
1899 "Add 'jurabiborder' to the jurabib "
1900 "package options if you used an\n"
1901 "earlier jurabib version." << endl;
1903 begin_inset(os, "LatexCommand ");
1904 os << command << after << before
1905 << '{' << citation << "}\n";
1909 else if (is_known(t.cs(), known_latex_commands)) {
1910 // This needs to be after the check for natbib and
1911 // jurabib commands, because "cite" has different
1912 // arguments with natbib and jurabib.
1913 context.check_layout(os);
1914 begin_inset(os, "LatexCommand ");
1915 os << '\\' << t.cs();
1916 // lyx cannot handle newlines in a latex command
1917 // FIXME: Move the substitution into parser::getOpt()?
1918 os << subst(p.getOpt(), "\n", " ");
1919 os << subst(p.getOpt(), "\n", " ");
1920 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1924 else if (is_known(t.cs(), known_quotes)) {
1925 char const * const * where = is_known(t.cs(), known_quotes);
1926 context.check_layout(os);
1927 begin_inset(os, "Quotes ");
1928 os << known_coded_quotes[where - known_quotes];
1930 // LyX adds {} after the quote, so we have to eat
1931 // spaces here if there are any before a possible
1933 eat_whitespace(p, os, context, false);
1937 else if (is_known(t.cs(), known_sizes) &&
1938 context.new_layout_allowed) {
1939 char const * const * where = is_known(t.cs(), known_sizes);
1940 context.check_layout(os);
1941 TeXFont const oldFont = context.font;
1942 context.font.size = known_coded_sizes[where - known_sizes];
1943 output_font_change(os, oldFont, context.font);
1944 eat_whitespace(p, os, context, false);
1947 else if (is_known(t.cs(), known_font_families) &&
1948 context.new_layout_allowed) {
1949 char const * const * where =
1950 is_known(t.cs(), known_font_families);
1951 context.check_layout(os);
1952 TeXFont const oldFont = context.font;
1953 context.font.family =
1954 known_coded_font_families[where - known_font_families];
1955 output_font_change(os, oldFont, context.font);
1956 eat_whitespace(p, os, context, false);
1959 else if (is_known(t.cs(), known_font_series) &&
1960 context.new_layout_allowed) {
1961 char const * const * where =
1962 is_known(t.cs(), known_font_series);
1963 context.check_layout(os);
1964 TeXFont const oldFont = context.font;
1965 context.font.series =
1966 known_coded_font_series[where - known_font_series];
1967 output_font_change(os, oldFont, context.font);
1968 eat_whitespace(p, os, context, false);
1971 else if (is_known(t.cs(), known_font_shapes) &&
1972 context.new_layout_allowed) {
1973 char const * const * where =
1974 is_known(t.cs(), known_font_shapes);
1975 context.check_layout(os);
1976 TeXFont const oldFont = context.font;
1977 context.font.shape =
1978 known_coded_font_shapes[where - known_font_shapes];
1979 output_font_change(os, oldFont, context.font);
1980 eat_whitespace(p, os, context, false);
1982 else if (is_known(t.cs(), known_old_font_families) &&
1983 context.new_layout_allowed) {
1984 char const * const * where =
1985 is_known(t.cs(), known_old_font_families);
1986 context.check_layout(os);
1987 TeXFont const oldFont = context.font;
1988 context.font.init();
1989 context.font.size = oldFont.size;
1990 context.font.family =
1991 known_coded_font_families[where - known_old_font_families];
1992 output_font_change(os, oldFont, context.font);
1993 eat_whitespace(p, os, context, false);
1996 else if (is_known(t.cs(), known_old_font_series) &&
1997 context.new_layout_allowed) {
1998 char const * const * where =
1999 is_known(t.cs(), known_old_font_series);
2000 context.check_layout(os);
2001 TeXFont const oldFont = context.font;
2002 context.font.init();
2003 context.font.size = oldFont.size;
2004 context.font.series =
2005 known_coded_font_series[where - known_old_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_old_font_shapes) &&
2011 context.new_layout_allowed) {
2012 char const * const * where =
2013 is_known(t.cs(), known_old_font_shapes);
2014 context.check_layout(os);
2015 TeXFont const oldFont = context.font;
2016 context.font.init();
2017 context.font.size = oldFont.size;
2018 context.font.shape =
2019 known_coded_font_shapes[where - known_old_font_shapes];
2020 output_font_change(os, oldFont, context.font);
2021 eat_whitespace(p, os, context, false);
2024 else if (t.cs() == "LyX" || t.cs() == "TeX"
2025 || t.cs() == "LaTeX") {
2026 context.check_layout(os);
2028 skip_braces(p); // eat {}
2031 else if (t.cs() == "LaTeXe") {
2032 context.check_layout(os);
2034 skip_braces(p); // eat {}
2037 else if (t.cs() == "ldots") {
2038 context.check_layout(os);
2040 os << "\\SpecialChar \\ldots{}\n";
2043 else if (t.cs() == "lyxarrow") {
2044 context.check_layout(os);
2045 os << "\\SpecialChar \\menuseparator\n";
2049 else if (t.cs() == "textcompwordmark") {
2050 context.check_layout(os);
2051 os << "\\SpecialChar \\textcompwordmark{}\n";
2055 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2056 context.check_layout(os);
2057 os << "\\SpecialChar \\@.\n";
2061 else if (t.cs() == "-") {
2062 context.check_layout(os);
2063 os << "\\SpecialChar \\-\n";
2066 else if (t.cs() == "textasciitilde") {
2067 context.check_layout(os);
2072 else if (t.cs() == "textasciicircum") {
2073 context.check_layout(os);
2078 else if (t.cs() == "textbackslash") {
2079 context.check_layout(os);
2080 os << "\n\\backslash\n";
2084 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2085 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2087 context.check_layout(os);
2091 else if (t.cs() == "char") {
2092 context.check_layout(os);
2093 if (p.next_token().character() == '`') {
2095 if (p.next_token().cs() == "\"") {
2100 handle_ert(os, "\\char`", context);
2103 handle_ert(os, "\\char", context);
2107 else if (t.cs() == "verb") {
2108 context.check_layout(os);
2109 char const delimiter = p.next_token().character();
2110 string const arg = p.getArg(delimiter, delimiter);
2112 oss << "\\verb" << delimiter << arg << delimiter;
2113 handle_ert(os, oss.str(), context);
2116 else if (t.cs() == "\"") {
2117 context.check_layout(os);
2118 string const name = p.verbatim_item();
2119 if (name == "a") os << '\xe4';
2120 else if (name == "o") os << '\xf6';
2121 else if (name == "u") os << '\xfc';
2122 else if (name == "A") os << '\xc4';
2123 else if (name == "O") os << '\xd6';
2124 else if (name == "U") os << '\xdc';
2125 else handle_ert(os, "\"{" + name + "}", context);
2128 // Problem: \= creates a tabstop inside the tabbing environment
2129 // and else an accent. In the latter case we really would want
2130 // \={o} instead of \= o.
2131 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2132 handle_ert(os, t.asInput(), context);
2134 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2135 || t.cs() == "'" || t.cs() == "`"
2136 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2137 // we need the trim as the LyX parser chokes on such spaces
2138 // The argument of InsetLatexAccent is parsed as a
2139 // subset of LaTeX, so don't parse anything here,
2140 // but use the raw argument.
2141 // Otherwise we would convert \~{\i} wrongly.
2142 // This will of course not translate \~{\ss} to \~{ß},
2143 // but that does at least compile and does only look
2144 // strange on screen.
2145 context.check_layout(os);
2146 os << "\\i \\" << t.cs() << "{"
2147 << trim(p.verbatim_item(), " ")
2151 else if (t.cs() == "ss") {
2152 context.check_layout(os);
2154 skip_braces(p); // eat {}
2157 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2159 context.check_layout(os);
2160 os << "\\i \\" << t.cs() << "{}\n";
2161 skip_braces(p); // eat {}
2164 else if (t.cs() == "\\") {
2165 context.check_layout(os);
2166 string const next = p.next_token().asInput();
2168 handle_ert(os, "\\\\" + p.getOpt(), context);
2169 else if (next == "*") {
2171 handle_ert(os, "\\\\*" + p.getOpt(), context);
2174 os << "\n\\newline\n";
2178 else if (t.cs() == "input" || t.cs() == "include"
2179 || t.cs() == "verbatiminput") {
2180 string name = '\\' + t.cs();
2181 if (t.cs() == "verbatiminput"
2182 && p.next_token().asInput() == "*")
2183 name += p.get_token().asInput();
2184 context.check_layout(os);
2185 begin_inset(os, "Include ");
2186 string filename(normalize_filename(p.getArg('{', '}')));
2187 string const path = getMasterFilePath();
2188 // We want to preserve relative / absolute filenames,
2189 // therefore path is only used for testing
2190 // FIXME UNICODE encoding of filename and path may be
2191 // wrong (makeAbsPath expects utf8)
2192 if ((t.cs() == "include" || t.cs() == "input") &&
2193 !fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2194 // The file extension is probably missing.
2195 // Now try to find it out.
2196 string const tex_name =
2197 find_file(filename, path,
2198 known_tex_extensions);
2199 if (!tex_name.empty())
2200 filename = tex_name;
2202 // FIXME UNICODE encoding of filename and path may be
2203 // wrong (makeAbsPath expects utf8)
2204 if (fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2205 string const abstexname =
2206 makeAbsPath(filename, path).absFilename();
2207 string const abslyxname =
2208 changeExtension(abstexname, ".lyx");
2209 fix_relative_filename(filename);
2210 string const lyxname =
2211 changeExtension(filename, ".lyx");
2212 if (t.cs() != "verbatiminput" &&
2213 tex2lyx(abstexname, FileName(abslyxname))) {
2214 os << name << '{' << lyxname << "}\n";
2216 os << name << '{' << filename << "}\n";
2219 cerr << "Warning: Could not find included file '"
2220 << filename << "'." << endl;
2221 os << name << '{' << filename << "}\n";
2223 os << "preview false\n";
2227 else if (t.cs() == "bibliographystyle") {
2228 // store new bibliographystyle
2229 bibliographystyle = p.verbatim_item();
2230 // output new bibliographystyle.
2231 // This is only necessary if used in some other macro than \bibliography.
2232 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2235 else if (t.cs() == "bibliography") {
2236 context.check_layout(os);
2237 begin_inset(os, "LatexCommand ");
2239 // Do we have a bibliographystyle set?
2240 if (!bibliographystyle.empty()) {
2241 os << '[' << bibliographystyle << ']';
2243 os << '{' << p.verbatim_item() << "}\n";
2247 else if (t.cs() == "parbox")
2248 parse_box(p, os, FLAG_ITEM, outer, context, true);
2250 else if (t.cs() == "smallskip" ||
2251 t.cs() == "medskip" ||
2252 t.cs() == "bigskip" ||
2253 t.cs() == "vfill") {
2254 context.check_layout(os);
2255 begin_inset(os, "VSpace ");
2261 else if (is_known(t.cs(), known_spaces)) {
2262 char const * const * where = is_known(t.cs(), known_spaces);
2263 context.check_layout(os);
2264 begin_inset(os, "InsetSpace ");
2265 os << '\\' << known_coded_spaces[where - known_spaces]
2267 // LaTeX swallows whitespace after all spaces except
2268 // "\\,". We have to do that here, too, because LyX
2269 // adds "{}" which would make the spaces significant.
2271 eat_whitespace(p, os, context, false);
2272 // LyX adds "{}" after all spaces except "\\ " and
2273 // "\\,", so we have to remove "{}".
2274 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2275 // remove the braces after "\\,", too.
2280 else if (t.cs() == "newpage" ||
2281 t.cs() == "clearpage" ||
2282 t.cs() == "cleardoublepage") {
2283 context.check_layout(os);
2284 // FIXME: what about \\pagebreak?
2285 os << "\n\\" << t.cs() << "\n";
2286 skip_braces(p); // eat {}
2289 else if (t.cs() == "newcommand" ||
2290 t.cs() == "providecommand" ||
2291 t.cs() == "renewcommand") {
2292 // these could be handled by parse_command(), but
2293 // we need to call add_known_command() here.
2294 string name = t.asInput();
2295 if (p.next_token().asInput() == "*") {
2296 // Starred form. Eat '*'
2300 string const command = p.verbatim_item();
2301 string const opt1 = p.getOpt();
2302 string const opt2 = p.getFullOpt();
2303 add_known_command(command, opt1, !opt2.empty());
2304 string const ert = name + '{' + command + '}' +
2306 '{' + p.verbatim_item() + '}';
2309 context.check_layout(os);
2310 begin_inset(os, "FormulaMacro");
2314 // we cannot handle optional argument, so only output ERT
2315 handle_ert(os, ert, context);
2318 else if (t.cs() == "vspace") {
2319 bool starred = false;
2320 if (p.next_token().asInput() == "*") {
2324 string const length = p.verbatim_item();
2327 bool valid = splitLatexLength(length, valstring, unit);
2328 bool known_vspace = false;
2329 bool known_unit = false;
2332 istringstream iss(valstring);
2335 if (unit == "\\smallskipamount") {
2337 known_vspace = true;
2338 } else if (unit == "\\medskipamount") {
2340 known_vspace = true;
2341 } else if (unit == "\\bigskipamount") {
2343 known_vspace = true;
2344 } else if (unit == "\\fill") {
2346 known_vspace = true;
2349 if (!known_vspace) {
2350 switch (unitFromString(unit)) {
2371 if (known_unit || known_vspace) {
2372 // Literal length or known variable
2373 context.check_layout(os);
2374 begin_inset(os, "VSpace ");
2382 // LyX can't handle other length variables in Inset VSpace
2383 string name = t.asInput();
2388 handle_ert(os, name + '{' + unit + '}', context);
2389 else if (value == -1.0)
2390 handle_ert(os, name + "{-" + unit + '}', context);
2392 handle_ert(os, name + '{' + valstring + unit + '}', context);
2394 handle_ert(os, name + '{' + length + '}', context);
2399 //cerr << "#: " << t << " mode: " << mode << endl;
2400 // heuristic: read up to next non-nested space
2402 string s = t.asInput();
2403 string z = p.verbatim_item();
2404 while (p.good() && z != " " && z.size()) {
2405 //cerr << "read: " << z << endl;
2407 z = p.verbatim_item();
2409 cerr << "found ERT: " << s << endl;
2410 handle_ert(os, s + ' ', context);
2412 string name = t.asInput();
2413 if (p.next_token().asInput() == "*") {
2414 // Starred commands like \vspace*{}
2415 p.get_token(); // Eat '*'
2418 if (! parse_command(name, p, os, outer, context))
2419 handle_ert(os, name, context);
2422 if (flags & FLAG_LEAVE) {
2423 flags &= ~FLAG_LEAVE;