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