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 trim(string const & a, char const * p)
101 if (a.empty() || !*p)
104 size_t r = a.find_last_not_of(p);
105 size_t l = a.find_first_not_of(p);
107 // Is this the minimal test? (lgb)
108 if (r == string::npos && l == string::npos)
111 return a.substr(l, r - l + 1);
115 void split(string const & s, vector<string> & result, char delim)
117 //cerr << "split 1: '" << s << "'\n";
120 while (getline(is, t, delim))
122 //cerr << "split 2\n";
126 string join(vector<string> const & input, char const * delim)
129 for (size_t i = 0; i != input.size(); ++i) {
138 char const * const * is_known(string const & str, char const * const * what)
140 for ( ; *what; ++what)
148 // current stack of nested environments
149 vector<string> active_environments;
152 string active_environment()
154 return active_environments.empty() ? string() : active_environments.back();
158 TeX2LyXDocClass textclass;
159 CommandMap known_commands;
160 CommandMap known_environments;
161 CommandMap known_math_environments;
162 FullCommandMap possible_textclass_commands;
163 FullEnvironmentMap possible_textclass_environments;
166 LayoutModuleList used_modules;
169 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
171 // We have to handle the following cases:
172 // definition o1 o2 invocation result
173 // \newcommand{\foo}{bar} "" false \foo bar
174 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
175 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
176 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
177 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
178 unsigned int nargs = 0;
179 string const opt1 = rtrim(ltrim(o1, "["), "]");
180 if (isStrUnsignedInt(opt1)) {
181 // The command has arguments
182 nargs = convert<unsigned int>(opt1);
183 if (nargs > 0 && o2) {
184 // The first argument is optional
185 arguments.push_back(optional);
189 for (unsigned int i = 0; i < nargs; ++i)
190 arguments.push_back(required);
194 void add_known_command(string const & command, string const & o1,
195 bool o2, docstring const & definition)
197 vector<ArgumentType> arguments;
198 convertArgs(o1, o2, arguments);
199 known_commands[command] = arguments;
200 if (!definition.empty())
201 possible_textclass_commands[command] =
202 FullCommand(arguments, definition);
206 void add_known_environment(string const & environment, string const & o1,
207 bool o2, docstring const & beg, docstring const &end)
209 vector<ArgumentType> arguments;
210 convertArgs(o1, o2, arguments);
211 known_environments[environment] = arguments;
212 if (!beg.empty() || ! end.empty())
213 possible_textclass_environments[environment] =
214 FullEnvironment(arguments, beg, end);
218 Layout const * findLayoutWithoutModule(TextClass const & textclass,
219 string const & name, bool command)
221 DocumentClass::const_iterator it = textclass.begin();
222 DocumentClass::const_iterator en = textclass.end();
223 for (; it != en; ++it) {
224 if (it->latexname() == name &&
225 ((command && it->isCommand()) || (!command && it->isEnvironment())))
232 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
233 string const & name, bool command)
235 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
236 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
237 for (; it != en; ++it) {
238 if (it->second.latexname() == name &&
239 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
240 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
241 return &(it->second);
247 bool checkModule(string const & name, bool command)
249 // Cache to avoid slowdown by repated searches
250 static set<string> failed[2];
252 // Only add the module if the command was actually defined in the LyX preamble
254 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
257 if (possible_textclass_environments.find(name) == possible_textclass_environments.end())
260 if (failed[command].find(name) != failed[command].end())
263 // Create list of dummy document classes if not already done.
264 // This is needed since a module cannot be read on its own, only as
265 // part of a document class.
266 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
267 typedef map<string, DocumentClass *> ModuleMap;
268 static ModuleMap modules;
269 static bool init = true;
272 DocumentClassBundle & bundle = DocumentClassBundle::get();
273 LyXModuleList::const_iterator const end = theModuleList.end();
274 LyXModuleList::const_iterator it = theModuleList.begin();
275 for (; it != end; it++) {
276 string const module = it->getID();
278 // FIXME this excludes all modules that depend on another one
279 if (!m.moduleCanBeAdded(module, &baseClass))
282 modules[module] = &bundle.makeDocumentClass(baseClass, m);
287 // Try to find a module that defines the command.
288 // Only add it if the definition can be found in the preamble of the
289 // style that corresponds to the command. This is a heuristic and
290 // different from the way how we parse the builtin commands of the
291 // text class (in that case we only compare the name), but it is
292 // needed since it is not unlikely that two different modules define a
293 // command with the same name.
294 ModuleMap::iterator const end = modules.end();
295 for (ModuleMap::iterator it = modules.begin(); it != end; it++) {
296 string const module = it->first;
297 if (!used_modules.moduleCanBeAdded(module, &baseClass))
299 if (findLayoutWithoutModule(textclass, name, command))
301 if (findInsetLayoutWithoutModule(textclass, name, command))
303 DocumentClass const * c = it->second;
304 Layout const * layout = findLayoutWithoutModule(*c, name, command);
305 InsetLayout const * insetlayout = layout ? 0 :
306 findInsetLayoutWithoutModule(*c, name, command);
309 preamble = layout->preamble();
310 else if (insetlayout)
311 preamble = insetlayout->preamble();
312 if (preamble.empty())
316 FullCommand const & cmd =
317 possible_textclass_commands['\\' + name];
318 if (preamble.find(cmd.def) != docstring::npos)
321 FullEnvironment const & env =
322 possible_textclass_environments[name];
323 if (preamble.find(env.beg) != docstring::npos &&
324 preamble.find(env.end) != docstring::npos)
328 FileName layout_file = libFileSearch("layouts", module, "module");
329 if (textclass.read(layout_file, TextClass::MODULE)) {
330 used_modules.push_back(module);
331 // speed up further searches:
332 // the module does not need to be checked anymore.
338 failed[command].insert(name);
343 bool noweb_mode = false;
344 bool pdflatex = false;
345 bool roundtrip = false;
352 * Read one command definition from the syntax file
354 void read_command(Parser & p, string command, CommandMap & commands)
356 if (p.next_token().asInput() == "*") {
360 vector<ArgumentType> arguments;
361 while (p.next_token().cat() == catBegin ||
362 p.next_token().asInput() == "[") {
363 if (p.next_token().cat() == catBegin) {
364 string const arg = p.getArg('{', '}');
365 if (arg == "translate")
366 arguments.push_back(required);
367 else if (arg == "item")
368 arguments.push_back(item);
370 arguments.push_back(verbatim);
373 arguments.push_back(optional);
376 commands[command] = arguments;
381 * Read a class of environments from the syntax file
383 void read_environment(Parser & p, string const & begin,
384 CommandMap & environments)
388 Token const & t = p.get_token();
389 if (t.cat() == catLetter)
390 environment += t.asInput();
391 else if (!environment.empty()) {
393 read_command(p, environment, environments);
396 if (t.cat() == catEscape && t.asInput() == "\\end") {
397 string const end = p.getArg('{', '}');
406 * Read a list of TeX commands from a reLyX compatible syntax file.
407 * Since this list is used after all commands that have a LyX counterpart
408 * are handled, it does not matter that the "syntax.default" file
409 * has almost all of them listed. For the same reason the reLyX-specific
410 * reLyXre environment is ignored.
412 void read_syntaxfile(FileName const & file_name)
414 ifdocstream is(file_name.toFilesystemEncoding().c_str());
416 cerr << "Could not open syntax file \"" << file_name
417 << "\" for reading." << endl;
420 // We can use our TeX parser, since the syntax of the layout file is
421 // modeled after TeX.
422 // Unknown tokens are just silently ignored, this helps us to skip some
423 // reLyX specific things.
426 Token const & t = p.get_token();
427 if (t.cat() == catEscape) {
428 string const command = t.asInput();
429 if (command == "\\begin") {
430 string const name = p.getArg('{', '}');
431 if (name == "environments" || name == "reLyXre")
432 // We understand "reLyXre", but it is
433 // not as powerful as "environments".
434 read_environment(p, name,
436 else if (name == "mathenvironments")
437 read_environment(p, name,
438 known_math_environments);
440 read_command(p, command, known_commands);
447 string documentclass;
448 string default_encoding;
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-e encoding Set the default encoding (latex name).\n"
463 "\t-f Force overwrite of .lyx files.\n"
464 "\t-help Print this message and quit.\n"
465 "\t-n translate a noweb (aka literate programming) file.\n"
466 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
467 "\t-s syntaxfile read additional syntax file.\n"
468 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
469 "\t Default: " << package().system_support() << "\n"
470 "\t-userdir USERDIR Set user directory to USERDIR.\n"
471 "\t Default: " << package().user_support() << "\n"
472 "\t-version Summarize version and build info.\n"
474 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
475 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
476 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
477 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
478 "Check the tex2lyx man page for more details."
484 int parse_version(string const &, string const &)
486 lyxerr << "tex2lyx " << lyx_version
487 << " (" << lyx_release_date << ")" << endl;
488 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
490 lyxerr << lyx_version_info << endl;
495 void error_message(string const & message)
497 cerr << "tex2lyx: " << message << "\n\n";
499 parse_help(string(), string());
503 int parse_class(string const & arg, string const &)
506 error_message("Missing textclass string after -c switch");
512 int parse_encoding(string const & arg, string const &)
515 error_message("Missing encoding string after -e switch");
516 default_encoding = arg;
521 int parse_syntaxfile(string const & arg, string const &)
524 error_message("Missing syntaxfile string after -s switch");
525 syntaxfile = internal_path(arg);
530 // Filled with the command line arguments "foo" of "-sysdir foo" or
532 string cl_system_support;
533 string cl_user_support;
536 int parse_sysdir(string const & arg, string const &)
539 error_message("Missing directory for -sysdir switch");
540 cl_system_support = internal_path(arg);
545 int parse_userdir(string const & arg, string const &)
548 error_message("Missing directory for -userdir switch");
549 cl_user_support = internal_path(arg);
554 int parse_force(string const &, string const &)
556 overwrite_files = true;
561 int parse_noweb(string const &, string const &)
568 int parse_roundtrip(string const &, string const &)
575 void easyParse(int & argc, char * argv[])
577 map<string, cmd_helper> cmdmap;
579 cmdmap["-h"] = parse_help;
580 cmdmap["-help"] = parse_help;
581 cmdmap["--help"] = parse_help;
582 cmdmap["-v"] = parse_version;
583 cmdmap["-version"] = parse_version;
584 cmdmap["--version"] = parse_version;
585 cmdmap["-c"] = parse_class;
586 cmdmap["-e"] = parse_encoding;
587 cmdmap["-f"] = parse_force;
588 cmdmap["-s"] = parse_syntaxfile;
589 cmdmap["-n"] = parse_noweb;
590 cmdmap["-sysdir"] = parse_sysdir;
591 cmdmap["-userdir"] = parse_userdir;
592 cmdmap["-roundtrip"] = parse_roundtrip;
594 for (int i = 1; i < argc; ++i) {
595 map<string, cmd_helper>::const_iterator it
596 = cmdmap.find(argv[i]);
598 // don't complain if not found - may be parsed later
599 if (it == cmdmap.end()) {
600 if (argv[i][0] == '-')
601 error_message(string("Unknown option `") + argv[i] + "'.");
606 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
607 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
609 int const remove = 1 + it->second(arg, arg2);
611 // Now, remove used arguments by shifting
612 // the following ones remove places down.
613 os::remove_internal_args(i, remove);
615 for (int j = i; j < argc; ++j)
616 argv[j] = argv[j + remove];
622 // path of the first parsed file
623 string masterFilePath;
624 // path of the currently parsed file
625 string parentFilePath;
627 } // anonymous namespace
630 string getMasterFilePath()
632 return masterFilePath;
635 string getParentFilePath()
637 return parentFilePath;
644 * Reads tex input from \a is and writes lyx output to \a os.
645 * Uses some common settings for the preamble, so this should only
646 * be used more than once for included documents.
647 * Caution: Overwrites the existing preamble settings if the new document
648 * contains a preamble.
649 * You must ensure that \p parentFilePath is properly set before calling
652 void tex2lyx(idocstream & is, ostream & os, string encoding)
654 // Set a sensible default encoding.
655 // This is used until an encoding command is found.
656 // For child documents use the encoding of the master, else latin1,
657 // since latin1 does not cause an iconv error if the actual encoding
658 // is different (bug 7509).
659 if (encoding.empty()) {
660 if (h_inputencoding == "auto")
663 encoding = h_inputencoding;
667 p.setEncoding(encoding);
671 parse_preamble(p, ps, documentclass, textclass);
673 active_environments.push_back("document");
674 Context context(true, textclass);
676 parse_text(p, ss, FLAG_END, true, context);
678 // Empty document body. LyX needs at least one paragraph.
679 context.check_layout(ss);
680 context.check_end_layout(ss);
681 ss << "\n\\end_body\n\\end_document\n";
682 active_environments.pop_back();
684 // We know the used modules only after parsing the full text
686 if (!used_modules.empty()) {
687 ms << "\\begin_modules\n";
688 LayoutModuleList::const_iterator const end = used_modules.end();
689 LayoutModuleList::const_iterator it = used_modules.begin();
690 for (; it != end; it++)
692 ms << "\\end_modules\n";
694 os << subst(ps.str(), modules_placeholder, ms.str());
700 ofdocstream parsertest("parsertest.tex");
702 parsertest << p.get_token().asInput();
703 // <origfile> and parsertest.tex should now have identical content
708 /// convert TeX from \p infilename to LyX and write it to \p os
709 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
712 // forbid buffering on this stream
713 is.rdbuf()->pubsetbuf(0,0);
714 is.open(infilename.toFilesystemEncoding().c_str());
716 cerr << "Could not open input file \"" << infilename
717 << "\" for reading." << endl;
720 string const oldParentFilePath = parentFilePath;
721 parentFilePath = onlyPath(infilename.absFileName());
722 tex2lyx(is, os, encoding);
723 parentFilePath = oldParentFilePath;
727 } // anonymous namespace
730 bool tex2lyx(string const & infilename, FileName const & outfilename,
731 string const & encoding)
733 if (outfilename.isReadableFile()) {
734 if (overwrite_files) {
735 cerr << "Overwriting existing file "
736 << outfilename << endl;
738 cerr << "Not overwriting existing file "
739 << outfilename << endl;
743 cerr << "Creating file " << outfilename << endl;
745 ofstream os(outfilename.toFilesystemEncoding().c_str());
747 cerr << "Could not open output file \"" << outfilename
748 << "\" for writing." << endl;
752 cerr << "Input file: " << infilename << "\n";
753 cerr << "Output file: " << outfilename << "\n";
755 return tex2lyx(FileName(infilename), os, encoding);
759 bool tex2tex(string const & infilename, FileName const & outfilename,
760 string const & encoding)
762 if (!tex2lyx(infilename, outfilename, encoding))
764 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
766 command += " -f main";
768 command += " -f none";
770 command += " -e pdflatex ";
772 command += " -e latex ";
773 command += quoteName(outfilename.toFilesystemEncoding());
775 if (one.startscript(Systemcall::Wait, command) == 0)
777 cerr << "Error: Running '" << command << "' failed." << endl;
784 int main(int argc, char * argv[])
788 //setlocale(LC_CTYPE, "");
790 lyxerr.setStream(cerr);
792 os::init(argc, argv);
795 init_package(internal_path(os::utf8_argv(0)), string(), string());
796 } catch (ExceptionMessage const & message) {
797 cerr << to_utf8(message.title_) << ":\n"
798 << to_utf8(message.details_) << endl;
799 if (message.type_ == ErrorException)
803 easyParse(argc, argv);
806 error_message("Not enough arguments.");
809 init_package(internal_path(os::utf8_argv(0)),
810 cl_system_support, cl_user_support);
811 } catch (ExceptionMessage const & message) {
812 cerr << to_utf8(message.title_) << ":\n"
813 << to_utf8(message.details_) << endl;
814 if (message.type_ == ErrorException)
818 // Now every known option is parsed. Look for input and output
819 // file name (the latter is optional).
820 string infilename = internal_path(os::utf8_argv(1));
821 infilename = makeAbsPath(infilename).absFileName();
826 // Do not allow a user supplied output filename
827 // (otherwise it could easily happen that LyX would
828 // overwrite the original .tex file)
829 cerr << "Error: output filename must not be given in roundtrip mode."
833 outfilename = changeExtension(infilename, ".lyx.lyx");
834 } else if (argc > 2) {
835 outfilename = internal_path(os::utf8_argv(2));
836 if (outfilename != "-")
837 outfilename = makeAbsPath(outfilename).absFileName();
839 outfilename = changeExtension(infilename, ".lyx");
841 // Read the syntax tables
842 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
843 if (system_syntaxfile.empty()) {
844 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
847 read_syntaxfile(system_syntaxfile);
848 if (!syntaxfile.empty())
849 read_syntaxfile(makeAbsPath(syntaxfile));
851 // Read the encodings table.
852 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
853 if (symbols_path.empty()) {
854 cerr << "Error: Could not find file \"unicodesymbols\"."
858 FileName const enc_path = libFileSearch(string(), "encodings");
859 if (enc_path.empty()) {
860 cerr << "Error: Could not find file \"encodings\"."
864 encodings.read(enc_path, symbols_path);
865 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
866 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
869 LayoutFileList::get().read();
871 theModuleList.read();
873 // The real work now.
874 masterFilePath = onlyPath(infilename);
875 parentFilePath = masterFilePath;
876 if (outfilename == "-") {
877 if (tex2lyx(FileName(infilename), cout, default_encoding))
879 } else if (roundtrip) {
880 if (tex2tex(infilename, FileName(outfilename), default_encoding))
883 if (tex2lyx(infilename, FileName(outfilename), default_encoding))