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