]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
saner borderline between buffer and exporter
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Buffer.h"
14
15 #include "Author.h"
16 #include "BiblioInfo.h"
17 #include "BranchList.h"
18 #include "buffer_funcs.h"
19 #include "BufferList.h"
20 #include "BufferParams.h"
21 #include "Bullet.h"
22 #include "Chktex.h"
23 #include "Converter.h"
24 #include "Counters.h"
25 #include "debug.h"
26 #include "DocIterator.h"
27 #include "Encoding.h"
28 #include "ErrorList.h"
29 #include "Exporter.h"
30 #include "Format.h"
31 #include "FuncRequest.h"
32 #include "gettext.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
35 #include "Language.h"
36 #include "LaTeX.h"
37 #include "LaTeXFeatures.h"
38 #include "Layout.h"
39 #include "LyXAction.h"
40 #include "Lexer.h"
41 #include "Text.h"
42 #include "LyX.h"
43 #include "LyXRC.h"
44 #include "LyXVC.h"
45 #include "Messages.h"
46 #include "output.h"
47 #include "output_docbook.h"
48 #include "output_latex.h"
49 #include "output_plaintext.h"
50 #include "Paragraph.h"
51 #include "paragraph_funcs.h"
52 #include "ParagraphParameters.h"
53 #include "ParIterator.h"
54 #include "Session.h"
55 #include "sgml.h"
56 #include "TexRow.h"
57 #include "TextClassList.h"
58 #include "TexStream.h"
59 #include "TocBackend.h"
60 #include "Undo.h"
61 #include "version.h"
62 #include "EmbeddedFiles.h"
63 #include "PDFOptions.h"
64
65 #include "insets/InsetBibitem.h"
66 #include "insets/InsetBibtex.h"
67 #include "insets/InsetInclude.h"
68 #include "insets/InsetText.h"
69
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MacroTable.h"
72 #include "mathed/MathSupport.h"
73
74 #include "frontends/alert.h"
75 #include "frontends/Delegates.h"
76 #include "frontends/WorkAreaManager.h"
77 #include "frontends/FileDialog.h"
78
79 #include "graphics/Previews.h"
80
81 #include "support/types.h"
82 #include "support/lyxalgo.h"
83 #include "support/FileFilterList.h"
84 #include "support/filetools.h"
85 #include "support/Forkedcall.h"
86 #include "support/fs_extras.h"
87 #include "support/gzstream.h"
88 #include "support/lyxlib.h"
89 #include "support/os.h"
90 #include "support/Path.h"
91 #include "support/textutils.h"
92 #include "support/convert.h"
93
94 #if !defined (HAVE_FORK)
95 # define fork() -1
96 #endif
97
98 #include <boost/bind.hpp>
99 #include <boost/filesystem/exception.hpp>
100 #include <boost/filesystem/operations.hpp>
101 #include <boost/shared_ptr.hpp>
102
103 #include <algorithm>
104 #include <iomanip>
105 #include <stack>
106 #include <sstream>
107 #include <fstream>
108
109 using std::endl;
110 using std::for_each;
111 using std::make_pair;
112
113 using std::ios;
114 using std::map;
115 using std::ostream;
116 using std::ostringstream;
117 using std::ofstream;
118 using std::ifstream;
119 using std::pair;
120 using std::stack;
121 using std::vector;
122 using std::string;
123 using std::time_t;
124
125 namespace lyx {
126
127 using support::addName;
128 using support::bformat;
129 using support::changeExtension;
130 using support::cmd_ret;
131 using support::createBufferTmpDir;
132 using support::destroyDir;
133 using support::FileName;
134 using support::getFormatFromContents;
135 using support::libFileSearch;
136 using support::latex_path;
137 using support::ltrim;
138 using support::makeAbsPath;
139 using support::makeDisplayPath;
140 using support::makeLatexName;
141 using support::onlyFilename;
142 using support::onlyPath;
143 using support::quoteName;
144 using support::removeAutosaveFile;
145 using support::rename;
146 using support::runCommand;
147 using support::split;
148 using support::subst;
149 using support::tempName;
150 using support::trim;
151 using support::sum;
152 using support::suffixIs;
153
154 namespace Alert = frontend::Alert;
155 namespace os = support::os;
156 namespace fs = boost::filesystem;
157
158 namespace {
159
160 int const LYX_FORMAT = 295; //Uwe: htmlurl, href
161
162 } // namespace anon
163
164
165 typedef std::map<string, bool> DepClean;
166
167 class Buffer::Impl
168 {
169 public:
170         Impl(Buffer & parent, FileName const & file, bool readonly);
171         
172         BufferParams params;
173         LyXVC lyxvc;
174         string temppath;
175         TexRow texrow;
176
177         /// need to regenerate .tex?
178         DepClean dep_clean;
179
180         /// is save needed?
181         mutable bool lyx_clean;
182
183         /// is autosave needed?
184         mutable bool bak_clean;
185
186         /// is this a unnamed file (New...)?
187         bool unnamed;
188
189         /// buffer is r/o
190         bool read_only;
191
192         /// name of the file the buffer is associated with.
193         FileName filename;
194
195         /** Set to true only when the file is fully loaded.
196          *  Used to prevent the premature generation of previews
197          *  and by the citation inset.
198          */
199         bool file_fully_loaded;
200
201         /// our Text that should be wrapped in an InsetText
202         InsetText inset;
203
204         ///
205         MacroTable macros;
206
207         ///
208         TocBackend toc_backend;
209
210         /// Container for all sort of Buffer dependant errors.
211         map<string, ErrorList> errorLists;
212
213         /// all embedded files of this buffer
214         EmbeddedFiles embedded_files;
215
216         /// timestamp and checksum used to test if the file has been externally
217         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
218         time_t timestamp_;
219         unsigned long checksum_;
220
221         ///
222         frontend::WorkAreaManager * wa_;
223
224         ///
225         Undo undo_;
226 };
227
228
229 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
230         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
231           filename(file), file_fully_loaded(false), inset(params),
232           toc_backend(&parent), embedded_files(&parent), timestamp_(0),
233           checksum_(0), wa_(0), undo_(parent)
234 {
235         inset.setAutoBreakRows(true);
236         lyxvc.buffer(&parent);
237         temppath = createBufferTmpDir();
238         params.filepath = onlyPath(file.absFilename());
239         // FIXME: And now do something if temppath == string(), because we
240         // assume from now on that temppath points to a valid temp dir.
241         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
242
243         if (use_gui)
244                 wa_ = new frontend::WorkAreaManager;
245 }
246
247
248 Buffer::Buffer(string const & file, bool readonly)
249         : pimpl_(new Impl(*this, FileName(file), readonly)), gui_(0)
250 {
251         LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
252 }
253
254
255 Buffer::~Buffer()
256 {
257         LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
258         // here the buffer should take care that it is
259         // saved properly, before it goes into the void.
260
261         Buffer * master = masterBuffer();
262         if (master != this && use_gui)
263                 // We are closing buf which was a child document so we
264                 // must update the labels and section numbering of its master
265                 // Buffer.
266                 updateLabels(*master);
267
268         if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
269                 Alert::warning(_("Could not remove temporary directory"),
270                         bformat(_("Could not remove the temporary directory %1$s"),
271                         from_utf8(temppath())));
272         }
273
274         // Remove any previewed LaTeX snippets associated with this buffer.
275         graphics::Previews::get().removeLoader(*this);
276
277         if (pimpl_->wa_) {
278                 pimpl_->wa_->closeAll();
279                 delete pimpl_->wa_;
280         }
281         delete pimpl_;
282 }
283
284
285 void Buffer::changed() const
286 {
287         if (pimpl_->wa_)
288                 pimpl_->wa_->redrawAll();
289 }
290
291
292 frontend::WorkAreaManager & Buffer::workAreaManager() const
293 {
294         BOOST_ASSERT(pimpl_->wa_);
295         return *pimpl_->wa_;
296 }
297
298
299 Text & Buffer::text() const
300 {
301         return const_cast<Text &>(pimpl_->inset.text_);
302 }
303
304
305 Inset & Buffer::inset() const
306 {
307         return const_cast<InsetText &>(pimpl_->inset);
308 }
309
310
311 BufferParams & Buffer::params()
312 {
313         return pimpl_->params;
314 }
315
316
317 BufferParams const & Buffer::params() const
318 {
319         return pimpl_->params;
320 }
321
322
323 ParagraphList & Buffer::paragraphs()
324 {
325         return text().paragraphs();
326 }
327
328
329 ParagraphList const & Buffer::paragraphs() const
330 {
331         return text().paragraphs();
332 }
333
334
335 LyXVC & Buffer::lyxvc()
336 {
337         return pimpl_->lyxvc;
338 }
339
340
341 LyXVC const & Buffer::lyxvc() const
342 {
343         return pimpl_->lyxvc;
344 }
345
346
347 string const & Buffer::temppath() const
348 {
349         return pimpl_->temppath;
350 }
351
352
353 TexRow & Buffer::texrow()
354 {
355         return pimpl_->texrow;
356 }
357
358
359 TexRow const & Buffer::texrow() const
360 {
361         return pimpl_->texrow;
362 }
363
364
365 TocBackend & Buffer::tocBackend()
366 {
367         return pimpl_->toc_backend;
368 }
369
370
371 TocBackend const & Buffer::tocBackend() const
372 {
373         return pimpl_->toc_backend;
374 }
375
376
377 EmbeddedFiles & Buffer::embeddedFiles()
378 {
379         return pimpl_->embedded_files;
380 }
381
382
383 EmbeddedFiles const & Buffer::embeddedFiles() const
384 {
385         return pimpl_->embedded_files;
386 }
387
388
389 Undo & Buffer::undo()
390 {
391         return pimpl_->undo_;
392 }
393
394
395 string Buffer::latexName(bool const no_path) const
396 {
397         string const name = changeExtension(makeLatexName(absFileName()), ".tex");
398         return no_path ? onlyFilename(name) : name;
399 }
400
401
402 pair<Buffer::LogType, string> Buffer::logName() const
403 {
404         string const filename = latexName(false);
405
406         if (filename.empty())
407                 return make_pair(Buffer::latexlog, string());
408
409         string const path = temppath();
410
411         FileName const fname(addName(temppath(),
412                                      onlyFilename(changeExtension(filename,
413                                                                   ".log"))));
414         FileName const bname(
415                 addName(path, onlyFilename(
416                         changeExtension(filename,
417                                         formats.extension("literate") + ".out"))));
418
419         // If no Latex log or Build log is newer, show Build log
420
421         if (bname.exists() &&
422             (!fname.exists() || fname.lastModified() < bname.lastModified())) {
423                 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
424                 return make_pair(Buffer::buildlog, bname.absFilename());
425         }
426         LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
427         return make_pair(Buffer::latexlog, fname.absFilename());
428 }
429
430
431 void Buffer::setReadonly(bool const flag)
432 {
433         if (pimpl_->read_only != flag) {
434                 pimpl_->read_only = flag;
435                 readonly(flag);
436         }
437 }
438
439
440 void Buffer::setFileName(string const & newfile)
441 {
442         pimpl_->filename = makeAbsPath(newfile);
443         params().filepath = onlyPath(pimpl_->filename.absFilename());
444         setReadonly(pimpl_->filename.isReadOnly());
445         updateTitles();
446 }
447
448
449 int Buffer::readHeader(Lexer & lex)
450 {
451         int unknown_tokens = 0;
452         int line = -1;
453         int begin_header_line = -1;
454
455         // Initialize parameters that may be/go lacking in header:
456         params().branchlist().clear();
457         params().preamble.erase();
458         params().options.erase();
459         params().float_placement.erase();
460         params().paperwidth.erase();
461         params().paperheight.erase();
462         params().leftmargin.erase();
463         params().rightmargin.erase();
464         params().topmargin.erase();
465         params().bottommargin.erase();
466         params().headheight.erase();
467         params().headsep.erase();
468         params().footskip.erase();
469         params().listings_params.clear();
470         params().clearLayoutModules();
471         params().pdfoptions().clear();
472         
473         for (int i = 0; i < 4; ++i) {
474                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
475                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
476         }
477
478         ErrorList & errorList = pimpl_->errorLists["Parse"];
479
480         while (lex.isOK()) {
481                 lex.next();
482                 string const token = lex.getString();
483
484                 if (token.empty())
485                         continue;
486
487                 if (token == "\\end_header")
488                         break;
489
490                 ++line;
491                 if (token == "\\begin_header") {
492                         begin_header_line = line;
493                         continue;
494                 }
495
496                 LYXERR(Debug::PARSER) << "Handling document header token: `"
497                                       << token << '\'' << endl;
498
499                 string unknown = params().readToken(lex, token);
500                 if (!unknown.empty()) {
501                         if (unknown[0] != '\\' && token == "\\textclass") {
502                                 Alert::warning(_("Unknown document class"),
503                        bformat(_("Using the default document class, because the "
504                                               "class %1$s is unknown."), from_utf8(unknown)));
505                         } else {
506                                 ++unknown_tokens;
507                                 docstring const s = bformat(_("Unknown token: "
508                                                                         "%1$s %2$s\n"),
509                                                          from_utf8(token),
510                                                          lex.getDocString());
511                                 errorList.push_back(ErrorItem(_("Document header error"),
512                                         s, -1, 0, 0));
513                         }
514                 }
515         }
516         if (begin_header_line) {
517                 docstring const s = _("\\begin_header is missing");
518                 errorList.push_back(ErrorItem(_("Document header error"),
519                         s, -1, 0, 0));
520         }
521
522         return unknown_tokens;
523 }
524
525
526 // Uwe C. Schroeder
527 // changed to be public and have one parameter
528 // Returns false if "\end_document" is not read (Asger)
529 bool Buffer::readDocument(Lexer & lex)
530 {
531         ErrorList & errorList = pimpl_->errorLists["Parse"];
532         errorList.clear();
533
534         lex.next();
535         string const token = lex.getString();
536         if (token != "\\begin_document") {
537                 docstring const s = _("\\begin_document is missing");
538                 errorList.push_back(ErrorItem(_("Document header error"),
539                         s, -1, 0, 0));
540         }
541
542         // we are reading in a brand new document
543         BOOST_ASSERT(paragraphs().empty());
544
545         readHeader(lex);
546         TextClass const & baseClass = textclasslist[params().getBaseClass()];
547         if (!baseClass.load(filePath())) {
548                 string theclass = baseClass.name();
549                 Alert::error(_("Can't load document class"), bformat(
550                         _("Using the default document class, because the "
551                                      "class %1$s could not be loaded."), from_utf8(theclass)));
552                 params().setBaseClass(defaultTextclass());
553         }
554
555         if (params().outputChanges) {
556                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
557                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
558                                   LaTeXFeatures::isAvailable("xcolor");
559
560                 if (!dvipost && !xcolorsoul) {
561                         Alert::warning(_("Changes not shown in LaTeX output"),
562                                        _("Changes will not be highlighted in LaTeX output, "
563                                          "because neither dvipost nor xcolor/soul are installed.\n"
564                                          "Please install these packages or redefine "
565                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
566                 } else if (!xcolorsoul) {
567                         Alert::warning(_("Changes not shown in LaTeX output"),
568                                        _("Changes will not be highlighted in LaTeX output "
569                                          "when using pdflatex, because xcolor and soul are not installed.\n"
570                                          "Please install both packages or redefine "
571                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
572                 }
573         }
574         // read manifest after header
575         embeddedFiles().readManifest(lex, errorList);   
576
577         // read main text
578         bool const res = text().read(*this, lex, errorList);
579         for_each(text().paragraphs().begin(),
580                  text().paragraphs().end(),
581                  bind(&Paragraph::setInsetOwner, _1, &inset()));
582
583         return res;
584 }
585
586
587 // needed to insert the selection
588 void Buffer::insertStringAsLines(ParagraphList & pars,
589         pit_type & pit, pos_type & pos,
590         Font const & fn, docstring const & str, bool autobreakrows)
591 {
592         Font font = fn;
593
594         // insert the string, don't insert doublespace
595         bool space_inserted = true;
596         for (docstring::const_iterator cit = str.begin();
597             cit != str.end(); ++cit) {
598                 Paragraph & par = pars[pit];
599                 if (*cit == '\n') {
600                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
601                                 breakParagraph(params(), pars, pit, pos,
602                                                par.layout()->isEnvironment());
603                                 ++pit;
604                                 pos = 0;
605                                 space_inserted = true;
606                         } else {
607                                 continue;
608                         }
609                         // do not insert consecutive spaces if !free_spacing
610                 } else if ((*cit == ' ' || *cit == '\t') &&
611                            space_inserted && !par.isFreeSpacing()) {
612                         continue;
613                 } else if (*cit == '\t') {
614                         if (!par.isFreeSpacing()) {
615                                 // tabs are like spaces here
616                                 par.insertChar(pos, ' ', font, params().trackChanges);
617                                 ++pos;
618                                 space_inserted = true;
619                         } else {
620                                 const pos_type n = 8 - pos % 8;
621                                 for (pos_type i = 0; i < n; ++i) {
622                                         par.insertChar(pos, ' ', font, params().trackChanges);
623                                         ++pos;
624                                 }
625                                 space_inserted = true;
626                         }
627                 } else if (!isPrintable(*cit)) {
628                         // Ignore unprintables
629                         continue;
630                 } else {
631                         // just insert the character
632                         par.insertChar(pos, *cit, font, params().trackChanges);
633                         ++pos;
634                         space_inserted = (*cit == ' ');
635                 }
636
637         }
638 }
639
640
641 bool Buffer::readString(std::string const & s)
642 {
643         params().compressed = false;
644
645         // remove dummy empty par
646         paragraphs().clear();
647         Lexer lex(0, 0);
648         std::istringstream is(s);
649         lex.setStream(is);
650         FileName const name(tempName());
651         switch (readFile(lex, name, true)) {
652         case failure:
653                 return false;
654         case wrongversion: {
655                 // We need to call lyx2lyx, so write the input to a file
656                 std::ofstream os(name.toFilesystemEncoding().c_str());
657                 os << s;
658                 os.close();
659                 return readFile(name);
660         }
661         case success:
662                 break;
663         }
664
665         return true;
666 }
667
668
669 bool Buffer::readFile(FileName const & filename)
670 {
671         FileName fname(filename);
672         // Check if the file is compressed.
673         string format = getFormatFromContents(filename);
674         if (format == "zip") {
675                 // decompress to a temp directory
676                 LYXERR(Debug::FILES) << filename << " is in zip format. Unzip to " << temppath() << endl;
677                 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
678                 //
679                 FileName lyxfile(addName(temppath(), "content.lyx"));
680                 // if both manifest.txt and file.lyx exist, this is am embedded file
681                 if (lyxfile.exists()) {
682                         params().embedded = true;
683                         fname = lyxfile;
684                 }
685         }
686         // The embedded lyx file can also be compressed, for backward compatibility
687         format = getFormatFromContents(fname);
688         if (format == "gzip" || format == "zip" || format == "compress") {
689                 params().compressed = true;
690         }
691
692         // remove dummy empty par
693         paragraphs().clear();
694         Lexer lex(0, 0);
695         lex.setFile(fname);
696         if (readFile(lex, fname) != success)
697                 return false;
698
699         return true;
700 }
701
702
703 bool Buffer::isFullyLoaded() const
704 {
705         return pimpl_->file_fully_loaded;
706 }
707
708
709 void Buffer::setFullyLoaded(bool value)
710 {
711         pimpl_->file_fully_loaded = value;
712 }
713
714
715 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
716                 bool fromstring)
717 {
718         BOOST_ASSERT(!filename.empty());
719
720         if (!lex.isOK()) {
721                 Alert::error(_("Document could not be read"),
722                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
723                 return failure;
724         }
725
726         lex.next();
727         string const token = lex.getString();
728
729         if (!lex) {
730                 Alert::error(_("Document could not be read"),
731                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
732                 return failure;
733         }
734
735         // the first token _must_ be...
736         if (token != "\\lyxformat") {
737                 lyxerr << "Token: " << token << endl;
738
739                 Alert::error(_("Document format failure"),
740                              bformat(_("%1$s is not a LyX document."),
741                                        from_utf8(filename.absFilename())));
742                 return failure;
743         }
744
745         lex.next();
746         string tmp_format = lex.getString();
747         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
748         // if present remove ".," from string.
749         string::size_type dot = tmp_format.find_first_of(".,");
750         //lyxerr << "           dot found at " << dot << endl;
751         if (dot != string::npos)
752                         tmp_format.erase(dot, 1);
753         int const file_format = convert<int>(tmp_format);
754         //lyxerr << "format: " << file_format << endl;
755
756         // save timestamp and checksum of the original disk file, making sure
757         // to not overwrite them with those of the file created in the tempdir
758         // when it has to be converted to the current format.
759         if (!pimpl_->checksum_) {
760                 // Save the timestamp and checksum of disk file. If filename is an
761                 // emergency file, save the timestamp and sum of the original lyx file
762                 // because isExternallyModified will check for this file. (BUG4193)
763                 string diskfile = filename.toFilesystemEncoding();
764                 if (suffixIs(diskfile, ".emergency"))
765                         diskfile = diskfile.substr(0, diskfile.size() - 10);
766                 saveCheckSum(FileName(diskfile));
767         }
768
769         if (file_format != LYX_FORMAT) {
770
771                 if (fromstring)
772                         // lyx2lyx would fail
773                         return wrongversion;
774
775                 FileName const tmpfile(tempName());
776                 if (tmpfile.empty()) {
777                         Alert::error(_("Conversion failed"),
778                                      bformat(_("%1$s is from a different"
779                                               " version of LyX, but a temporary"
780                                               " file for converting it could"
781                                                             " not be created."),
782                                               from_utf8(filename.absFilename())));
783                         return failure;
784                 }
785                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
786                 if (lyx2lyx.empty()) {
787                         Alert::error(_("Conversion script not found"),
788                                      bformat(_("%1$s is from a different"
789                                                " version of LyX, but the"
790                                                " conversion script lyx2lyx"
791                                                             " could not be found."),
792                                                from_utf8(filename.absFilename())));
793                         return failure;
794                 }
795                 ostringstream command;
796                 command << os::python()
797                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
798                         << " -t " << convert<string>(LYX_FORMAT)
799                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
800                         << ' ' << quoteName(filename.toFilesystemEncoding());
801                 string const command_str = command.str();
802
803                 LYXERR(Debug::INFO) << "Running '"
804                                     << command_str << '\''
805                                     << endl;
806
807                 cmd_ret const ret = runCommand(command_str);
808                 if (ret.first != 0) {
809                         Alert::error(_("Conversion script failed"),
810                                      bformat(_("%1$s is from a different version"
811                                               " of LyX, but the lyx2lyx script"
812                                                             " failed to convert it."),
813                                               from_utf8(filename.absFilename())));
814                         return failure;
815                 } else {
816                         bool const ret = readFile(tmpfile);
817                         // Do stuff with tmpfile name and buffer name here.
818                         return ret ? success : failure;
819                 }
820
821         }
822
823         if (readDocument(lex)) {
824                 Alert::error(_("Document format failure"),
825                              bformat(_("%1$s ended unexpectedly, which means"
826                                                     " that it is probably corrupted."),
827                                        from_utf8(filename.absFilename())));
828         }
829
830         //lyxerr << "removing " << MacroTable::localMacros().size()
831         //      << " temporary macro entries" << endl;
832         //MacroTable::localMacros().clear();
833
834         pimpl_->file_fully_loaded = true;
835         return success;
836 }
837
838
839 // Should probably be moved to somewhere else: BufferView? LyXView?
840 bool Buffer::save() const
841 {
842         // We don't need autosaves in the immediate future. (Asger)
843         resetAutosaveTimers();
844
845         string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
846
847         FileName backupName;
848         bool madeBackup = false;
849
850         // make a backup if the file already exists
851         if (lyxrc.make_backup && fs::exists(encodedFilename)) {
852                 backupName = FileName(absFileName() + '~');
853                 if (!lyxrc.backupdir_path.empty())
854                         backupName = FileName(addName(lyxrc.backupdir_path,
855                                               subst(os::internal_path(backupName.absFilename()), '/', '!')));
856
857                 try {
858                         fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
859                         madeBackup = true;
860                 } catch (fs::filesystem_error const & fe) {
861                         Alert::error(_("Backup failure"),
862                                      bformat(_("Cannot create backup file %1$s.\n"
863                                                "Please check whether the directory exists and is writeable."),
864                                              from_utf8(backupName.absFilename())));
865                         LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
866                 }
867         }
868
869         // ask if the disk file has been externally modified (use checksum method)
870         if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
871                 docstring const file = makeDisplayPath(absFileName(), 20);
872                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
873                                                              "you want to overwrite this file?"), file);
874                 int const ret = Alert::prompt(_("Overwrite modified file?"),
875                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
876                 if (ret == 1)
877                         return false;
878         }
879
880         if (writeFile(pimpl_->filename)) {
881                 markClean();
882                 removeAutosaveFile(absFileName());
883                 saveCheckSum(pimpl_->filename);
884                 return true;
885         } else {
886                 // Saving failed, so backup is not backup
887                 if (madeBackup)
888                         rename(backupName, pimpl_->filename);
889                 return false;
890         }
891 }
892
893
894 bool Buffer::writeFile(FileName const & fname) const
895 {
896         if (pimpl_->read_only && fname == pimpl_->filename)
897                 return false;
898
899         bool retval = false;
900
901         FileName content;
902         if (params().embedded)
903                 // first write the .lyx file to the temporary directory
904                 content = FileName(addName(temppath(), "content.lyx"));
905         else
906                 content = fname;
907         
908         if (params().compressed) {
909                 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
910                 if (!ofs)
911                         return false;
912
913                 retval = write(ofs);
914         } else {
915                 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
916                 if (!ofs)
917                         return false;
918
919                 retval = write(ofs);
920         }
921
922         if (retval && params().embedded) {
923                 // write file.lyx and all the embedded files to the zip file fname
924                 // if embedding is enabled
925                 return pimpl_->embedded_files.writeFile(fname);
926         }
927         return retval;
928 }
929
930
931 bool Buffer::write(ostream & ofs) const
932 {
933 #ifdef HAVE_LOCALE
934         // Use the standard "C" locale for file output.
935         ofs.imbue(std::locale::classic());
936 #endif
937
938         // The top of the file should not be written by params().
939
940         // write out a comment in the top of the file
941         ofs << "#LyX " << lyx_version
942             << " created this file. For more info see http://www.lyx.org/\n"
943             << "\\lyxformat " << LYX_FORMAT << "\n"
944             << "\\begin_document\n";
945
946
947         /// For each author, set 'used' to true if there is a change
948         /// by this author in the document; otherwise set it to 'false'.
949         AuthorList::Authors::const_iterator a_it = params().authors().begin();
950         AuthorList::Authors::const_iterator a_end = params().authors().end();
951         for (; a_it != a_end; ++a_it)
952                 a_it->second.used(false);
953
954         ParIterator const end = par_iterator_end();
955         ParIterator it = par_iterator_begin();
956         for ( ; it != end; ++it)
957                 it->checkAuthors(params().authors());
958
959         // now write out the buffer parameters.
960         ofs << "\\begin_header\n";
961         params().writeFile(ofs);
962         ofs << "\\end_header\n";
963
964         // write the manifest after header
965         ofs << "\n\\begin_manifest\n";
966         pimpl_->embedded_files.update();
967         embeddedFiles().writeManifest(ofs);
968         ofs << "\\end_manifest\n";
969
970         // write the text
971         ofs << "\n\\begin_body\n";
972         text().write(*this, ofs);
973         ofs << "\n\\end_body\n";
974
975         // Write marker that shows file is complete
976         ofs << "\\end_document" << endl;
977
978         // Shouldn't really be needed....
979         //ofs.close();
980
981         // how to check if close went ok?
982         // Following is an attempt... (BE 20001011)
983
984         // good() returns false if any error occured, including some
985         //        formatting error.
986         // bad()  returns true if something bad happened in the buffer,
987         //        which should include file system full errors.
988
989         bool status = true;
990         if (!ofs) {
991                 status = false;
992                 lyxerr << "File was not closed properly." << endl;
993         }
994
995         return status;
996 }
997
998
999 bool Buffer::makeLaTeXFile(FileName const & fname,
1000                            string const & original_path,
1001                            OutputParams const & runparams,
1002                            bool output_preamble, bool output_body)
1003 {
1004         string const encoding = runparams.encoding->iconvName();
1005         LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
1006                 << encoding << "..." << endl;
1007
1008         odocfstream ofs(encoding);
1009         if (!openFileWrite(ofs, fname))
1010                 return false;
1011
1012         //TexStream ts(ofs.rdbuf(), &texrow());
1013
1014         bool failed_export = false;
1015         try {
1016                 texrow().reset();
1017                 writeLaTeXSource(ofs, original_path,
1018                       runparams, output_preamble, output_body);
1019         }
1020         catch (iconv_codecvt_facet_exception & e) {
1021                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1022                 failed_export = true;
1023         }
1024         catch (std::exception const & e) {
1025                 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1026                 failed_export = true;
1027         }
1028         catch (...) {
1029                 lyxerr << "Caught some really weird exception..." << endl;
1030                 LyX::cref().emergencyCleanup();
1031                 abort();
1032         }
1033
1034         ofs.close();
1035         if (ofs.fail()) {
1036                 failed_export = true;
1037                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1038         }
1039
1040         if (failed_export) {
1041                 Alert::error(_("Encoding error"),
1042                         _("Some characters of your document are probably not "
1043                         "representable in the chosen encoding.\n"
1044                         "Changing the document encoding to utf8 could help."));
1045                 return false;
1046         }
1047         return true;
1048 }
1049
1050
1051 void Buffer::writeLaTeXSource(odocstream & os,
1052                            string const & original_path,
1053                            OutputParams const & runparams_in,
1054                            bool const output_preamble, bool const output_body)
1055 {
1056         OutputParams runparams = runparams_in;
1057
1058         // validate the buffer.
1059         LYXERR(Debug::LATEX) << "  Validating buffer..." << endl;
1060         LaTeXFeatures features(*this, params(), runparams);
1061         validate(features);
1062         LYXERR(Debug::LATEX) << "  Buffer validation done." << endl;
1063
1064         // The starting paragraph of the coming rows is the
1065         // first paragraph of the document. (Asger)
1066         if (output_preamble && runparams.nice) {
1067                 os << "%% LyX " << lyx_version << " created this file.  "
1068                         "For more info, see http://www.lyx.org/.\n"
1069                         "%% Do not edit unless you really know what "
1070                         "you are doing.\n";
1071                 texrow().newline();
1072                 texrow().newline();
1073         }
1074         LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1075         // There are a few differences between nice LaTeX and usual files:
1076         // usual is \batchmode and has a
1077         // special input@path to allow the including of figures
1078         // with either \input or \includegraphics (what figinsets do).
1079         // input@path is set when the actual parameter
1080         // original_path is set. This is done for usual tex-file, but not
1081         // for nice-latex-file. (Matthias 250696)
1082         // Note that input@path is only needed for something the user does
1083         // in the preamble, included .tex files or ERT, files included by
1084         // LyX work without it.
1085         if (output_preamble) {
1086                 if (!runparams.nice) {
1087                         // code for usual, NOT nice-latex-file
1088                         os << "\\batchmode\n"; // changed
1089                         // from \nonstopmode
1090                         texrow().newline();
1091                 }
1092                 if (!original_path.empty()) {
1093                         // FIXME UNICODE
1094                         // We don't know the encoding of inputpath
1095                         docstring const inputpath = from_utf8(latex_path(original_path));
1096                         os << "\\makeatletter\n"
1097                            << "\\def\\input@path{{"
1098                            << inputpath << "/}}\n"
1099                            << "\\makeatother\n";
1100                         texrow().newline();
1101                         texrow().newline();
1102                         texrow().newline();
1103                 }
1104
1105                 // Write the preamble
1106                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1107
1108                 if (!output_body)
1109                         return;
1110
1111                 // make the body.
1112                 os << "\\begin{document}\n";
1113                 texrow().newline();
1114         } // output_preamble
1115
1116         texrow().start(paragraphs().begin()->id(), 0);
1117         
1118         LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1119
1120         if (!lyxrc.language_auto_begin &&
1121             !params().language->babel().empty()) {
1122                 // FIXME UNICODE
1123                 os << from_utf8(subst(lyxrc.language_command_begin,
1124                                            "$$lang",
1125                                            params().language->babel()))
1126                    << '\n';
1127                 texrow().newline();
1128         }
1129
1130         Encoding const & encoding = params().encoding();
1131         if (encoding.package() == Encoding::CJK) {
1132                 // Open a CJK environment, since in contrast to the encodings
1133                 // handled by inputenc the document encoding is not set in
1134                 // the preamble if it is handled by CJK.sty.
1135                 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1136                    << "}{}\n";
1137                 texrow().newline();
1138         }
1139
1140         // if we are doing a real file with body, even if this is the
1141         // child of some other buffer, let's cut the link here.
1142         // This happens for example if only a child document is printed.
1143         string save_parentname;
1144         if (output_preamble) {
1145                 save_parentname = params().parentname;
1146                 params().parentname.erase();
1147         }
1148
1149         loadChildDocuments();
1150
1151         // the real stuff
1152         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1153
1154         // Restore the parenthood if needed
1155         if (output_preamble)
1156                 params().parentname = save_parentname;
1157
1158         // add this just in case after all the paragraphs
1159         os << endl;
1160         texrow().newline();
1161
1162         if (encoding.package() == Encoding::CJK) {
1163                 // Close the open CJK environment.
1164                 // latexParagraphs will have opened one even if the last text
1165                 // was not CJK.
1166                 os << "\\end{CJK}\n";
1167                 texrow().newline();
1168         }
1169
1170         if (!lyxrc.language_auto_end &&
1171             !params().language->babel().empty()) {
1172                 os << from_utf8(subst(lyxrc.language_command_end,
1173                                            "$$lang",
1174                                            params().language->babel()))
1175                    << '\n';
1176                 texrow().newline();
1177         }
1178
1179         if (output_preamble) {
1180                 os << "\\end{document}\n";
1181                 texrow().newline();
1182
1183                 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1184         } else {
1185                 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1186                                      << endl;
1187         }
1188         runparams_in.encoding = runparams.encoding;
1189
1190         // Just to be sure. (Asger)
1191         texrow().newline();
1192
1193         LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1194         LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1195                             << '.' << endl;
1196 }
1197
1198
1199 bool Buffer::isLatex() const
1200 {
1201         return params().getTextClass().outputType() == LATEX;
1202 }
1203
1204
1205 bool Buffer::isLiterate() const
1206 {
1207         return params().getTextClass().outputType() == LITERATE;
1208 }
1209
1210
1211 bool Buffer::isDocBook() const
1212 {
1213         return params().getTextClass().outputType() == DOCBOOK;
1214 }
1215
1216
1217 void Buffer::makeDocBookFile(FileName const & fname,
1218                               OutputParams const & runparams,
1219                               bool const body_only)
1220 {
1221         LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1222
1223         //ofstream ofs;
1224         odocfstream ofs;
1225         if (!openFileWrite(ofs, fname))
1226                 return;
1227
1228         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1229
1230         ofs.close();
1231         if (ofs.fail())
1232                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1233 }
1234
1235
1236 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1237                              OutputParams const & runparams,
1238                              bool const only_body)
1239 {
1240         LaTeXFeatures features(*this, params(), runparams);
1241         validate(features);
1242
1243         texrow().reset();
1244
1245         TextClass const & tclass = params().getTextClass();
1246         string const top_element = tclass.latexname();
1247
1248         if (!only_body) {
1249                 if (runparams.flavor == OutputParams::XML)
1250                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1251
1252                 // FIXME UNICODE
1253                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1254
1255                 // FIXME UNICODE
1256                 if (! tclass.class_header().empty())
1257                         os << from_ascii(tclass.class_header());
1258                 else if (runparams.flavor == OutputParams::XML)
1259                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1260                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1261                 else
1262                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1263
1264                 docstring preamble = from_utf8(params().preamble);
1265                 if (runparams.flavor != OutputParams::XML ) {
1266                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1267                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1268                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1269                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1270                 }
1271
1272                 string const name = runparams.nice
1273                         ? changeExtension(absFileName(), ".sgml") : fname;
1274                 preamble += features.getIncludedFiles(name);
1275                 preamble += features.getLyXSGMLEntities();
1276
1277                 if (!preamble.empty()) {
1278                         os << "\n [ " << preamble << " ]";
1279                 }
1280                 os << ">\n\n";
1281         }
1282
1283         string top = top_element;
1284         top += " lang=\"";
1285         if (runparams.flavor == OutputParams::XML)
1286                 top += params().language->code();
1287         else
1288                 top += params().language->code().substr(0,2);
1289         top += '"';
1290
1291         if (!params().options.empty()) {
1292                 top += ' ';
1293                 top += params().options;
1294         }
1295
1296         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1297             << " file was created by LyX " << lyx_version
1298             << "\n  See http://www.lyx.org/ for more information -->\n";
1299
1300         params().getTextClass().counters().reset();
1301
1302         loadChildDocuments();
1303
1304         sgml::openTag(os, top);
1305         os << '\n';
1306         docbookParagraphs(paragraphs(), *this, os, runparams);
1307         sgml::closeTag(os, top_element);
1308 }
1309
1310
1311 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1312 // Other flags: -wall -v0 -x
1313 int Buffer::runChktex()
1314 {
1315         busy(true);
1316
1317         // get LaTeX-Filename
1318         FileName const path(temppath());
1319         string const name = addName(path.absFilename(), latexName());
1320         string const org_path = filePath();
1321
1322         support::Path p(path); // path to LaTeX file
1323         message(_("Running chktex..."));
1324
1325         // Generate the LaTeX file if neccessary
1326         OutputParams runparams(&params().encoding());
1327         runparams.flavor = OutputParams::LATEX;
1328         runparams.nice = false;
1329         makeLaTeXFile(FileName(name), org_path, runparams);
1330
1331         TeXErrors terr;
1332         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1333         int const res = chktex.run(terr); // run chktex
1334
1335         if (res == -1) {
1336                 Alert::error(_("chktex failure"),
1337                              _("Could not run chktex successfully."));
1338         } else if (res > 0) {
1339                 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1340                 // Clear out old errors
1341                 errorList.clear();
1342                 // Fill-in the error list with the TeX errors
1343                 bufferErrors(*this, terr, errorList);
1344         }
1345
1346         busy(false);
1347
1348         errors("ChkTeX");
1349
1350         return res;
1351 }
1352
1353
1354 void Buffer::validate(LaTeXFeatures & features) const
1355 {
1356         TextClass const & tclass = params().getTextClass();
1357
1358         if (params().outputChanges) {
1359                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1360                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1361                                   LaTeXFeatures::isAvailable("xcolor");
1362
1363                 if (features.runparams().flavor == OutputParams::LATEX) {
1364                         if (dvipost) {
1365                                 features.require("ct-dvipost");
1366                                 features.require("dvipost");
1367                         } else if (xcolorsoul) {
1368                                 features.require("ct-xcolor-soul");
1369                                 features.require("soul");
1370                                 features.require("xcolor");
1371                         } else {
1372                                 features.require("ct-none");
1373                         }
1374                 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1375                         if (xcolorsoul) {
1376                                 features.require("ct-xcolor-soul");
1377                                 features.require("soul");
1378                                 features.require("xcolor");
1379                                 features.require("pdfcolmk"); // improves color handling in PDF output
1380                         } else {
1381                                 features.require("ct-none");
1382                         }
1383                 }
1384         }
1385
1386         // AMS Style is at document level
1387         if (params().use_amsmath == BufferParams::package_on
1388             || tclass.provides("amsmath"))
1389                 features.require("amsmath");
1390         if (params().use_esint == BufferParams::package_on)
1391                 features.require("esint");
1392
1393         loadChildDocuments();
1394
1395         for_each(paragraphs().begin(), paragraphs().end(),
1396                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1397
1398         // the bullet shapes are buffer level not paragraph level
1399         // so they are tested here
1400         for (int i = 0; i < 4; ++i) {
1401                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1402                         int const font = params().user_defined_bullet(i).getFont();
1403                         if (font == 0) {
1404                                 int const c = params()
1405                                         .user_defined_bullet(i)
1406                                         .getCharacter();
1407                                 if (c == 16
1408                                    || c == 17
1409                                    || c == 25
1410                                    || c == 26
1411                                    || c == 31) {
1412                                         features.require("latexsym");
1413                                 }
1414                         } else if (font == 1) {
1415                                 features.require("amssymb");
1416                         } else if ((font >= 2 && font <= 5)) {
1417                                 features.require("pifont");
1418                         }
1419                 }
1420         }
1421
1422         if (lyxerr.debugging(Debug::LATEX)) {
1423                 features.showStruct();
1424         }
1425 }
1426
1427
1428 void Buffer::getLabelList(vector<docstring> & list) const
1429 {
1430         /// if this is a child document and the parent is already loaded
1431         /// Use the parent's list instead  [ale990407]
1432         Buffer const * tmp = masterBuffer();
1433         if (!tmp) {
1434                 lyxerr << "masterBuffer() failed!" << endl;
1435                 BOOST_ASSERT(tmp);
1436         }
1437         if (tmp != this) {
1438                 tmp->getLabelList(list);
1439                 return;
1440         }
1441
1442         loadChildDocuments();
1443
1444         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1445                 it.nextInset()->getLabelList(*this, list);
1446 }
1447
1448
1449 void Buffer::updateBibfilesCache()
1450 {
1451         // if this is a child document and the parent is already loaded
1452         // update the parent's cache instead
1453         Buffer * tmp = masterBuffer();
1454         BOOST_ASSERT(tmp);
1455         if (tmp != this) {
1456                 tmp->updateBibfilesCache();
1457                 return;
1458         }
1459
1460         bibfilesCache_.clear();
1461         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1462                 if (it->lyxCode() == BIBTEX_CODE) {
1463                         InsetBibtex const & inset =
1464                                 static_cast<InsetBibtex const &>(*it);
1465                         vector<FileName> const bibfiles = inset.getFiles(*this);
1466                         bibfilesCache_.insert(bibfilesCache_.end(),
1467                                 bibfiles.begin(),
1468                                 bibfiles.end());
1469                 } else if (it->lyxCode() == INCLUDE_CODE) {
1470                         InsetInclude & inset =
1471                                 static_cast<InsetInclude &>(*it);
1472                         inset.updateBibfilesCache(*this);
1473                         vector<FileName> const & bibfiles =
1474                                         inset.getBibfilesCache(*this);
1475                         bibfilesCache_.insert(bibfilesCache_.end(),
1476                                 bibfiles.begin(),
1477                                 bibfiles.end());
1478                 }
1479         }
1480 }
1481
1482
1483 vector<FileName> const & Buffer::getBibfilesCache() const
1484 {
1485         // if this is a child document and the parent is already loaded
1486         // use the parent's cache instead
1487         Buffer const * tmp = masterBuffer();
1488         BOOST_ASSERT(tmp);
1489         if (tmp != this)
1490                 return tmp->getBibfilesCache();
1491
1492         // We update the cache when first used instead of at loading time.
1493         if (bibfilesCache_.empty())
1494                 const_cast<Buffer *>(this)->updateBibfilesCache();
1495
1496         return bibfilesCache_;
1497 }
1498
1499
1500 bool Buffer::isDepClean(string const & name) const
1501 {
1502         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1503         if (it == pimpl_->dep_clean.end())
1504                 return true;
1505         return it->second;
1506 }
1507
1508
1509 void Buffer::markDepClean(string const & name)
1510 {
1511         pimpl_->dep_clean[name] = true;
1512 }
1513
1514
1515 bool Buffer::dispatch(string const & command, bool * result)
1516 {
1517         return dispatch(lyxaction.lookupFunc(command), result);
1518 }
1519
1520
1521 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1522 {
1523         bool dispatched = true;
1524
1525         switch (func.action) {
1526                 case LFUN_BUFFER_EXPORT: {
1527                         bool const tmp = doExport(to_utf8(func.argument()), false);
1528                         if (result)
1529                                 *result = tmp;
1530                         break;
1531                 }
1532
1533                 default:
1534                         dispatched = false;
1535         }
1536         return dispatched;
1537 }
1538
1539
1540 void Buffer::changeLanguage(Language const * from, Language const * to)
1541 {
1542         BOOST_ASSERT(from);
1543         BOOST_ASSERT(to);
1544
1545         for_each(par_iterator_begin(),
1546                  par_iterator_end(),
1547                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1548 }
1549
1550
1551 bool Buffer::isMultiLingual() const
1552 {
1553         ParConstIterator end = par_iterator_end();
1554         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1555                 if (it->isMultiLingual(params()))
1556                         return true;
1557
1558         return false;
1559 }
1560
1561
1562 ParIterator Buffer::getParFromID(int const id) const
1563 {
1564         ParConstIterator it = par_iterator_begin();
1565         ParConstIterator const end = par_iterator_end();
1566
1567         if (id < 0) {
1568                 // John says this is called with id == -1 from undo
1569                 lyxerr << "getParFromID(), id: " << id << endl;
1570                 return end;
1571         }
1572
1573         for (; it != end; ++it)
1574                 if (it->id() == id)
1575                         return it;
1576
1577         return end;
1578 }
1579
1580
1581 bool Buffer::hasParWithID(int const id) const
1582 {
1583         ParConstIterator const it = getParFromID(id);
1584         return it != par_iterator_end();
1585 }
1586
1587
1588 ParIterator Buffer::par_iterator_begin()
1589 {
1590         return lyx::par_iterator_begin(inset());
1591 }
1592
1593
1594 ParIterator Buffer::par_iterator_end()
1595 {
1596         return lyx::par_iterator_end(inset());
1597 }
1598
1599
1600 ParConstIterator Buffer::par_iterator_begin() const
1601 {
1602         return lyx::par_const_iterator_begin(inset());
1603 }
1604
1605
1606 ParConstIterator Buffer::par_iterator_end() const
1607 {
1608         return lyx::par_const_iterator_end(inset());
1609 }
1610
1611
1612 Language const * Buffer::language() const
1613 {
1614         return params().language;
1615 }
1616
1617
1618 docstring const Buffer::B_(string const & l10n) const
1619 {
1620         return params().B_(l10n);
1621 }
1622
1623
1624 bool Buffer::isClean() const
1625 {
1626         return pimpl_->lyx_clean;
1627 }
1628
1629
1630 bool Buffer::isBakClean() const
1631 {
1632         return pimpl_->bak_clean;
1633 }
1634
1635
1636 bool Buffer::isExternallyModified(CheckMethod method) const
1637 {
1638         BOOST_ASSERT(pimpl_->filename.exists());
1639         // if method == timestamp, check timestamp before checksum
1640         return (method == checksum_method 
1641                 || pimpl_->timestamp_ != pimpl_->filename.lastModified())
1642                 && pimpl_->checksum_ != sum(pimpl_->filename);
1643 }
1644
1645
1646 void Buffer::saveCheckSum(FileName const & file) const
1647 {
1648         if (file.exists()) {
1649                 pimpl_->timestamp_ = file.lastModified();
1650                 pimpl_->checksum_ = sum(file);
1651         } else {
1652                 // in the case of save to a new file.
1653                 pimpl_->timestamp_ = 0;
1654                 pimpl_->checksum_ = 0;
1655         }
1656 }
1657
1658
1659 void Buffer::markClean() const
1660 {
1661         if (!pimpl_->lyx_clean) {
1662                 pimpl_->lyx_clean = true;
1663                 updateTitles();
1664         }
1665         // if the .lyx file has been saved, we don't need an
1666         // autosave
1667         pimpl_->bak_clean = true;
1668 }
1669
1670
1671 void Buffer::markBakClean() const
1672 {
1673         pimpl_->bak_clean = true;
1674 }
1675
1676
1677 void Buffer::setUnnamed(bool flag)
1678 {
1679         pimpl_->unnamed = flag;
1680 }
1681
1682
1683 bool Buffer::isUnnamed() const
1684 {
1685         return pimpl_->unnamed;
1686 }
1687
1688
1689 // FIXME: this function should be moved to buffer_pimpl.C
1690 void Buffer::markDirty()
1691 {
1692         if (pimpl_->lyx_clean) {
1693                 pimpl_->lyx_clean = false;
1694                 updateTitles();
1695         }
1696         pimpl_->bak_clean = false;
1697
1698         DepClean::iterator it = pimpl_->dep_clean.begin();
1699         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1700
1701         for (; it != end; ++it)
1702                 it->second = false;
1703 }
1704
1705
1706 string Buffer::absFileName() const
1707 {
1708         return pimpl_->filename.absFilename();
1709 }
1710
1711
1712 string const & Buffer::filePath() const
1713 {
1714         return params().filepath;
1715 }
1716
1717
1718 bool Buffer::isReadonly() const
1719 {
1720         return pimpl_->read_only;
1721 }
1722
1723
1724 void Buffer::setParentName(string const & name)
1725 {
1726         if (name == pimpl_->filename.absFilename())
1727                 // Avoids recursive include.
1728                 params().parentname.clear();
1729         else
1730                 params().parentname = name;
1731 }
1732
1733
1734 Buffer const * Buffer::masterBuffer() const
1735 {
1736         if (!params().parentname.empty()
1737             && theBufferList().exists(params().parentname)) {
1738                 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1739                 //We need to check if the parent is us...
1740                 //FIXME RECURSIVE INCLUDE
1741                 //This is not sufficient, since recursive includes could be downstream.
1742                 if (buf && buf != this)
1743                         return buf->masterBuffer();
1744         }
1745
1746         return this;
1747 }
1748
1749
1750 Buffer * Buffer::masterBuffer()
1751 {
1752         if (!params().parentname.empty()
1753             && theBufferList().exists(params().parentname)) {
1754                 Buffer * buf = theBufferList().getBuffer(params().parentname);
1755                 //We need to check if the parent is us...
1756                 //FIXME RECURSIVE INCLUDE
1757                 //This is not sufficient, since recursive includes could be downstream.
1758                 if (buf && buf != this)
1759                         return buf->masterBuffer();
1760         }
1761
1762         return this;
1763 }
1764
1765
1766 MacroData const & Buffer::getMacro(docstring const & name) const
1767 {
1768         return pimpl_->macros.get(name);
1769 }
1770
1771
1772 bool Buffer::hasMacro(docstring const & name) const
1773 {
1774         return pimpl_->macros.has(name);
1775 }
1776
1777
1778 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1779 {
1780         MacroTable::globalMacros().insert(name, data);
1781         pimpl_->macros.insert(name, data);
1782 }
1783
1784
1785 void Buffer::buildMacros()
1786 {
1787         // Start with global table.
1788         pimpl_->macros = MacroTable::globalMacros();
1789
1790         // Now add our own.
1791         ParagraphList const & pars = text().paragraphs();
1792         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1793                 //lyxerr << "searching main par " << i
1794                 //      << " for macro definitions" << std::endl;
1795                 InsetList const & insets = pars[i].insetList();
1796                 InsetList::const_iterator it = insets.begin();
1797                 InsetList::const_iterator end = insets.end();
1798                 for ( ; it != end; ++it) {
1799                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1800                         if (it->inset->lyxCode() == MATHMACRO_CODE) {
1801                                 MathMacroTemplate const & mac
1802                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1803                                 insertMacro(mac.name(), mac.asMacroData());
1804                         }
1805                 }
1806         }
1807 }
1808
1809
1810 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1811         InsetCode code)
1812 {
1813         //FIXME: This does not work for child documents yet.
1814         BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1815         // Check if the label 'from' appears more than once
1816         vector<docstring> labels;
1817
1818         if (code == CITE_CODE) {
1819                 BiblioInfo keys;
1820                 keys.fillWithBibKeys(this);
1821                 BiblioInfo::const_iterator bit  = keys.begin();
1822                 BiblioInfo::const_iterator bend = keys.end();
1823
1824                 for (; bit != bend; ++bit)
1825                         // FIXME UNICODE
1826                         labels.push_back(bit->first);
1827         } else
1828                 getLabelList(labels);
1829
1830         if (std::count(labels.begin(), labels.end(), from) > 1)
1831                 return;
1832
1833         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1834                 if (it->lyxCode() == code) {
1835                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
1836                         inset.replaceContents(to_utf8(from), to_utf8(to));
1837                 }
1838         }
1839 }
1840
1841
1842 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1843         pit_type par_end, bool full_source)
1844 {
1845         OutputParams runparams(&params().encoding());
1846         runparams.nice = true;
1847         runparams.flavor = OutputParams::LATEX;
1848         runparams.linelen = lyxrc.plaintext_linelen;
1849         // No side effect of file copying and image conversion
1850         runparams.dryrun = true;
1851
1852         texrow().reset();
1853         if (full_source) {
1854                 os << "% " << _("Preview source code") << "\n\n";
1855                 texrow().newline();
1856                 texrow().newline();
1857                 if (isLatex())
1858                         writeLaTeXSource(os, filePath(), runparams, true, true);
1859                 else {
1860                         writeDocBookSource(os, absFileName(), runparams, false);
1861                 }
1862         } else {
1863                 runparams.par_begin = par_begin;
1864                 runparams.par_end = par_end;
1865                 if (par_begin + 1 == par_end)
1866                         os << "% "
1867                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1868                            << "\n\n";
1869                 else
1870                         os << "% "
1871                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1872                                         convert<docstring>(par_begin),
1873                                         convert<docstring>(par_end - 1))
1874                            << "\n\n";
1875                 texrow().newline();
1876                 texrow().newline();
1877                 // output paragraphs
1878                 if (isLatex()) {
1879                         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1880                 } else {
1881                         // DocBook
1882                         docbookParagraphs(paragraphs(), *this, os, runparams);
1883                 }
1884         }
1885 }
1886
1887
1888 ErrorList const & Buffer::errorList(string const & type) const
1889 {
1890         static ErrorList const emptyErrorList;
1891         std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1892         if (I == pimpl_->errorLists.end())
1893                 return emptyErrorList;
1894
1895         return I->second;
1896 }
1897
1898
1899 ErrorList & Buffer::errorList(string const & type)
1900 {
1901         return pimpl_->errorLists[type];
1902 }
1903
1904
1905 void Buffer::structureChanged() const
1906 {
1907         if (gui_)
1908                 gui_->structureChanged();
1909 }
1910
1911
1912 void Buffer::embeddingChanged() const
1913 {
1914         if (gui_)
1915                 gui_->embeddingChanged();
1916 }
1917
1918
1919 void Buffer::errors(std::string const & err) const
1920 {
1921         if (gui_)
1922                 gui_->errors(err);
1923 }
1924
1925
1926 void Buffer::message(docstring const & msg) const
1927 {
1928         if (gui_)
1929                 gui_->message(msg);
1930 }
1931
1932
1933 void Buffer::busy(bool on) const
1934 {
1935         if (gui_)
1936                 gui_->busy(on);
1937 }
1938
1939
1940 void Buffer::readonly(bool on) const
1941 {
1942         if (gui_)
1943                 gui_->readonly(on);
1944 }
1945
1946
1947 void Buffer::updateTitles() const
1948 {
1949         if (gui_)
1950                 gui_->updateTitles();
1951 }
1952
1953
1954 void Buffer::resetAutosaveTimers() const
1955 {
1956         if (gui_)
1957                 gui_->resetAutosaveTimers();
1958 }
1959
1960
1961 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1962 {
1963         gui_ = gui;
1964 }
1965
1966
1967
1968 namespace {
1969
1970 class AutoSaveBuffer : public support::ForkedProcess {
1971 public:
1972         ///
1973         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1974                 : buffer_(buffer), fname_(fname) {}
1975         ///
1976         virtual boost::shared_ptr<ForkedProcess> clone() const
1977         {
1978                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1979         }
1980         ///
1981         int start()
1982         {
1983                 command_ = to_utf8(bformat(_("Auto-saving %1$s"), 
1984                                                  from_utf8(fname_.absFilename())));
1985                 return run(DontWait);
1986         }
1987 private:
1988         ///
1989         virtual int generateChild();
1990         ///
1991         Buffer const & buffer_;
1992         FileName fname_;
1993 };
1994
1995
1996 #if !defined (HAVE_FORK)
1997 # define fork() -1
1998 #endif
1999
2000 int AutoSaveBuffer::generateChild()
2001 {
2002         // tmp_ret will be located (usually) in /tmp
2003         // will that be a problem?
2004         pid_t const pid = fork();
2005         // If you want to debug the autosave
2006         // you should set pid to -1, and comment out the fork.
2007         if (pid == 0 || pid == -1) {
2008                 // pid = -1 signifies that lyx was unable
2009                 // to fork. But we will do the save
2010                 // anyway.
2011                 bool failed = false;
2012
2013                 FileName const tmp_ret(tempName(FileName(), "lyxauto"));
2014                 if (!tmp_ret.empty()) {
2015                         buffer_.writeFile(tmp_ret);
2016                         // assume successful write of tmp_ret
2017                         if (!rename(tmp_ret, fname_)) {
2018                                 failed = true;
2019                                 // most likely couldn't move between
2020                                 // filesystems unless write of tmp_ret
2021                                 // failed so remove tmp file (if it
2022                                 // exists)
2023                                 unlink(tmp_ret);
2024                         }
2025                 } else {
2026                         failed = true;
2027                 }
2028
2029                 if (failed) {
2030                         // failed to write/rename tmp_ret so try writing direct
2031                         if (!buffer_.writeFile(fname_)) {
2032                                 // It is dangerous to do this in the child,
2033                                 // but safe in the parent, so...
2034                                 if (pid == -1) // emit message signal.
2035                                         buffer_.message(_("Autosave failed!"));
2036                         }
2037                 }
2038                 if (pid == 0) { // we are the child so...
2039                         _exit(0);
2040                 }
2041         }
2042         return pid;
2043 }
2044
2045 } // namespace anon
2046
2047
2048 // Perfect target for a thread...
2049 void Buffer::autoSave() const
2050 {
2051         if (isBakClean() || isReadonly()) {
2052                 // We don't save now, but we'll try again later
2053                 resetAutosaveTimers();
2054                 return;
2055         }
2056
2057         // emit message signal.
2058         message(_("Autosaving current document..."));
2059
2060         // create autosave filename
2061         string fname = filePath();
2062         fname += '#';
2063         fname += onlyFilename(absFileName());
2064         fname += '#';
2065
2066         AutoSaveBuffer autosave(*this, FileName(fname));
2067         autosave.start();
2068
2069         markBakClean();
2070         resetAutosaveTimers();
2071 }
2072
2073
2074 /** Write a buffer to a new file name and rename the buffer
2075     according to the new file name.
2076
2077     This function is e.g. used by menu callbacks and
2078     LFUN_BUFFER_WRITE_AS.
2079
2080     If 'newname' is empty (the default), the user is asked via a
2081     dialog for the buffer's new name and location.
2082
2083     If 'newname' is non-empty and has an absolute path, that is used.
2084     Otherwise the base directory of the buffer is used as the base
2085     for any relative path in 'newname'.
2086 */
2087
2088 bool Buffer::writeAs(string const & newname)
2089 {
2090         string fname = absFileName();
2091         string const oldname = fname;
2092
2093         if (newname.empty()) {  /// No argument? Ask user through dialog
2094
2095                 // FIXME UNICODE
2096                 FileDialog fileDlg(_("Choose a filename to save document as"),
2097                                    LFUN_BUFFER_WRITE_AS,
2098                                    make_pair(_("Documents|#o#O"), 
2099                                              from_utf8(lyxrc.document_path)),
2100                                    make_pair(_("Templates|#T#t"), 
2101                                              from_utf8(lyxrc.template_path)));
2102
2103                 if (!support::isLyXFilename(fname))
2104                         fname += ".lyx";
2105
2106                 support::FileFilterList const filter(_("LyX Documents (*.lyx)"));
2107
2108                 FileDialog::Result result =
2109                         fileDlg.save(from_utf8(onlyPath(fname)),
2110                                      filter,
2111                                      from_utf8(onlyFilename(fname)));
2112
2113                 if (result.first == FileDialog::Later)
2114                         return false;
2115
2116                 fname = to_utf8(result.second);
2117
2118                 if (fname.empty())
2119                         return false;
2120
2121                 // Make sure the absolute filename ends with appropriate suffix
2122                 fname = makeAbsPath(fname).absFilename();
2123                 if (!support::isLyXFilename(fname))
2124                         fname += ".lyx";
2125
2126         } else 
2127                 fname = makeAbsPath(newname, onlyPath(oldname)).absFilename();
2128
2129         if (FileName(fname).exists()) {
2130                 docstring const file = makeDisplayPath(fname, 30);
2131                 docstring text = bformat(_("The document %1$s already "
2132                                            "exists.\n\nDo you want to "
2133                                            "overwrite that document?"), 
2134                                          file);
2135                 int const ret = Alert::prompt(_("Overwrite document?"),
2136                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
2137
2138                 if (ret == 1)
2139                         return false;
2140         }
2141
2142         // Ok, change the name of the buffer
2143         setFileName(fname);
2144         markDirty();
2145         bool unnamed = isUnnamed();
2146         setUnnamed(false);
2147         saveCheckSum(FileName(fname));
2148
2149         if (!menuWrite()) {
2150                 setFileName(oldname);
2151                 setUnnamed(unnamed);
2152                 saveCheckSum(FileName(oldname));
2153                 return false;
2154         }
2155
2156         removeAutosaveFile(oldname);
2157         return true;
2158 }
2159
2160
2161 bool Buffer::menuWrite()
2162 {
2163         if (save()) {
2164                 LyX::ref().session().lastFiles().add(FileName(absFileName()));
2165                 return true;
2166         }
2167
2168         // FIXME: we don't tell the user *WHY* the save failed !!
2169
2170         docstring const file = makeDisplayPath(absFileName(), 30);
2171
2172         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2173                                    "Do you want to rename the document and "
2174                                    "try again?"), file);
2175         int const ret = Alert::prompt(_("Rename and save?"),
2176                 text, 0, 1, _("&Rename"), _("&Cancel"));
2177
2178         if (ret != 0)
2179                 return false;
2180
2181         return writeAs();
2182 }
2183
2184
2185 void Buffer::loadChildDocuments() const
2186 {
2187         bool parse_error = false;
2188                 
2189         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2190                 if (it->lyxCode() != INCLUDE_CODE)
2191                         continue;
2192                 InsetInclude const & inset = static_cast<InsetInclude const &>(*it);
2193                 InsetCommandParams const & ip = inset.params();
2194                 Buffer * child = loadIfNeeded(*this, ip);
2195                 if (!child)
2196                         continue;
2197                 parse_error |= !child->errorList("Parse").empty();
2198                 child->loadChildDocuments();
2199         }
2200
2201         if (use_gui && masterBuffer() == this)
2202                 updateLabels(*this);
2203 }
2204
2205
2206 string Buffer::bufferFormat() const
2207 {
2208         if (isDocBook())
2209                 return "docbook";
2210         if (isLiterate())
2211                 return "literate";
2212         return "latex";
2213 }
2214
2215
2216 bool Buffer::doExport(string const & format,
2217         bool put_in_tempdir, string & result_file)
2218 {
2219         string backend_format;
2220         OutputParams runparams(&params().encoding());
2221         runparams.flavor = OutputParams::LATEX;
2222         runparams.linelen = lyxrc.plaintext_linelen;
2223         vector<string> backs = backends();
2224         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2225                 // Get shortest path to format
2226                 Graph::EdgePath path;
2227                 for (vector<string>::const_iterator it = backs.begin();
2228                      it != backs.end(); ++it) {
2229                         Graph::EdgePath p = theConverters().getPath(*it, format);
2230                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2231                                 backend_format = *it;
2232                                 path = p;
2233                         }
2234                 }
2235                 if (!path.empty())
2236                         runparams.flavor = theConverters().getFlavor(path);
2237                 else {
2238                         Alert::error(_("Couldn't export file"),
2239                                 bformat(_("No information for exporting the format %1$s."),
2240                                    formats.prettyName(format)));
2241                         return false;
2242                 }
2243         } else {
2244                 backend_format = format;
2245                 // FIXME: Don't hardcode format names here, but use a flag
2246                 if (backend_format == "pdflatex")
2247                         runparams.flavor = OutputParams::PDFLATEX;
2248         }
2249
2250         string filename = latexName(false);
2251         filename = addName(temppath(), filename);
2252         filename = changeExtension(filename,
2253                                    formats.extension(backend_format));
2254
2255         // Plain text backend
2256         if (backend_format == "text")
2257                 writePlaintextFile(*this, FileName(filename), runparams);
2258         // no backend
2259         else if (backend_format == "lyx")
2260                 writeFile(FileName(filename));
2261         // Docbook backend
2262         else if (isDocBook()) {
2263                 runparams.nice = !put_in_tempdir;
2264                 makeDocBookFile(FileName(filename), runparams);
2265         }
2266         // LaTeX backend
2267         else if (backend_format == format) {
2268                 runparams.nice = true;
2269                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2270                         return false;
2271         } else if (!lyxrc.tex_allows_spaces
2272                    && support::contains(filePath(), ' ')) {
2273                 Alert::error(_("File name error"),
2274                            _("The directory path to the document cannot contain spaces."));
2275                 return false;
2276         } else {
2277                 runparams.nice = false;
2278                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2279                         return false;
2280         }
2281
2282         string const error_type = (format == "program")
2283                 ? "Build" : bufferFormat();
2284         string const ext = formats.extension(format);
2285         FileName const tmp_result_file(changeExtension(filename, ext));
2286         bool const success = theConverters().convert(this, FileName(filename),
2287                 tmp_result_file, FileName(absFileName()), backend_format, format,
2288                 errorList(error_type));
2289         // Emit the signal to show the error list.
2290         if (format != backend_format)
2291                 errors(error_type);
2292         if (!success)
2293                 return false;
2294
2295         if (put_in_tempdir)
2296                 result_file = tmp_result_file.absFilename();
2297         else {
2298                 result_file = changeExtension(absFileName(), ext);
2299                 // We need to copy referenced files (e. g. included graphics
2300                 // if format == "dvi") to the result dir.
2301                 vector<ExportedFile> const files =
2302                         runparams.exportdata->externalFiles(format);
2303                 string const dest = onlyPath(result_file);
2304                 CopyStatus status = SUCCESS;
2305                 for (vector<ExportedFile>::const_iterator it = files.begin();
2306                                 it != files.end() && status != CANCEL; ++it) {
2307                         string const fmt =
2308                                 formats.getFormatFromFile(it->sourceName);
2309                         status = copyFile(fmt, it->sourceName,
2310                                           makeAbsPath(it->exportName, dest),
2311                                           it->exportName, status == FORCE);
2312                 }
2313                 if (status == CANCEL) {
2314                         message(_("Document export cancelled."));
2315                 } else if (tmp_result_file.exists()) {
2316                         // Finally copy the main file
2317                         status = copyFile(format, tmp_result_file,
2318                                           FileName(result_file), result_file,
2319                                           status == FORCE);
2320                         message(bformat(_("Document exported as %1$s "
2321                                                                "to file `%2$s'"),
2322                                                 formats.prettyName(format),
2323                                                 makeDisplayPath(result_file)));
2324                 } else {
2325                         // This must be a dummy converter like fax (bug 1888)
2326                         message(bformat(_("Document exported as %1$s"),
2327                                                 formats.prettyName(format)));
2328                 }
2329         }
2330
2331         return true;
2332 }
2333
2334
2335 bool Buffer::doExport(string const & format, bool put_in_tempdir)
2336 {
2337         string result_file;
2338         return doExport(format, put_in_tempdir, result_file);
2339 }
2340
2341
2342 bool Buffer::preview(string const & format)
2343 {
2344         string result_file;
2345         if (!doExport(format, true, result_file))
2346                 return false;
2347         return formats.view(*this, FileName(result_file), format);
2348 }
2349
2350
2351 bool Buffer::isExportable(string const & format) const
2352 {
2353         vector<string> backs = backends();
2354         for (vector<string>::const_iterator it = backs.begin();
2355              it != backs.end(); ++it)
2356                 if (theConverters().isReachable(*it, format))
2357                         return true;
2358         return false;
2359 }
2360
2361
2362 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2363 {
2364         vector<string> backs = backends();
2365         vector<Format const *> result =
2366                 theConverters().getReachable(backs[0], only_viewable, true);
2367         for (vector<string>::const_iterator it = backs.begin() + 1;
2368              it != backs.end(); ++it) {
2369                 vector<Format const *>  r =
2370                         theConverters().getReachable(*it, only_viewable, false);
2371                 result.insert(result.end(), r.begin(), r.end());
2372         }
2373         return result;
2374 }
2375
2376
2377 vector<string> Buffer::backends() const
2378 {
2379         vector<string> v;
2380         if (params().getTextClass().isTeXClassAvailable()) {
2381                 v.push_back(bufferFormat());
2382                 // FIXME: Don't hardcode format names here, but use a flag
2383                 if (v.back() == "latex")
2384                         v.push_back("pdflatex");
2385         }
2386         v.push_back("text");
2387         v.push_back("lyx");
2388         return v;
2389 }
2390
2391
2392 } // namespace lyx