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;
157 vector<string> preloaded_modules;
160 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
162 // We have to handle the following cases:
163 // definition o1 o2 invocation result
164 // \newcommand{\foo}{bar} "" false \foo bar
165 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
166 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
167 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
168 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
169 unsigned int nargs = 0;
170 string const opt1 = rtrim(ltrim(o1, "["), "]");
171 if (isStrUnsignedInt(opt1)) {
172 // The command has arguments
173 nargs = convert<unsigned int>(opt1);
174 if (nargs > 0 && o2) {
175 // The first argument is optional
176 arguments.push_back(optional);
180 for (unsigned int i = 0; i < nargs; ++i)
181 arguments.push_back(required);
185 void add_known_command(string const & command, string const & o1,
186 bool o2, docstring const & definition)
188 vector<ArgumentType> arguments;
189 convertArgs(o1, o2, arguments);
190 known_commands[command] = arguments;
191 if (!definition.empty())
192 possible_textclass_commands[command] =
193 FullCommand(arguments, definition);
197 void add_known_environment(string const & environment, string const & o1,
198 bool o2, docstring const & beg, docstring const &end)
200 vector<ArgumentType> arguments;
201 convertArgs(o1, o2, arguments);
202 known_environments[environment] = arguments;
203 if (!beg.empty() || ! end.empty())
204 possible_textclass_environments[environment] =
205 FullEnvironment(arguments, beg, end);
209 Layout const * findLayoutWithoutModule(TextClass const & textclass,
210 string const & name, bool command)
212 DocumentClass::const_iterator it = textclass.begin();
213 DocumentClass::const_iterator en = textclass.end();
214 for (; it != en; ++it) {
215 if (it->latexname() == name &&
216 ((command && it->isCommand()) || (!command && it->isEnvironment())))
223 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
224 string const & name, bool command)
226 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
227 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
228 for (; it != en; ++it) {
229 if (it->second.latexname() == name &&
230 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
231 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
232 return &(it->second);
240 typedef map<string, DocumentClassPtr> ModuleMap;
244 // Create list of dummy document classes if not already done.
245 // This is needed since a module cannot be read on its own, only as
246 // part of a document class.
247 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
248 static bool init = true;
251 LyXModuleList::const_iterator const end = theModuleList.end();
252 LyXModuleList::const_iterator it = theModuleList.begin();
253 for (; it != end; ++it) {
254 string const module = it->getID();
256 // FIXME this excludes all modules that depend on another one
257 if (!m.moduleCanBeAdded(module, &baseClass))
260 modules[module] = getDocumentClass(baseClass, m);
267 bool addModule(string const & module)
270 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
271 if (!used_modules.moduleCanBeAdded(module, &baseClass))
273 FileName layout_file = libFileSearch("layouts", module, "module");
274 if (textclass.read(layout_file, TextClass::MODULE)) {
275 used_modules.push_back(module);
276 // speed up further searches:
277 // the module does not need to be checked anymore.
278 ModuleMap::iterator const it = modules.find(module);
279 if (it != modules.end())
289 bool checkModule(string const & name, bool command)
291 // Cache to avoid slowdown by repated searches
292 static set<string> failed[2];
294 // Only add the module if the command was actually defined in the LyX preamble
296 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
299 if (possible_textclass_environments.find(name) == possible_textclass_environments.end())
302 if (failed[command].find(name) != failed[command].end())
306 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
308 // Try to find a module that defines the command.
309 // Only add it if the definition can be found in the preamble of the
310 // style that corresponds to the command. This is a heuristic and
311 // different from the way how we parse the builtin commands of the
312 // text class (in that case we only compare the name), but it is
313 // needed since it is not unlikely that two different modules define a
314 // command with the same name.
315 ModuleMap::iterator const end = modules.end();
316 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
317 string const module = it->first;
318 if (!used_modules.moduleCanBeAdded(module, &baseClass))
320 if (findLayoutWithoutModule(textclass, name, command))
322 if (findInsetLayoutWithoutModule(textclass, name, command))
324 DocumentClassConstPtr c = it->second;
325 Layout const * layout = findLayoutWithoutModule(*c, name, command);
326 InsetLayout const * insetlayout = layout ? 0 :
327 findInsetLayoutWithoutModule(*c, name, command);
330 preamble = layout->preamble();
331 else if (insetlayout)
332 preamble = insetlayout->preamble();
333 if (preamble.empty())
337 FullCommand const & cmd =
338 possible_textclass_commands['\\' + name];
339 if (preamble.find(cmd.def) != docstring::npos)
342 FullEnvironment const & env =
343 possible_textclass_environments[name];
344 if (preamble.find(env.beg) != docstring::npos &&
345 preamble.find(env.end) != docstring::npos)
349 FileName layout_file = libFileSearch("layouts", module, "module");
350 if (textclass.read(layout_file, TextClass::MODULE)) {
351 used_modules.push_back(module);
352 // speed up further searches:
353 // the module does not need to be checked anymore.
359 failed[command].insert(name);
364 bool noweb_mode = false;
365 bool pdflatex = false;
367 bool is_nonCJKJapanese = false;
368 bool roundtrip = false;
375 * Read one command definition from the syntax file
377 void read_command(Parser & p, string command, CommandMap & commands)
379 if (p.next_token().asInput() == "*") {
383 vector<ArgumentType> arguments;
384 while (p.next_token().cat() == catBegin ||
385 p.next_token().asInput() == "[") {
386 if (p.next_token().cat() == catBegin) {
387 string const arg = p.getArg('{', '}');
388 if (arg == "translate")
389 arguments.push_back(required);
390 else if (arg == "group")
391 arguments.push_back(req_group);
392 else if (arg == "item")
393 arguments.push_back(item);
394 else if (arg == "displaymath")
395 arguments.push_back(displaymath);
397 arguments.push_back(verbatim);
399 string const arg = p.getArg('[', ']');
401 arguments.push_back(opt_group);
403 arguments.push_back(optional);
406 commands[command] = arguments;
411 * Read a class of environments from the syntax file
413 void read_environment(Parser & p, string const & begin,
414 CommandMap & environments)
418 Token const & t = p.get_token();
419 if (t.cat() == catLetter)
420 environment += t.asInput();
421 else if (!environment.empty()) {
423 read_command(p, environment, environments);
426 if (t.cat() == catEscape && t.asInput() == "\\end") {
427 string const end = p.getArg('{', '}');
436 * Read a list of TeX commands from a reLyX compatible syntax file.
437 * Since this list is used after all commands that have a LyX counterpart
438 * are handled, it does not matter that the "syntax.default" file
439 * has almost all of them listed. For the same reason the reLyX-specific
440 * reLyXre environment is ignored.
442 void read_syntaxfile(FileName const & file_name)
444 ifdocstream is(file_name.toFilesystemEncoding().c_str());
446 cerr << "Could not open syntax file \"" << file_name
447 << "\" for reading." << endl;
450 // We can use our TeX parser, since the syntax of the layout file is
451 // modeled after TeX.
452 // Unknown tokens are just silently ignored, this helps us to skip some
453 // reLyX specific things.
456 Token const & t = p.get_token();
457 if (t.cat() == catEscape) {
458 string const command = t.asInput();
459 if (command == "\\begin") {
460 string const name = p.getArg('{', '}');
461 if (name == "environments" || name == "reLyXre")
462 // We understand "reLyXre", but it is
463 // not as powerful as "environments".
464 read_environment(p, name,
466 else if (name == "mathenvironments")
467 read_environment(p, name,
468 known_math_environments);
470 read_command(p, command, known_commands);
477 string documentclass;
478 string default_encoding;
480 bool copy_files = false;
481 bool overwrite_files = false;
482 bool skip_children = false;
485 /// return the number of arguments consumed
486 typedef int (*cmd_helper)(string const &, string const &);
489 int parse_help(string const &, string const &)
491 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
493 "\t-c textclass Declare the textclass.\n"
494 "\t-m mod1[,mod2...] Load the given modules.\n"
495 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
496 "\t-e encoding Set the default encoding (latex name).\n"
497 "\t-f Force overwrite of .lyx files.\n"
498 "\t-help Print this message and quit.\n"
499 "\t-n translate a noweb (aka literate programming) file.\n"
500 "\t-skipchildren Do not translate included child documents.\n"
501 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
502 "\t-s syntaxfile read additional syntax file.\n"
503 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
504 "\t Default: " << package().system_support() << "\n"
505 "\t-userdir USERDIR Set user directory to USERDIR.\n"
506 "\t Default: " << package().user_support() << "\n"
507 "\t-version Summarize version and build info.\n"
509 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
510 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
511 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
512 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
513 "Check the tex2lyx man page for more details."
519 int parse_version(string const &, string const &)
521 lyxerr << "tex2lyx " << lyx_version
522 << " (" << lyx_release_date << ")" << endl;
523 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
525 lyxerr << lyx_version_info << endl;
530 void error_message(string const & message)
532 cerr << "tex2lyx: " << message << "\n\n";
534 parse_help(string(), string());
538 int parse_class(string const & arg, string const &)
541 error_message("Missing textclass string after -c switch");
547 int parse_module(string const & arg, string const &)
550 error_message("Missing modules string after -m switch");
551 split(arg, preloaded_modules, ',');
556 int parse_encoding(string const & arg, string const &)
559 error_message("Missing encoding string after -e switch");
560 default_encoding = arg;
565 int parse_syntaxfile(string const & arg, string const &)
568 error_message("Missing syntaxfile string after -s switch");
569 syntaxfile = internal_path(arg);
574 // Filled with the command line arguments "foo" of "-sysdir foo" or
576 string cl_system_support;
577 string cl_user_support;
580 int parse_sysdir(string const & arg, string const &)
583 error_message("Missing directory for -sysdir switch");
584 cl_system_support = internal_path(arg);
589 int parse_userdir(string const & arg, string const &)
592 error_message("Missing directory for -userdir switch");
593 cl_user_support = internal_path(arg);
598 int parse_force(string const &, string const &)
600 overwrite_files = true;
605 int parse_noweb(string const &, string const &)
612 int parse_skipchildren(string const &, string const &)
614 skip_children = true;
619 int parse_roundtrip(string const &, string const &)
626 int parse_copyfiles(string const &, string const &)
633 void easyParse(int & argc, char * argv[])
635 map<string, cmd_helper> cmdmap;
637 cmdmap["-h"] = parse_help;
638 cmdmap["-help"] = parse_help;
639 cmdmap["--help"] = parse_help;
640 cmdmap["-v"] = parse_version;
641 cmdmap["-version"] = parse_version;
642 cmdmap["--version"] = parse_version;
643 cmdmap["-c"] = parse_class;
644 cmdmap["-m"] = parse_module;
645 cmdmap["-e"] = parse_encoding;
646 cmdmap["-f"] = parse_force;
647 cmdmap["-s"] = parse_syntaxfile;
648 cmdmap["-n"] = parse_noweb;
649 cmdmap["-skipchildren"] = parse_skipchildren;
650 cmdmap["-sysdir"] = parse_sysdir;
651 cmdmap["-userdir"] = parse_userdir;
652 cmdmap["-roundtrip"] = parse_roundtrip;
653 cmdmap["-copyfiles"] = parse_copyfiles;
655 for (int i = 1; i < argc; ++i) {
656 map<string, cmd_helper>::const_iterator it
657 = cmdmap.find(argv[i]);
659 // don't complain if not found - may be parsed later
660 if (it == cmdmap.end()) {
661 if (argv[i][0] == '-')
662 error_message(string("Unknown option `") + argv[i] + "'.");
667 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
668 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
670 int const remove = 1 + it->second(arg, arg2);
672 // Now, remove used arguments by shifting
673 // the following ones remove places down.
674 os::remove_internal_args(i, remove);
676 for (int j = i; j < argc; ++j)
677 argv[j] = argv[j + remove];
683 // path of the first parsed file
684 string masterFilePathLyX;
685 string masterFilePathTeX;
686 // path of the currently parsed file
687 string parentFilePathTeX;
689 } // anonymous namespace
692 string getMasterFilePath(bool input)
694 return input ? masterFilePathTeX : masterFilePathLyX;
697 string getParentFilePath(bool input)
700 return parentFilePathTeX;
701 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
702 from_utf8(parentFilePathTeX)));
703 if (rel.substr(0, 3) == "../") {
704 // The parent is not below the master - keep the path
705 return parentFilePathTeX;
707 return makeAbsPath(rel, masterFilePathLyX).absFileName();
717 bool overwriteFiles()
719 return overwrite_files;
725 return skip_children;
732 * Reads tex input from \a is and writes lyx output to \a os.
733 * Uses some common settings for the preamble, so this should only
734 * be used more than once for included documents.
735 * Caution: Overwrites the existing preamble settings if the new document
736 * contains a preamble.
737 * You must ensure that \p parentFilePathTeX is properly set before calling
740 bool tex2lyx(idocstream & is, ostream & os, string encoding)
742 // Set a sensible default encoding.
743 // This is used until an encoding command is found.
744 // For child documents use the encoding of the master, else latin1,
745 // since latin1 does not cause an iconv error if the actual encoding
746 // is different (bug 7509).
747 if (encoding.empty()) {
748 if (preamble.inputencoding() == "auto")
751 encoding = preamble.inputencoding();
755 p.setEncoding(encoding);
758 preamble.parse(p, documentclass, textclass);
760 // Load preloaded modules.
761 // This needs to be done after the preamble is parsed, since the text
762 // class may not be known before. It neds to be done before parsing
763 // body, since otherwise the commands/environments provided by the
764 // modules would be parsed as ERT.
765 for (size_t i = 0; i < preloaded_modules.size(); ++i) {
766 if (!addModule(preloaded_modules[i])) {
767 cerr << "Error: Could not load module \""
768 << preloaded_modules[i] << "\"." << endl;
772 // Ensure that the modules are not loaded again for included files
773 preloaded_modules.clear();
775 active_environments.push_back("document");
776 Context context(true, textclass);
778 // store the document language in the context to be able to handle the
779 // commands like \foreignlanguage and \textenglish etc.
780 context.font.language = preamble.defaultLanguage();
781 // parse the main text
782 parse_text(p, ss, FLAG_END, true, context);
784 // Empty document body. LyX needs at least one paragraph.
785 context.check_layout(ss);
786 context.check_end_layout(ss);
787 ss << "\n\\end_body\n\\end_document\n";
788 active_environments.pop_back();
790 // We know the used modules only after parsing the full text
791 if (!used_modules.empty()) {
792 LayoutModuleList::const_iterator const end = used_modules.end();
793 LayoutModuleList::const_iterator it = used_modules.begin();
794 for (; it != end; ++it)
795 preamble.addModule(*it);
797 if (!preamble.writeLyXHeader(os, !active_environments.empty())) {
798 cerr << "Could write LyX file header." << endl;
806 ofdocstream parsertest("parsertest.tex");
808 parsertest << p.get_token().asInput();
809 // <origfile> and parsertest.tex should now have identical content
815 /// convert TeX from \p infilename to LyX and write it to \p os
816 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
819 // forbid buffering on this stream
820 is.rdbuf()->pubsetbuf(0,0);
821 is.open(infilename.toFilesystemEncoding().c_str());
823 cerr << "Could not open input file \"" << infilename
824 << "\" for reading." << endl;
827 string const oldParentFilePath = parentFilePathTeX;
828 parentFilePathTeX = onlyPath(infilename.absFileName());
829 bool retval = tex2lyx(is, os, encoding);
830 parentFilePathTeX = oldParentFilePath;
834 } // anonymous namespace
837 bool tex2lyx(string const & infilename, FileName const & outfilename,
838 string const & encoding)
840 if (outfilename.isReadableFile()) {
841 if (overwrite_files) {
842 cerr << "Overwriting existing file "
843 << outfilename << endl;
845 cerr << "Not overwriting existing file "
846 << outfilename << endl;
850 cerr << "Creating file " << outfilename << endl;
852 ofstream os(outfilename.toFilesystemEncoding().c_str());
854 cerr << "Could not open output file \"" << outfilename
855 << "\" for writing." << endl;
859 cerr << "Input file: " << infilename << "\n";
860 cerr << "Output file: " << outfilename << "\n";
862 return tex2lyx(FileName(infilename), os, encoding);
866 bool tex2tex(string const & infilename, FileName const & outfilename,
867 string const & encoding)
869 if (!tex2lyx(infilename, outfilename, encoding))
871 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
873 command += " -f main";
875 command += " -f none";
877 command += " -e pdflatex ";
879 command += " -e xetex ";
881 command += " -e latex ";
882 command += quoteName(outfilename.toFilesystemEncoding());
884 if (one.startscript(Systemcall::Wait, command) == 0)
886 cerr << "Error: Running '" << command << "' failed." << endl;
893 int main(int argc, char * argv[])
897 //setlocale(LC_CTYPE, "");
899 lyxerr.setStream(cerr);
901 os::init(argc, argv);
904 init_package(internal_path(os::utf8_argv(0)), string(), string());
905 } catch (ExceptionMessage const & message) {
906 cerr << to_utf8(message.title_) << ":\n"
907 << to_utf8(message.details_) << endl;
908 if (message.type_ == ErrorException)
912 easyParse(argc, argv);
915 error_message("Not enough arguments.");
918 init_package(internal_path(os::utf8_argv(0)),
919 cl_system_support, cl_user_support);
920 } catch (ExceptionMessage const & message) {
921 cerr << to_utf8(message.title_) << ":\n"
922 << to_utf8(message.details_) << endl;
923 if (message.type_ == ErrorException)
927 // Now every known option is parsed. Look for input and output
928 // file name (the latter is optional).
929 string infilename = internal_path(os::utf8_argv(1));
930 infilename = makeAbsPath(infilename).absFileName();
934 outfilename = internal_path(os::utf8_argv(2));
935 if (outfilename != "-")
936 outfilename = makeAbsPath(outfilename).absFileName();
938 if (outfilename == "-") {
939 cerr << "Error: Writing to standard output is "
940 "not supported in roundtrip mode."
944 string texfilename = changeExtension(outfilename, ".tex");
945 if (equivalent(FileName(infilename), FileName(texfilename))) {
946 cerr << "Error: The input file `" << infilename
947 << "´ would be overwritten by the TeX file exported from `"
948 << outfilename << "´ in roundtrip mode." << endl;
952 } else if (roundtrip) {
953 // avoid overwriting the input file
954 outfilename = changeExtension(infilename, ".lyx.lyx");
956 outfilename = changeExtension(infilename, ".lyx");
958 // Read the syntax tables
959 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
960 if (system_syntaxfile.empty()) {
961 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
964 read_syntaxfile(system_syntaxfile);
965 if (!syntaxfile.empty())
966 read_syntaxfile(makeAbsPath(syntaxfile));
968 // Read the encodings table.
969 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
970 if (symbols_path.empty()) {
971 cerr << "Error: Could not find file \"unicodesymbols\"."
975 FileName const enc_path = libFileSearch(string(), "encodings");
976 if (enc_path.empty()) {
977 cerr << "Error: Could not find file \"encodings\"."
981 encodings.read(enc_path, symbols_path);
982 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
983 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
986 LayoutFileList::get().read();
988 theModuleList.read();
990 // The real work now.
991 masterFilePathTeX = onlyPath(infilename);
992 parentFilePathTeX = masterFilePathTeX;
993 if (outfilename == "-") {
994 // assume same directory as input file
995 masterFilePathLyX = masterFilePathTeX;
996 if (tex2lyx(FileName(infilename), cout, default_encoding))
999 masterFilePathLyX = onlyPath(outfilename);
1001 FileName const path(masterFilePathLyX);
1002 if (!path.isDirectory()) {
1003 if (!path.createPath()) {
1004 cerr << "Warning: Could not create directory for file `"
1005 << masterFilePathLyX << "´." << endl;
1006 return EXIT_FAILURE;
1011 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1012 return EXIT_SUCCESS;
1014 if (tex2lyx(infilename, FileName(outfilename), default_encoding))
1015 return EXIT_SUCCESS;
1018 return EXIT_FAILURE;