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.
20 #include "LayoutFile.h"
21 #include "LayoutModuleList.h"
22 #include "ModuleList.h"
23 #include "TextClass.h"
25 #include "support/convert.h"
26 #include "support/debug.h"
27 #include "support/ExceptionMessage.h"
28 #include "support/filetools.h"
29 #include "support/lassert.h"
30 #include "support/lstrings.h"
31 #include "support/Messages.h"
32 #include "support/os.h"
33 #include "support/Package.h"
34 #include "support/Systemcall.h"
44 using namespace lyx::support;
45 using namespace lyx::support::os;
51 void warning(docstring const & title, docstring const & message,
61 // Dummy texrow support
62 void TexRow::newline()
66 void TexRow::newlines(int)
70 // Dummy translation support
72 Messages const & getMessages(std::string const &)
78 Messages const & getGuiMessages()
84 // Keep the linker happy on Windows
89 string const trim(string const & a, char const * p)
96 size_t r = a.find_last_not_of(p);
97 size_t l = a.find_first_not_of(p);
99 // Is this the minimal test? (lgb)
100 if (r == string::npos && l == string::npos)
103 return a.substr(l, r - l + 1);
107 void split(string const & s, vector<string> & result, char delim)
109 //cerr << "split 1: '" << s << "'\n";
112 while (getline(is, t, delim))
114 //cerr << "split 2\n";
118 string join(vector<string> const & input, char const * delim)
121 for (size_t i = 0; i != input.size(); ++i) {
130 char const * const * is_known(string const & str, char const * const * what)
132 for ( ; *what; ++what)
140 // current stack of nested environments
141 vector<string> active_environments;
144 string active_environment()
146 return active_environments.empty() ? string() : active_environments.back();
150 TeX2LyXDocClass textclass;
151 CommandMap known_commands;
152 CommandMap known_environments;
153 CommandMap known_math_environments;
154 FullCommandMap possible_textclass_commands;
155 FullEnvironmentMap possible_textclass_environments;
158 LayoutModuleList used_modules;
161 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
163 // We have to handle the following cases:
164 // definition o1 o2 invocation result
165 // \newcommand{\foo}{bar} "" false \foo bar
166 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
167 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
168 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
169 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
170 unsigned int nargs = 0;
171 string const opt1 = rtrim(ltrim(o1, "["), "]");
172 if (isStrUnsignedInt(opt1)) {
173 // The command has arguments
174 nargs = convert<unsigned int>(opt1);
175 if (nargs > 0 && o2) {
176 // The first argument is optional
177 arguments.push_back(optional);
181 for (unsigned int i = 0; i < nargs; ++i)
182 arguments.push_back(required);
186 void add_known_command(string const & command, string const & o1,
187 bool o2, docstring const & definition)
189 vector<ArgumentType> arguments;
190 convertArgs(o1, o2, arguments);
191 known_commands[command] = arguments;
192 if (!definition.empty())
193 possible_textclass_commands[command] =
194 FullCommand(arguments, definition);
198 void add_known_environment(string const & environment, string const & o1,
199 bool o2, docstring const & beg, docstring const &end)
201 vector<ArgumentType> arguments;
202 convertArgs(o1, o2, arguments);
203 known_environments[environment] = arguments;
204 if (!beg.empty() || ! end.empty())
205 possible_textclass_environments[environment] =
206 FullEnvironment(arguments, beg, end);
210 Layout const * findLayoutWithoutModule(TextClass const & textclass,
211 string const & name, bool command)
213 DocumentClass::const_iterator it = textclass.begin();
214 DocumentClass::const_iterator en = textclass.end();
215 for (; it != en; ++it) {
216 if (it->latexname() == name &&
217 ((command && it->isCommand()) || (!command && it->isEnvironment())))
224 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
225 string const & name, bool command)
227 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
228 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
229 for (; it != en; ++it) {
230 if (it->second.latexname() == name &&
231 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
232 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
233 return &(it->second);
239 bool checkModule(string const & name, bool command)
241 // Cache to avoid slowdown by repated searches
242 static set<string> failed[2];
244 // Only add the module if the command was actually defined in the LyX preamble
246 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
249 if (possible_textclass_environments.find(name) == possible_textclass_environments.end())
252 if (failed[command].find(name) != failed[command].end())
255 // Create list of dummy document classes if not already done.
256 // This is needed since a module cannot be read on its own, only as
257 // part of a document class.
258 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
259 typedef map<string, DocumentClass *> ModuleMap;
260 static ModuleMap modules;
261 static bool init = true;
264 DocumentClassBundle & bundle = DocumentClassBundle::get();
265 LyXModuleList::const_iterator const end = theModuleList.end();
266 LyXModuleList::const_iterator it = theModuleList.begin();
267 for (; it != end; it++) {
268 string const module = it->getID();
270 // FIXME this excludes all modules that depend on another one
271 if (!m.moduleCanBeAdded(module, &baseClass))
274 modules[module] = &bundle.makeDocumentClass(baseClass, m);
279 // Try to find a module that defines the command.
280 // Only add it if the definition can be found in the preamble of the
281 // style that corresponds to the command. This is a heuristic and
282 // different from the way how we parse the builtin commands of the
283 // text class (in that case we only compare the name), but it is
284 // needed since it is not unlikely that two different modules define a
285 // command with the same name.
286 ModuleMap::iterator const end = modules.end();
287 for (ModuleMap::iterator it = modules.begin(); it != end; it++) {
288 string const module = it->first;
289 if (!used_modules.moduleCanBeAdded(module, &baseClass))
291 if (findLayoutWithoutModule(textclass, name, command))
293 if (findInsetLayoutWithoutModule(textclass, name, command))
295 DocumentClass const * c = it->second;
296 Layout const * layout = findLayoutWithoutModule(*c, name, command);
297 InsetLayout const * insetlayout = layout ? 0 :
298 findInsetLayoutWithoutModule(*c, name, command);
301 preamble = layout->preamble();
302 else if (insetlayout)
303 preamble = insetlayout->preamble();
304 if (preamble.empty())
308 FullCommand const & cmd =
309 possible_textclass_commands['\\' + name];
310 if (preamble.find(cmd.def) != docstring::npos)
313 FullEnvironment const & env =
314 possible_textclass_environments[name];
315 if (preamble.find(env.beg) != docstring::npos &&
316 preamble.find(env.end) != docstring::npos)
320 FileName layout_file = libFileSearch("layouts", module, "module");
321 if (textclass.read(layout_file, TextClass::MODULE)) {
322 used_modules.push_back(module);
323 // speed up further searches:
324 // the module does not need to be checked anymore.
330 failed[command].insert(name);
335 bool noweb_mode = false;
336 bool pdflatex = 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 == "item")
360 arguments.push_back(item);
362 arguments.push_back(verbatim);
365 arguments.push_back(optional);
368 commands[command] = arguments;
373 * Read a class of environments from the syntax file
375 void read_environment(Parser & p, string const & begin,
376 CommandMap & environments)
380 Token const & t = p.get_token();
381 if (t.cat() == catLetter)
382 environment += t.asInput();
383 else if (!environment.empty()) {
385 read_command(p, environment, environments);
388 if (t.cat() == catEscape && t.asInput() == "\\end") {
389 string const end = p.getArg('{', '}');
398 * Read a list of TeX commands from a reLyX compatible syntax file.
399 * Since this list is used after all commands that have a LyX counterpart
400 * are handled, it does not matter that the "syntax.default" file
401 * has almost all of them listed. For the same reason the reLyX-specific
402 * reLyXre environment is ignored.
404 void read_syntaxfile(FileName const & file_name)
406 ifdocstream is(file_name.toFilesystemEncoding().c_str());
408 cerr << "Could not open syntax file \"" << file_name
409 << "\" for reading." << endl;
412 // We can use our TeX parser, since the syntax of the layout file is
413 // modeled after TeX.
414 // Unknown tokens are just silently ignored, this helps us to skip some
415 // reLyX specific things.
418 Token const & t = p.get_token();
419 if (t.cat() == catEscape) {
420 string const command = t.asInput();
421 if (command == "\\begin") {
422 string const name = p.getArg('{', '}');
423 if (name == "environments" || name == "reLyXre")
424 // We understand "reLyXre", but it is
425 // not as powerful as "environments".
426 read_environment(p, name,
428 else if (name == "mathenvironments")
429 read_environment(p, name,
430 known_math_environments);
432 read_command(p, command, known_commands);
439 string documentclass;
440 string default_encoding;
442 bool overwrite_files = false;
445 /// return the number of arguments consumed
446 typedef int (*cmd_helper)(string const &, string const &);
449 int parse_help(string const &, string const &)
451 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
453 "\t-c textclass Declare the textclass.\n"
454 "\t-e encoding Set the default encoding (latex name).\n"
455 "\t-f Force overwrite of .lyx files.\n"
456 "\t-help Print this message and quit.\n"
457 "\t-n translate a noweb (aka literate programming) file.\n"
458 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
459 "\t-s syntaxfile read additional syntax file.\n"
460 "\t-sysdir dir Set system directory to DIR.\n"
461 "\t-userdir DIR Set user directory to DIR."
467 void error_message(string const & message)
469 cerr << "tex2lyx: " << message << "\n\n";
471 parse_help(string(), string());
475 int parse_class(string const & arg, string const &)
478 error_message("Missing textclass string after -c switch");
484 int parse_encoding(string const & arg, string const &)
487 error_message("Missing encoding string after -e switch");
488 default_encoding = arg;
493 int parse_syntaxfile(string const & arg, string const &)
496 error_message("Missing syntaxfile string after -s switch");
497 syntaxfile = internal_path(arg);
502 // Filled with the command line arguments "foo" of "-sysdir foo" or
504 string cl_system_support;
505 string cl_user_support;
508 int parse_sysdir(string const & arg, string const &)
511 error_message("Missing directory for -sysdir switch");
512 cl_system_support = internal_path(arg);
517 int parse_userdir(string const & arg, string const &)
520 error_message("Missing directory for -userdir switch");
521 cl_user_support = internal_path(arg);
526 int parse_force(string const &, string const &)
528 overwrite_files = true;
533 int parse_noweb(string const &, string const &)
540 int parse_roundtrip(string const &, string const &)
547 void easyParse(int & argc, char * argv[])
549 map<string, cmd_helper> cmdmap;
551 cmdmap["-c"] = parse_class;
552 cmdmap["-e"] = parse_encoding;
553 cmdmap["-f"] = parse_force;
554 cmdmap["-s"] = parse_syntaxfile;
555 cmdmap["-help"] = parse_help;
556 cmdmap["--help"] = parse_help;
557 cmdmap["-n"] = parse_noweb;
558 cmdmap["-sysdir"] = parse_sysdir;
559 cmdmap["-userdir"] = parse_userdir;
560 cmdmap["-roundtrip"] = parse_roundtrip;
562 for (int i = 1; i < argc; ++i) {
563 map<string, cmd_helper>::const_iterator it
564 = cmdmap.find(argv[i]);
566 // don't complain if not found - may be parsed later
567 if (it == cmdmap.end()) {
568 if (argv[i][0] == '-')
569 error_message(string("Unknown option `") + argv[i] + "'.");
574 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
575 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
577 int const remove = 1 + it->second(arg, arg2);
579 // Now, remove used arguments by shifting
580 // the following ones remove places down.
581 os::remove_internal_args(i, remove);
583 for (int j = i; j < argc; ++j)
584 argv[j] = argv[j + remove];
590 // path of the first parsed file
591 string masterFilePath;
592 // path of the currently parsed file
593 string parentFilePath;
595 } // anonymous namespace
598 string getMasterFilePath()
600 return masterFilePath;
603 string getParentFilePath()
605 return parentFilePath;
612 * Reads tex input from \a is and writes lyx output to \a os.
613 * Uses some common settings for the preamble, so this should only
614 * be used more than once for included documents.
615 * Caution: Overwrites the existing preamble settings if the new document
616 * contains a preamble.
617 * You must ensure that \p parentFilePath is properly set before calling
620 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
623 if (!encoding.empty())
624 p.setEncoding(encoding);
628 parse_preamble(p, ps, documentclass, textclass);
630 active_environments.push_back("document");
631 Context context(true, textclass);
633 parse_text(p, ss, FLAG_END, true, context);
635 // Empty document body. LyX needs at least one paragraph.
636 context.check_layout(ss);
637 context.check_end_layout(ss);
638 ss << "\n\\end_body\n\\end_document\n";
639 active_environments.pop_back();
641 // We know the used modules only after parsing the full text
643 if (!used_modules.empty()) {
644 ms << "\\begin_modules\n";
645 LayoutModuleList::const_iterator const end = used_modules.end();
646 LayoutModuleList::const_iterator it = used_modules.begin();
647 for (; it != end; it++)
649 ms << "\\end_modules\n";
651 os << subst(ps.str(), modules_placeholder, ms.str());
657 ofdocstream parsertest("parsertest.tex");
659 parsertest << p.get_token().asInput();
660 // <origfile> and parsertest.tex should now have identical content
665 /// convert TeX from \p infilename to LyX and write it to \p os
666 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
669 // forbid buffering on this stream
670 is.rdbuf()->pubsetbuf(0,0);
671 is.open(infilename.toFilesystemEncoding().c_str());
673 cerr << "Could not open input file \"" << infilename
674 << "\" for reading." << endl;
677 string const oldParentFilePath = parentFilePath;
678 parentFilePath = onlyPath(infilename.absFileName());
679 tex2lyx(is, os, encoding);
680 parentFilePath = oldParentFilePath;
684 } // anonymous namespace
687 bool tex2lyx(string const & infilename, FileName const & outfilename,
688 string const & encoding)
690 if (outfilename.isReadableFile()) {
691 if (overwrite_files) {
692 cerr << "Overwriting existing file "
693 << outfilename << endl;
695 cerr << "Not overwriting existing file "
696 << outfilename << endl;
700 cerr << "Creating file " << outfilename << endl;
702 ofstream os(outfilename.toFilesystemEncoding().c_str());
704 cerr << "Could not open output file \"" << outfilename
705 << "\" for writing." << endl;
709 cerr << "Input file: " << infilename << "\n";
710 cerr << "Output file: " << outfilename << "\n";
712 return tex2lyx(FileName(infilename), os, encoding);
716 bool tex2tex(string const & infilename, FileName const & outfilename,
717 string const & encoding)
719 if (!tex2lyx(infilename, outfilename, encoding))
721 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
723 command += " -f main";
725 command += " -f none";
727 command += " -e pdflatex ";
729 command += " -e latex ";
730 command += quoteName(outfilename.toFilesystemEncoding());
732 if (one.startscript(Systemcall::Wait, command) == 0)
734 cerr << "Error: Running '" << command << "' failed." << endl;
741 int main(int argc, char * argv[])
745 //setlocale(LC_CTYPE, "");
747 lyxerr.setStream(cerr);
749 os::init(argc, argv);
751 easyParse(argc, argv);
754 error_message("Not enough arguments.");
757 init_package(internal_path(os::utf8_argv(0)),
758 cl_system_support, cl_user_support,
759 top_build_dir_is_two_levels_up);
760 } catch (ExceptionMessage const & message) {
761 cerr << to_utf8(message.title_) << ":\n"
762 << to_utf8(message.details_) << endl;
763 if (message.type_ == ErrorException)
767 // Now every known option is parsed. Look for input and output
768 // file name (the latter is optional).
769 string infilename = internal_path(os::utf8_argv(1));
770 infilename = makeAbsPath(infilename).absFileName();
775 // Do not allow a user supplied output filename
776 // (otherwise it could easily happen that LyX would
777 // overwrite the original .tex file)
778 cerr << "Error: output filename must not be given in roundtrip mode."
782 outfilename = changeExtension(infilename, ".lyx.lyx");
783 } else if (argc > 2) {
784 outfilename = internal_path(os::utf8_argv(2));
785 if (outfilename != "-")
786 outfilename = makeAbsPath(outfilename).absFileName();
788 outfilename = changeExtension(infilename, ".lyx");
790 // Read the syntax tables
791 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
792 if (system_syntaxfile.empty()) {
793 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
796 read_syntaxfile(system_syntaxfile);
797 if (!syntaxfile.empty())
798 read_syntaxfile(makeAbsPath(syntaxfile));
800 // Read the encodings table.
801 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
802 if (symbols_path.empty()) {
803 cerr << "Error: Could not find file \"unicodesymbols\"."
807 FileName const enc_path = libFileSearch(string(), "encodings");
808 if (enc_path.empty()) {
809 cerr << "Error: Could not find file \"encodings\"."
813 encodings.read(enc_path, symbols_path);
814 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
815 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
818 LayoutFileList::get().read();
820 theModuleList.read();
822 // The real work now.
823 masterFilePath = onlyPath(infilename);
824 parentFilePath = masterFilePath;
825 if (outfilename == "-") {
826 if (tex2lyx(FileName(infilename), cout, default_encoding))
828 } else if (roundtrip) {
829 if (tex2tex(infilename, FileName(outfilename), default_encoding))
832 if (tex2lyx(infilename, FileName(outfilename), default_encoding))