]> git.lyx.org Git - lyx.git/blob - src/Format.cpp
Provide proper fallback if a bibliography processor is not found
[lyx.git] / src / Format.cpp
1 /**
2  * \file Format.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Dekel Tsur
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Format.h"
14 #include "Buffer.h"
15 #include "BufferParams.h"
16 #include "LyXRC.h"
17 #include "ServerSocket.h"
18
19 #include "frontends/alert.h" //to be removed?
20
21 #include "support/debug.h"
22 #include "support/filetools.h"
23 #include "support/gettext.h"
24 #include "support/lstrings.h"
25 #include "support/mutex.h"
26 #include "support/docstream.h"
27 #include "support/os.h"
28 #include "support/PathChanger.h"
29 #include "support/Systemcall.h"
30 #include "support/textutils.h"
31 #include "support/Translator.h"
32
33 #include <algorithm>
34 #include <map>
35 #include <ctime>
36
37 // FIXME: Q_OS_MAC is not available, it's in Qt
38 #ifdef USE_MACOSX_PACKAGING
39 #include "support/linkback/LinkBackProxy.h"
40 #endif
41
42 #ifdef HAVE_MAGIC_H
43 #include <magic.h>
44 #endif
45
46 using namespace std;
47 using namespace lyx::support;
48
49 namespace lyx {
50
51 namespace Alert = frontend::Alert;
52 namespace os = support::os;
53
54 namespace {
55
56 string const token_from_format("$$i");
57 string const token_path_format("$$p");
58 string const token_socket_format("$$a");
59
60
61 class FormatNamesEqual : public unary_function<Format, bool> {
62 public:
63         FormatNamesEqual(string const & name)
64                 : name_(name)
65         {}
66         bool operator()(Format const & f) const
67         {
68                 return f.name() == name_;
69         }
70 private:
71         string name_;
72 };
73
74
75 class FormatExtensionsEqual : public unary_function<Format, bool> {
76 public:
77         FormatExtensionsEqual(string const & extension)
78                 : extension_(extension)
79         {}
80         bool operator()(Format const & f) const
81         {
82                 return f.hasExtension(extension_);
83         }
84 private:
85         string extension_;
86 };
87
88
89 class FormatMimeEqual : public unary_function<Format, bool> {
90 public:
91         FormatMimeEqual(string const & mime)
92                 : mime_(mime)
93         {}
94         bool operator()(Format const & f) const
95         {
96                 // The test for empty mime strings is needed since we allow
97                 // formats with empty mime types.
98                 return f.mime() == mime_ && !mime_.empty();
99         }
100 private:
101         string mime_;
102 };
103
104
105 } // namespace
106
107 bool Format::formatSorter(Format const * lhs, Format const * rhs)
108 {
109         return compare_locale(translateIfPossible(lhs->prettyname()),
110                               translateIfPossible(rhs->prettyname())) < 0;
111 }
112
113 bool operator<(Format const & a, Format const & b)
114 {
115         return compare_locale(translateIfPossible(a.prettyname()),
116                               translateIfPossible(b.prettyname())) < 0;
117 }
118
119
120 Format::Format(string const & n, string const & e, docstring const & p,
121                string const & s, string const & v, string const & ed,
122                string const & m, int flags)
123         : name_(n), prettyname_(p), shortcut_(s), viewer_(v),
124           editor_(ed), mime_(m), flags_(flags)
125 {
126         extension_list_ = getVectorFromString(e, ",");
127         LYXERR(Debug::GRAPHICS, "New Format: n=" << n << ", flags=" << flags);
128 }
129
130
131 bool Format::dummy() const
132 {
133         return extension().empty();
134 }
135
136
137 string const Format::extensions() const
138 {
139         return getStringFromVector(extension_list_, ", ");
140 }
141
142
143 bool Format::hasExtension(string const & e) const
144 {
145         return (find(extension_list_.begin(), extension_list_.end(), e)
146                 != extension_list_.end());
147 }
148
149
150 bool Format::isChildFormat() const
151 {
152         if (name_.empty())
153                 return false;
154         return isDigitASCII(name_[name_.length() - 1]);
155 }
156
157
158 string const Format::parentFormat() const
159 {
160         return name_.substr(0, name_.length() - 1);
161 }
162
163
164 void Format::setExtensions(string const & e)
165 {
166         extension_list_ = getVectorFromString(e, ",");
167 }
168
169
170 // This method should return a reference, and throw an exception
171 // if the format named name cannot be found (Lgb)
172 Format const * Formats::getFormat(string const & name) const
173 {
174         FormatList::const_iterator cit =
175                 find_if(formatlist_.begin(), formatlist_.end(),
176                         FormatNamesEqual(name));
177         if (cit != formatlist_.end())
178                 return &(*cit);
179         else
180                 return 0;
181 }
182
183
184 namespace {
185
186 /** Guess the file format name (as in Format::name()) from contents.
187  *  Normally you don't want to use this directly, but rather
188  *  Formats::getFormatFromFile().
189  */
190 string guessFormatFromContents(FileName const & fn)
191 {
192         // the different filetypes and what they contain in one of the first lines
193         // (dots are any characters).           (Herbert 20020131)
194         // AGR  Grace...
195         // BMP  BM...
196         // EPS  %!PS-Adobe-3.0 EPSF...
197         // FIG  #FIG...
198         // FITS ...BITPIX...
199         // GIF  GIF...
200         // JPG  \377\330...     (0xFFD8)
201         // PDF  %PDF-...
202         // PNG  .PNG...
203         // PBM  P1... or P4     (B/W)
204         // PGM  P2... or P5     (Grayscale)
205         // PPM  P3... or P6     (color)
206         // PS   %!PS-Adobe-2.0 or 1.0,  no "EPSF"!
207         // SGI  \001\332...     (decimal 474)
208         // TGIF %TGIF...
209         // TIFF II... or MM...
210         // XBM  ..._bits[]...
211         // XPM  /* XPM */    sometimes missing (f.ex. tgif-export)
212         //      ...static char *...
213         // XWD  \000\000\000\151        (0x00006900) decimal 105
214         //
215         // GZIP \037\213        http://www.ietf.org/rfc/rfc1952.txt
216         // ZIP  PK...                   http://www.halyava.ru/document/ind_arch.htm
217         // Z    \037\235                UNIX compress
218
219         // paranoia check
220         if (fn.empty() || !fn.isReadableFile())
221                 return string();
222
223         ifstream ifs(fn.toFilesystemEncoding().c_str());
224         if (!ifs)
225                 // Couldn't open file...
226                 return string();
227
228         // gnuzip
229         static string const gzipStamp = "\037\213";
230
231         // PKZIP
232         static string const zipStamp = "PK";
233
234         // ZIP containers (koffice, openoffice.org etc).
235         static string const nonzipStamp = "\010\0\0\0mimetypeapplication/";
236
237         // compress
238         static string const compressStamp = "\037\235";
239
240         // DOS binary EPS according to Adobe TN-5002
241         static string const binEPSStamp = "\xC5\xD0\xD3\xC6";
242
243
244         // Maximum strings to read
245         int const max_count = 50;
246         int count = 0;
247
248         string str;
249         string format;
250         bool firstLine = true;
251         bool backslash = false;
252         bool maybelatex = false;
253         int dollars = 0;
254         while ((count++ < max_count) && format.empty() && !maybelatex) {
255                 if (ifs.eof())
256                         break;
257
258                 getline(ifs, str);
259                 string const stamp = str.substr(0, 2);
260                 if (firstLine && str.size() >= 2) {
261                         // at first we check for a zipped file, because this
262                         // information is saved in the first bytes of the file!
263                         // also some graphic formats which save the information
264                         // in the first line, too.
265                         if (prefixIs(str, gzipStamp)) {
266                                 format =  "gzip";
267
268                         } else if (stamp == zipStamp &&
269                                    !contains(str, nonzipStamp)) {
270                                 format =  "zip";
271
272                         } else if (stamp == compressStamp) {
273                                 format =  "compress";
274
275                         // the graphics part
276                         } else if (stamp == "BM") {
277                                 format =  "bmp";
278
279                         } else if (stamp == "\377\330") {
280                                 format =  "jpg";
281
282                         } else if (stamp == "\001\332") {
283                                 format =  "sgi";
284                         } else if (prefixIs(str, binEPSStamp)) {
285                                 format =  "eps";
286
287                         // PBM family
288                         // Don't need to use str.at(0), str.at(1) because
289                         // we already know that str.size() >= 2
290                         } else if (str[0] == 'P') {
291                                 switch (str[1]) {
292                                 case '1':
293                                 case '4':
294                                         format =  "pbm";
295                                     break;
296                                 case '2':
297                                 case '5':
298                                         format =  "pgm";
299                                     break;
300                                 case '3':
301                                 case '6':
302                                         format =  "ppm";
303                                 }
304                                 break;
305
306                         } else if ((stamp == "II") || (stamp == "MM")) {
307                                 format =  "tiff";
308
309                         } else if (prefixIs(str,"%TGIF")) {
310                                 format =  "tgif";
311
312                         } else if (prefixIs(str,"#FIG")) {
313                                 format =  "fig";
314
315                         } else if (prefixIs(str,"GIF")) {
316                                 format =  "gif";
317
318                         } else if (str.size() > 3) {
319                                 int const c = ((str[0] << 24) & (str[1] << 16) &
320                                                (str[2] << 8)  & str[3]);
321                                 if (c == 105) {
322                                         format =  "xwd";
323                                 }
324                         }
325
326                         firstLine = false;
327                 }
328
329                 if (!format.empty())
330                     break;
331                 else if (contains(str,"EPSF"))
332                         // dummy, if we have wrong file description like
333                         // %!PS-Adobe-2.0EPSF"
334                         format = "eps";
335
336                 else if (contains(str, "Grace"))
337                         format = "agr";
338
339                 else if (contains(str, "%PDF"))
340                         // autodetect pdf format for graphics inclusion
341                         format = "pdf6";
342
343                 else if (contains(str, "PNG"))
344                         format = "png";
345
346                 else if (contains(str, "%!PS-Adobe")) {
347                         // eps or ps
348                         ifs >> str;
349                         if (contains(str,"EPSF"))
350                                 format = "eps";
351                         else
352                             format = "ps";
353                 }
354
355                 else if (contains(str, "_bits[]"))
356                         format = "xbm";
357
358                 else if (contains(str, "XPM") || contains(str, "static char *"))
359                         format = "xpm";
360
361                 else if (contains(str, "BITPIX"))
362                         format = "fits";
363
364                 else if (contains(str, "\\documentclass") ||
365                          contains(str, "\\chapter") ||
366                          contains(str, "\\section") ||
367                          contains(str, "\\begin") ||
368                          contains(str, "\\end") ||
369                          contains(str, "$$") ||
370                          contains(str, "\\[") ||
371                          contains(str, "\\]"))
372                         maybelatex = true;
373                 else {
374                         if (contains(str, '\\'))
375                                 backslash = true;
376                         dollars += count_char(str, '$');
377                         if (backslash && dollars > 1)
378                                 // inline equation
379                                 maybelatex = true;
380                 }
381         }
382
383         if (format.empty() && maybelatex && !isBinaryFile(fn))
384                 format = "latex";
385
386         if (format.empty()) {
387                 if (ifs.eof())
388                         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
389                                "\tFile type not recognised before EOF!");
390         } else {
391                 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
392                 return format;
393         }
394
395         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
396                 << "\tCouldn't find a known format!");
397         return string();
398 }
399
400 } // namespace
401
402
403 string Formats::getFormatFromFile(FileName const & filename) const
404 {
405         if (filename.empty())
406                 return string();
407
408         string psformat;
409         string format;
410 #ifdef HAVE_MAGIC_H
411         if (filename.exists()) {
412                 magic_t magic_cookie = magic_open(MAGIC_MIME);
413                 if (magic_cookie) {
414                         if (magic_load(magic_cookie, NULL) != 0) {
415                                 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
416                                         << "\tCouldn't load magic database - "
417                                         << magic_error(magic_cookie));
418                         } else {
419                                 char const * result = magic_file(magic_cookie,
420                                         filename.toFilesystemEncoding().c_str());
421                                 string mime;
422                                 if (result)
423                                         mime = token(result, ';', 0);
424                                 else {
425                                         LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
426                                                 << "\tCouldn't query magic database - "
427                                                 << magic_error(magic_cookie));
428                                 }
429                                 // our own detection is better for binary files (can be anything)
430                                 // and different plain text formats
431                                 if (!mime.empty() && mime != "application/octet-stream" &&
432                                     mime != "text/plain") {
433                                         Formats::const_iterator cit =
434                                                 find_if(formatlist_.begin(), formatlist_.end(),
435                                                         FormatMimeEqual(mime));
436                                         if (cit != formatlist_.end()) {
437                                                 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
438                                                         << mime << " -> " << cit->name());
439                                                 // See special eps/ps handling below
440                                                 if (mime == "application/postscript")
441                                                         psformat = cit->name();
442                                                 else
443                                                         format = cit->name();
444                                         }
445                                 }
446                         }
447                         magic_close(magic_cookie);
448                         // libmagic recognizes as latex also some formats of ours
449                         // such as pstex and pdftex. Therefore we have to perform
450                         // additional checks in this case (bug 9244).
451                         if (!format.empty() && format != "latex")
452                                 return format;
453                 }
454         }
455 #endif
456
457         string const ext = getExtension(filename.absFileName());
458         if (format.empty()) {
459                 // libmagic does not distinguish eps and ps.
460                 // Therefore we need to use our own detection here, but only if it
461                 // recognizes either ps or eps. Otherwise the libmagic guess will
462                 // be better (bug 9146).
463                 format = guessFormatFromContents(filename);
464                 if (!psformat.empty()) {
465                         if (isPostScriptFileFormat(format))
466                                 return format;
467                         else
468                                 return psformat;
469                 }
470
471                 if (isZippedFileFormat(format) && !ext.empty()) {
472                         string const & fmt_name = getFormatFromExtension(ext);
473                         if (!fmt_name.empty()) {
474                                 Format const * p_format = getFormat(fmt_name);
475                                 if (p_format && p_format->zippedNative())
476                                         return p_format->name();
477                         }
478                 }
479                 // Don't simply return latex (bug 9244).
480                 if (!format.empty() && format != "latex")
481                         return format;
482         }
483
484         // Both libmagic and our guessing from contents may return as latex
485         // also lyx files and our pstex and pdftex formats. In this case we
486         // give precedence to the format determined by the extension.
487         if (format == "latex") {
488                 format = getFormatFromExtension(ext);
489                 return format.empty() ? "latex" : format;
490         }
491
492         // try to find a format from the file extension.
493         return getFormatFromExtension(ext);
494 }
495
496
497 string Formats::getFormatFromExtension(string const & ext) const
498 {
499         if (!ext.empty()) {
500                 // this is ambigous if two formats have the same extension,
501                 // but better than nothing
502                 Formats::const_iterator cit =
503                         find_if(formatlist_.begin(), formatlist_.end(),
504                                 FormatExtensionsEqual(ext));
505                 if (cit != formatlist_.end()) {
506                         LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
507                                 << ext << " -> " << cit->name());
508                         return cit->name();
509                 }
510         }
511         return string();
512 }
513
514
515 /// Used to store last timestamp of file and whether it is (was) zipped
516 struct ZippedInfo {
517         bool zipped;
518         std::time_t timestamp;
519         ZippedInfo(bool zipped, std::time_t timestamp)
520         : zipped(zipped), timestamp(timestamp) { }
521 };
522
523
524 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
525 static std::map<std::string, ZippedInfo> zipped_;
526 static Mutex zipped_mutex;
527
528
529 bool Formats::isZippedFile(support::FileName const & filename) const {
530         string const & fname = filename.absFileName();
531         time_t timestamp = filename.lastModified();
532         Mutex::Locker lock(&zipped_mutex);
533         map<string, ZippedInfo>::iterator it = zipped_.find(fname);
534         if (it != zipped_.end() && it->second.timestamp == timestamp)
535                 return it->second.zipped;
536         // FIXME perf: This very expensive function is called on startup on each
537         // file whic is going to be parsed, and also on svgz icons. Maybe there is a
538         // quicker way to check whether a file is zipped?  I.e. for icons we
539         // probably just need to check the extension (svgz vs svg).
540         string const & format = getFormatFromFile(filename);
541         bool zipped = (format == "gzip" || format == "zip");
542         zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
543         return zipped;
544 }
545
546
547 bool Formats::isZippedFileFormat(string const & format)
548 {
549         return contains("gzip zip compress", format) && !format.empty();
550 }
551
552
553 bool Formats::isPostScriptFileFormat(string const & format)
554 {
555         return format == "ps" || format == "eps";
556 }
557
558 static string fixCommand(string const & cmd, string const & ext,
559                   os::auto_open_mode mode)
560 {
561         // configure.py says we do not want a viewer/editor
562         if (cmd.empty())
563                 return cmd;
564
565         // Does the OS manage this format?
566         if (os::canAutoOpenFile(ext, mode))
567                 return "auto";
568
569         // if configure.py found nothing, clear the command
570         if (token(cmd, ' ', 0) == "auto")
571                 return string();
572
573         // use the command found by configure.py
574         return cmd;
575 }
576
577
578 void Formats::setAutoOpen()
579 {
580         FormatList::iterator fit = formatlist_.begin();
581         FormatList::iterator const fend = formatlist_.end();
582         for ( ; fit != fend ; ++fit) {
583                 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
584                 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
585         }
586 }
587
588
589 int Formats::getNumber(string const & name) const
590 {
591         FormatList::const_iterator cit =
592                 find_if(formatlist_.begin(), formatlist_.end(),
593                         FormatNamesEqual(name));
594         if (cit != formatlist_.end())
595                 return distance(formatlist_.begin(), cit);
596         else
597                 return -1;
598 }
599
600
601 void Formats::add(string const & name)
602 {
603         if (!getFormat(name))
604                 add(name, name, from_utf8(name), string(), string(), string(),
605                     string(), Format::document);
606 }
607
608
609 void Formats::add(string const & name, string const & extensions,
610                   docstring const & prettyname, string const & shortcut,
611                   string const & viewer, string const & editor,
612                   string const & mime, int flags)
613 {
614         FormatList::iterator it =
615                 find_if(formatlist_.begin(), formatlist_.end(),
616                         FormatNamesEqual(name));
617         if (it == formatlist_.end())
618                 formatlist_.push_back(Format(name, extensions, prettyname,
619                                             shortcut, viewer, editor, mime, flags));
620         else
621                 *it = Format(name, extensions, prettyname, shortcut, viewer,
622                              editor, mime, flags);
623 }
624
625
626 void Formats::erase(string const & name)
627 {
628         FormatList::iterator it =
629                 find_if(formatlist_.begin(), formatlist_.end(),
630                         FormatNamesEqual(name));
631         if (it != formatlist_.end())
632                 formatlist_.erase(it);
633 }
634
635
636 void Formats::sort()
637 {
638         std::sort(formatlist_.begin(), formatlist_.end());
639 }
640
641
642 void Formats::setViewer(string const & name, string const & command)
643 {
644         add(name);
645         FormatList::iterator it =
646                 find_if(formatlist_.begin(), formatlist_.end(),
647                         FormatNamesEqual(name));
648         if (it != formatlist_.end())
649                 it->setViewer(command);
650 }
651
652
653 void Formats::setEditor(string const & name, string const & command)
654 {
655         add(name);
656         FormatList::iterator it =
657                 find_if(formatlist_.begin(), formatlist_.end(),
658                         FormatNamesEqual(name));
659         if (it != formatlist_.end())
660                 it->setEditor(command);
661 }
662
663
664 bool Formats::view(Buffer const & buffer, FileName const & filename,
665                    string const & format_name) const
666 {
667         if (filename.empty() || !filename.exists()) {
668                 Alert::error(_("Cannot view file"),
669                         bformat(_("File does not exist: %1$s"),
670                                 from_utf8(filename.absFileName())));
671                 return false;
672         }
673
674         Format const * format = getFormat(format_name);
675         if (format && format->viewer().empty() &&
676             format->isChildFormat())
677                 format = getFormat(format->parentFormat());
678         if (!format || format->viewer().empty()) {
679 // FIXME: I believe this is the wrong place to show alerts, it should be done
680 // by the caller (this should be "utility" code)
681                 Alert::error(_("Cannot view file"),
682                         bformat(_("No information for viewing %1$s"),
683                                 translateIfPossible(prettyName(format_name))));
684                 return false;
685         }
686         // viewer is 'auto'
687         if (format->viewer() == "auto") {
688                 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
689                         return true;
690                 else {
691                         Alert::error(_("Cannot view file"),
692                                 bformat(_("Auto-view file %1$s failed"),
693                                         from_utf8(filename.absFileName())));
694                         return false;
695                 }
696         }
697
698         string command = format->viewer();
699
700         // Escape backslashes if not already in double or single quotes.
701         // We cannot simply quote the whole command as there may be arguments.
702         if (contains(command, '\\')) {
703                 bool inquote1 = false;
704                 bool inquote2 = false;
705                 string::iterator cit = command.begin();
706                 for (; cit != command.end(); ++cit) {
707                         switch (*cit) {
708                         case '"':
709                                 inquote1 = !inquote1;
710                                 break;
711                         case '\'':
712                                 inquote2 = !inquote2;
713                                 break;
714                         case '\\':
715                                 if (!inquote1 && !inquote2)
716                                         cit = ++command.insert(cit, '\\');
717                                 break;
718                         }
719                 }
720         }
721
722         if (format_name == "dvi" &&
723             !lyxrc.view_dvi_paper_option.empty()) {
724                 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
725                 if (!paper_size.empty()) {
726                         command += ' ' + lyxrc.view_dvi_paper_option;
727                         command += ' ' + paper_size;
728                         if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
729                             buffer.params().papersize != PAPER_CUSTOM)
730                                 command += 'r';
731                 }
732         }
733
734         if (!contains(command, token_from_format))
735                 command += ' ' + token_from_format;
736
737         command = subst(command, token_from_format,
738                         quoteName(onlyFileName(filename.toFilesystemEncoding()), quote_shell_filename));
739         command = subst(command, token_path_format,
740                         quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
741         command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
742         LYXERR(Debug::FILES, "Executing command: " << command);
743         // FIXME UNICODE utf8 can be wrong for files
744         buffer.message(_("Executing command: ") + from_utf8(command));
745
746         PathChanger p(filename.onlyPath());
747         Systemcall one;
748         one.startscript(Systemcall::DontWait, command,
749                         buffer.filePath(), buffer.layoutPos());
750
751         // we can't report any sort of error, since we aren't waiting
752         return true;
753 }
754
755
756 bool Formats::edit(Buffer const & buffer, FileName const & filename,
757                          string const & format_name) const
758 {
759         if (filename.empty() || !filename.exists()) {
760                 Alert::error(_("Cannot edit file"),
761                         bformat(_("File does not exist: %1$s"),
762                                 from_utf8(filename.absFileName())));
763                 return false;
764         }
765
766         // LinkBack files look like PDF, but have the .linkback extension
767         string const ext = getExtension(filename.absFileName());
768         if (format_name == "pdf6" && ext == "linkback") {
769 #ifdef USE_MACOSX_PACKAGING
770                 return editLinkBackFile(filename.absFileName().c_str());
771 #else
772                 Alert::error(_("Cannot edit file"),
773                              _("LinkBack files can only be edited on Apple Mac OSX."));
774                 return false;
775 #endif // USE_MACOSX_PACKAGING
776         }
777
778         Format const * format = getFormat(format_name);
779         if (format && format->editor().empty() &&
780             format->isChildFormat())
781                 format = getFormat(format->parentFormat());
782         if (!format || format->editor().empty()) {
783 // FIXME: I believe this is the wrong place to show alerts, it should
784 // be done by the caller (this should be "utility" code)
785                 Alert::error(_("Cannot edit file"),
786                         bformat(_("No information for editing %1$s"),
787                                 translateIfPossible(prettyName(format_name))));
788                 return false;
789         }
790
791         // editor is 'auto'
792         if (format->editor() == "auto") {
793                 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
794                         return true;
795                 else {
796                         Alert::error(_("Cannot edit file"),
797                                 bformat(_("Auto-edit file %1$s failed"),
798                                         from_utf8(filename.absFileName())));
799                         return false;
800                 }
801         }
802
803         string command = format->editor();
804
805         if (!contains(command, token_from_format))
806                 command += ' ' + token_from_format;
807
808         command = subst(command, token_from_format,
809                         quoteName(filename.toFilesystemEncoding(), quote_shell_filename));
810         command = subst(command, token_path_format,
811                         quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
812         command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
813         LYXERR(Debug::FILES, "Executing command: " << command);
814         // FIXME UNICODE utf8 can be wrong for files
815         buffer.message(_("Executing command: ") + from_utf8(command));
816
817         Systemcall one;
818         one.startscript(Systemcall::DontWait, command,
819                         buffer.filePath(), buffer.layoutPos());
820
821         // we can't report any sort of error, since we aren't waiting
822         return true;
823 }
824
825
826 docstring const Formats::prettyName(string const & name) const
827 {
828         Format const * format = getFormat(name);
829         if (format)
830                 return format->prettyname();
831         else
832                 return from_utf8(name);
833 }
834
835
836 string const Formats::extension(string const & name) const
837 {
838         Format const * format = getFormat(name);
839         if (format)
840                 return format->extension();
841         else
842                 return name;
843 }
844
845
846 string const Formats::extensions(string const & name) const
847 {
848         Format const * format = getFormat(name);
849         if (format)
850                 return format->extensions();
851         else
852                 return name;
853 }
854
855
856 namespace {
857
858 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
859
860
861 FlavorTranslator initFlavorTranslator()
862 {
863         FlavorTranslator f(OutputParams::LATEX, "latex");
864         f.addPair(OutputParams::DVILUATEX, "dviluatex");
865         f.addPair(OutputParams::LUATEX, "luatex");
866         f.addPair(OutputParams::PDFLATEX, "pdflatex");
867         f.addPair(OutputParams::XETEX, "xetex");
868         f.addPair(OutputParams::XML, "docbook-xml");
869         f.addPair(OutputParams::HTML, "xhtml");
870         f.addPair(OutputParams::TEXT, "text");
871         f.addPair(OutputParams::LYX, "lyx");
872         return f;
873 }
874
875
876 FlavorTranslator const & flavorTranslator()
877 {
878         static FlavorTranslator const translator = initFlavorTranslator();
879         return translator;
880 }
881
882 } // namespace
883
884
885 std::string flavor2format(OutputParams::FLAVOR flavor)
886 {
887         return flavorTranslator().find(flavor);
888 }
889
890
891 /* Not currently needed, but I'll leave the code in case it is.
892 OutputParams::FLAVOR format2flavor(std::string fmt)
893 {
894         return flavorTranslator().find(fmt);
895 } */
896
897 } // namespace lyx