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;
47 void warning(docstring const & title, docstring const & message,
57 // Dummy translation support
59 Messages const & getMessages(std::string const &)
65 Messages const & getGuiMessages()
71 // Keep the linker happy on Windows
76 string const trim(string const & a, char const * p)
83 size_t r = a.find_last_not_of(p);
84 size_t l = a.find_first_not_of(p);
86 // Is this the minimal test? (lgb)
87 if (r == string::npos && l == string::npos)
90 return a.substr(l, r - l + 1);
94 void split(string const & s, vector<string> & result, char delim)
96 //cerr << "split 1: '" << s << "'\n";
99 while (getline(is, t, delim))
101 //cerr << "split 2\n";
105 string join(vector<string> const & input, char const * delim)
108 for (size_t i = 0; i != input.size(); ++i) {
117 char const * const * is_known(string const & str, char const * const * what)
119 for ( ; *what; ++what)
127 // current stack of nested environments
128 vector<string> active_environments;
131 string active_environment()
133 return active_environments.empty() ? string() : active_environments.back();
137 CommandMap known_commands;
138 CommandMap known_environments;
139 CommandMap known_math_environments;
142 void add_known_command(string const & command, string const & o1,
145 // We have to handle the following cases:
146 // definition o1 o2 invocation result
147 // \newcommand{\foo}{bar} "" false \foo bar
148 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
149 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
150 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
151 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
152 unsigned int nargs = 0;
153 vector<ArgumentType> arguments;
154 string const opt1 = rtrim(ltrim(o1, "["), "]");
155 if (isStrUnsignedInt(opt1)) {
156 // The command has arguments
157 nargs = convert<unsigned int>(opt1);
158 if (nargs > 0 && o2) {
159 // The first argument is optional
160 arguments.push_back(optional);
164 for (unsigned int i = 0; i < nargs; ++i)
165 arguments.push_back(required);
166 known_commands[command] = arguments;
170 bool noweb_mode = false;
177 * Read one command definition from the syntax file
179 void read_command(Parser & p, string command, CommandMap & commands)
181 if (p.next_token().asInput() == "*") {
185 vector<ArgumentType> arguments;
186 while (p.next_token().cat() == catBegin ||
187 p.next_token().asInput() == "[") {
188 if (p.next_token().cat() == catBegin) {
189 string const arg = p.getArg('{', '}');
190 if (arg == "translate")
191 arguments.push_back(required);
193 arguments.push_back(verbatim);
196 arguments.push_back(optional);
199 commands[command] = arguments;
204 * Read a class of environments from the syntax file
206 void read_environment(Parser & p, string const & begin,
207 CommandMap & environments)
211 Token const & t = p.get_token();
212 if (t.cat() == catLetter)
213 environment += t.asInput();
214 else if (!environment.empty()) {
216 read_command(p, environment, environments);
219 if (t.cat() == catEscape && t.asInput() == "\\end") {
220 string const end = p.getArg('{', '}');
229 * Read a list of TeX commands from a reLyX compatible syntax file.
230 * Since this list is used after all commands that have a LyX counterpart
231 * are handled, it does not matter that the "syntax.default" file
232 * has almost all of them listed. For the same reason the reLyX-specific
233 * reLyXre environment is ignored.
235 void read_syntaxfile(FileName const & file_name)
237 ifdocstream is(file_name.toFilesystemEncoding().c_str());
239 cerr << "Could not open syntax file \"" << file_name
240 << "\" for reading." << endl;
243 // We can use our TeX parser, since the syntax of the layout file is
244 // modeled after TeX.
245 // Unknown tokens are just silently ignored, this helps us to skip some
246 // reLyX specific things.
249 Token const & t = p.get_token();
250 if (t.cat() == catEscape) {
251 string const command = t.asInput();
252 if (command == "\\begin") {
253 string const name = p.getArg('{', '}');
254 if (name == "environments" || name == "reLyXre")
255 // We understand "reLyXre", but it is
256 // not as powerful as "environments".
257 read_environment(p, name,
259 else if (name == "mathenvironments")
260 read_environment(p, name,
261 known_math_environments);
263 read_command(p, command, known_commands);
270 string documentclass;
271 string default_encoding;
273 bool overwrite_files = false;
276 /// return the number of arguments consumed
277 typedef int (*cmd_helper)(string const &, string const &);
280 int parse_help(string const &, string const &)
282 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
284 "\t-c textclass Declare the textclass.\n"
285 "\t-e encoding Set the default encoding (latex name).\n"
286 "\t-f Force overwrite of .lyx files.\n"
287 "\t-help Print this message and quit.\n"
288 "\t-n translate a noweb (aka literate programming) file.\n"
289 "\t-s syntaxfile read additional syntax file.\n"
290 "\t-sysdir dir Set system directory to DIR.\n"
291 "\t-userdir DIR Set user directory to DIR."
297 void error_message(string const & message)
299 cerr << "tex2lyx: " << message << "\n\n";
301 parse_help(string(), string());
305 int parse_class(string const & arg, string const &)
308 error_message("Missing textclass string after -c switch");
314 int parse_encoding(string const & arg, string const &)
317 error_message("Missing encoding string after -e switch");
318 default_encoding = arg;
323 int parse_syntaxfile(string const & arg, string const &)
326 error_message("Missing syntaxfile string after -s switch");
327 syntaxfile = internal_path(arg);
332 // Filled with the command line arguments "foo" of "-sysdir foo" or
334 string cl_system_support;
335 string cl_user_support;
338 int parse_sysdir(string const & arg, string const &)
341 error_message("Missing directory for -sysdir switch");
342 cl_system_support = internal_path(arg);
347 int parse_userdir(string const & arg, string const &)
350 error_message("Missing directory for -userdir switch");
351 cl_user_support = internal_path(arg);
356 int parse_force(string const &, string const &)
358 overwrite_files = true;
363 int parse_noweb(string const &, string const &)
370 void easyParse(int & argc, char * argv[])
372 map<string, cmd_helper> cmdmap;
374 cmdmap["-c"] = parse_class;
375 cmdmap["-e"] = parse_encoding;
376 cmdmap["-f"] = parse_force;
377 cmdmap["-s"] = parse_syntaxfile;
378 cmdmap["-help"] = parse_help;
379 cmdmap["--help"] = parse_help;
380 cmdmap["-n"] = parse_noweb;
381 cmdmap["-sysdir"] = parse_sysdir;
382 cmdmap["-userdir"] = parse_userdir;
384 for (int i = 1; i < argc; ++i) {
385 map<string, cmd_helper>::const_iterator it
386 = cmdmap.find(argv[i]);
388 // don't complain if not found - may be parsed later
389 if (it == cmdmap.end()) {
390 if (argv[i][0] == '-')
391 error_message(string("Unknown option `") + argv[i] + "'.");
396 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
397 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
399 int const remove = 1 + it->second(arg, arg2);
401 // Now, remove used arguments by shifting
402 // the following ones remove places down.
403 os::remove_internal_args(i, remove);
405 for (int j = i; j < argc; ++j)
406 argv[j] = argv[j + remove];
412 // path of the first parsed file
413 string masterFilePath;
414 // path of the currently parsed file
415 string parentFilePath;
417 } // anonymous namespace
420 string getMasterFilePath()
422 return masterFilePath;
425 string getParentFilePath()
427 return parentFilePath;
434 * Reads tex input from \a is and writes lyx output to \a os.
435 * Uses some common settings for the preamble, so this should only
436 * be used more than once for included documents.
437 * Caution: Overwrites the existing preamble settings if the new document
438 * contains a preamble.
439 * You must ensure that \p parentFilePath is properly set before calling
442 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
445 if (!encoding.empty())
446 p.setEncoding(encoding);
450 TeX2LyXDocClass textclass;
451 parse_preamble(p, ss, documentclass, textclass);
453 active_environments.push_back("document");
454 Context context(true, textclass);
455 parse_text(p, ss, FLAG_END, true, context);
457 // Empty document body. LyX needs at least one paragraph.
458 context.check_layout(ss);
459 context.check_end_layout(ss);
460 ss << "\n\\end_body\n\\end_document\n";
461 active_environments.pop_back();
466 ofdocstream parsertest("parsertest.tex");
468 parsertest << p.get_token().asInput();
469 // <origfile> and parsertest.tex should now have identical content
474 /// convert TeX from \p infilename to LyX and write it to \p os
475 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
478 // forbid buffering on this stream
479 is.rdbuf()->pubsetbuf(0,0);
480 is.open(infilename.toFilesystemEncoding().c_str());
482 cerr << "Could not open input file \"" << infilename
483 << "\" for reading." << endl;
486 string const oldParentFilePath = parentFilePath;
487 parentFilePath = onlyPath(infilename.absFileName());
488 tex2lyx(is, os, encoding);
489 parentFilePath = oldParentFilePath;
493 } // anonymous namespace
496 bool tex2lyx(string const & infilename, FileName const & outfilename,
497 string const & encoding)
499 if (outfilename.isReadableFile()) {
500 if (overwrite_files) {
501 cerr << "Overwriting existing file "
502 << outfilename << endl;
504 cerr << "Not overwriting existing file "
505 << outfilename << endl;
509 cerr << "Creating file " << outfilename << endl;
511 ofstream os(outfilename.toFilesystemEncoding().c_str());
513 cerr << "Could not open output file \"" << outfilename
514 << "\" for writing." << endl;
518 cerr << "Input file: " << infilename << "\n";
519 cerr << "Output file: " << outfilename << "\n";
521 return tex2lyx(FileName(infilename), os, encoding);
527 int main(int argc, char * argv[])
531 //setlocale(LC_CTYPE, "");
533 lyxerr.setStream(cerr);
535 os::init(argc, argv);
537 easyParse(argc, argv);
540 error_message("Not enough arguments.");
543 init_package(internal_path(os::utf8_argv(0)),
544 cl_system_support, cl_user_support,
545 top_build_dir_is_two_levels_up);
546 } catch (ExceptionMessage const & message) {
547 cerr << to_utf8(message.title_) << ":\n"
548 << to_utf8(message.details_) << endl;
549 if (message.type_ == ErrorException)
553 // Now every known option is parsed. Look for input and output
554 // file name (the latter is optional).
555 string infilename = internal_path(os::utf8_argv(1));
556 infilename = makeAbsPath(infilename).absFileName();
560 outfilename = internal_path(os::utf8_argv(2));
561 if (outfilename != "-")
562 outfilename = makeAbsPath(outfilename).absFileName();
564 outfilename = changeExtension(infilename, ".lyx");
566 // Read the syntax tables
567 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
568 if (system_syntaxfile.empty()) {
569 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
572 read_syntaxfile(system_syntaxfile);
573 if (!syntaxfile.empty())
574 read_syntaxfile(makeAbsPath(syntaxfile));
576 // Read the encodings table.
577 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
578 if (symbols_path.empty()) {
579 cerr << "Error: Could not find file \"unicodesymbols\"."
583 FileName const enc_path = libFileSearch(string(), "encodings");
584 if (enc_path.empty()) {
585 cerr << "Error: Could not find file \"encodings\"."
589 encodings.read(enc_path, symbols_path);
590 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
591 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
593 // The real work now.
594 masterFilePath = onlyPath(infilename);
595 parentFilePath = masterFilePath;
596 if (outfilename == "-") {
597 if (tex2lyx(FileName(infilename), cout, default_encoding))
602 if (tex2lyx(infilename, FileName(outfilename), default_encoding))