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, DocumentClassPtr > ModuleMap;
258 static ModuleMap modules;
259 static bool init = true;
262 LyXModuleList::const_iterator const end = theModuleList.end();
263 LyXModuleList::const_iterator it = theModuleList.begin();
264 for (; it != end; ++it) {
265 string const module = it->getID();
267 // FIXME this excludes all modules that depend on another one
268 if (!m.moduleCanBeAdded(module, &baseClass))
271 modules[module] = getDocumentClass(baseClass, m);
276 // Try to find a module that defines the command.
277 // Only add it if the definition can be found in the preamble of the
278 // style that corresponds to the command. This is a heuristic and
279 // different from the way how we parse the builtin commands of the
280 // text class (in that case we only compare the name), but it is
281 // needed since it is not unlikely that two different modules define a
282 // command with the same name.
283 ModuleMap::iterator const end = modules.end();
284 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
285 string const module = it->first;
286 if (!used_modules.moduleCanBeAdded(module, &baseClass))
288 if (findLayoutWithoutModule(textclass, name, command))
290 if (findInsetLayoutWithoutModule(textclass, name, command))
292 DocumentClassConstPtr c = it->second;
293 Layout const * layout = findLayoutWithoutModule(*c, name, command);
294 InsetLayout const * insetlayout = layout ? 0 :
295 findInsetLayoutWithoutModule(*c, name, command);
298 preamble = layout->preamble();
299 else if (insetlayout)
300 preamble = insetlayout->preamble();
301 if (preamble.empty())
305 FullCommand const & cmd =
306 possible_textclass_commands['\\' + name];
307 if (preamble.find(cmd.def) != docstring::npos)
310 FullEnvironment const & env =
311 possible_textclass_environments[name];
312 if (preamble.find(env.beg) != docstring::npos &&
313 preamble.find(env.end) != docstring::npos)
317 FileName layout_file = libFileSearch("layouts", module, "module");
318 if (textclass.read(layout_file, TextClass::MODULE)) {
319 used_modules.push_back(module);
320 // speed up further searches:
321 // the module does not need to be checked anymore.
327 failed[command].insert(name);
332 bool noweb_mode = false;
333 bool pdflatex = false;
335 bool have_CJK = false;
336 bool is_nonCJKJapanese = false;
337 bool roundtrip = false;
344 * Read one command definition from the syntax file
346 void read_command(Parser & p, string command, CommandMap & commands)
348 if (p.next_token().asInput() == "*") {
352 vector<ArgumentType> arguments;
353 while (p.next_token().cat() == catBegin ||
354 p.next_token().asInput() == "[") {
355 if (p.next_token().cat() == catBegin) {
356 string const arg = p.getArg('{', '}');
357 if (arg == "translate")
358 arguments.push_back(required);
359 else if (arg == "group")
360 arguments.push_back(req_group);
361 else if (arg == "item")
362 arguments.push_back(item);
363 else if (arg == "displaymath")
364 arguments.push_back(displaymath);
366 arguments.push_back(verbatim);
368 string const arg = p.getArg('[', ']');
370 arguments.push_back(opt_group);
372 arguments.push_back(optional);
375 commands[command] = arguments;
380 * Read a class of environments from the syntax file
382 void read_environment(Parser & p, string const & begin,
383 CommandMap & environments)
387 Token const & t = p.get_token();
388 if (t.cat() == catLetter)
389 environment += t.asInput();
390 else if (!environment.empty()) {
392 read_command(p, environment, environments);
395 if (t.cat() == catEscape && t.asInput() == "\\end") {
396 string const end = p.getArg('{', '}');
405 * Read a list of TeX commands from a reLyX compatible syntax file.
406 * Since this list is used after all commands that have a LyX counterpart
407 * are handled, it does not matter that the "syntax.default" file
408 * has almost all of them listed. For the same reason the reLyX-specific
409 * reLyXre environment is ignored.
411 void read_syntaxfile(FileName const & file_name)
413 ifdocstream is(file_name.toFilesystemEncoding().c_str());
415 cerr << "Could not open syntax file \"" << file_name
416 << "\" for reading." << endl;
419 // We can use our TeX parser, since the syntax of the layout file is
420 // modeled after TeX.
421 // Unknown tokens are just silently ignored, this helps us to skip some
422 // reLyX specific things.
425 Token const & t = p.get_token();
426 if (t.cat() == catEscape) {
427 string const command = t.asInput();
428 if (command == "\\begin") {
429 string const name = p.getArg('{', '}');
430 if (name == "environments" || name == "reLyXre")
431 // We understand "reLyXre", but it is
432 // not as powerful as "environments".
433 read_environment(p, name,
435 else if (name == "mathenvironments")
436 read_environment(p, name,
437 known_math_environments);
439 read_command(p, command, known_commands);
446 string documentclass;
447 string default_encoding;
449 bool copy_files = false;
450 bool overwrite_files = false;
453 /// return the number of arguments consumed
454 typedef int (*cmd_helper)(string const &, string const &);
457 int parse_help(string const &, string const &)
459 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
461 "\t-c textclass Declare the textclass.\n"
462 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
463 "\t-e encoding Set the default encoding (latex name).\n"
464 "\t-f Force overwrite of .lyx files.\n"
465 "\t-help Print this message and quit.\n"
466 "\t-n translate a noweb (aka literate programming) file.\n"
467 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
468 "\t-s syntaxfile read additional syntax file.\n"
469 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
470 "\t Default: " << package().system_support() << "\n"
471 "\t-userdir USERDIR Set user directory to USERDIR.\n"
472 "\t Default: " << package().user_support() << "\n"
473 "\t-version Summarize version and build info.\n"
475 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
476 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
477 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
478 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
479 "Check the tex2lyx man page for more details."
485 int parse_version(string const &, string const &)
487 lyxerr << "tex2lyx " << lyx_version
488 << " (" << lyx_release_date << ")" << endl;
489 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
491 lyxerr << lyx_version_info << endl;
496 void error_message(string const & message)
498 cerr << "tex2lyx: " << message << "\n\n";
500 parse_help(string(), string());
504 int parse_class(string const & arg, string const &)
507 error_message("Missing textclass string after -c switch");
513 int parse_encoding(string const & arg, string const &)
516 error_message("Missing encoding string after -e switch");
517 default_encoding = arg;
522 int parse_syntaxfile(string const & arg, string const &)
525 error_message("Missing syntaxfile string after -s switch");
526 syntaxfile = internal_path(arg);
531 // Filled with the command line arguments "foo" of "-sysdir foo" or
533 string cl_system_support;
534 string cl_user_support;
537 int parse_sysdir(string const & arg, string const &)
540 error_message("Missing directory for -sysdir switch");
541 cl_system_support = internal_path(arg);
546 int parse_userdir(string const & arg, string const &)
549 error_message("Missing directory for -userdir switch");
550 cl_user_support = internal_path(arg);
555 int parse_force(string const &, string const &)
557 overwrite_files = true;
562 int parse_noweb(string const &, string const &)
569 int parse_roundtrip(string const &, string const &)
576 int parse_copyfiles(string const &, string const &)
583 void easyParse(int & argc, char * argv[])
585 map<string, cmd_helper> cmdmap;
587 cmdmap["-h"] = parse_help;
588 cmdmap["-help"] = parse_help;
589 cmdmap["--help"] = parse_help;
590 cmdmap["-v"] = parse_version;
591 cmdmap["-version"] = parse_version;
592 cmdmap["--version"] = parse_version;
593 cmdmap["-c"] = parse_class;
594 cmdmap["-e"] = parse_encoding;
595 cmdmap["-f"] = parse_force;
596 cmdmap["-s"] = parse_syntaxfile;
597 cmdmap["-n"] = parse_noweb;
598 cmdmap["-sysdir"] = parse_sysdir;
599 cmdmap["-userdir"] = parse_userdir;
600 cmdmap["-roundtrip"] = parse_roundtrip;
601 cmdmap["-copyfiles"] = parse_copyfiles;
603 for (int i = 1; i < argc; ++i) {
604 map<string, cmd_helper>::const_iterator it
605 = cmdmap.find(argv[i]);
607 // don't complain if not found - may be parsed later
608 if (it == cmdmap.end()) {
609 if (argv[i][0] == '-')
610 error_message(string("Unknown option `") + argv[i] + "'.");
615 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
616 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
618 int const remove = 1 + it->second(arg, arg2);
620 // Now, remove used arguments by shifting
621 // the following ones remove places down.
622 os::remove_internal_args(i, remove);
624 for (int j = i; j < argc; ++j)
625 argv[j] = argv[j + remove];
631 // path of the first parsed file
632 string masterFilePathLyX;
633 string masterFilePathTeX;
634 // path of the currently parsed file
635 string parentFilePathTeX;
637 } // anonymous namespace
640 string getMasterFilePath(bool input)
642 return input ? masterFilePathTeX : masterFilePathLyX;
645 string getParentFilePath(bool input)
648 return parentFilePathTeX;
649 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
650 from_utf8(parentFilePathTeX)));
651 if (rel.substr(0, 3) == "../") {
652 // The parent is not below the master - keep the path
653 return parentFilePathTeX;
655 return makeAbsPath(rel, masterFilePathLyX).absFileName();
665 bool overwriteFiles()
667 return overwrite_files;
674 * Reads tex input from \a is and writes lyx output to \a os.
675 * Uses some common settings for the preamble, so this should only
676 * be used more than once for included documents.
677 * Caution: Overwrites the existing preamble settings if the new document
678 * contains a preamble.
679 * You must ensure that \p parentFilePathTeX is properly set before calling
682 bool tex2lyx(idocstream & is, ostream & os, string encoding)
684 // Set a sensible default encoding.
685 // This is used until an encoding command is found.
686 // For child documents use the encoding of the master, else latin1,
687 // since latin1 does not cause an iconv error if the actual encoding
688 // is different (bug 7509).
689 if (encoding.empty()) {
690 if (preamble.inputencoding() == "auto")
693 encoding = preamble.inputencoding();
697 p.setEncoding(encoding);
700 preamble.parse(p, documentclass, textclass);
702 active_environments.push_back("document");
703 Context context(true, textclass);
705 // store the document language in the context to be able to handle the
706 // commands like \foreignlanguage and \textenglish etc.
707 context.font.language = preamble.language();
708 // parse the main text
709 parse_text(p, ss, FLAG_END, true, context);
711 // Empty document body. LyX needs at least one paragraph.
712 context.check_layout(ss);
713 context.check_end_layout(ss);
714 ss << "\n\\end_body\n\\end_document\n";
715 active_environments.pop_back();
717 // We know the used modules only after parsing the full text
718 if (!used_modules.empty()) {
719 LayoutModuleList::const_iterator const end = used_modules.end();
720 LayoutModuleList::const_iterator it = used_modules.begin();
721 for (; it != end; ++it)
722 preamble.addModule(*it);
724 if (!preamble.writeLyXHeader(os, !active_environments.empty())) {
725 cerr << "Could write LyX file header." << endl;
733 ofdocstream parsertest("parsertest.tex");
735 parsertest << p.get_token().asInput();
736 // <origfile> and parsertest.tex should now have identical content
742 /// convert TeX from \p infilename to LyX and write it to \p os
743 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
746 // forbid buffering on this stream
747 is.rdbuf()->pubsetbuf(0,0);
748 is.open(infilename.toFilesystemEncoding().c_str());
750 cerr << "Could not open input file \"" << infilename
751 << "\" for reading." << endl;
754 string const oldParentFilePath = parentFilePathTeX;
755 parentFilePathTeX = onlyPath(infilename.absFileName());
756 bool retval = tex2lyx(is, os, encoding);
757 parentFilePathTeX = oldParentFilePath;
761 } // anonymous namespace
764 bool tex2lyx(string const & infilename, FileName const & outfilename,
765 string const & encoding)
767 if (outfilename.isReadableFile()) {
768 if (overwrite_files) {
769 cerr << "Overwriting existing file "
770 << outfilename << endl;
772 cerr << "Not overwriting existing file "
773 << outfilename << endl;
777 cerr << "Creating file " << outfilename << endl;
779 ofstream os(outfilename.toFilesystemEncoding().c_str());
781 cerr << "Could not open output file \"" << outfilename
782 << "\" for writing." << endl;
786 cerr << "Input file: " << infilename << "\n";
787 cerr << "Output file: " << outfilename << "\n";
789 return tex2lyx(FileName(infilename), os, encoding);
793 bool tex2tex(string const & infilename, FileName const & outfilename,
794 string const & encoding)
796 if (!tex2lyx(infilename, outfilename, encoding))
798 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
800 command += " -f main";
802 command += " -f none";
804 command += " -e pdflatex ";
806 command += " -e xetex ";
808 command += " -e latex ";
809 command += quoteName(outfilename.toFilesystemEncoding());
811 if (one.startscript(Systemcall::Wait, command) == 0)
813 cerr << "Error: Running '" << command << "' failed." << endl;
820 int main(int argc, char * argv[])
824 //setlocale(LC_CTYPE, "");
826 lyxerr.setStream(cerr);
828 os::init(argc, argv);
831 init_package(internal_path(os::utf8_argv(0)), string(), string());
832 } catch (ExceptionMessage const & message) {
833 cerr << to_utf8(message.title_) << ":\n"
834 << to_utf8(message.details_) << endl;
835 if (message.type_ == ErrorException)
839 easyParse(argc, argv);
842 error_message("Not enough arguments.");
845 init_package(internal_path(os::utf8_argv(0)),
846 cl_system_support, cl_user_support);
847 } catch (ExceptionMessage const & message) {
848 cerr << to_utf8(message.title_) << ":\n"
849 << to_utf8(message.details_) << endl;
850 if (message.type_ == ErrorException)
854 // Now every known option is parsed. Look for input and output
855 // file name (the latter is optional).
856 string infilename = internal_path(os::utf8_argv(1));
857 infilename = makeAbsPath(infilename).absFileName();
861 outfilename = internal_path(os::utf8_argv(2));
862 if (outfilename != "-")
863 outfilename = makeAbsPath(outfilename).absFileName();
865 if (outfilename == "-") {
866 cerr << "Error: Writing to standard output is "
867 "not supported in roundtrip mode."
871 string texfilename = changeExtension(outfilename, ".tex");
872 if (equivalent(FileName(infilename), FileName(texfilename))) {
873 cerr << "Error: The input file `" << infilename
874 << "´ would be overwritten by the TeX file exported from `"
875 << outfilename << "´ in roundtrip mode." << endl;
879 } else if (roundtrip) {
880 // avoid overwriting the input file
881 outfilename = changeExtension(infilename, ".lyx.lyx");
883 outfilename = changeExtension(infilename, ".lyx");
885 // Read the syntax tables
886 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
887 if (system_syntaxfile.empty()) {
888 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
891 read_syntaxfile(system_syntaxfile);
892 if (!syntaxfile.empty())
893 read_syntaxfile(makeAbsPath(syntaxfile));
895 // Read the encodings table.
896 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
897 if (symbols_path.empty()) {
898 cerr << "Error: Could not find file \"unicodesymbols\"."
902 FileName const enc_path = libFileSearch(string(), "encodings");
903 if (enc_path.empty()) {
904 cerr << "Error: Could not find file \"encodings\"."
908 encodings.read(enc_path, symbols_path);
909 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
910 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
913 LayoutFileList::get().read();
915 theModuleList.read();
917 // The real work now.
918 masterFilePathTeX = onlyPath(infilename);
919 parentFilePathTeX = masterFilePathTeX;
920 if (outfilename == "-") {
921 // assume same directory as input file
922 masterFilePathLyX = masterFilePathTeX;
923 if (tex2lyx(FileName(infilename), cout, default_encoding))
926 masterFilePathLyX = onlyPath(outfilename);
928 if (tex2tex(infilename, FileName(outfilename), default_encoding))
931 if (tex2lyx(infilename, FileName(outfilename), default_encoding))