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/os.h"
29 #include "support/Package.h"
39 using namespace lyx::support;
40 using namespace lyx::support::os;
44 string const trim(string const & a, char const * p)
51 size_t r = a.find_last_not_of(p);
52 size_t l = a.find_first_not_of(p);
54 // Is this the minimal test? (lgb)
55 if (r == string::npos && l == string::npos)
58 return a.substr(l, r - l + 1);
62 void split(string const & s, vector<string> & result, char delim)
64 //cerr << "split 1: '" << s << "'\n";
67 while (getline(is, t, delim))
69 //cerr << "split 2\n";
73 string join(vector<string> const & input, char const * delim)
76 for (size_t i = 0; i != input.size(); ++i) {
85 char const * const * is_known(string const & str, char const * const * what)
87 for ( ; *what; ++what)
95 // current stack of nested environments
96 vector<string> active_environments;
99 string active_environment()
101 return active_environments.empty() ? string() : active_environments.back();
105 CommandMap known_commands;
106 CommandMap known_environments;
107 CommandMap known_math_environments;
110 void add_known_command(string const & command, string const & o1,
113 // We have to handle the following cases:
114 // definition o1 o2 invocation result
115 // \newcommand{\foo}{bar} "" false \foo bar
116 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
117 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
118 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
119 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
120 unsigned int nargs = 0;
121 vector<ArgumentType> arguments;
122 string const opt1 = rtrim(ltrim(o1, "["), "]");
123 if (isStrUnsignedInt(opt1)) {
124 // The command has arguments
125 nargs = convert<unsigned int>(opt1);
126 if (nargs > 0 && o2) {
127 // The first argument is optional
128 arguments.push_back(optional);
132 for (unsigned int i = 0; i < nargs; ++i)
133 arguments.push_back(required);
134 known_commands[command] = arguments;
138 bool noweb_mode = false;
145 * Read one command definition from the syntax file
147 void read_command(Parser & p, string command, CommandMap & commands)
149 if (p.next_token().asInput() == "*") {
153 vector<ArgumentType> arguments;
154 while (p.next_token().cat() == catBegin ||
155 p.next_token().asInput() == "[") {
156 if (p.next_token().cat() == catBegin) {
157 string const arg = p.getArg('{', '}');
158 if (arg == "translate")
159 arguments.push_back(required);
161 arguments.push_back(verbatim);
164 arguments.push_back(optional);
167 commands[command] = arguments;
172 * Read a class of environments from the syntax file
174 void read_environment(Parser & p, string const & begin,
175 CommandMap & environments)
179 Token const & t = p.get_token();
180 if (t.cat() == catLetter)
181 environment += t.asInput();
182 else if (!environment.empty()) {
184 read_command(p, environment, environments);
187 if (t.cat() == catEscape && t.asInput() == "\\end") {
188 string const end = p.getArg('{', '}');
197 * Read a list of TeX commands from a reLyX compatible syntax file.
198 * Since this list is used after all commands that have a LyX counterpart
199 * are handled, it does not matter that the "syntax.default" file
200 * has almost all of them listed. For the same reason the reLyX-specific
201 * reLyXre environment is ignored.
203 void read_syntaxfile(FileName const & file_name)
205 ifdocstream is(file_name.toFilesystemEncoding().c_str());
207 cerr << "Could not open syntax file \"" << file_name
208 << "\" for reading." << endl;
211 // We can use our TeX parser, since the syntax of the layout file is
212 // modeled after TeX.
213 // Unknown tokens are just silently ignored, this helps us to skip some
214 // reLyX specific things.
217 Token const & t = p.get_token();
218 if (t.cat() == catEscape) {
219 string const command = t.asInput();
220 if (command == "\\begin") {
221 string const name = p.getArg('{', '}');
222 if (name == "environments" || name == "reLyXre")
223 // We understand "reLyXre", but it is
224 // not as powerful as "environments".
225 read_environment(p, name,
227 else if (name == "mathenvironments")
228 read_environment(p, name,
229 known_math_environments);
231 read_command(p, command, known_commands);
238 string documentclass;
239 string default_encoding;
241 bool overwrite_files = false;
244 /// return the number of arguments consumed
245 typedef int (*cmd_helper)(string const &, string const &);
248 int parse_help(string const &, string const &)
250 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
252 "\t-c textclass Declare the textclass.\n"
253 "\t-e encoding Set the default encoding (latex name).\n"
254 "\t-f Force overwrite of .lyx files.\n"
255 "\t-help Print this message and quit.\n"
256 "\t-n translate a noweb (aka literate programming) file.\n"
257 "\t-s syntaxfile read additional syntax file.\n"
258 "\t-sysdir dir Set system directory to DIR.\n"
259 "\t-userdir DIR Set user directory to DIR."
265 void error_message(string const & message)
267 cerr << "tex2lyx: " << message << "\n\n";
269 parse_help(string(), string());
273 int parse_class(string const & arg, string const &)
276 error_message("Missing textclass string after -c switch");
282 int parse_encoding(string const & arg, string const &)
285 error_message("Missing encoding string after -e switch");
286 default_encoding = arg;
291 int parse_syntaxfile(string const & arg, string const &)
294 error_message("Missing syntaxfile string after -s switch");
295 syntaxfile = internal_path(arg);
300 // Filled with the command line arguments "foo" of "-sysdir foo" or
302 string cl_system_support;
303 string cl_user_support;
306 int parse_sysdir(string const & arg, string const &)
309 error_message("Missing directory for -sysdir switch");
310 cl_system_support = internal_path(arg);
315 int parse_userdir(string const & arg, string const &)
318 error_message("Missing directory for -userdir switch");
319 cl_user_support = internal_path(arg);
324 int parse_force(string const &, string const &)
326 overwrite_files = true;
331 int parse_noweb(string const &, string const &)
338 void easyParse(int & argc, char * argv[])
340 map<string, cmd_helper> cmdmap;
342 cmdmap["-c"] = parse_class;
343 cmdmap["-e"] = parse_encoding;
344 cmdmap["-f"] = parse_force;
345 cmdmap["-s"] = parse_syntaxfile;
346 cmdmap["-help"] = parse_help;
347 cmdmap["--help"] = parse_help;
348 cmdmap["-n"] = parse_noweb;
349 cmdmap["-sysdir"] = parse_sysdir;
350 cmdmap["-userdir"] = parse_userdir;
352 for (int i = 1; i < argc; ++i) {
353 map<string, cmd_helper>::const_iterator it
354 = cmdmap.find(argv[i]);
356 // don't complain if not found - may be parsed later
357 if (it == cmdmap.end()) {
358 if (argv[i][0] == '-')
359 error_message(string("Unknown option `") + argv[i] + "'.");
364 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
365 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
367 int const remove = 1 + it->second(arg, arg2);
369 // Now, remove used arguments by shifting
370 // the following ones remove places down.
372 for (int j = i; j < argc; ++j)
373 argv[j] = argv[j + remove];
379 // path of the first parsed file
380 string masterFilePath;
381 // path of the currently parsed file
382 string parentFilePath;
384 } // anonymous namespace
387 string getMasterFilePath()
389 return masterFilePath;
392 string getParentFilePath()
394 return parentFilePath;
401 * Reads tex input from \a is and writes lyx output to \a os.
402 * Uses some common settings for the preamble, so this should only
403 * be used more than once for included documents.
404 * Caution: Overwrites the existing preamble settings if the new document
405 * contains a preamble.
406 * You must ensure that \p parentFilePath is properly set before calling
409 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
412 if (!encoding.empty())
413 p.setEncoding(encoding);
417 TeX2LyXDocClass textclass;
418 parse_preamble(p, ss, documentclass, textclass);
420 active_environments.push_back("document");
421 Context context(true, textclass);
422 parse_text(p, ss, FLAG_END, true, context);
424 // Empty document body. LyX needs at least one paragraph.
425 context.check_layout(ss);
426 context.check_end_layout(ss);
427 ss << "\n\\end_body\n\\end_document\n";
428 active_environments.pop_back();
433 ofdocstream parsertest("parsertest.tex");
435 parsertest << p.get_token().asInput();
436 // <origfile> and parsertest.tex should now have identical content
441 /// convert TeX from \p infilename to LyX and write it to \p os
442 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
445 // forbid buffering on this stream
446 is.rdbuf()->pubsetbuf(0,0);
447 is.open(infilename.toFilesystemEncoding().c_str());
449 cerr << "Could not open input file \"" << infilename
450 << "\" for reading." << endl;
453 string const oldParentFilePath = parentFilePath;
454 parentFilePath = onlyPath(infilename.absFilename());
455 tex2lyx(is, os, encoding);
456 parentFilePath = oldParentFilePath;
460 } // anonymous namespace
463 bool tex2lyx(string const & infilename, FileName const & outfilename,
464 string const & encoding)
466 if (outfilename.isReadableFile()) {
467 if (overwrite_files) {
468 cerr << "Overwriting existing file "
469 << outfilename << endl;
471 cerr << "Not overwriting existing file "
472 << outfilename << endl;
476 cerr << "Creating file " << outfilename << endl;
478 ofstream os(outfilename.toFilesystemEncoding().c_str());
480 cerr << "Could not open output file \"" << outfilename
481 << "\" for writing." << endl;
485 cerr << "Input file: " << infilename << "\n";
486 cerr << "Output file: " << outfilename << "\n";
488 return tex2lyx(FileName(infilename), os, encoding);
494 int main(int argc, char * argv[])
498 //setlocale(LC_CTYPE, "");
500 lyxerr.setStream(cerr);
502 easyParse(argc, argv);
505 error_message("Not enough arguments.");
506 os::init(argc, argv);
509 init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
510 cl_system_support, cl_user_support,
511 top_build_dir_is_two_levels_up);
512 } catch (ExceptionMessage const & message) {
513 cerr << to_utf8(message.title_) << ":\n"
514 << to_utf8(message.details_) << endl;
515 if (message.type_ == ErrorException)
519 // Now every known option is parsed. Look for input and output
520 // file name (the latter is optional).
521 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
522 infilename = makeAbsPath(infilename).absFilename();
526 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
527 if (outfilename != "-")
528 outfilename = makeAbsPath(outfilename).absFilename();
530 outfilename = changeExtension(infilename, ".lyx");
532 // Read the syntax tables
533 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
534 if (system_syntaxfile.empty()) {
535 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
538 read_syntaxfile(system_syntaxfile);
539 if (!syntaxfile.empty())
540 read_syntaxfile(makeAbsPath(syntaxfile));
542 // Read the encodings table.
543 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
544 if (symbols_path.empty()) {
545 cerr << "Error: Could not find file \"unicodesymbols\"."
549 FileName const enc_path = libFileSearch(string(), "encodings");
550 if (enc_path.empty()) {
551 cerr << "Error: Could not find file \"encodings\"."
555 encodings.read(enc_path, symbols_path);
556 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
557 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
559 // The real work now.
560 masterFilePath = onlyPath(infilename);
561 parentFilePath = masterFilePath;
562 if (outfilename == "-") {
563 if (tex2lyx(FileName(infilename), cout, default_encoding))
568 if (tex2lyx(infilename, FileName(outfilename), default_encoding))