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 LyXRC support
77 // Dummy translation support
79 Messages const & getMessages(std::string const &)
85 Messages const & getGuiMessages()
91 // Keep the linker happy on Windows
96 string const trim(string const & a, char const * p)
100 if (a.empty() || !*p)
103 size_t r = a.find_last_not_of(p);
104 size_t l = a.find_first_not_of(p);
106 // Is this the minimal test? (lgb)
107 if (r == string::npos && l == string::npos)
110 return a.substr(l, r - l + 1);
114 void split(string const & s, vector<string> & result, char delim)
116 //cerr << "split 1: '" << s << "'\n";
119 while (getline(is, t, delim))
121 //cerr << "split 2\n";
125 string join(vector<string> const & input, char const * delim)
128 for (size_t i = 0; i != input.size(); ++i) {
137 char const * const * is_known(string const & str, char const * const * what)
139 for ( ; *what; ++what)
147 // current stack of nested environments
148 vector<string> active_environments;
151 string active_environment()
153 return active_environments.empty() ? string() : active_environments.back();
157 TeX2LyXDocClass textclass;
158 CommandMap known_commands;
159 CommandMap known_environments;
160 CommandMap known_math_environments;
161 FullCommandMap possible_textclass_commands;
162 FullEnvironmentMap possible_textclass_environments;
165 LayoutModuleList used_modules;
168 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
170 // We have to handle the following cases:
171 // definition o1 o2 invocation result
172 // \newcommand{\foo}{bar} "" false \foo bar
173 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
174 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
175 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
176 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
177 unsigned int nargs = 0;
178 string const opt1 = rtrim(ltrim(o1, "["), "]");
179 if (isStrUnsignedInt(opt1)) {
180 // The command has arguments
181 nargs = convert<unsigned int>(opt1);
182 if (nargs > 0 && o2) {
183 // The first argument is optional
184 arguments.push_back(optional);
188 for (unsigned int i = 0; i < nargs; ++i)
189 arguments.push_back(required);
193 void add_known_command(string const & command, string const & o1,
194 bool o2, docstring const & definition)
196 vector<ArgumentType> arguments;
197 convertArgs(o1, o2, arguments);
198 known_commands[command] = arguments;
199 if (!definition.empty())
200 possible_textclass_commands[command] =
201 FullCommand(arguments, definition);
205 void add_known_environment(string const & environment, string const & o1,
206 bool o2, docstring const & beg, docstring const &end)
208 vector<ArgumentType> arguments;
209 convertArgs(o1, o2, arguments);
210 known_environments[environment] = arguments;
211 if (!beg.empty() || ! end.empty())
212 possible_textclass_environments[environment] =
213 FullEnvironment(arguments, beg, end);
217 Layout const * findLayoutWithoutModule(TextClass const & textclass,
218 string const & name, bool command)
220 DocumentClass::const_iterator it = textclass.begin();
221 DocumentClass::const_iterator en = textclass.end();
222 for (; it != en; ++it) {
223 if (it->latexname() == name &&
224 ((command && it->isCommand()) || (!command && it->isEnvironment())))
231 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
232 string const & name, bool command)
234 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
235 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
236 for (; it != en; ++it) {
237 if (it->second.latexname() == name &&
238 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
239 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
240 return &(it->second);
246 bool checkModule(string const & name, bool command)
248 // Cache to avoid slowdown by repated searches
249 static set<string> failed[2];
251 // Only add the module if the command was actually defined in the LyX preamble
253 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
256 if (possible_textclass_environments.find(name) == possible_textclass_environments.end())
259 if (failed[command].find(name) != failed[command].end())
262 // Create list of dummy document classes if not already done.
263 // This is needed since a module cannot be read on its own, only as
264 // part of a document class.
265 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
266 typedef map<string, DocumentClass *> ModuleMap;
267 static ModuleMap modules;
268 static bool init = true;
271 DocumentClassBundle & bundle = DocumentClassBundle::get();
272 LyXModuleList::const_iterator const end = theModuleList.end();
273 LyXModuleList::const_iterator it = theModuleList.begin();
274 for (; it != end; it++) {
275 string const module = it->getID();
277 // FIXME this excludes all modules that depend on another one
278 if (!m.moduleCanBeAdded(module, &baseClass))
281 modules[module] = &bundle.makeDocumentClass(baseClass, m);
286 // Try to find a module that defines the command.
287 // Only add it if the definition can be found in the preamble of the
288 // style that corresponds to the command. This is a heuristic and
289 // different from the way how we parse the builtin commands of the
290 // text class (in that case we only compare the name), but it is
291 // needed since it is not unlikely that two different modules define a
292 // command with the same name.
293 ModuleMap::iterator const end = modules.end();
294 for (ModuleMap::iterator it = modules.begin(); it != end; it++) {
295 string const module = it->first;
296 if (!used_modules.moduleCanBeAdded(module, &baseClass))
298 if (findLayoutWithoutModule(textclass, name, command))
300 if (findInsetLayoutWithoutModule(textclass, name, command))
302 DocumentClass const * c = it->second;
303 Layout const * layout = findLayoutWithoutModule(*c, name, command);
304 InsetLayout const * insetlayout = layout ? 0 :
305 findInsetLayoutWithoutModule(*c, name, command);
308 preamble = layout->preamble();
309 else if (insetlayout)
310 preamble = insetlayout->preamble();
311 if (preamble.empty())
315 FullCommand const & cmd =
316 possible_textclass_commands['\\' + name];
317 if (preamble.find(cmd.def) != docstring::npos)
320 FullEnvironment const & env =
321 possible_textclass_environments[name];
322 if (preamble.find(env.beg) != docstring::npos &&
323 preamble.find(env.end) != docstring::npos)
327 FileName layout_file = libFileSearch("layouts", module, "module");
328 if (textclass.read(layout_file, TextClass::MODULE)) {
329 used_modules.push_back(module);
330 // speed up further searches:
331 // the module does not need to be checked anymore.
337 failed[command].insert(name);
342 bool noweb_mode = false;
343 bool pdflatex = false;
344 bool roundtrip = false;
351 * Read one command definition from the syntax file
353 void read_command(Parser & p, string command, CommandMap & commands)
355 if (p.next_token().asInput() == "*") {
359 vector<ArgumentType> arguments;
360 while (p.next_token().cat() == catBegin ||
361 p.next_token().asInput() == "[") {
362 if (p.next_token().cat() == catBegin) {
363 string const arg = p.getArg('{', '}');
364 if (arg == "translate")
365 arguments.push_back(required);
366 else if (arg == "item")
367 arguments.push_back(item);
369 arguments.push_back(verbatim);
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 overwrite_files = false;
452 /// return the number of arguments consumed
453 typedef int (*cmd_helper)(string const &, string const &);
456 int parse_help(string const &, string const &)
458 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
460 "\t-c textclass Declare the textclass.\n"
461 "\t-e encoding Set the default encoding (latex name).\n"
462 "\t-f Force overwrite of .lyx files.\n"
463 "\t-help Print this message and quit.\n"
464 "\t-n translate a noweb (aka literate programming) file.\n"
465 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
466 "\t-s syntaxfile read additional syntax file.\n"
467 "\t-sysdir dir Set system directory to DIR.\n"
468 "\t-userdir DIR Set user directory to DIR."
474 void error_message(string const & message)
476 cerr << "tex2lyx: " << message << "\n\n";
478 parse_help(string(), string());
482 int parse_class(string const & arg, string const &)
485 error_message("Missing textclass string after -c switch");
491 int parse_encoding(string const & arg, string const &)
494 error_message("Missing encoding string after -e switch");
495 default_encoding = arg;
500 int parse_syntaxfile(string const & arg, string const &)
503 error_message("Missing syntaxfile string after -s switch");
504 syntaxfile = internal_path(arg);
509 // Filled with the command line arguments "foo" of "-sysdir foo" or
511 string cl_system_support;
512 string cl_user_support;
515 int parse_sysdir(string const & arg, string const &)
518 error_message("Missing directory for -sysdir switch");
519 cl_system_support = internal_path(arg);
524 int parse_userdir(string const & arg, string const &)
527 error_message("Missing directory for -userdir switch");
528 cl_user_support = internal_path(arg);
533 int parse_force(string const &, string const &)
535 overwrite_files = true;
540 int parse_noweb(string const &, string const &)
547 int parse_roundtrip(string const &, string const &)
554 void easyParse(int & argc, char * argv[])
556 map<string, cmd_helper> cmdmap;
558 cmdmap["-c"] = parse_class;
559 cmdmap["-e"] = parse_encoding;
560 cmdmap["-f"] = parse_force;
561 cmdmap["-s"] = parse_syntaxfile;
562 cmdmap["-help"] = parse_help;
563 cmdmap["--help"] = parse_help;
564 cmdmap["-n"] = parse_noweb;
565 cmdmap["-sysdir"] = parse_sysdir;
566 cmdmap["-userdir"] = parse_userdir;
567 cmdmap["-roundtrip"] = parse_roundtrip;
569 for (int i = 1; i < argc; ++i) {
570 map<string, cmd_helper>::const_iterator it
571 = cmdmap.find(argv[i]);
573 // don't complain if not found - may be parsed later
574 if (it == cmdmap.end()) {
575 if (argv[i][0] == '-')
576 error_message(string("Unknown option `") + argv[i] + "'.");
581 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
582 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
584 int const remove = 1 + it->second(arg, arg2);
586 // Now, remove used arguments by shifting
587 // the following ones remove places down.
588 os::remove_internal_args(i, remove);
590 for (int j = i; j < argc; ++j)
591 argv[j] = argv[j + remove];
597 // path of the first parsed file
598 string masterFilePath;
599 // path of the currently parsed file
600 string parentFilePath;
602 } // anonymous namespace
605 string getMasterFilePath()
607 return masterFilePath;
610 string getParentFilePath()
612 return parentFilePath;
619 * Reads tex input from \a is and writes lyx output to \a os.
620 * Uses some common settings for the preamble, so this should only
621 * be used more than once for included documents.
622 * Caution: Overwrites the existing preamble settings if the new document
623 * contains a preamble.
624 * You must ensure that \p parentFilePath is properly set before calling
627 void tex2lyx(idocstream & is, ostream & os, string encoding)
629 // Set a sensible default encoding.
630 // This is used until an encoding command is found.
631 // For child documents use the encoding of the master, else latin1,
632 // since latin1 does not cause an iconv error if the actual encoding
633 // is different (bug 7509).
634 if (encoding.empty()) {
635 if (h_inputencoding == "auto")
638 encoding = h_inputencoding;
642 p.setEncoding(encoding);
646 parse_preamble(p, ps, documentclass, textclass);
648 active_environments.push_back("document");
649 Context context(true, textclass);
651 parse_text(p, ss, FLAG_END, true, context);
653 // Empty document body. LyX needs at least one paragraph.
654 context.check_layout(ss);
655 context.check_end_layout(ss);
656 ss << "\n\\end_body\n\\end_document\n";
657 active_environments.pop_back();
659 // We know the used modules only after parsing the full text
661 if (!used_modules.empty()) {
662 ms << "\\begin_modules\n";
663 LayoutModuleList::const_iterator const end = used_modules.end();
664 LayoutModuleList::const_iterator it = used_modules.begin();
665 for (; it != end; it++)
667 ms << "\\end_modules\n";
669 os << subst(ps.str(), modules_placeholder, ms.str());
675 ofdocstream parsertest("parsertest.tex");
677 parsertest << p.get_token().asInput();
678 // <origfile> and parsertest.tex should now have identical content
683 /// convert TeX from \p infilename to LyX and write it to \p os
684 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
687 // forbid buffering on this stream
688 is.rdbuf()->pubsetbuf(0,0);
689 is.open(infilename.toFilesystemEncoding().c_str());
691 cerr << "Could not open input file \"" << infilename
692 << "\" for reading." << endl;
695 string const oldParentFilePath = parentFilePath;
696 parentFilePath = onlyPath(infilename.absFileName());
697 tex2lyx(is, os, encoding);
698 parentFilePath = oldParentFilePath;
702 } // anonymous namespace
705 bool tex2lyx(string const & infilename, FileName const & outfilename,
706 string const & encoding)
708 if (outfilename.isReadableFile()) {
709 if (overwrite_files) {
710 cerr << "Overwriting existing file "
711 << outfilename << endl;
713 cerr << "Not overwriting existing file "
714 << outfilename << endl;
718 cerr << "Creating file " << outfilename << endl;
720 ofstream os(outfilename.toFilesystemEncoding().c_str());
722 cerr << "Could not open output file \"" << outfilename
723 << "\" for writing." << endl;
727 cerr << "Input file: " << infilename << "\n";
728 cerr << "Output file: " << outfilename << "\n";
730 return tex2lyx(FileName(infilename), os, encoding);
734 bool tex2tex(string const & infilename, FileName const & outfilename,
735 string const & encoding)
737 if (!tex2lyx(infilename, outfilename, encoding))
739 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
741 command += " -f main";
743 command += " -f none";
745 command += " -e pdflatex ";
747 command += " -e latex ";
748 command += quoteName(outfilename.toFilesystemEncoding());
750 if (one.startscript(Systemcall::Wait, command) == 0)
752 cerr << "Error: Running '" << command << "' failed." << endl;
759 int main(int argc, char * argv[])
763 //setlocale(LC_CTYPE, "");
765 lyxerr.setStream(cerr);
767 os::init(argc, argv);
769 easyParse(argc, argv);
772 error_message("Not enough arguments.");
775 init_package(internal_path(os::utf8_argv(0)),
776 cl_system_support, cl_user_support);
777 } catch (ExceptionMessage const & message) {
778 cerr << to_utf8(message.title_) << ":\n"
779 << to_utf8(message.details_) << endl;
780 if (message.type_ == ErrorException)
784 // Now every known option is parsed. Look for input and output
785 // file name (the latter is optional).
786 string infilename = internal_path(os::utf8_argv(1));
787 infilename = makeAbsPath(infilename).absFileName();
792 // Do not allow a user supplied output filename
793 // (otherwise it could easily happen that LyX would
794 // overwrite the original .tex file)
795 cerr << "Error: output filename must not be given in roundtrip mode."
799 outfilename = changeExtension(infilename, ".lyx.lyx");
800 } else if (argc > 2) {
801 outfilename = internal_path(os::utf8_argv(2));
802 if (outfilename != "-")
803 outfilename = makeAbsPath(outfilename).absFileName();
805 outfilename = changeExtension(infilename, ".lyx");
807 // Read the syntax tables
808 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
809 if (system_syntaxfile.empty()) {
810 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
813 read_syntaxfile(system_syntaxfile);
814 if (!syntaxfile.empty())
815 read_syntaxfile(makeAbsPath(syntaxfile));
817 // Read the encodings table.
818 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
819 if (symbols_path.empty()) {
820 cerr << "Error: Could not find file \"unicodesymbols\"."
824 FileName const enc_path = libFileSearch(string(), "encodings");
825 if (enc_path.empty()) {
826 cerr << "Error: Could not find file \"encodings\"."
830 encodings.read(enc_path, symbols_path);
831 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
832 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
835 LayoutFileList::get().read();
837 theModuleList.read();
839 // The real work now.
840 masterFilePath = onlyPath(infilename);
841 parentFilePath = masterFilePath;
842 if (outfilename == "-") {
843 if (tex2lyx(FileName(infilename), cout, default_encoding))
845 } else if (roundtrip) {
846 if (tex2tex(infilename, FileName(outfilename), default_encoding))
849 if (tex2lyx(infilename, FileName(outfilename), default_encoding))