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