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