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 "TextClass.h"
22 #include "support/convert.h"
23 #include "support/debug.h"
24 #include "support/ExceptionMessage.h"
25 #include "support/filetools.h"
26 #include "support/lassert.h"
27 #include "support/lstrings.h"
28 #include "support/Messages.h"
29 #include "support/os.h"
30 #include "support/Package.h"
40 using namespace lyx::support;
41 using namespace lyx::support::os;
45 // Dummy translation support
47 Messages & getMessages(std::string const &)
53 Messages & getGuiMessages()
59 // Keep the linker happy on Windows
64 string const trim(string const & a, char const * p)
71 size_t r = a.find_last_not_of(p);
72 size_t l = a.find_first_not_of(p);
74 // Is this the minimal test? (lgb)
75 if (r == string::npos && l == string::npos)
78 return a.substr(l, r - l + 1);
82 void split(string const & s, vector<string> & result, char delim)
84 //cerr << "split 1: '" << s << "'\n";
87 while (getline(is, t, delim))
89 //cerr << "split 2\n";
93 string join(vector<string> const & input, char const * delim)
96 for (size_t i = 0; i != input.size(); ++i) {
105 char const * const * is_known(string const & str, char const * const * what)
107 for ( ; *what; ++what)
115 // current stack of nested environments
116 vector<string> active_environments;
119 string active_environment()
121 return active_environments.empty() ? string() : active_environments.back();
125 CommandMap known_commands;
126 CommandMap known_environments;
127 CommandMap known_math_environments;
130 void add_known_command(string const & command, string const & o1,
133 // We have to handle the following cases:
134 // definition o1 o2 invocation result
135 // \newcommand{\foo}{bar} "" false \foo bar
136 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
137 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
138 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
139 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
140 unsigned int nargs = 0;
141 vector<ArgumentType> arguments;
142 string const opt1 = rtrim(ltrim(o1, "["), "]");
143 if (isStrUnsignedInt(opt1)) {
144 // The command has arguments
145 nargs = convert<unsigned int>(opt1);
146 if (nargs > 0 && o2) {
147 // The first argument is optional
148 arguments.push_back(optional);
152 for (unsigned int i = 0; i < nargs; ++i)
153 arguments.push_back(required);
154 known_commands[command] = arguments;
158 bool noweb_mode = false;
165 * Read one command definition from the syntax file
167 void read_command(Parser & p, string command, CommandMap & commands)
169 if (p.next_token().asInput() == "*") {
173 vector<ArgumentType> arguments;
174 while (p.next_token().cat() == catBegin ||
175 p.next_token().asInput() == "[") {
176 if (p.next_token().cat() == catBegin) {
177 string const arg = p.getArg('{', '}');
178 if (arg == "translate")
179 arguments.push_back(required);
181 arguments.push_back(verbatim);
184 arguments.push_back(optional);
187 commands[command] = arguments;
192 * Read a class of environments from the syntax file
194 void read_environment(Parser & p, string const & begin,
195 CommandMap & environments)
199 Token const & t = p.get_token();
200 if (t.cat() == catLetter)
201 environment += t.asInput();
202 else if (!environment.empty()) {
204 read_command(p, environment, environments);
207 if (t.cat() == catEscape && t.asInput() == "\\end") {
208 string const end = p.getArg('{', '}');
217 * Read a list of TeX commands from a reLyX compatible syntax file.
218 * Since this list is used after all commands that have a LyX counterpart
219 * are handled, it does not matter that the "syntax.default" file
220 * has almost all of them listed. For the same reason the reLyX-specific
221 * reLyXre environment is ignored.
223 void read_syntaxfile(FileName const & file_name)
225 ifdocstream is(file_name.toFilesystemEncoding().c_str());
227 cerr << "Could not open syntax file \"" << file_name
228 << "\" for reading." << endl;
231 // We can use our TeX parser, since the syntax of the layout file is
232 // modeled after TeX.
233 // Unknown tokens are just silently ignored, this helps us to skip some
234 // reLyX specific things.
237 Token const & t = p.get_token();
238 if (t.cat() == catEscape) {
239 string const command = t.asInput();
240 if (command == "\\begin") {
241 string const name = p.getArg('{', '}');
242 if (name == "environments" || name == "reLyXre")
243 // We understand "reLyXre", but it is
244 // not as powerful as "environments".
245 read_environment(p, name,
247 else if (name == "mathenvironments")
248 read_environment(p, name,
249 known_math_environments);
251 read_command(p, command, known_commands);
258 string documentclass;
259 string default_encoding;
261 bool overwrite_files = false;
264 /// return the number of arguments consumed
265 typedef int (*cmd_helper)(string const &, string const &);
268 int parse_help(string const &, string const &)
270 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
272 "\t-c textclass Declare the textclass.\n"
273 "\t-e encoding Set the default encoding (latex name).\n"
274 "\t-f Force overwrite of .lyx files.\n"
275 "\t-help Print this message and quit.\n"
276 "\t-n translate a noweb (aka literate programming) file.\n"
277 "\t-s syntaxfile read additional syntax file.\n"
278 "\t-sysdir dir Set system directory to DIR.\n"
279 "\t-userdir DIR Set user directory to DIR."
285 void error_message(string const & message)
287 cerr << "tex2lyx: " << message << "\n\n";
289 parse_help(string(), string());
293 int parse_class(string const & arg, string const &)
296 error_message("Missing textclass string after -c switch");
302 int parse_encoding(string const & arg, string const &)
305 error_message("Missing encoding string after -e switch");
306 default_encoding = arg;
311 int parse_syntaxfile(string const & arg, string const &)
314 error_message("Missing syntaxfile string after -s switch");
315 syntaxfile = internal_path(arg);
320 // Filled with the command line arguments "foo" of "-sysdir foo" or
322 string cl_system_support;
323 string cl_user_support;
326 int parse_sysdir(string const & arg, string const &)
329 error_message("Missing directory for -sysdir switch");
330 cl_system_support = internal_path(arg);
335 int parse_userdir(string const & arg, string const &)
338 error_message("Missing directory for -userdir switch");
339 cl_user_support = internal_path(arg);
344 int parse_force(string const &, string const &)
346 overwrite_files = true;
351 int parse_noweb(string const &, string const &)
358 void easyParse(int & argc, char * argv[])
360 map<string, cmd_helper> cmdmap;
362 cmdmap["-c"] = parse_class;
363 cmdmap["-e"] = parse_encoding;
364 cmdmap["-f"] = parse_force;
365 cmdmap["-s"] = parse_syntaxfile;
366 cmdmap["-help"] = parse_help;
367 cmdmap["--help"] = parse_help;
368 cmdmap["-n"] = parse_noweb;
369 cmdmap["-sysdir"] = parse_sysdir;
370 cmdmap["-userdir"] = parse_userdir;
372 for (int i = 1; i < argc; ++i) {
373 map<string, cmd_helper>::const_iterator it
374 = cmdmap.find(argv[i]);
376 // don't complain if not found - may be parsed later
377 if (it == cmdmap.end()) {
378 if (argv[i][0] == '-')
379 error_message(string("Unknown option `") + argv[i] + "'.");
384 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
385 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
387 int const remove = 1 + it->second(arg, arg2);
389 // Now, remove used arguments by shifting
390 // the following ones remove places down.
391 os::remove_internal_args(i, remove);
393 for (int j = i; j < argc; ++j)
394 argv[j] = argv[j + remove];
400 // path of the first parsed file
401 string masterFilePath;
402 // path of the currently parsed file
403 string parentFilePath;
405 } // anonymous namespace
408 string getMasterFilePath()
410 return masterFilePath;
413 string getParentFilePath()
415 return parentFilePath;
422 * Reads tex input from \a is and writes lyx output to \a os.
423 * Uses some common settings for the preamble, so this should only
424 * be used more than once for included documents.
425 * Caution: Overwrites the existing preamble settings if the new document
426 * contains a preamble.
427 * You must ensure that \p parentFilePath is properly set before calling
430 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
433 if (!encoding.empty())
434 p.setEncoding(encoding);
438 TeX2LyXDocClass textclass;
439 parse_preamble(p, ss, documentclass, textclass);
441 active_environments.push_back("document");
442 Context context(true, textclass);
443 parse_text(p, ss, FLAG_END, true, context);
445 // Empty document body. LyX needs at least one paragraph.
446 context.check_layout(ss);
447 context.check_end_layout(ss);
448 ss << "\n\\end_body\n\\end_document\n";
449 active_environments.pop_back();
454 ofdocstream parsertest("parsertest.tex");
456 parsertest << p.get_token().asInput();
457 // <origfile> and parsertest.tex should now have identical content
462 /// convert TeX from \p infilename to LyX and write it to \p os
463 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
466 // forbid buffering on this stream
467 is.rdbuf()->pubsetbuf(0,0);
468 is.open(infilename.toFilesystemEncoding().c_str());
470 cerr << "Could not open input file \"" << infilename
471 << "\" for reading." << endl;
474 string const oldParentFilePath = parentFilePath;
475 parentFilePath = onlyPath(infilename.absFilename());
476 tex2lyx(is, os, encoding);
477 parentFilePath = oldParentFilePath;
481 } // anonymous namespace
484 bool tex2lyx(string const & infilename, FileName const & outfilename,
485 string const & encoding)
487 if (outfilename.isReadableFile()) {
488 if (overwrite_files) {
489 cerr << "Overwriting existing file "
490 << outfilename << endl;
492 cerr << "Not overwriting existing file "
493 << outfilename << endl;
497 cerr << "Creating file " << outfilename << endl;
499 ofstream os(outfilename.toFilesystemEncoding().c_str());
501 cerr << "Could not open output file \"" << outfilename
502 << "\" for writing." << endl;
506 cerr << "Input file: " << infilename << "\n";
507 cerr << "Output file: " << outfilename << "\n";
509 return tex2lyx(FileName(infilename), os, encoding);
515 int main(int argc, char * argv[])
519 //setlocale(LC_CTYPE, "");
521 lyxerr.setStream(cerr);
523 os::init(argc, argv);
525 easyParse(argc, argv);
528 error_message("Not enough arguments.");
531 init_package(internal_path(os::utf8_argv(0)),
532 cl_system_support, cl_user_support,
533 top_build_dir_is_two_levels_up);
534 } catch (ExceptionMessage const & message) {
535 cerr << to_utf8(message.title_) << ":\n"
536 << to_utf8(message.details_) << endl;
537 if (message.type_ == ErrorException)
541 // Now every known option is parsed. Look for input and output
542 // file name (the latter is optional).
543 string infilename = internal_path(os::utf8_argv(1));
544 infilename = makeAbsPath(infilename).absFilename();
548 outfilename = internal_path(os::utf8_argv(2));
549 if (outfilename != "-")
550 outfilename = makeAbsPath(outfilename).absFilename();
552 outfilename = changeExtension(infilename, ".lyx");
554 // Read the syntax tables
555 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
556 if (system_syntaxfile.empty()) {
557 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
560 read_syntaxfile(system_syntaxfile);
561 if (!syntaxfile.empty())
562 read_syntaxfile(makeAbsPath(syntaxfile));
564 // Read the encodings table.
565 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
566 if (symbols_path.empty()) {
567 cerr << "Error: Could not find file \"unicodesymbols\"."
571 FileName const enc_path = libFileSearch(string(), "encodings");
572 if (enc_path.empty()) {
573 cerr << "Error: Could not find file \"encodings\"."
577 encodings.read(enc_path, symbols_path);
578 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
579 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
581 // The real work now.
582 masterFilePath = onlyPath(infilename);
583 parentFilePath = masterFilePath;
584 if (outfilename == "-") {
585 if (tex2lyx(FileName(infilename), cout, default_encoding))
590 if (tex2lyx(infilename, FileName(outfilename), default_encoding))