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"
24 #include "TextClass.h"
26 #include "support/convert.h"
27 #include "support/debug.h"
28 #include "support/ExceptionMessage.h"
29 #include "support/filetools.h"
30 #include "support/lassert.h"
31 #include "support/lstrings.h"
32 #include "support/Messages.h"
33 #include "support/os.h"
34 #include "support/Package.h"
35 #include "support/Systemcall.h"
45 using namespace lyx::support;
46 using namespace lyx::support::os;
52 void warning(docstring const & title, docstring const & message,
62 // Dummy texrow support
63 void TexRow::newline()
67 void TexRow::newlines(int)
71 // Dummy LyXRC support
78 // Dummy translation support
80 Messages const & getMessages(std::string const &)
86 Messages const & getGuiMessages()
92 // Keep the linker happy on Windows
97 string const trimSpaceAndEol(string const & a)
99 return trim(a, " \t\n\r");
103 void split(string const & s, vector<string> & result, char delim)
105 //cerr << "split 1: '" << s << "'\n";
108 while (getline(is, t, delim))
110 //cerr << "split 2\n";
114 string join(vector<string> const & input, char const * delim)
117 for (size_t i = 0; i != input.size(); ++i) {
126 char const * const * is_known(string const & str, char const * const * what)
128 for ( ; *what; ++what)
136 // current stack of nested environments
137 vector<string> active_environments;
140 string active_environment()
142 return active_environments.empty() ? string() : active_environments.back();
146 TeX2LyXDocClass textclass;
147 CommandMap known_commands;
148 CommandMap known_environments;
149 CommandMap known_math_environments;
150 FullCommandMap possible_textclass_commands;
151 FullEnvironmentMap possible_textclass_environments;
154 LayoutModuleList used_modules;
157 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
159 // We have to handle the following cases:
160 // definition o1 o2 invocation result
161 // \newcommand{\foo}{bar} "" false \foo bar
162 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
163 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
164 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
165 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
166 unsigned int nargs = 0;
167 string const opt1 = rtrim(ltrim(o1, "["), "]");
168 if (isStrUnsignedInt(opt1)) {
169 // The command has arguments
170 nargs = convert<unsigned int>(opt1);
171 if (nargs > 0 && o2) {
172 // The first argument is optional
173 arguments.push_back(optional);
177 for (unsigned int i = 0; i < nargs; ++i)
178 arguments.push_back(required);
182 void add_known_command(string const & command, string const & o1,
183 bool o2, docstring const & definition)
185 vector<ArgumentType> arguments;
186 convertArgs(o1, o2, arguments);
187 known_commands[command] = arguments;
188 if (!definition.empty())
189 possible_textclass_commands[command] =
190 FullCommand(arguments, definition);
194 void add_known_environment(string const & environment, string const & o1,
195 bool o2, docstring const & beg, docstring const &end)
197 vector<ArgumentType> arguments;
198 convertArgs(o1, o2, arguments);
199 known_environments[environment] = arguments;
200 if (!beg.empty() || ! end.empty())
201 possible_textclass_environments[environment] =
202 FullEnvironment(arguments, beg, end);
206 Layout const * findLayoutWithoutModule(TextClass const & textclass,
207 string const & name, bool command)
209 DocumentClass::const_iterator it = textclass.begin();
210 DocumentClass::const_iterator en = textclass.end();
211 for (; it != en; ++it) {
212 if (it->latexname() == name &&
213 ((command && it->isCommand()) || (!command && it->isEnvironment())))
220 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
221 string const & name, bool command)
223 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
224 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
225 for (; it != en; ++it) {
226 if (it->second.latexname() == name &&
227 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
228 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
229 return &(it->second);
235 bool checkModule(string const & name, bool command)
237 // Cache to avoid slowdown by repated searches
238 static set<string> failed[2];
240 // Only add the module if the command was actually defined in the LyX preamble
242 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
245 if (possible_textclass_environments.find(name) == possible_textclass_environments.end())
248 if (failed[command].find(name) != failed[command].end())
251 // Create list of dummy document classes if not already done.
252 // This is needed since a module cannot be read on its own, only as
253 // part of a document class.
254 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
255 typedef map<string, DocumentClass *> ModuleMap;
256 static ModuleMap modules;
257 static bool init = true;
260 DocumentClassBundle & bundle = DocumentClassBundle::get();
261 LyXModuleList::const_iterator const end = theModuleList.end();
262 LyXModuleList::const_iterator it = theModuleList.begin();
263 for (; it != end; it++) {
264 string const module = it->getID();
266 // FIXME this excludes all modules that depend on another one
267 if (!m.moduleCanBeAdded(module, &baseClass))
270 modules[module] = &bundle.makeDocumentClass(baseClass, m);
275 // Try to find a module that defines the command.
276 // Only add it if the definition can be found in the preamble of the
277 // style that corresponds to the command. This is a heuristic and
278 // different from the way how we parse the builtin commands of the
279 // text class (in that case we only compare the name), but it is
280 // needed since it is not unlikely that two different modules define a
281 // command with the same name.
282 ModuleMap::iterator const end = modules.end();
283 for (ModuleMap::iterator it = modules.begin(); it != end; it++) {
284 string const module = it->first;
285 if (!used_modules.moduleCanBeAdded(module, &baseClass))
287 if (findLayoutWithoutModule(textclass, name, command))
289 if (findInsetLayoutWithoutModule(textclass, name, command))
291 DocumentClass const * c = it->second;
292 Layout const * layout = findLayoutWithoutModule(*c, name, command);
293 InsetLayout const * insetlayout = layout ? 0 :
294 findInsetLayoutWithoutModule(*c, name, command);
297 preamble = layout->preamble();
298 else if (insetlayout)
299 preamble = insetlayout->preamble();
300 if (preamble.empty())
304 FullCommand const & cmd =
305 possible_textclass_commands['\\' + name];
306 if (preamble.find(cmd.def) != docstring::npos)
309 FullEnvironment const & env =
310 possible_textclass_environments[name];
311 if (preamble.find(env.beg) != docstring::npos &&
312 preamble.find(env.end) != docstring::npos)
316 FileName layout_file = libFileSearch("layouts", module, "module");
317 if (textclass.read(layout_file, TextClass::MODULE)) {
318 used_modules.push_back(module);
319 // speed up further searches:
320 // the module does not need to be checked anymore.
326 failed[command].insert(name);
331 bool noweb_mode = false;
332 bool pdflatex = false;
333 bool roundtrip = false;
340 * Read one command definition from the syntax file
342 void read_command(Parser & p, string command, CommandMap & commands)
344 if (p.next_token().asInput() == "*") {
348 vector<ArgumentType> arguments;
349 while (p.next_token().cat() == catBegin ||
350 p.next_token().asInput() == "[") {
351 if (p.next_token().cat() == catBegin) {
352 string const arg = p.getArg('{', '}');
353 if (arg == "translate")
354 arguments.push_back(required);
355 else if (arg == "item")
356 arguments.push_back(item);
358 arguments.push_back(verbatim);
361 arguments.push_back(optional);
364 commands[command] = arguments;
369 * Read a class of environments from the syntax file
371 void read_environment(Parser & p, string const & begin,
372 CommandMap & environments)
376 Token const & t = p.get_token();
377 if (t.cat() == catLetter)
378 environment += t.asInput();
379 else if (!environment.empty()) {
381 read_command(p, environment, environments);
384 if (t.cat() == catEscape && t.asInput() == "\\end") {
385 string const end = p.getArg('{', '}');
394 * Read a list of TeX commands from a reLyX compatible syntax file.
395 * Since this list is used after all commands that have a LyX counterpart
396 * are handled, it does not matter that the "syntax.default" file
397 * has almost all of them listed. For the same reason the reLyX-specific
398 * reLyXre environment is ignored.
400 void read_syntaxfile(FileName const & file_name)
402 ifdocstream is(file_name.toFilesystemEncoding().c_str());
404 cerr << "Could not open syntax file \"" << file_name
405 << "\" for reading." << endl;
408 // We can use our TeX parser, since the syntax of the layout file is
409 // modeled after TeX.
410 // Unknown tokens are just silently ignored, this helps us to skip some
411 // reLyX specific things.
414 Token const & t = p.get_token();
415 if (t.cat() == catEscape) {
416 string const command = t.asInput();
417 if (command == "\\begin") {
418 string const name = p.getArg('{', '}');
419 if (name == "environments" || name == "reLyXre")
420 // We understand "reLyXre", but it is
421 // not as powerful as "environments".
422 read_environment(p, name,
424 else if (name == "mathenvironments")
425 read_environment(p, name,
426 known_math_environments);
428 read_command(p, command, known_commands);
435 string documentclass;
436 string default_encoding;
438 bool overwrite_files = false;
441 /// return the number of arguments consumed
442 typedef int (*cmd_helper)(string const &, string const &);
445 int parse_help(string const &, string const &)
447 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
449 "\t-c textclass Declare the textclass.\n"
450 "\t-e encoding Set the default encoding (latex name).\n"
451 "\t-f Force overwrite of .lyx files.\n"
452 "\t-help Print this message and quit.\n"
453 "\t-n translate a noweb (aka literate programming) file.\n"
454 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
455 "\t-s syntaxfile read additional syntax file.\n"
456 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
457 "\t Default: " << package().system_support() << "\n"
458 "\t-userdir USERDIR Set user directory to USERDIR.\n"
459 "\t Default: " << package().user_support() << "\n"
460 "\t-version Summarize version and build info.\n"
462 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
463 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
464 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
465 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
466 "Check the tex2lyx man page for more details."
472 int parse_version(string const &, string const &)
474 lyxerr << "tex2lyx " << lyx_version
475 << " (" << lyx_release_date << ")" << endl;
476 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
478 lyxerr << lyx_version_info << endl;
483 void error_message(string const & message)
485 cerr << "tex2lyx: " << message << "\n\n";
487 parse_help(string(), string());
491 int parse_class(string const & arg, string const &)
494 error_message("Missing textclass string after -c switch");
500 int parse_encoding(string const & arg, string const &)
503 error_message("Missing encoding string after -e switch");
504 default_encoding = arg;
509 int parse_syntaxfile(string const & arg, string const &)
512 error_message("Missing syntaxfile string after -s switch");
513 syntaxfile = internal_path(arg);
518 // Filled with the command line arguments "foo" of "-sysdir foo" or
520 string cl_system_support;
521 string cl_user_support;
524 int parse_sysdir(string const & arg, string const &)
527 error_message("Missing directory for -sysdir switch");
528 cl_system_support = internal_path(arg);
533 int parse_userdir(string const & arg, string const &)
536 error_message("Missing directory for -userdir switch");
537 cl_user_support = internal_path(arg);
542 int parse_force(string const &, string const &)
544 overwrite_files = true;
549 int parse_noweb(string const &, string const &)
556 int parse_roundtrip(string const &, string const &)
563 void easyParse(int & argc, char * argv[])
565 map<string, cmd_helper> cmdmap;
567 cmdmap["-h"] = parse_help;
568 cmdmap["-help"] = parse_help;
569 cmdmap["--help"] = parse_help;
570 cmdmap["-v"] = parse_version;
571 cmdmap["-version"] = parse_version;
572 cmdmap["--version"] = parse_version;
573 cmdmap["-c"] = parse_class;
574 cmdmap["-e"] = parse_encoding;
575 cmdmap["-f"] = parse_force;
576 cmdmap["-s"] = parse_syntaxfile;
577 cmdmap["-n"] = parse_noweb;
578 cmdmap["-sysdir"] = parse_sysdir;
579 cmdmap["-userdir"] = parse_userdir;
580 cmdmap["-roundtrip"] = parse_roundtrip;
582 for (int i = 1; i < argc; ++i) {
583 map<string, cmd_helper>::const_iterator it
584 = cmdmap.find(argv[i]);
586 // don't complain if not found - may be parsed later
587 if (it == cmdmap.end()) {
588 if (argv[i][0] == '-')
589 error_message(string("Unknown option `") + argv[i] + "'.");
594 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
595 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
597 int const remove = 1 + it->second(arg, arg2);
599 // Now, remove used arguments by shifting
600 // the following ones remove places down.
601 os::remove_internal_args(i, remove);
603 for (int j = i; j < argc; ++j)
604 argv[j] = argv[j + remove];
610 // path of the first parsed file
611 string masterFilePath;
612 // path of the currently parsed file
613 string parentFilePath;
615 } // anonymous namespace
618 string getMasterFilePath()
620 return masterFilePath;
623 string getParentFilePath()
625 return parentFilePath;
632 * Reads tex input from \a is and writes lyx output to \a os.
633 * Uses some common settings for the preamble, so this should only
634 * be used more than once for included documents.
635 * Caution: Overwrites the existing preamble settings if the new document
636 * contains a preamble.
637 * You must ensure that \p parentFilePath is properly set before calling
640 void tex2lyx(idocstream & is, ostream & os, string encoding)
642 // Set a sensible default encoding.
643 // This is used until an encoding command is found.
644 // For child documents use the encoding of the master, else latin1,
645 // since latin1 does not cause an iconv error if the actual encoding
646 // is different (bug 7509).
647 if (encoding.empty()) {
648 if (h_inputencoding == "auto")
651 encoding = h_inputencoding;
655 p.setEncoding(encoding);
659 parse_preamble(p, ps, documentclass, textclass);
661 active_environments.push_back("document");
662 Context context(true, textclass);
664 parse_text(p, ss, FLAG_END, true, context);
666 // Empty document body. LyX needs at least one paragraph.
667 context.check_layout(ss);
668 context.check_end_layout(ss);
669 ss << "\n\\end_body\n\\end_document\n";
670 active_environments.pop_back();
672 // We know the used modules only after parsing the full text
674 if (!used_modules.empty()) {
675 ms << "\\begin_modules\n";
676 LayoutModuleList::const_iterator const end = used_modules.end();
677 LayoutModuleList::const_iterator it = used_modules.begin();
678 for (; it != end; it++)
680 ms << "\\end_modules\n";
682 os << subst(ps.str(), modules_placeholder, ms.str());
688 ofdocstream parsertest("parsertest.tex");
690 parsertest << p.get_token().asInput();
691 // <origfile> and parsertest.tex should now have identical content
696 /// convert TeX from \p infilename to LyX and write it to \p os
697 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
700 // forbid buffering on this stream
701 is.rdbuf()->pubsetbuf(0,0);
702 is.open(infilename.toFilesystemEncoding().c_str());
704 cerr << "Could not open input file \"" << infilename
705 << "\" for reading." << endl;
708 string const oldParentFilePath = parentFilePath;
709 parentFilePath = onlyPath(infilename.absFileName());
710 tex2lyx(is, os, encoding);
711 parentFilePath = oldParentFilePath;
715 } // anonymous namespace
718 bool tex2lyx(string const & infilename, FileName const & outfilename,
719 string const & encoding)
721 if (outfilename.isReadableFile()) {
722 if (overwrite_files) {
723 cerr << "Overwriting existing file "
724 << outfilename << endl;
726 cerr << "Not overwriting existing file "
727 << outfilename << endl;
731 cerr << "Creating file " << outfilename << endl;
733 ofstream os(outfilename.toFilesystemEncoding().c_str());
735 cerr << "Could not open output file \"" << outfilename
736 << "\" for writing." << endl;
740 cerr << "Input file: " << infilename << "\n";
741 cerr << "Output file: " << outfilename << "\n";
743 return tex2lyx(FileName(infilename), os, encoding);
747 bool tex2tex(string const & infilename, FileName const & outfilename,
748 string const & encoding)
750 if (!tex2lyx(infilename, outfilename, encoding))
752 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
754 command += " -f main";
756 command += " -f none";
758 command += " -e pdflatex ";
760 command += " -e latex ";
761 command += quoteName(outfilename.toFilesystemEncoding());
763 if (one.startscript(Systemcall::Wait, command) == 0)
765 cerr << "Error: Running '" << command << "' failed." << endl;
772 int main(int argc, char * argv[])
776 //setlocale(LC_CTYPE, "");
778 lyxerr.setStream(cerr);
780 os::init(argc, argv);
783 init_package(internal_path(os::utf8_argv(0)), string(), string());
784 } catch (ExceptionMessage const & message) {
785 cerr << to_utf8(message.title_) << ":\n"
786 << to_utf8(message.details_) << endl;
787 if (message.type_ == ErrorException)
791 easyParse(argc, argv);
794 error_message("Not enough arguments.");
797 init_package(internal_path(os::utf8_argv(0)),
798 cl_system_support, cl_user_support);
799 } catch (ExceptionMessage const & message) {
800 cerr << to_utf8(message.title_) << ":\n"
801 << to_utf8(message.details_) << endl;
802 if (message.type_ == ErrorException)
806 // Now every known option is parsed. Look for input and output
807 // file name (the latter is optional).
808 string infilename = internal_path(os::utf8_argv(1));
809 infilename = makeAbsPath(infilename).absFileName();
814 // Do not allow a user supplied output filename
815 // (otherwise it could easily happen that LyX would
816 // overwrite the original .tex file)
817 cerr << "Error: output filename must not be given in roundtrip mode."
821 outfilename = changeExtension(infilename, ".lyx.lyx");
822 } else if (argc > 2) {
823 outfilename = internal_path(os::utf8_argv(2));
824 if (outfilename != "-")
825 outfilename = makeAbsPath(outfilename).absFileName();
827 outfilename = changeExtension(infilename, ".lyx");
829 // Read the syntax tables
830 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
831 if (system_syntaxfile.empty()) {
832 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
835 read_syntaxfile(system_syntaxfile);
836 if (!syntaxfile.empty())
837 read_syntaxfile(makeAbsPath(syntaxfile));
839 // Read the encodings table.
840 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
841 if (symbols_path.empty()) {
842 cerr << "Error: Could not find file \"unicodesymbols\"."
846 FileName const enc_path = libFileSearch(string(), "encodings");
847 if (enc_path.empty()) {
848 cerr << "Error: Could not find file \"encodings\"."
852 encodings.read(enc_path, symbols_path);
853 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
854 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
857 LayoutFileList::get().read();
859 theModuleList.read();
861 // The real work now.
862 masterFilePath = onlyPath(infilename);
863 parentFilePath = masterFilePath;
864 if (outfilename == "-") {
865 if (tex2lyx(FileName(infilename), cout, default_encoding))
867 } else if (roundtrip) {
868 if (tex2tex(infilename, FileName(outfilename), default_encoding))
871 if (tex2lyx(infilename, FileName(outfilename), default_encoding))