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
60 void emergencyCleanup()
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(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
385 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
387 int const remove = 1 + it->second(arg, arg2);
389 // Now, remove used arguments by shifting
390 // the following ones remove places down.
392 for (int j = i; j < argc; ++j)
393 argv[j] = argv[j + remove];
399 // path of the first parsed file
400 string masterFilePath;
401 // path of the currently parsed file
402 string parentFilePath;
404 } // anonymous namespace
407 string getMasterFilePath()
409 return masterFilePath;
412 string getParentFilePath()
414 return parentFilePath;
421 * Reads tex input from \a is and writes lyx output to \a os.
422 * Uses some common settings for the preamble, so this should only
423 * be used more than once for included documents.
424 * Caution: Overwrites the existing preamble settings if the new document
425 * contains a preamble.
426 * You must ensure that \p parentFilePath is properly set before calling
429 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
432 if (!encoding.empty())
433 p.setEncoding(encoding);
437 TeX2LyXDocClass textclass;
438 parse_preamble(p, ss, documentclass, textclass);
440 active_environments.push_back("document");
441 Context context(true, textclass);
442 parse_text(p, ss, FLAG_END, true, context);
444 // Empty document body. LyX needs at least one paragraph.
445 context.check_layout(ss);
446 context.check_end_layout(ss);
447 ss << "\n\\end_body\n\\end_document\n";
448 active_environments.pop_back();
453 ofdocstream parsertest("parsertest.tex");
455 parsertest << p.get_token().asInput();
456 // <origfile> and parsertest.tex should now have identical content
461 /// convert TeX from \p infilename to LyX and write it to \p os
462 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
465 // forbid buffering on this stream
466 is.rdbuf()->pubsetbuf(0,0);
467 is.open(infilename.toFilesystemEncoding().c_str());
469 cerr << "Could not open input file \"" << infilename
470 << "\" for reading." << endl;
473 string const oldParentFilePath = parentFilePath;
474 parentFilePath = onlyPath(infilename.absFilename());
475 tex2lyx(is, os, encoding);
476 parentFilePath = oldParentFilePath;
480 } // anonymous namespace
483 bool tex2lyx(string const & infilename, FileName const & outfilename,
484 string const & encoding)
486 if (outfilename.isReadableFile()) {
487 if (overwrite_files) {
488 cerr << "Overwriting existing file "
489 << outfilename << endl;
491 cerr << "Not overwriting existing file "
492 << outfilename << endl;
496 cerr << "Creating file " << outfilename << endl;
498 ofstream os(outfilename.toFilesystemEncoding().c_str());
500 cerr << "Could not open output file \"" << outfilename
501 << "\" for writing." << endl;
505 cerr << "Input file: " << infilename << "\n";
506 cerr << "Output file: " << outfilename << "\n";
508 return tex2lyx(FileName(infilename), os, encoding);
514 int main(int argc, char * argv[])
518 //setlocale(LC_CTYPE, "");
520 lyxerr.setStream(cerr);
522 easyParse(argc, argv);
525 error_message("Not enough arguments.");
526 os::init(argc, argv);
529 init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
530 cl_system_support, cl_user_support,
531 top_build_dir_is_two_levels_up);
532 } catch (ExceptionMessage const & message) {
533 cerr << to_utf8(message.title_) << ":\n"
534 << to_utf8(message.details_) << endl;
535 if (message.type_ == ErrorException)
539 // Now every known option is parsed. Look for input and output
540 // file name (the latter is optional).
541 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
542 infilename = makeAbsPath(infilename).absFilename();
546 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
547 if (outfilename != "-")
548 outfilename = makeAbsPath(outfilename).absFilename();
550 outfilename = changeExtension(infilename, ".lyx");
552 // Read the syntax tables
553 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
554 if (system_syntaxfile.empty()) {
555 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
558 read_syntaxfile(system_syntaxfile);
559 if (!syntaxfile.empty())
560 read_syntaxfile(makeAbsPath(syntaxfile));
562 // Read the encodings table.
563 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
564 if (symbols_path.empty()) {
565 cerr << "Error: Could not find file \"unicodesymbols\"."
569 FileName const enc_path = libFileSearch(string(), "encodings");
570 if (enc_path.empty()) {
571 cerr << "Error: Could not find file \"encodings\"."
575 encodings.read(enc_path, symbols_path);
576 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
577 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
579 // The real work now.
580 masterFilePath = onlyPath(infilename);
581 parentFilePath = masterFilePath;
582 if (outfilename == "-") {
583 if (tex2lyx(FileName(infilename), cout, default_encoding))
588 if (tex2lyx(infilename, FileName(outfilename), default_encoding))