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