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;
152 int const LYX_FORMAT = LYX_FORMAT_TEX2LYX;
155 LayoutModuleList used_modules;
158 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
160 // We have to handle the following cases:
161 // definition o1 o2 invocation result
162 // \newcommand{\foo}{bar} "" false \foo bar
163 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
164 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
165 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
166 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
167 unsigned int nargs = 0;
168 string const opt1 = rtrim(ltrim(o1, "["), "]");
169 if (isStrUnsignedInt(opt1)) {
170 // The command has arguments
171 nargs = convert<unsigned int>(opt1);
172 if (nargs > 0 && o2) {
173 // The first argument is optional
174 arguments.push_back(optional);
178 for (unsigned int i = 0; i < nargs; ++i)
179 arguments.push_back(required);
183 void add_known_command(string const & command, string const & o1,
184 bool o2, docstring const & definition)
186 vector<ArgumentType> arguments;
187 convertArgs(o1, o2, arguments);
188 known_commands[command] = arguments;
189 if (!definition.empty())
190 possible_textclass_commands[command] =
191 FullCommand(arguments, definition);
195 void add_known_environment(string const & environment, string const & o1,
196 bool o2, docstring const & beg, docstring const &end)
198 vector<ArgumentType> arguments;
199 convertArgs(o1, o2, arguments);
200 known_environments[environment] = arguments;
201 if (!beg.empty() || ! end.empty())
202 possible_textclass_environments[environment] =
203 FullEnvironment(arguments, beg, end);
207 Layout const * findLayoutWithoutModule(TextClass const & textclass,
208 string const & name, bool command)
210 DocumentClass::const_iterator it = textclass.begin();
211 DocumentClass::const_iterator en = textclass.end();
212 for (; it != en; ++it) {
213 if (it->latexname() == name &&
214 ((command && it->isCommand()) || (!command && it->isEnvironment())))
221 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
222 string const & name, bool command)
224 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
225 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
226 for (; it != en; ++it) {
227 if (it->second.latexname() == name &&
228 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
229 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
230 return &(it->second);
236 bool checkModule(string const & name, bool command)
238 // Cache to avoid slowdown by repated searches
239 static set<string> failed[2];
241 // Only add the module if the command was actually defined in the LyX preamble
243 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
246 if (possible_textclass_environments.find(name) == possible_textclass_environments.end())
249 if (failed[command].find(name) != failed[command].end())
252 // Create list of dummy document classes if not already done.
253 // This is needed since a module cannot be read on its own, only as
254 // part of a document class.
255 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
256 typedef map<string, DocumentClass *> ModuleMap;
257 static ModuleMap modules;
258 static bool init = true;
261 DocumentClassBundle & bundle = DocumentClassBundle::get();
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] = &bundle.makeDocumentClass(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 DocumentClass const * 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;
334 bool roundtrip = false;
341 * Read one command definition from the syntax file
343 void read_command(Parser & p, string command, CommandMap & commands)
345 if (p.next_token().asInput() == "*") {
349 vector<ArgumentType> arguments;
350 while (p.next_token().cat() == catBegin ||
351 p.next_token().asInput() == "[") {
352 if (p.next_token().cat() == catBegin) {
353 string const arg = p.getArg('{', '}');
354 if (arg == "translate")
355 arguments.push_back(required);
356 else if (arg == "item")
357 arguments.push_back(item);
359 arguments.push_back(verbatim);
362 arguments.push_back(optional);
365 commands[command] = arguments;
370 * Read a class of environments from the syntax file
372 void read_environment(Parser & p, string const & begin,
373 CommandMap & environments)
377 Token const & t = p.get_token();
378 if (t.cat() == catLetter)
379 environment += t.asInput();
380 else if (!environment.empty()) {
382 read_command(p, environment, environments);
385 if (t.cat() == catEscape && t.asInput() == "\\end") {
386 string const end = p.getArg('{', '}');
395 * Read a list of TeX commands from a reLyX compatible syntax file.
396 * Since this list is used after all commands that have a LyX counterpart
397 * are handled, it does not matter that the "syntax.default" file
398 * has almost all of them listed. For the same reason the reLyX-specific
399 * reLyXre environment is ignored.
401 void read_syntaxfile(FileName const & file_name)
403 ifdocstream is(file_name.toFilesystemEncoding().c_str());
405 cerr << "Could not open syntax file \"" << file_name
406 << "\" for reading." << endl;
409 // We can use our TeX parser, since the syntax of the layout file is
410 // modeled after TeX.
411 // Unknown tokens are just silently ignored, this helps us to skip some
412 // reLyX specific things.
415 Token const & t = p.get_token();
416 if (t.cat() == catEscape) {
417 string const command = t.asInput();
418 if (command == "\\begin") {
419 string const name = p.getArg('{', '}');
420 if (name == "environments" || name == "reLyXre")
421 // We understand "reLyXre", but it is
422 // not as powerful as "environments".
423 read_environment(p, name,
425 else if (name == "mathenvironments")
426 read_environment(p, name,
427 known_math_environments);
429 read_command(p, command, known_commands);
436 string documentclass;
437 string default_encoding;
439 bool overwrite_files = false;
442 /// return the number of arguments consumed
443 typedef int (*cmd_helper)(string const &, string const &);
446 int parse_help(string const &, string const &)
448 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
450 "\t-c textclass Declare the textclass.\n"
451 "\t-e encoding Set the default encoding (latex name).\n"
452 "\t-f Force overwrite of .lyx files.\n"
453 "\t-help Print this message and quit.\n"
454 "\t-n translate a noweb (aka literate programming) file.\n"
455 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
456 "\t-s syntaxfile read additional syntax file.\n"
457 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
458 "\t Default: " << package().system_support() << "\n"
459 "\t-userdir USERDIR Set user directory to USERDIR.\n"
460 "\t Default: " << package().user_support() << "\n"
461 "\t-version Summarize version and build info.\n"
463 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
464 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
465 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
466 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
467 "Check the tex2lyx man page for more details."
473 int parse_version(string const &, string const &)
475 lyxerr << "tex2lyx " << lyx_version
476 << " (" << lyx_release_date << ")" << endl;
477 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
479 lyxerr << lyx_version_info << endl;
484 void error_message(string const & message)
486 cerr << "tex2lyx: " << message << "\n\n";
488 parse_help(string(), string());
492 int parse_class(string const & arg, string const &)
495 error_message("Missing textclass string after -c switch");
501 int parse_encoding(string const & arg, string const &)
504 error_message("Missing encoding string after -e switch");
505 default_encoding = arg;
510 int parse_syntaxfile(string const & arg, string const &)
513 error_message("Missing syntaxfile string after -s switch");
514 syntaxfile = internal_path(arg);
519 // Filled with the command line arguments "foo" of "-sysdir foo" or
521 string cl_system_support;
522 string cl_user_support;
525 int parse_sysdir(string const & arg, string const &)
528 error_message("Missing directory for -sysdir switch");
529 cl_system_support = internal_path(arg);
534 int parse_userdir(string const & arg, string const &)
537 error_message("Missing directory for -userdir switch");
538 cl_user_support = internal_path(arg);
543 int parse_force(string const &, string const &)
545 overwrite_files = true;
550 int parse_noweb(string const &, string const &)
557 int parse_roundtrip(string const &, string const &)
564 void easyParse(int & argc, char * argv[])
566 map<string, cmd_helper> cmdmap;
568 cmdmap["-h"] = parse_help;
569 cmdmap["-help"] = parse_help;
570 cmdmap["--help"] = parse_help;
571 cmdmap["-v"] = parse_version;
572 cmdmap["-version"] = parse_version;
573 cmdmap["--version"] = parse_version;
574 cmdmap["-c"] = parse_class;
575 cmdmap["-e"] = parse_encoding;
576 cmdmap["-f"] = parse_force;
577 cmdmap["-s"] = parse_syntaxfile;
578 cmdmap["-n"] = parse_noweb;
579 cmdmap["-sysdir"] = parse_sysdir;
580 cmdmap["-userdir"] = parse_userdir;
581 cmdmap["-roundtrip"] = parse_roundtrip;
583 for (int i = 1; i < argc; ++i) {
584 map<string, cmd_helper>::const_iterator it
585 = cmdmap.find(argv[i]);
587 // don't complain if not found - may be parsed later
588 if (it == cmdmap.end()) {
589 if (argv[i][0] == '-')
590 error_message(string("Unknown option `") + argv[i] + "'.");
595 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
596 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
598 int const remove = 1 + it->second(arg, arg2);
600 // Now, remove used arguments by shifting
601 // the following ones remove places down.
602 os::remove_internal_args(i, remove);
604 for (int j = i; j < argc; ++j)
605 argv[j] = argv[j + remove];
611 // path of the first parsed file
612 string masterFilePath;
613 // path of the currently parsed file
614 string parentFilePath;
616 } // anonymous namespace
619 string getMasterFilePath()
621 return masterFilePath;
624 string getParentFilePath()
626 return parentFilePath;
633 * Reads tex input from \a is and writes lyx output to \a os.
634 * Uses some common settings for the preamble, so this should only
635 * be used more than once for included documents.
636 * Caution: Overwrites the existing preamble settings if the new document
637 * contains a preamble.
638 * You must ensure that \p parentFilePath is properly set before calling
641 void tex2lyx(idocstream & is, ostream & os, string encoding)
643 // Set a sensible default encoding.
644 // This is used until an encoding command is found.
645 // For child documents use the encoding of the master, else latin1,
646 // since latin1 does not cause an iconv error if the actual encoding
647 // is different (bug 7509).
648 if (encoding.empty()) {
649 if (h_inputencoding == "auto")
652 encoding = h_inputencoding;
656 p.setEncoding(encoding);
660 parse_preamble(p, ps, documentclass, textclass);
662 active_environments.push_back("document");
663 Context context(true, textclass);
665 parse_text(p, ss, FLAG_END, true, context);
667 // Empty document body. LyX needs at least one paragraph.
668 context.check_layout(ss);
669 context.check_end_layout(ss);
670 ss << "\n\\end_body\n\\end_document\n";
671 active_environments.pop_back();
673 // We know the used modules only after parsing the full text
675 if (!used_modules.empty()) {
676 ms << "\\begin_modules\n";
677 LayoutModuleList::const_iterator const end = used_modules.end();
678 LayoutModuleList::const_iterator it = used_modules.begin();
679 for (; it != end; it++)
681 ms << "\\end_modules\n";
683 os << subst(ps.str(), modules_placeholder, ms.str());
689 ofdocstream parsertest("parsertest.tex");
691 parsertest << p.get_token().asInput();
692 // <origfile> and parsertest.tex should now have identical content
697 /// convert TeX from \p infilename to LyX and write it to \p os
698 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
701 // forbid buffering on this stream
702 is.rdbuf()->pubsetbuf(0,0);
703 is.open(infilename.toFilesystemEncoding().c_str());
705 cerr << "Could not open input file \"" << infilename
706 << "\" for reading." << endl;
709 string const oldParentFilePath = parentFilePath;
710 parentFilePath = onlyPath(infilename.absFileName());
711 tex2lyx(is, os, encoding);
712 parentFilePath = oldParentFilePath;
716 } // anonymous namespace
719 bool tex2lyx(string const & infilename, FileName const & outfilename,
720 string const & encoding)
722 if (outfilename.isReadableFile()) {
723 if (overwrite_files) {
724 cerr << "Overwriting existing file "
725 << outfilename << endl;
727 cerr << "Not overwriting existing file "
728 << outfilename << endl;
732 cerr << "Creating file " << outfilename << endl;
734 ofstream os(outfilename.toFilesystemEncoding().c_str());
736 cerr << "Could not open output file \"" << outfilename
737 << "\" for writing." << endl;
741 cerr << "Input file: " << infilename << "\n";
742 cerr << "Output file: " << outfilename << "\n";
744 return tex2lyx(FileName(infilename), os, encoding);
748 bool tex2tex(string const & infilename, FileName const & outfilename,
749 string const & encoding)
751 if (!tex2lyx(infilename, outfilename, encoding))
753 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
755 command += " -f main";
757 command += " -f none";
759 command += " -e pdflatex ";
761 command += " -e latex ";
762 command += quoteName(outfilename.toFilesystemEncoding());
764 if (one.startscript(Systemcall::Wait, command) == 0)
766 cerr << "Error: Running '" << command << "' failed." << endl;
773 int main(int argc, char * argv[])
777 //setlocale(LC_CTYPE, "");
779 lyxerr.setStream(cerr);
781 os::init(argc, argv);
784 init_package(internal_path(os::utf8_argv(0)), string(), string());
785 } catch (ExceptionMessage const & message) {
786 cerr << to_utf8(message.title_) << ":\n"
787 << to_utf8(message.details_) << endl;
788 if (message.type_ == ErrorException)
792 easyParse(argc, argv);
795 error_message("Not enough arguments.");
798 init_package(internal_path(os::utf8_argv(0)),
799 cl_system_support, cl_user_support);
800 } catch (ExceptionMessage const & message) {
801 cerr << to_utf8(message.title_) << ":\n"
802 << to_utf8(message.details_) << endl;
803 if (message.type_ == ErrorException)
807 // Now every known option is parsed. Look for input and output
808 // file name (the latter is optional).
809 string infilename = internal_path(os::utf8_argv(1));
810 infilename = makeAbsPath(infilename).absFileName();
815 // Do not allow a user supplied output filename
816 // (otherwise it could easily happen that LyX would
817 // overwrite the original .tex file)
818 cerr << "Error: output filename must not be given in roundtrip mode."
822 outfilename = changeExtension(infilename, ".lyx.lyx");
823 } else if (argc > 2) {
824 outfilename = internal_path(os::utf8_argv(2));
825 if (outfilename != "-")
826 outfilename = makeAbsPath(outfilename).absFileName();
828 outfilename = changeExtension(infilename, ".lyx");
830 // Read the syntax tables
831 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
832 if (system_syntaxfile.empty()) {
833 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
836 read_syntaxfile(system_syntaxfile);
837 if (!syntaxfile.empty())
838 read_syntaxfile(makeAbsPath(syntaxfile));
840 // Read the encodings table.
841 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
842 if (symbols_path.empty()) {
843 cerr << "Error: Could not find file \"unicodesymbols\"."
847 FileName const enc_path = libFileSearch(string(), "encodings");
848 if (enc_path.empty()) {
849 cerr << "Error: Could not find file \"encodings\"."
853 encodings.read(enc_path, symbols_path);
854 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
855 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
858 LayoutFileList::get().read();
860 theModuleList.read();
862 // The real work now.
863 masterFilePath = onlyPath(infilename);
864 parentFilePath = masterFilePath;
865 if (outfilename == "-") {
866 if (tex2lyx(FileName(infilename), cout, default_encoding))
868 } else if (roundtrip) {
869 if (tex2tex(infilename, FileName(outfilename), default_encoding))
872 if (tex2lyx(infilename, FileName(outfilename), default_encoding))