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