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