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