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