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 roundtrip = false;
342 * Read one command definition from the syntax file
344 void read_command(Parser & p, string command, CommandMap & commands)
346 if (p.next_token().asInput() == "*") {
350 vector<ArgumentType> arguments;
351 while (p.next_token().cat() == catBegin ||
352 p.next_token().asInput() == "[") {
353 if (p.next_token().cat() == catBegin) {
354 string const arg = p.getArg('{', '}');
355 if (arg == "translate")
356 arguments.push_back(required);
357 else if (arg == "group")
358 arguments.push_back(req_group);
359 else if (arg == "item")
360 arguments.push_back(item);
361 else if (arg == "displaymath")
362 arguments.push_back(displaymath);
364 arguments.push_back(verbatim);
366 string const arg = p.getArg('[', ']');
368 arguments.push_back(opt_group);
370 arguments.push_back(optional);
373 commands[command] = arguments;
378 * Read a class of environments from the syntax file
380 void read_environment(Parser & p, string const & begin,
381 CommandMap & environments)
385 Token const & t = p.get_token();
386 if (t.cat() == catLetter)
387 environment += t.asInput();
388 else if (!environment.empty()) {
390 read_command(p, environment, environments);
393 if (t.cat() == catEscape && t.asInput() == "\\end") {
394 string const end = p.getArg('{', '}');
403 * Read a list of TeX commands from a reLyX compatible syntax file.
404 * Since this list is used after all commands that have a LyX counterpart
405 * are handled, it does not matter that the "syntax.default" file
406 * has almost all of them listed. For the same reason the reLyX-specific
407 * reLyXre environment is ignored.
409 void read_syntaxfile(FileName const & file_name)
411 ifdocstream is(file_name.toFilesystemEncoding().c_str());
413 cerr << "Could not open syntax file \"" << file_name
414 << "\" for reading." << endl;
417 // We can use our TeX parser, since the syntax of the layout file is
418 // modeled after TeX.
419 // Unknown tokens are just silently ignored, this helps us to skip some
420 // reLyX specific things.
423 Token const & t = p.get_token();
424 if (t.cat() == catEscape) {
425 string const command = t.asInput();
426 if (command == "\\begin") {
427 string const name = p.getArg('{', '}');
428 if (name == "environments" || name == "reLyXre")
429 // We understand "reLyXre", but it is
430 // not as powerful as "environments".
431 read_environment(p, name,
433 else if (name == "mathenvironments")
434 read_environment(p, name,
435 known_math_environments);
437 read_command(p, command, known_commands);
444 string documentclass;
445 string default_encoding;
447 bool overwrite_files = false;
450 /// return the number of arguments consumed
451 typedef int (*cmd_helper)(string const &, string const &);
454 int parse_help(string const &, string const &)
456 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
458 "\t-c textclass Declare the textclass.\n"
459 "\t-e encoding Set the default encoding (latex name).\n"
460 "\t-f Force overwrite of .lyx files.\n"
461 "\t-help Print this message and quit.\n"
462 "\t-n translate a noweb (aka literate programming) file.\n"
463 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
464 "\t-s syntaxfile read additional syntax file.\n"
465 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
466 "\t Default: " << package().system_support() << "\n"
467 "\t-userdir USERDIR Set user directory to USERDIR.\n"
468 "\t Default: " << package().user_support() << "\n"
469 "\t-version Summarize version and build info.\n"
471 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
472 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
473 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
474 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
475 "Check the tex2lyx man page for more details."
481 int parse_version(string const &, string const &)
483 lyxerr << "tex2lyx " << lyx_version
484 << " (" << lyx_release_date << ")" << endl;
485 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
487 lyxerr << lyx_version_info << endl;
492 void error_message(string const & message)
494 cerr << "tex2lyx: " << message << "\n\n";
496 parse_help(string(), string());
500 int parse_class(string const & arg, string const &)
503 error_message("Missing textclass string after -c switch");
509 int parse_encoding(string const & arg, string const &)
512 error_message("Missing encoding string after -e switch");
513 default_encoding = arg;
518 int parse_syntaxfile(string const & arg, string const &)
521 error_message("Missing syntaxfile string after -s switch");
522 syntaxfile = internal_path(arg);
527 // Filled with the command line arguments "foo" of "-sysdir foo" or
529 string cl_system_support;
530 string cl_user_support;
533 int parse_sysdir(string const & arg, string const &)
536 error_message("Missing directory for -sysdir switch");
537 cl_system_support = internal_path(arg);
542 int parse_userdir(string const & arg, string const &)
545 error_message("Missing directory for -userdir switch");
546 cl_user_support = internal_path(arg);
551 int parse_force(string const &, string const &)
553 overwrite_files = true;
558 int parse_noweb(string const &, string const &)
565 int parse_roundtrip(string const &, string const &)
572 void easyParse(int & argc, char * argv[])
574 map<string, cmd_helper> cmdmap;
576 cmdmap["-h"] = parse_help;
577 cmdmap["-help"] = parse_help;
578 cmdmap["--help"] = parse_help;
579 cmdmap["-v"] = parse_version;
580 cmdmap["-version"] = parse_version;
581 cmdmap["--version"] = parse_version;
582 cmdmap["-c"] = parse_class;
583 cmdmap["-e"] = parse_encoding;
584 cmdmap["-f"] = parse_force;
585 cmdmap["-s"] = parse_syntaxfile;
586 cmdmap["-n"] = parse_noweb;
587 cmdmap["-sysdir"] = parse_sysdir;
588 cmdmap["-userdir"] = parse_userdir;
589 cmdmap["-roundtrip"] = parse_roundtrip;
591 for (int i = 1; i < argc; ++i) {
592 map<string, cmd_helper>::const_iterator it
593 = cmdmap.find(argv[i]);
595 // don't complain if not found - may be parsed later
596 if (it == cmdmap.end()) {
597 if (argv[i][0] == '-')
598 error_message(string("Unknown option `") + argv[i] + "'.");
603 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
604 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
606 int const remove = 1 + it->second(arg, arg2);
608 // Now, remove used arguments by shifting
609 // the following ones remove places down.
610 os::remove_internal_args(i, remove);
612 for (int j = i; j < argc; ++j)
613 argv[j] = argv[j + remove];
619 // path of the first parsed file
620 string masterFilePath;
621 // path of the currently parsed file
622 string parentFilePath;
624 } // anonymous namespace
627 string getMasterFilePath()
629 return masterFilePath;
632 string getParentFilePath()
634 return parentFilePath;
641 * Reads tex input from \a is and writes lyx output to \a os.
642 * Uses some common settings for the preamble, so this should only
643 * be used more than once for included documents.
644 * Caution: Overwrites the existing preamble settings if the new document
645 * contains a preamble.
646 * You must ensure that \p parentFilePath is properly set before calling
649 bool tex2lyx(idocstream & is, ostream & os, string encoding)
651 // Set a sensible default encoding.
652 // This is used until an encoding command is found.
653 // For child documents use the encoding of the master, else latin1,
654 // since latin1 does not cause an iconv error if the actual encoding
655 // is different (bug 7509).
656 if (encoding.empty()) {
657 if (preamble.inputencoding() == "auto")
660 encoding = preamble.inputencoding();
664 p.setEncoding(encoding);
667 preamble.parse(p, documentclass, textclass);
669 active_environments.push_back("document");
670 Context context(true, textclass);
672 parse_text(p, ss, FLAG_END, true, context);
674 // Empty document body. LyX needs at least one paragraph.
675 context.check_layout(ss);
676 context.check_end_layout(ss);
677 ss << "\n\\end_body\n\\end_document\n";
678 active_environments.pop_back();
680 // We know the used modules only after parsing the full text
681 if (!used_modules.empty()) {
682 LayoutModuleList::const_iterator const end = used_modules.end();
683 LayoutModuleList::const_iterator it = used_modules.begin();
684 for (; it != end; ++it)
685 preamble.addModule(*it);
687 if (!preamble.writeLyXHeader(os, !active_environments.empty())) {
688 cerr << "Could write LyX file header." << endl;
696 ofdocstream parsertest("parsertest.tex");
698 parsertest << p.get_token().asInput();
699 // <origfile> and parsertest.tex should now have identical content
705 /// convert TeX from \p infilename to LyX and write it to \p os
706 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
709 // forbid buffering on this stream
710 is.rdbuf()->pubsetbuf(0,0);
711 is.open(infilename.toFilesystemEncoding().c_str());
713 cerr << "Could not open input file \"" << infilename
714 << "\" for reading." << endl;
717 string const oldParentFilePath = parentFilePath;
718 parentFilePath = onlyPath(infilename.absFileName());
719 bool retval = tex2lyx(is, os, encoding);
720 parentFilePath = oldParentFilePath;
724 } // anonymous namespace
727 bool tex2lyx(string const & infilename, FileName const & outfilename,
728 string const & encoding)
730 if (outfilename.isReadableFile()) {
731 if (overwrite_files) {
732 cerr << "Overwriting existing file "
733 << outfilename << endl;
735 cerr << "Not overwriting existing file "
736 << outfilename << endl;
740 cerr << "Creating file " << outfilename << endl;
742 ofstream os(outfilename.toFilesystemEncoding().c_str());
744 cerr << "Could not open output file \"" << outfilename
745 << "\" for writing." << endl;
749 cerr << "Input file: " << infilename << "\n";
750 cerr << "Output file: " << outfilename << "\n";
752 return tex2lyx(FileName(infilename), os, encoding);
756 bool tex2tex(string const & infilename, FileName const & outfilename,
757 string const & encoding)
759 if (!tex2lyx(infilename, outfilename, encoding))
761 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
763 command += " -f main";
765 command += " -f none";
767 command += " -e pdflatex ";
769 command += " -e latex ";
770 command += quoteName(outfilename.toFilesystemEncoding());
772 if (one.startscript(Systemcall::Wait, command) == 0)
774 cerr << "Error: Running '" << command << "' failed." << endl;
781 int main(int argc, char * argv[])
785 //setlocale(LC_CTYPE, "");
787 lyxerr.setStream(cerr);
789 os::init(argc, argv);
792 init_package(internal_path(os::utf8_argv(0)), string(), string());
793 } catch (ExceptionMessage const & message) {
794 cerr << to_utf8(message.title_) << ":\n"
795 << to_utf8(message.details_) << endl;
796 if (message.type_ == ErrorException)
800 easyParse(argc, argv);
803 error_message("Not enough arguments.");
806 init_package(internal_path(os::utf8_argv(0)),
807 cl_system_support, cl_user_support);
808 } catch (ExceptionMessage const & message) {
809 cerr << to_utf8(message.title_) << ":\n"
810 << to_utf8(message.details_) << endl;
811 if (message.type_ == ErrorException)
815 // Now every known option is parsed. Look for input and output
816 // file name (the latter is optional).
817 string infilename = internal_path(os::utf8_argv(1));
818 infilename = makeAbsPath(infilename).absFileName();
823 // Do not allow a user supplied output filename
824 // (otherwise it could easily happen that LyX would
825 // overwrite the original .tex file)
826 cerr << "Error: output filename must not be given in roundtrip mode."
830 outfilename = changeExtension(infilename, ".lyx.lyx");
831 } else if (argc > 2) {
832 outfilename = internal_path(os::utf8_argv(2));
833 if (outfilename != "-")
834 outfilename = makeAbsPath(outfilename).absFileName();
836 outfilename = changeExtension(infilename, ".lyx");
838 // Read the syntax tables
839 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
840 if (system_syntaxfile.empty()) {
841 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
844 read_syntaxfile(system_syntaxfile);
845 if (!syntaxfile.empty())
846 read_syntaxfile(makeAbsPath(syntaxfile));
848 // Read the encodings table.
849 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
850 if (symbols_path.empty()) {
851 cerr << "Error: Could not find file \"unicodesymbols\"."
855 FileName const enc_path = libFileSearch(string(), "encodings");
856 if (enc_path.empty()) {
857 cerr << "Error: Could not find file \"encodings\"."
861 encodings.read(enc_path, symbols_path);
862 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
863 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
866 LayoutFileList::get().read();
868 theModuleList.read();
870 // The real work now.
871 masterFilePath = onlyPath(infilename);
872 parentFilePath = masterFilePath;
873 if (outfilename == "-") {
874 if (tex2lyx(FileName(infilename), cout, default_encoding))
876 } else if (roundtrip) {
877 if (tex2tex(infilename, FileName(outfilename), default_encoding))
880 if (tex2lyx(infilename, FileName(outfilename), default_encoding))