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.
21 #include "LayoutFile.h"
22 #include "LayoutModuleList.h"
23 #include "ModuleList.h"
25 #include "TextClass.h"
27 #include "support/convert.h"
28 #include "support/debug.h"
29 #include "support/ExceptionMessage.h"
30 #include "support/filetools.h"
31 #include "support/lassert.h"
32 #include "support/lstrings.h"
33 #include "support/Messages.h"
34 #include "support/os.h"
35 #include "support/Package.h"
36 #include "support/Systemcall.h"
46 using namespace lyx::support;
47 using namespace lyx::support::os;
53 void warning(docstring const & title, docstring const & message,
63 // Dummy texrow support
64 void TexRow::newline()
68 void TexRow::newlines(int)
72 // Dummy LyXRC support
79 // Dummy translation support
81 Messages const & getMessages(std::string const &)
87 Messages const & getGuiMessages()
93 // Keep the linker happy on Windows
98 string const trimSpaceAndEol(string const & a)
100 return trim(a, " \t\n\r");
104 void split(string const & s, vector<string> & result, char delim)
106 //cerr << "split 1: '" << s << "'\n";
109 while (getline(is, t, delim))
111 //cerr << "split 2\n";
115 string join(vector<string> const & input, char const * delim)
118 for (size_t i = 0; i != input.size(); ++i) {
127 char const * const * is_known(string const & str, char const * const * what)
129 for ( ; *what; ++what)
137 // current stack of nested environments
138 vector<string> active_environments;
141 string active_environment()
143 return active_environments.empty() ? string() : active_environments.back();
147 TeX2LyXDocClass textclass;
148 CommandMap known_commands;
149 CommandMap known_environments;
150 CommandMap known_math_environments;
151 FullCommandMap possible_textclass_commands;
152 FullEnvironmentMap possible_textclass_environments;
153 int const LYX_FORMAT = LYX_FORMAT_TEX2LYX;
156 LayoutModuleList used_modules;
159 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
161 // We have to handle the following cases:
162 // definition o1 o2 invocation result
163 // \newcommand{\foo}{bar} "" false \foo bar
164 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
165 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
166 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
167 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
168 unsigned int nargs = 0;
169 string const opt1 = rtrim(ltrim(o1, "["), "]");
170 if (isStrUnsignedInt(opt1)) {
171 // The command has arguments
172 nargs = convert<unsigned int>(opt1);
173 if (nargs > 0 && o2) {
174 // The first argument is optional
175 arguments.push_back(optional);
179 for (unsigned int i = 0; i < nargs; ++i)
180 arguments.push_back(required);
184 void add_known_command(string const & command, string const & o1,
185 bool o2, docstring const & definition)
187 vector<ArgumentType> arguments;
188 convertArgs(o1, o2, arguments);
189 known_commands[command] = arguments;
190 if (!definition.empty())
191 possible_textclass_commands[command] =
192 FullCommand(arguments, definition);
196 void add_known_environment(string const & environment, string const & o1,
197 bool o2, docstring const & beg, docstring const &end)
199 vector<ArgumentType> arguments;
200 convertArgs(o1, o2, arguments);
201 known_environments[environment] = arguments;
202 if (!beg.empty() || ! end.empty())
203 possible_textclass_environments[environment] =
204 FullEnvironment(arguments, beg, end);
208 Layout const * findLayoutWithoutModule(TextClass const & textclass,
209 string const & name, bool command)
211 DocumentClass::const_iterator it = textclass.begin();
212 DocumentClass::const_iterator en = textclass.end();
213 for (; it != en; ++it) {
214 if (it->latexname() == name &&
215 ((command && it->isCommand()) || (!command && it->isEnvironment())))
222 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
223 string const & name, bool command)
225 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
226 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
227 for (; it != en; ++it) {
228 if (it->second.latexname() == name &&
229 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
230 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
231 return &(it->second);
237 bool checkModule(string const & name, bool command)
239 // Cache to avoid slowdown by repated searches
240 static set<string> failed[2];
242 // Only add the module if the command was actually defined in the LyX preamble
244 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
247 if (possible_textclass_environments.find(name) == possible_textclass_environments.end())
250 if (failed[command].find(name) != failed[command].end())
253 // Create list of dummy document classes if not already done.
254 // This is needed since a module cannot be read on its own, only as
255 // part of a document class.
256 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
257 typedef map<string, DocumentClass *> ModuleMap;
258 static ModuleMap modules;
259 static bool init = true;
262 DocumentClassBundle & bundle = DocumentClassBundle::get();
263 LyXModuleList::const_iterator const end = theModuleList.end();
264 LyXModuleList::const_iterator it = theModuleList.begin();
265 for (; it != end; it++) {
266 string const module = it->getID();
268 // FIXME this excludes all modules that depend on another one
269 if (!m.moduleCanBeAdded(module, &baseClass))
272 modules[module] = &bundle.makeDocumentClass(baseClass, m);
277 // Try to find a module that defines the command.
278 // Only add it if the definition can be found in the preamble of the
279 // style that corresponds to the command. This is a heuristic and
280 // different from the way how we parse the builtin commands of the
281 // text class (in that case we only compare the name), but it is
282 // needed since it is not unlikely that two different modules define a
283 // command with the same name.
284 ModuleMap::iterator const end = modules.end();
285 for (ModuleMap::iterator it = modules.begin(); it != end; it++) {
286 string const module = it->first;
287 if (!used_modules.moduleCanBeAdded(module, &baseClass))
289 if (findLayoutWithoutModule(textclass, name, command))
291 if (findInsetLayoutWithoutModule(textclass, name, command))
293 DocumentClass const * c = it->second;
294 Layout const * layout = findLayoutWithoutModule(*c, name, command);
295 InsetLayout const * insetlayout = layout ? 0 :
296 findInsetLayoutWithoutModule(*c, name, command);
299 preamble = layout->preamble();
300 else if (insetlayout)
301 preamble = insetlayout->preamble();
302 if (preamble.empty())
306 FullCommand const & cmd =
307 possible_textclass_commands['\\' + name];
308 if (preamble.find(cmd.def) != docstring::npos)
311 FullEnvironment const & env =
312 possible_textclass_environments[name];
313 if (preamble.find(env.beg) != docstring::npos &&
314 preamble.find(env.end) != docstring::npos)
318 FileName layout_file = libFileSearch("layouts", module, "module");
319 if (textclass.read(layout_file, TextClass::MODULE)) {
320 used_modules.push_back(module);
321 // speed up further searches:
322 // the module does not need to be checked anymore.
328 failed[command].insert(name);
333 bool noweb_mode = false;
334 bool pdflatex = false;
336 bool roundtrip = false;
343 * Read one command definition from the syntax file
345 void read_command(Parser & p, string command, CommandMap & commands)
347 if (p.next_token().asInput() == "*") {
351 vector<ArgumentType> arguments;
352 while (p.next_token().cat() == catBegin ||
353 p.next_token().asInput() == "[") {
354 if (p.next_token().cat() == catBegin) {
355 string const arg = p.getArg('{', '}');
356 if (arg == "translate")
357 arguments.push_back(required);
358 else if (arg == "group")
359 arguments.push_back(req_group);
360 else if (arg == "item")
361 arguments.push_back(item);
362 else if (arg == "displaymath")
363 arguments.push_back(displaymath);
365 arguments.push_back(verbatim);
367 string const arg = p.getArg('[', ']');
369 arguments.push_back(opt_group);
371 arguments.push_back(optional);
374 commands[command] = arguments;
379 * Read a class of environments from the syntax file
381 void read_environment(Parser & p, string const & begin,
382 CommandMap & environments)
386 Token const & t = p.get_token();
387 if (t.cat() == catLetter)
388 environment += t.asInput();
389 else if (!environment.empty()) {
391 read_command(p, environment, environments);
394 if (t.cat() == catEscape && t.asInput() == "\\end") {
395 string const end = p.getArg('{', '}');
404 * Read a list of TeX commands from a reLyX compatible syntax file.
405 * Since this list is used after all commands that have a LyX counterpart
406 * are handled, it does not matter that the "syntax.default" file
407 * has almost all of them listed. For the same reason the reLyX-specific
408 * reLyXre environment is ignored.
410 void read_syntaxfile(FileName const & file_name)
412 ifdocstream is(file_name.toFilesystemEncoding().c_str());
414 cerr << "Could not open syntax file \"" << file_name
415 << "\" for reading." << endl;
418 // We can use our TeX parser, since the syntax of the layout file is
419 // modeled after TeX.
420 // Unknown tokens are just silently ignored, this helps us to skip some
421 // reLyX specific things.
424 Token const & t = p.get_token();
425 if (t.cat() == catEscape) {
426 string const command = t.asInput();
427 if (command == "\\begin") {
428 string const name = p.getArg('{', '}');
429 if (name == "environments" || name == "reLyXre")
430 // We understand "reLyXre", but it is
431 // not as powerful as "environments".
432 read_environment(p, name,
434 else if (name == "mathenvironments")
435 read_environment(p, name,
436 known_math_environments);
438 read_command(p, command, known_commands);
445 string documentclass;
446 string default_encoding;
448 bool overwrite_files = false;
451 /// return the number of arguments consumed
452 typedef int (*cmd_helper)(string const &, string const &);
455 int parse_help(string const &, string const &)
457 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
459 "\t-c textclass Declare the textclass.\n"
460 "\t-e encoding Set the default encoding (latex name).\n"
461 "\t-f Force overwrite of .lyx files.\n"
462 "\t-help Print this message and quit.\n"
463 "\t-n translate a noweb (aka literate programming) file.\n"
464 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
465 "\t-s syntaxfile read additional syntax file.\n"
466 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
467 "\t Default: " << package().system_support() << "\n"
468 "\t-userdir USERDIR Set user directory to USERDIR.\n"
469 "\t Default: " << package().user_support() << "\n"
470 "\t-version Summarize version and build info.\n"
472 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
473 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
474 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
475 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
476 "Check the tex2lyx man page for more details."
482 int parse_version(string const &, string const &)
484 lyxerr << "tex2lyx " << lyx_version
485 << " (" << lyx_release_date << ")" << endl;
486 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
488 lyxerr << lyx_version_info << endl;
493 void error_message(string const & message)
495 cerr << "tex2lyx: " << message << "\n\n";
497 parse_help(string(), string());
501 int parse_class(string const & arg, string const &)
504 error_message("Missing textclass string after -c switch");
510 int parse_encoding(string const & arg, string const &)
513 error_message("Missing encoding string after -e switch");
514 default_encoding = arg;
519 int parse_syntaxfile(string const & arg, string const &)
522 error_message("Missing syntaxfile string after -s switch");
523 syntaxfile = internal_path(arg);
528 // Filled with the command line arguments "foo" of "-sysdir foo" or
530 string cl_system_support;
531 string cl_user_support;
534 int parse_sysdir(string const & arg, string const &)
537 error_message("Missing directory for -sysdir switch");
538 cl_system_support = internal_path(arg);
543 int parse_userdir(string const & arg, string const &)
546 error_message("Missing directory for -userdir switch");
547 cl_user_support = internal_path(arg);
552 int parse_force(string const &, string const &)
554 overwrite_files = true;
559 int parse_noweb(string const &, string const &)
566 int parse_roundtrip(string const &, string const &)
573 void easyParse(int & argc, char * argv[])
575 map<string, cmd_helper> cmdmap;
577 cmdmap["-h"] = parse_help;
578 cmdmap["-help"] = parse_help;
579 cmdmap["--help"] = parse_help;
580 cmdmap["-v"] = parse_version;
581 cmdmap["-version"] = parse_version;
582 cmdmap["--version"] = parse_version;
583 cmdmap["-c"] = parse_class;
584 cmdmap["-e"] = parse_encoding;
585 cmdmap["-f"] = parse_force;
586 cmdmap["-s"] = parse_syntaxfile;
587 cmdmap["-n"] = parse_noweb;
588 cmdmap["-sysdir"] = parse_sysdir;
589 cmdmap["-userdir"] = parse_userdir;
590 cmdmap["-roundtrip"] = parse_roundtrip;
592 for (int i = 1; i < argc; ++i) {
593 map<string, cmd_helper>::const_iterator it
594 = cmdmap.find(argv[i]);
596 // don't complain if not found - may be parsed later
597 if (it == cmdmap.end()) {
598 if (argv[i][0] == '-')
599 error_message(string("Unknown option `") + argv[i] + "'.");
604 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
605 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
607 int const remove = 1 + it->second(arg, arg2);
609 // Now, remove used arguments by shifting
610 // the following ones remove places down.
611 os::remove_internal_args(i, remove);
613 for (int j = i; j < argc; ++j)
614 argv[j] = argv[j + remove];
620 // path of the first parsed file
621 string masterFilePath;
622 // path of the currently parsed file
623 string parentFilePath;
625 } // anonymous namespace
628 string getMasterFilePath()
630 return masterFilePath;
633 string getParentFilePath()
635 return parentFilePath;
642 * Reads tex input from \a is and writes lyx output to \a os.
643 * Uses some common settings for the preamble, so this should only
644 * be used more than once for included documents.
645 * Caution: Overwrites the existing preamble settings if the new document
646 * contains a preamble.
647 * You must ensure that \p parentFilePath is properly set before calling
650 bool tex2lyx(idocstream & is, ostream & os, string encoding)
652 // Set a sensible default encoding.
653 // This is used until an encoding command is found.
654 // For child documents use the encoding of the master, else latin1,
655 // since latin1 does not cause an iconv error if the actual encoding
656 // is different (bug 7509).
657 if (encoding.empty()) {
658 if (preamble.inputencoding() == "auto")
661 encoding = preamble.inputencoding();
665 p.setEncoding(encoding);
668 preamble.parse(p, documentclass, textclass);
670 active_environments.push_back("document");
671 Context context(true, textclass);
673 parse_text(p, ss, FLAG_END, true, context);
675 // Empty document body. LyX needs at least one paragraph.
676 context.check_layout(ss);
677 context.check_end_layout(ss);
678 ss << "\n\\end_body\n\\end_document\n";
679 active_environments.pop_back();
681 // We know the used modules only after parsing the full text
682 if (!used_modules.empty()) {
683 LayoutModuleList::const_iterator const end = used_modules.end();
684 LayoutModuleList::const_iterator it = used_modules.begin();
685 for (; it != end; it++)
686 preamble.addModule(*it);
688 if (!preamble.writeLyXHeader(os, !active_environments.empty())) {
689 cerr << "Could write LyX file header." << endl;
697 ofdocstream parsertest("parsertest.tex");
699 parsertest << p.get_token().asInput();
700 // <origfile> and parsertest.tex should now have identical content
706 /// convert TeX from \p infilename to LyX and write it to \p os
707 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
710 // forbid buffering on this stream
711 is.rdbuf()->pubsetbuf(0,0);
712 is.open(infilename.toFilesystemEncoding().c_str());
714 cerr << "Could not open input file \"" << infilename
715 << "\" for reading." << endl;
718 string const oldParentFilePath = parentFilePath;
719 parentFilePath = onlyPath(infilename.absFileName());
720 bool retval = tex2lyx(is, os, encoding);
721 parentFilePath = oldParentFilePath;
725 } // anonymous namespace
728 bool tex2lyx(string const & infilename, FileName const & outfilename,
729 string const & encoding)
731 if (outfilename.isReadableFile()) {
732 if (overwrite_files) {
733 cerr << "Overwriting existing file "
734 << outfilename << endl;
736 cerr << "Not overwriting existing file "
737 << outfilename << endl;
741 cerr << "Creating file " << outfilename << endl;
743 ofstream os(outfilename.toFilesystemEncoding().c_str());
745 cerr << "Could not open output file \"" << outfilename
746 << "\" for writing." << endl;
750 cerr << "Input file: " << infilename << "\n";
751 cerr << "Output file: " << outfilename << "\n";
753 return tex2lyx(FileName(infilename), os, encoding);
757 bool tex2tex(string const & infilename, FileName const & outfilename,
758 string const & encoding)
760 if (!tex2lyx(infilename, outfilename, encoding))
762 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
764 command += " -f main";
766 command += " -f none";
768 command += " -e pdflatex ";
770 command += " -e latex ";
771 command += quoteName(outfilename.toFilesystemEncoding());
773 if (one.startscript(Systemcall::Wait, command) == 0)
775 cerr << "Error: Running '" << command << "' failed." << endl;
782 int main(int argc, char * argv[])
786 //setlocale(LC_CTYPE, "");
788 lyxerr.setStream(cerr);
790 os::init(argc, argv);
793 init_package(internal_path(os::utf8_argv(0)), string(), string());
794 } catch (ExceptionMessage const & message) {
795 cerr << to_utf8(message.title_) << ":\n"
796 << to_utf8(message.details_) << endl;
797 if (message.type_ == ErrorException)
801 easyParse(argc, argv);
804 error_message("Not enough arguments.");
807 init_package(internal_path(os::utf8_argv(0)),
808 cl_system_support, cl_user_support);
809 } catch (ExceptionMessage const & message) {
810 cerr << to_utf8(message.title_) << ":\n"
811 << to_utf8(message.details_) << endl;
812 if (message.type_ == ErrorException)
816 // Now every known option is parsed. Look for input and output
817 // file name (the latter is optional).
818 string infilename = internal_path(os::utf8_argv(1));
819 infilename = makeAbsPath(infilename).absFileName();
824 // Do not allow a user supplied output filename
825 // (otherwise it could easily happen that LyX would
826 // overwrite the original .tex file)
827 cerr << "Error: output filename must not be given in roundtrip mode."
831 outfilename = changeExtension(infilename, ".lyx.lyx");
832 } else if (argc > 2) {
833 outfilename = internal_path(os::utf8_argv(2));
834 if (outfilename != "-")
835 outfilename = makeAbsPath(outfilename).absFileName();
837 outfilename = changeExtension(infilename, ".lyx");
839 // Read the syntax tables
840 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
841 if (system_syntaxfile.empty()) {
842 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
845 read_syntaxfile(system_syntaxfile);
846 if (!syntaxfile.empty())
847 read_syntaxfile(makeAbsPath(syntaxfile));
849 // Read the encodings table.
850 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
851 if (symbols_path.empty()) {
852 cerr << "Error: Could not find file \"unicodesymbols\"."
856 FileName const enc_path = libFileSearch(string(), "encodings");
857 if (enc_path.empty()) {
858 cerr << "Error: Could not find file \"encodings\"."
862 encodings.read(enc_path, symbols_path);
863 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
864 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
867 LayoutFileList::get().read();
869 theModuleList.read();
871 // The real work now.
872 masterFilePath = onlyPath(infilename);
873 parentFilePath = masterFilePath;
874 if (outfilename == "-") {
875 if (tex2lyx(FileName(infilename), cout, default_encoding))
877 } else if (roundtrip) {
878 if (tex2tex(infilename, FileName(outfilename), default_encoding))
881 if (tex2lyx(infilename, FileName(outfilename), default_encoding))