3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
20 #include "LayoutFile.h"
21 #include "LayoutModuleList.h"
22 #include "ModuleList.h"
23 #include "TextClass.h"
25 #include "support/convert.h"
26 #include "support/debug.h"
27 #include "support/ExceptionMessage.h"
28 #include "support/filetools.h"
29 #include "support/lassert.h"
30 #include "support/lstrings.h"
31 #include "support/Messages.h"
32 #include "support/os.h"
33 #include "support/Package.h"
34 #include "support/Systemcall.h"
44 using namespace lyx::support;
45 using namespace lyx::support::os;
51 void warning(docstring const & title, docstring const & message,
61 // Dummy translation support
63 Messages const & getMessages(std::string const &)
69 Messages const & getGuiMessages()
75 // Keep the linker happy on Windows
80 string const trim(string const & a, char const * p)
87 size_t r = a.find_last_not_of(p);
88 size_t l = a.find_first_not_of(p);
90 // Is this the minimal test? (lgb)
91 if (r == string::npos && l == string::npos)
94 return a.substr(l, r - l + 1);
98 void split(string const & s, vector<string> & result, char delim)
100 //cerr << "split 1: '" << s << "'\n";
103 while (getline(is, t, delim))
105 //cerr << "split 2\n";
109 string join(vector<string> const & input, char const * delim)
112 for (size_t i = 0; i != input.size(); ++i) {
121 char const * const * is_known(string const & str, char const * const * what)
123 for ( ; *what; ++what)
131 // current stack of nested environments
132 vector<string> active_environments;
135 string active_environment()
137 return active_environments.empty() ? string() : active_environments.back();
141 TeX2LyXDocClass textclass;
142 CommandMap known_commands;
143 CommandMap known_environments;
144 CommandMap known_math_environments;
145 FullCommandMap possible_textclass_commands;
146 FullEnvironmentMap possible_textclass_environments;
149 LayoutModuleList used_modules;
152 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
154 // We have to handle the following cases:
155 // definition o1 o2 invocation result
156 // \newcommand{\foo}{bar} "" false \foo bar
157 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
158 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
159 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
160 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
161 unsigned int nargs = 0;
162 string const opt1 = rtrim(ltrim(o1, "["), "]");
163 if (isStrUnsignedInt(opt1)) {
164 // The command has arguments
165 nargs = convert<unsigned int>(opt1);
166 if (nargs > 0 && o2) {
167 // The first argument is optional
168 arguments.push_back(optional);
172 for (unsigned int i = 0; i < nargs; ++i)
173 arguments.push_back(required);
177 void add_known_command(string const & command, string const & o1,
178 bool o2, docstring const & definition)
180 vector<ArgumentType> arguments;
181 convertArgs(o1, o2, arguments);
182 known_commands[command] = arguments;
183 if (!definition.empty())
184 possible_textclass_commands[command] =
185 FullCommand(arguments, definition);
189 void add_known_environment(string const & environment, string const & o1,
190 bool o2, docstring const & beg, docstring const &end)
192 vector<ArgumentType> arguments;
193 convertArgs(o1, o2, arguments);
194 known_environments[environment] = arguments;
195 if (!beg.empty() || ! end.empty())
196 possible_textclass_environments[environment] =
197 FullEnvironment(arguments, beg, end);
201 Layout const * findLayoutWithoutModule(TextClass const & textclass,
202 string const & name, bool command)
204 DocumentClass::const_iterator it = textclass.begin();
205 DocumentClass::const_iterator en = textclass.end();
206 for (; it != en; ++it) {
207 if (it->latexname() == name &&
208 ((command && it->isCommand()) || (!command && it->isEnvironment())))
215 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
216 string const & name, bool command)
218 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
219 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
220 for (; it != en; ++it) {
221 if (it->second.latexname() == name &&
222 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
223 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
224 return &(it->second);
230 bool checkModule(string const & name, bool command)
232 // Cache to avoid slowdown by repated searches
233 static set<string> failed[2];
235 // Only add the module if the command was actually defined in the LyX preamble
237 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
240 if (possible_textclass_environments.find(name) == possible_textclass_environments.end())
243 if (failed[command].find(name) != failed[command].end())
246 // Create list of dummy document classes if not already done.
247 // This is needed since a module cannot be read on its own, only as
248 // part of a document class.
249 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
250 typedef map<string, DocumentClass *> ModuleMap;
251 static ModuleMap modules;
252 static bool init = true;
255 DocumentClassBundle & bundle = DocumentClassBundle::get();
256 LyXModuleList::const_iterator const end = theModuleList.end();
257 LyXModuleList::const_iterator it = theModuleList.begin();
258 for (; it != end; it++) {
259 string const module = it->getID();
261 // FIXME this excludes all modules that depend on another one
262 if (!m.moduleCanBeAdded(module, &baseClass))
265 modules[module] = &bundle.makeDocumentClass(baseClass, m);
270 // Try to find a module that defines the command.
271 // Only add it if the definition can be found in the preamble of the
272 // style that corresponds to the command. This is a heuristic and
273 // different from the way how we parse the builtin commands of the
274 // text class (in that case we only compare the name), but it is
275 // needed since it is not unlikely that two different modules define a
276 // command with the same name.
277 ModuleMap::iterator const end = modules.end();
278 for (ModuleMap::iterator it = modules.begin(); it != end; it++) {
279 string const module = it->first;
280 if (!used_modules.moduleCanBeAdded(module, &baseClass))
282 if (findLayoutWithoutModule(textclass, name, command))
284 if (findInsetLayoutWithoutModule(textclass, name, command))
286 DocumentClass const * c = it->second;
287 Layout const * layout = findLayoutWithoutModule(*c, name, command);
288 InsetLayout const * insetlayout = layout ? 0 :
289 findInsetLayoutWithoutModule(*c, name, command);
292 preamble = layout->preamble();
293 else if (insetlayout)
294 preamble = insetlayout->preamble();
295 if (preamble.empty())
299 FullCommand const & cmd =
300 possible_textclass_commands['\\' + name];
301 if (preamble.find(cmd.def) != docstring::npos)
304 FullEnvironment const & env =
305 possible_textclass_environments[name];
306 if (preamble.find(env.beg) != docstring::npos &&
307 preamble.find(env.end) != docstring::npos)
311 FileName layout_file = libFileSearch("layouts", module, "module");
312 if (textclass.read(layout_file, TextClass::MODULE)) {
313 used_modules.push_back(module);
314 // speed up further searches:
315 // the module does not need to be checked anymore.
321 failed[command].insert(name);
326 bool noweb_mode = false;
327 bool pdflatex = false;
328 bool roundtrip = false;
335 * Read one command definition from the syntax file
337 void read_command(Parser & p, string command, CommandMap & commands)
339 if (p.next_token().asInput() == "*") {
343 vector<ArgumentType> arguments;
344 while (p.next_token().cat() == catBegin ||
345 p.next_token().asInput() == "[") {
346 if (p.next_token().cat() == catBegin) {
347 string const arg = p.getArg('{', '}');
348 if (arg == "translate")
349 arguments.push_back(required);
350 else if (arg == "item")
351 arguments.push_back(item);
353 arguments.push_back(verbatim);
356 arguments.push_back(optional);
359 commands[command] = arguments;
364 * Read a class of environments from the syntax file
366 void read_environment(Parser & p, string const & begin,
367 CommandMap & environments)
371 Token const & t = p.get_token();
372 if (t.cat() == catLetter)
373 environment += t.asInput();
374 else if (!environment.empty()) {
376 read_command(p, environment, environments);
379 if (t.cat() == catEscape && t.asInput() == "\\end") {
380 string const end = p.getArg('{', '}');
389 * Read a list of TeX commands from a reLyX compatible syntax file.
390 * Since this list is used after all commands that have a LyX counterpart
391 * are handled, it does not matter that the "syntax.default" file
392 * has almost all of them listed. For the same reason the reLyX-specific
393 * reLyXre environment is ignored.
395 void read_syntaxfile(FileName const & file_name)
397 ifdocstream is(file_name.toFilesystemEncoding().c_str());
399 cerr << "Could not open syntax file \"" << file_name
400 << "\" for reading." << endl;
403 // We can use our TeX parser, since the syntax of the layout file is
404 // modeled after TeX.
405 // Unknown tokens are just silently ignored, this helps us to skip some
406 // reLyX specific things.
409 Token const & t = p.get_token();
410 if (t.cat() == catEscape) {
411 string const command = t.asInput();
412 if (command == "\\begin") {
413 string const name = p.getArg('{', '}');
414 if (name == "environments" || name == "reLyXre")
415 // We understand "reLyXre", but it is
416 // not as powerful as "environments".
417 read_environment(p, name,
419 else if (name == "mathenvironments")
420 read_environment(p, name,
421 known_math_environments);
423 read_command(p, command, known_commands);
430 string documentclass;
431 string default_encoding;
433 bool overwrite_files = false;
436 /// return the number of arguments consumed
437 typedef int (*cmd_helper)(string const &, string const &);
440 int parse_help(string const &, string const &)
442 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
444 "\t-c textclass Declare the textclass.\n"
445 "\t-e encoding Set the default encoding (latex name).\n"
446 "\t-f Force overwrite of .lyx files.\n"
447 "\t-help Print this message and quit.\n"
448 "\t-n translate a noweb (aka literate programming) file.\n"
449 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
450 "\t-s syntaxfile read additional syntax file.\n"
451 "\t-sysdir dir Set system directory to DIR.\n"
452 "\t-userdir DIR Set user directory to DIR."
458 void error_message(string const & message)
460 cerr << "tex2lyx: " << message << "\n\n";
462 parse_help(string(), string());
466 int parse_class(string const & arg, string const &)
469 error_message("Missing textclass string after -c switch");
475 int parse_encoding(string const & arg, string const &)
478 error_message("Missing encoding string after -e switch");
479 default_encoding = arg;
484 int parse_syntaxfile(string const & arg, string const &)
487 error_message("Missing syntaxfile string after -s switch");
488 syntaxfile = internal_path(arg);
493 // Filled with the command line arguments "foo" of "-sysdir foo" or
495 string cl_system_support;
496 string cl_user_support;
499 int parse_sysdir(string const & arg, string const &)
502 error_message("Missing directory for -sysdir switch");
503 cl_system_support = internal_path(arg);
508 int parse_userdir(string const & arg, string const &)
511 error_message("Missing directory for -userdir switch");
512 cl_user_support = internal_path(arg);
517 int parse_force(string const &, string const &)
519 overwrite_files = true;
524 int parse_noweb(string const &, string const &)
531 int parse_roundtrip(string const &, string const &)
538 void easyParse(int & argc, char * argv[])
540 map<string, cmd_helper> cmdmap;
542 cmdmap["-c"] = parse_class;
543 cmdmap["-e"] = parse_encoding;
544 cmdmap["-f"] = parse_force;
545 cmdmap["-s"] = parse_syntaxfile;
546 cmdmap["-help"] = parse_help;
547 cmdmap["--help"] = parse_help;
548 cmdmap["-n"] = parse_noweb;
549 cmdmap["-sysdir"] = parse_sysdir;
550 cmdmap["-userdir"] = parse_userdir;
551 cmdmap["-roundtrip"] = parse_roundtrip;
553 for (int i = 1; i < argc; ++i) {
554 map<string, cmd_helper>::const_iterator it
555 = cmdmap.find(argv[i]);
557 // don't complain if not found - may be parsed later
558 if (it == cmdmap.end()) {
559 if (argv[i][0] == '-')
560 error_message(string("Unknown option `") + argv[i] + "'.");
565 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
566 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
568 int const remove = 1 + it->second(arg, arg2);
570 // Now, remove used arguments by shifting
571 // the following ones remove places down.
572 os::remove_internal_args(i, remove);
574 for (int j = i; j < argc; ++j)
575 argv[j] = argv[j + remove];
581 // path of the first parsed file
582 string masterFilePath;
583 // path of the currently parsed file
584 string parentFilePath;
586 } // anonymous namespace
589 string getMasterFilePath()
591 return masterFilePath;
594 string getParentFilePath()
596 return parentFilePath;
603 * Reads tex input from \a is and writes lyx output to \a os.
604 * Uses some common settings for the preamble, so this should only
605 * be used more than once for included documents.
606 * Caution: Overwrites the existing preamble settings if the new document
607 * contains a preamble.
608 * You must ensure that \p parentFilePath is properly set before calling
611 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
614 if (!encoding.empty())
615 p.setEncoding(encoding);
619 parse_preamble(p, ps, documentclass, textclass);
621 active_environments.push_back("document");
622 Context context(true, textclass);
624 parse_text(p, ss, FLAG_END, true, context);
626 // Empty document body. LyX needs at least one paragraph.
627 context.check_layout(ss);
628 context.check_end_layout(ss);
629 ss << "\n\\end_body\n\\end_document\n";
630 active_environments.pop_back();
632 // We know the used modules only after parsing the full text
634 if (!used_modules.empty()) {
635 ms << "\\begin_modules\n";
636 LayoutModuleList::const_iterator const end = used_modules.end();
637 LayoutModuleList::const_iterator it = used_modules.begin();
638 for (; it != end; it++)
640 ms << "\\end_modules\n";
642 os << subst(ps.str(), modules_placeholder, ms.str());
648 ofdocstream parsertest("parsertest.tex");
650 parsertest << p.get_token().asInput();
651 // <origfile> and parsertest.tex should now have identical content
656 /// convert TeX from \p infilename to LyX and write it to \p os
657 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
660 // forbid buffering on this stream
661 is.rdbuf()->pubsetbuf(0,0);
662 is.open(infilename.toFilesystemEncoding().c_str());
664 cerr << "Could not open input file \"" << infilename
665 << "\" for reading." << endl;
668 string const oldParentFilePath = parentFilePath;
669 parentFilePath = onlyPath(infilename.absFileName());
670 tex2lyx(is, os, encoding);
671 parentFilePath = oldParentFilePath;
675 } // anonymous namespace
678 bool tex2lyx(string const & infilename, FileName const & outfilename,
679 string const & encoding)
681 if (outfilename.isReadableFile()) {
682 if (overwrite_files) {
683 cerr << "Overwriting existing file "
684 << outfilename << endl;
686 cerr << "Not overwriting existing file "
687 << outfilename << endl;
691 cerr << "Creating file " << outfilename << endl;
693 ofstream os(outfilename.toFilesystemEncoding().c_str());
695 cerr << "Could not open output file \"" << outfilename
696 << "\" for writing." << endl;
700 cerr << "Input file: " << infilename << "\n";
701 cerr << "Output file: " << outfilename << "\n";
703 return tex2lyx(FileName(infilename), os, encoding);
707 bool tex2tex(string const & infilename, FileName const & outfilename,
708 string const & encoding)
710 if (!tex2lyx(infilename, outfilename, encoding))
712 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
714 command += " -f main";
716 command += " -f none";
718 command += " -e pdflatex ";
720 command += " -e latex ";
721 command += quoteName(outfilename.toFilesystemEncoding());
723 if (one.startscript(Systemcall::Wait, command) == 0)
725 cerr << "Error: Running '" << command << "' failed." << endl;
732 int main(int argc, char * argv[])
736 //setlocale(LC_CTYPE, "");
738 lyxerr.setStream(cerr);
740 os::init(argc, argv);
742 easyParse(argc, argv);
745 error_message("Not enough arguments.");
748 init_package(internal_path(os::utf8_argv(0)),
749 cl_system_support, cl_user_support,
750 top_build_dir_is_two_levels_up);
751 } catch (ExceptionMessage const & message) {
752 cerr << to_utf8(message.title_) << ":\n"
753 << to_utf8(message.details_) << endl;
754 if (message.type_ == ErrorException)
758 // Now every known option is parsed. Look for input and output
759 // file name (the latter is optional).
760 string infilename = internal_path(os::utf8_argv(1));
761 infilename = makeAbsPath(infilename).absFileName();
766 // Do not allow a user supplied output filename
767 // (otherwise it could easily happen that LyX would
768 // overwrite the original .tex file)
769 cerr << "Error: output filename must not be given in roundtrip mode."
773 outfilename = changeExtension(infilename, ".lyx.lyx");
774 } else if (argc > 2) {
775 outfilename = internal_path(os::utf8_argv(2));
776 if (outfilename != "-")
777 outfilename = makeAbsPath(outfilename).absFileName();
779 outfilename = changeExtension(infilename, ".lyx");
781 // Read the syntax tables
782 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
783 if (system_syntaxfile.empty()) {
784 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
787 read_syntaxfile(system_syntaxfile);
788 if (!syntaxfile.empty())
789 read_syntaxfile(makeAbsPath(syntaxfile));
791 // Read the encodings table.
792 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
793 if (symbols_path.empty()) {
794 cerr << "Error: Could not find file \"unicodesymbols\"."
798 FileName const enc_path = libFileSearch(string(), "encodings");
799 if (enc_path.empty()) {
800 cerr << "Error: Could not find file \"encodings\"."
804 encodings.read(enc_path, symbols_path);
805 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
806 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
809 LayoutFileList::get().read();
811 theModuleList.read();
813 // The real work now.
814 masterFilePath = onlyPath(infilename);
815 parentFilePath = masterFilePath;
816 if (outfilename == "-") {
817 if (tex2lyx(FileName(infilename), cout, default_encoding))
819 } else if (roundtrip) {
820 if (tex2tex(infilename, FileName(outfilename), default_encoding))
823 if (tex2lyx(infilename, FileName(outfilename), default_encoding))