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